diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/__pycache__/deep_gemm_moe.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/__pycache__/deep_gemm_moe.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf5e0cb475b393af3a24ed3909f2547d8371bc67 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/__pycache__/deep_gemm_moe.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/__pycache__/deepep_ll_prepare_finalize.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/__pycache__/deepep_ll_prepare_finalize.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc648fdc905f8f45535a15fd09d9ed834f4d4b35 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/__pycache__/deepep_ll_prepare_finalize.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/__pycache__/flashinfer_cutlass_prepare_finalize.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/__pycache__/flashinfer_cutlass_prepare_finalize.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcc50a248be3e070113e84bd5aa03dfc0cd082fe Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/__pycache__/flashinfer_cutlass_prepare_finalize.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/__pycache__/fused_moe.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/__pycache__/fused_moe.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..116e543cfc7aa6f4992560f21a580e3938f9a60f Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/__pycache__/fused_moe.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=1,N=3072,device_name=NVIDIA_H100_80GB_HBM3,dtype=int8_w8a16.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=1,N=3072,device_name=NVIDIA_H100_80GB_HBM3,dtype=int8_w8a16.json new file mode 100644 index 0000000000000000000000000000000000000000..2c78bfaba7890772bf266721f5577202ea443882 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=1,N=3072,device_name=NVIDIA_H100_80GB_HBM3,dtype=int8_w8a16.json @@ -0,0 +1,218 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 5 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 5 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 5 + }, + "24": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "256": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "5120": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "9216": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "13312": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "17408": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "25600": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "33792": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "41984": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "50176": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "58368": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=1,N=3584,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=1,N=3584,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json new file mode 100644 index 0000000000000000000000000000000000000000..200356713c0d0a76e199671c7ec8f10d0e5ee0ac --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=1,N=3584,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json @@ -0,0 +1,218 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "5120": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "9216": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "13312": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "17408": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "25600": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "33792": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "41984": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "50176": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "58368": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=1,N=7168,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=1,N=7168,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json new file mode 100644 index 0000000000000000000000000000000000000000..ee896554b921040d7810bb6e9368cc200777951d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=1,N=7168,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a16.json @@ -0,0 +1,218 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "5120": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "9216": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "13312": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "17408": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "25600": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "33792": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "41984": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "50176": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "58368": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=1024,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=1024,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..555d173644522713f502ee8ee21efa5f04916184 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=1024,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json @@ -0,0 +1,164 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "256": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "512": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1024": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1536": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=1024,device_name=AMD_Instinct_MI300X.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=1024,device_name=AMD_Instinct_MI300X.json new file mode 100644 index 0000000000000000000000000000000000000000..e539335d4dc73ebf7fbcad65b64422c1d1afaeb8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=1024,device_name=AMD_Instinct_MI300X.json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 1, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "256": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "512": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1024": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=192,device_name=NVIDIA_H100_80GB_HBM3.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=192,device_name=NVIDIA_H100_80GB_HBM3.json new file mode 100644 index 0000000000000000000000000000000000000000..5de5605d401c2e84b42134e4a3ed7e5811a8ffe3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=192,device_name=NVIDIA_H100_80GB_HBM3.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 5 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 5 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 2 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json new file mode 100644 index 0000000000000000000000000000000000000000..c275cecc1591f16e91791e9b007cdb6fcaac40b4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json @@ -0,0 +1,164 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "256": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H20-3e,dtype=fp8_w8a8,block_shape=[128,128].json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H20-3e,dtype=fp8_w8a8,block_shape=[128,128].json new file mode 100644 index 0000000000000000000000000000000000000000..60ccde1351598b2ad2b800bdf20e7f987d360698 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H20-3e,dtype=fp8_w8a8,block_shape=[128,128].json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H20-3e.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H20-3e.json new file mode 100644 index 0000000000000000000000000000000000000000..b0139b9f2af405e3a91209ae366886a2e9755445 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H20-3e.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H20.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H20.json new file mode 100644 index 0000000000000000000000000000000000000000..ab169a0183ddc11ace79bc480aefd7db154bea67 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H20.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 5 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json new file mode 100644 index 0000000000000000000000000000000000000000..324ad7b22fedf6b353029e6fe38675fb73968419 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 5 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 5 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 5 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H200.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H200.json new file mode 100644 index 0000000000000000000000000000000000000000..ab6e15552909b795ad63eff23c3161fd29c7b824 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=384,device_name=NVIDIA_H200.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 2 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=768,device_name=NVIDIA_H20-3e,dtype=fp8_w8a8,block_shape=[128,128].json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=768,device_name=NVIDIA_H20-3e,dtype=fp8_w8a8,block_shape=[128,128].json new file mode 100644 index 0000000000000000000000000000000000000000..3559f33f444b92b0cf82b56b0d8303799fcc7ac9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=128,N=768,device_name=NVIDIA_H20-3e,dtype=fp8_w8a8,block_shape=[128,128].json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=16,N=2688,device_name=NVIDIA_A100-SXM4-80GB.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=16,N=2688,device_name=NVIDIA_A100-SXM4-80GB.json new file mode 100644 index 0000000000000000000000000000000000000000..039a10ed127b77836a7f41c03513292613852b30 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=16,N=2688,device_name=NVIDIA_A100-SXM4-80GB.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=16,N=3200,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=16,N=3200,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..cd0cdbea0c3372674cb610870dd0b30325864549 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=16,N=3200,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json @@ -0,0 +1,130 @@ +{ + "3328": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 2 + }, + "256": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 4 + }, + "768": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 4 + }, + "1792": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "2560": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 2 + }, + "2816": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "3584": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 2 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 2 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 2 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 4 + }, + "3840": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "1280": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 2 + }, + "2304": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 2 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 2 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=16,N=7168,device_name=NVIDIA_A100-SXM4-80GB.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=16,N=7168,device_name=NVIDIA_A100-SXM4-80GB.json new file mode 100644 index 0000000000000000000000000000000000000000..dbf9a2dd6f048d8adee290961e2aea72035f7615 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=16,N=7168,device_name=NVIDIA_A100-SXM4-80GB.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 5 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 5 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 3 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=16,N=7168,device_name=NVIDIA_H100_80GB_HBM3,dtype=int8_w8a16.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=16,N=7168,device_name=NVIDIA_H100_80GB_HBM3,dtype=int8_w8a16.json new file mode 100644 index 0000000000000000000000000000000000000000..bbb2386046b1135a2cc7ab7cb26c1d0b039bcf3a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=16,N=7168,device_name=NVIDIA_H100_80GB_HBM3,dtype=int8_w8a16.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 5 + }, + "1536": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=160,N=192,device_name=NVIDIA_A800-SXM4-80GB.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=160,N=192,device_name=NVIDIA_A800-SXM4-80GB.json new file mode 100644 index 0000000000000000000000000000000000000000..0611620eb33626ac891454637723eabec9aa1183 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=160,N=192,device_name=NVIDIA_A800-SXM4-80GB.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 5 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 5 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 2 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=160,N=192,device_name=NVIDIA_H20-3e.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=160,N=192,device_name=NVIDIA_H20-3e.json new file mode 100644 index 0000000000000000000000000000000000000000..f2ed716c8bec292102c8c96ba2b14c0ee9d43eb2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=160,N=192,device_name=NVIDIA_H20-3e.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=20,N=2560,device_name=NVIDIA_H20-3e,dtype=fp8_w8a8,block_shape=[128,128].json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=20,N=2560,device_name=NVIDIA_H20-3e,dtype=fp8_w8a8,block_shape=[128,128].json new file mode 100644 index 0000000000000000000000000000000000000000..307c9240938c5840b606e953df650976bb4eea44 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=20,N=2560,device_name=NVIDIA_H20-3e,dtype=fp8_w8a8,block_shape=[128,128].json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "256": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 5 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 5 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=1024,device_name=AMD_Instinct_MI325X,block_shape=[128,128].json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=1024,device_name=AMD_Instinct_MI325X,block_shape=[128,128].json new file mode 100644 index 0000000000000000000000000000000000000000..43c249d2530e1fafb46f6594b73e11f33fa8ffe7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=1024,device_name=AMD_Instinct_MI325X,block_shape=[128,128].json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 1, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 1, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=1024,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=1024,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json new file mode 100644 index 0000000000000000000000000000000000000000..43c249d2530e1fafb46f6594b73e11f33fa8ffe7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=1024,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 1, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 1, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json new file mode 100644 index 0000000000000000000000000000000000000000..4dd00d110e486c0a7670504ace778fd5995de727 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a8,block_shape=[128,128].json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 2 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 5 + }, + "256": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..48f9697af2639bd4afd45c768c7a8e9442924e2d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_A100-SXM4-80GB,dtype=int8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 2 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 2 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 2 + }, + "256": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 2 + }, + "512": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_A800-SXM4-80GB,dtype=int8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_A800-SXM4-80GB,dtype=int8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..f1244c61efb019183e892f848700072c3be03ef9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_A800-SXM4-80GB,dtype=int8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 2 + }, + "256": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 2 + }, + "512": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json new file mode 100644 index 0000000000000000000000000000000000000000..2e692a1583a4ad95f020634d55f7f4e327be5da0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json new file mode 100644 index 0000000000000000000000000000000000000000..857d11e488917b22dabd44f58de013bf61f754c6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_L20Y,dtype=fp8_w8a8,block_shape=[128,128].json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_L20Y,dtype=fp8_w8a8,block_shape=[128,128].json new file mode 100644 index 0000000000000000000000000000000000000000..a2ee05da1d7c632aa6b1c3ccc8af2546f987ee93 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=128,device_name=NVIDIA_L20Y,dtype=fp8_w8a8,block_shape=[128,128].json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json new file mode 100644 index 0000000000000000000000000000000000000000..e6769604ee6bcc75c41a5bea296cb55da3c755e8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "24": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 1, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "256": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "512": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json new file mode 100644 index 0000000000000000000000000000000000000000..e6769604ee6bcc75c41a5bea296cb55da3c755e8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "24": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 1, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "256": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "512": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=NVIDIA_B200,dtype=fp8_w8a8,block_shape=[128,128].json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=NVIDIA_B200,dtype=fp8_w8a8,block_shape=[128,128].json new file mode 100644 index 0000000000000000000000000000000000000000..fc573cd6e8561f56830c8f8ca3033f2d2f7bc1b3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=NVIDIA_B200,dtype=fp8_w8a8,block_shape=[128,128].json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 5 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json new file mode 100644 index 0000000000000000000000000000000000000000..3e0ad0d5a98914bb5e825496fbfdf356e7fdd9c3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=NVIDIA_H20,dtype=fp8_w8a8,block_shape=[128,128].json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=NVIDIA_H20,dtype=int8_w8a8,block_shape=[128,128].json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=NVIDIA_H20,dtype=int8_w8a8,block_shape=[128,128].json new file mode 100644 index 0000000000000000000000000000000000000000..c6d7e96c7f0aea61a2bd57723ecb91b1c1230895 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=NVIDIA_H20,dtype=int8_w8a8,block_shape=[128,128].json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=NVIDIA_L20,dtype=fp8_w8a8,block_shape=[128,128].json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=NVIDIA_L20,dtype=fp8_w8a8,block_shape=[128,128].json new file mode 100644 index 0000000000000000000000000000000000000000..c6eabea66a39aa86f5becc04d32ee01dbe627dce --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=256,device_name=NVIDIA_L20,dtype=fp8_w8a8,block_shape=[128,128].json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "2": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 2 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 2 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 2 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 2 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 2 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 2 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 2 + }, + "256": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 2 + }, + "512": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 2 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=512,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=512,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json new file mode 100644 index 0000000000000000000000000000000000000000..e6769604ee6bcc75c41a5bea296cb55da3c755e8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=512,device_name=AMD_Instinct_MI325_OAM,dtype=fp8_w8a8,block_shape=[128,128].json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "24": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 1, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "256": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "512": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=64,device_name=NVIDIA_A800-SXM4-80GB.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=64,device_name=NVIDIA_A800-SXM4-80GB.json new file mode 100644 index 0000000000000000000000000000000000000000..21f60229ff875ca6dc0cd0a3cb4fa51a845bf881 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=256,N=64,device_name=NVIDIA_A800-SXM4-80GB.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 2 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 2 + }, + "2048": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 2 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=60,N=176,device_name=AMD_Instinct_MI300X.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=60,N=176,device_name=AMD_Instinct_MI300X.json new file mode 100644 index 0000000000000000000000000000000000000000..746463af4d56315af3c31348c2253e43c926553e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=60,N=176,device_name=AMD_Instinct_MI300X.json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 1, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 1, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "256": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "3072": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=60,N=704,device_name=AMD_Instinct_MI300X.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=60,N=704,device_name=AMD_Instinct_MI300X.json new file mode 100644 index 0000000000000000000000000000000000000000..43584b1eb6b65f02fc919490b0ff4b9569de58c4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=60,N=704,device_name=AMD_Instinct_MI300X.json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "8": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "256": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=62,N=256,device_name=NVIDIA_H100_80GB_HBM3.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=62,N=256,device_name=NVIDIA_H100_80GB_HBM3.json new file mode 100644 index 0000000000000000000000000000000000000000..147a836602fe3660bf8674f20630e30d73fb6dc5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=62,N=256,device_name=NVIDIA_H100_80GB_HBM3.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 2 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "256": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=62,N=512,device_name=NVIDIA_H100_80GB_HBM3.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=62,N=512,device_name=NVIDIA_H100_80GB_HBM3.json new file mode 100644 index 0000000000000000000000000000000000000000..a01e9c317ea88e12d942827f63446f8de892a4a2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=62,N=512,device_name=NVIDIA_H100_80GB_HBM3.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 2 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 2 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "256": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 2 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_A100-SXM4-80GB.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_A100-SXM4-80GB.json new file mode 100644 index 0000000000000000000000000000000000000000..8cc6c643f236d2f7f9ad29354d9e469d00b20d3f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_A100-SXM4-80GB.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 5 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 5 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_A800-SXM4-80GB.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_A800-SXM4-80GB.json new file mode 100644 index 0000000000000000000000000000000000000000..39a9912fa4bddc48de38d5a8b4fadd71326485d2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_A800-SXM4-80GB.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 5 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_H200,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_H200,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..c17a4ec346915af69f10f65410450cbd66614810 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_H200,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_H200.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_H200.json new file mode 100644 index 0000000000000000000000000000000000000000..170ae7f3fff1d09961d368853dcfc2f24c1b878c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=1280,device_name=NVIDIA_H200.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 5 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=1536,device_name=NVIDIA_H20,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=1536,device_name=NVIDIA_H20,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..298a36175e60d47ec2b7bb65e6b0de8e6d93424e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=1536,device_name=NVIDIA_H20,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 5 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=2560,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=2560,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..1d9d352edebc3f228353873677d2369e6a721158 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=2560,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=2560,device_name=NVIDIA_H200,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=2560,device_name=NVIDIA_H200,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..9ad5b316750051e4a5dc39b195f6a29eeaa882f0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=2560,device_name=NVIDIA_H200,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 5 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=2560,device_name=NVIDIA_H200.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=2560,device_name=NVIDIA_H200.json new file mode 100644 index 0000000000000000000000000000000000000000..2883dfd11e7f3a7db429ae0aaeb98d554f271cdf --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=2560,device_name=NVIDIA_H200.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 2 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 5 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=3072,device_name=NVIDIA_H20,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=3072,device_name=NVIDIA_H20,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..0e210cb0f38dfa883d78d77c76c334fcb1b0b1a8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=3072,device_name=NVIDIA_H20,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 2 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 5 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=3072,device_name=NVIDIA_H20.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=3072,device_name=NVIDIA_H20.json new file mode 100644 index 0000000000000000000000000000000000000000..e4fa1e2e6e9b9a3f7b30ab9933157dc76d568263 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=3072,device_name=NVIDIA_H20.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 5 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=320,device_name=NVIDIA_H100_80GB_HBM3.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=320,device_name=NVIDIA_H100_80GB_HBM3.json new file mode 100644 index 0000000000000000000000000000000000000000..2fc18a5e43d298ddabc57dc9f357296890fb7e29 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=320,device_name=NVIDIA_H100_80GB_HBM3.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "128": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=320,device_name=NVIDIA_H200,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=320,device_name=NVIDIA_H200,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..be8d4a7fd23d994ac838d45bf249e39764552ccf --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=320,device_name=NVIDIA_H200,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=320,device_name=NVIDIA_H200.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=320,device_name=NVIDIA_H200.json new file mode 100644 index 0000000000000000000000000000000000000000..71fdd88643c6ff515808fdc2d67e9fda3ac62ae9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=320,device_name=NVIDIA_H200.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 3 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=384,device_name=NVIDIA_H20,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=384,device_name=NVIDIA_H20,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..082456d319d344fdce00acea6bcc4b44c0a458e6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=384,device_name=NVIDIA_H20,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=384,device_name=NVIDIA_H20.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=384,device_name=NVIDIA_H20.json new file mode 100644 index 0000000000000000000000000000000000000000..c3b2e7fa91eb082a7265ac83f1205c8a666828e4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=384,device_name=NVIDIA_H20.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_A100-SXM4-80GB.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_A100-SXM4-80GB.json new file mode 100644 index 0000000000000000000000000000000000000000..b2799ed3a866e25b78d60d92910c000ebb21ff71 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_A100-SXM4-80GB.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_A800-SXM4-80GB.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_A800-SXM4-80GB.json new file mode 100644 index 0000000000000000000000000000000000000000..c02de2f628b716456373978f600f9fc8c4b98d24 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_A800-SXM4-80GB.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 5 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "32": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_GeForce_RTX_4090,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_GeForce_RTX_4090,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..3e0bc75ff87c43ad3a0b3f132e5367a8ef39619a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_GeForce_RTX_4090,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 2 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 2 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 2 + }, + "256": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 2 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..9f7ed6726f44e60dea5af588e441b269b6c5cc3d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_H100_80GB_HBM3.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_H100_80GB_HBM3.json new file mode 100644 index 0000000000000000000000000000000000000000..b8d3be2313fa14025d8aeb2fd11e0d1ee997ffa6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_H100_80GB_HBM3.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "128": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_H200,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_H200,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..21b72557e365d01011f48a046915765e67dbd13f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_H200,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_H200.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_H200.json new file mode 100644 index 0000000000000000000000000000000000000000..eaf32f6d76c0a6aa50a5fbc2f055a5e7c9e10b66 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=640,device_name=NVIDIA_H200.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 5 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 2 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=768,device_name=NVIDIA_H20,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=768,device_name=NVIDIA_H20,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..bba1d21aa2b6b8707f45f798f9eebbceec1b24c3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=768,device_name=NVIDIA_H20,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=768,device_name=NVIDIA_H20.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=768,device_name=NVIDIA_H20.json new file mode 100644 index 0000000000000000000000000000000000000000..de1c413b6e1aec73f35346e628b69709bf211e21 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=768,device_name=NVIDIA_H20.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=896,device_name=NVIDIA_H20.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=896,device_name=NVIDIA_H20.json new file mode 100644 index 0000000000000000000000000000000000000000..5a9910a4d37eafb96d9cf56aaff1953c37ddd934 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=64,N=896,device_name=NVIDIA_H20.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 5 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=72,N=384,device_name=NVIDIA_H100_80GB_HBM3.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=72,N=384,device_name=NVIDIA_H100_80GB_HBM3.json new file mode 100644 index 0000000000000000000000000000000000000000..a7cfd175d72cc9fba8dc234a00cdd2dd29637088 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=72,N=384,device_name=NVIDIA_H100_80GB_HBM3.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 2 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 2 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=72,N=768,device_name=NVIDIA_H100_80GB_HBM3.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=72,N=768,device_name=NVIDIA_H100_80GB_HBM3.json new file mode 100644 index 0000000000000000000000000000000000000000..3caae02cb912480758663ea9ef9621d76823d66c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=72,N=768,device_name=NVIDIA_H100_80GB_HBM3.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 5 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..b6f1d01f886524c58932ac28c31dcf6f10788e14 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json @@ -0,0 +1,164 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "512": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4096": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=AMD_Instinct_MI300X.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=AMD_Instinct_MI300X.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf775347eccb3e76e20ea0018d71343f9848313 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=AMD_Instinct_MI300X.json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 1, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 32, + "kpack": 2 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..f245285bd821717f2280fa89b5f0aa6bbce2262d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json @@ -0,0 +1,164 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "24": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "512": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1536": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4096": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=AMD_Instinct_MI325X.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=AMD_Instinct_MI325X.json new file mode 100644 index 0000000000000000000000000000000000000000..3918c93b160a39e55153cbf6ff634d59e724d021 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=AMD_Instinct_MI325X.json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 1, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 1, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 32, + "kpack": 2 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..3f3ccdafa88f3452a695efad4cb9622d6ae79e6a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json @@ -0,0 +1,138 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 5 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 3 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=NVIDIA_H200,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=NVIDIA_H200,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..841044a4fc6e2da81f18b2765fa30b9de7092b3d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=NVIDIA_H200,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 5 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 5 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 3 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=NVIDIA_H200.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=NVIDIA_H200.json new file mode 100644 index 0000000000000000000000000000000000000000..59be497fc428755f010e490277f4b945d6ed0195 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=14336,device_name=NVIDIA_H200.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "2": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=16384,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=16384,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..0e5fd1eec77d7e0aca0f1e3376b2c45217ce234a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=16384,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json @@ -0,0 +1,164 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4096": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=16384,device_name=AMD_Instinct_MI300X.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=16384,device_name=AMD_Instinct_MI300X.json new file mode 100644 index 0000000000000000000000000000000000000000..d6ad63509f1573d25fbdc370b93bc39a0d00b51a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=16384,device_name=AMD_Instinct_MI300X.json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 1, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=16384,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=16384,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..16e0a91baf31d9a819f27eeea719e564f399379c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=16384,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json @@ -0,0 +1,164 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1536": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4096": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=16384,device_name=AMD_Instinct_MI325X.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=16384,device_name=AMD_Instinct_MI325X.json new file mode 100644 index 0000000000000000000000000000000000000000..d766fc062ddcce10d38bdc68ab1f700d193b8ba7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=16384,device_name=AMD_Instinct_MI325X.json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "16": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..8323f512db0158570427a7eb0a69bd889bc2d9ed --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json @@ -0,0 +1,164 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=AMD_Instinct_MI300X.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=AMD_Instinct_MI300X.json new file mode 100644 index 0000000000000000000000000000000000000000..1b46cb5716514f290c6b4bc3a18dba490c799272 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=AMD_Instinct_MI300X.json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "256": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..6d5b1ae5b15fc333d3cdaa5dbcacab33267339cc --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json @@ -0,0 +1,164 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=AMD_Instinct_MI325X.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=AMD_Instinct_MI325X.json new file mode 100644 index 0000000000000000000000000000000000000000..ffc1b23ea90ddefd24b4b98a222e67e84442cf9c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=AMD_Instinct_MI325X.json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "16": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_A100-SXM4-40GB.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_A100-SXM4-40GB.json new file mode 100644 index 0000000000000000000000000000000000000000..f4c0f8417b384870050a95e0cf57edbdf6352b23 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_A100-SXM4-40GB.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_A100-SXM4-80GB.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_A100-SXM4-80GB.json new file mode 100644 index 0000000000000000000000000000000000000000..5c8185cfdeec167ec4b88de51b4b395e28769cc5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_A100-SXM4-80GB.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_H100_80GB_HBM3.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_H100_80GB_HBM3.json new file mode 100644 index 0000000000000000000000000000000000000000..97c9f4445b166657ad29f1db9fc8281f9c463ec4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_H100_80GB_HBM3.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_H200,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_H200,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..e4110a5d2e70f4d2698d4c28b1668f8e4a48688a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_H200,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 5 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 5 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 5 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_H200.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_H200.json new file mode 100644 index 0000000000000000000000000000000000000000..0883ef40582ea4f1b08c629edcd6dd9beaaf2dad --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=1792,device_name=NVIDIA_H200.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..81bb765d30031ca3031636d7a442dc2c2292a6a9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json @@ -0,0 +1,164 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "128": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4096": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=AMD_Instinct_MI300X.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=AMD_Instinct_MI300X.json new file mode 100644 index 0000000000000000000000000000000000000000..811c77ab4109319c9f079e414bd4f7d2cf4ac9f1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=AMD_Instinct_MI300X.json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "16": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 32, + "kpack": 2 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..2758e48fc4065cd05ceb6fe22574acf2b3aae633 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json @@ -0,0 +1,164 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 1, + "num_stages": 2, + "waves_per_eu": 0 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "3072": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4096": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=AMD_Instinct_MI325X.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=AMD_Instinct_MI325X.json new file mode 100644 index 0000000000000000000000000000000000000000..fc31215cbae8afeee27d923e176a25daf1f2b43d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=AMD_Instinct_MI325X.json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 32, + "kpack": 2 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 32, + "kpack": 2 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_A100-SXM4-80GB.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_A100-SXM4-80GB.json new file mode 100644 index 0000000000000000000000000000000000000000..0bb423b28f5ab3825929a4870b96393262a9dd9f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_A100-SXM4-80GB.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..55571873395464a3b58f549523905f439a8f1716 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 5 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H100_80GB_HBM3.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H100_80GB_HBM3.json new file mode 100644 index 0000000000000000000000000000000000000000..26bcbf26970c7a77c99e2c8eacd83eefa86967bf --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H100_80GB_HBM3.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H200,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H200,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..1a0aa331933291f0c32b2cf26672771b5c7b4196 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H200,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H200.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H200.json new file mode 100644 index 0000000000000000000000000000000000000000..9952be6ba4abe434e2924e9505e834de4ce0528e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=2048,device_name=NVIDIA_H200.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 5 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 5 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..379ca107a9469a5e5777e4e648f3f25ffc382a0a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json @@ -0,0 +1,164 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=AMD_Instinct_MI300X.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=AMD_Instinct_MI300X.json new file mode 100644 index 0000000000000000000000000000000000000000..5a3f415d54142383fa7677d8192f7a4c4df66b2e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=AMD_Instinct_MI300X.json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 32, + "kpack": 2 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..6cb80f48329f5718e892fd6f78000df4003832f2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json @@ -0,0 +1,164 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "96": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=AMD_Instinct_MI325X.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=AMD_Instinct_MI325X.json new file mode 100644 index 0000000000000000000000000000000000000000..de9d0aba75a7ed45fdfd92c123736f1e981a06eb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=AMD_Instinct_MI325X.json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 32, + "kpack": 2 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_A100-SXM4-40GB.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_A100-SXM4-40GB.json new file mode 100644 index 0000000000000000000000000000000000000000..b41f9d443e50678334f906b44fce6d018d69500e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_A100-SXM4-40GB.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_A100-SXM4-80GB.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_A100-SXM4-80GB.json new file mode 100644 index 0000000000000000000000000000000000000000..edf2a38d12ad3f420f232d2cd61ab149ad138725 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_A100-SXM4-80GB.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_GeForce_RTX_4090,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_GeForce_RTX_4090,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..32bbadbb9eae8d36e30895d863a8d10ff65167b2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_GeForce_RTX_4090,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 2 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 5 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 2 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 2 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 2 + }, + "128": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 2 + }, + "256": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 2 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..673bae2ba8ef80ed4d4930739ca7daf0e8f28ee1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 5 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H100_80GB_HBM3.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H100_80GB_HBM3.json new file mode 100644 index 0000000000000000000000000000000000000000..b2100cebb7f589747430be9ca8c8db368c152d78 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H100_80GB_HBM3.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H200,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H200,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..e6f753cdba35b55e8d021597dc4911bab27caa8d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H200,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H200.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H200.json new file mode 100644 index 0000000000000000000000000000000000000000..53f3394693f060daebff9960a95ed3753e8522c9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_H200.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_L40S.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_L40S.json new file mode 100644 index 0000000000000000000000000000000000000000..d720deb4bdd73d194b1023c99e190b8fcfecdaef --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=3584,device_name=NVIDIA_L40S.json @@ -0,0 +1,173 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_ctas": 1, + "num_stages": 2 + }, + "2": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 2, + "num_warps": 4, + "num_ctas": 1, + "num_stages": 7 + }, + "4": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 128, + "num_warps": 2, + "num_ctas": 1, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_ctas": 1, + "num_stages": 1 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_ctas": 1, + "num_stages": 1 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 2, + "num_warps": 4, + "num_ctas": 1, + "num_stages": 2 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 2, + "num_warps": 4, + "num_ctas": 1, + "num_stages": 2 + }, + "64": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 2, + "num_warps": 4, + "num_ctas": 1, + "num_stages": 2 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_ctas": 1, + "num_stages": 2 + }, + "128": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_ctas": 1, + "num_stages": 2 + }, + "192": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 8, + "num_warps": 8, + "num_ctas": 1, + "num_stages": 2 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 16, + "num_ctas": 1, + "num_stages": 2 + }, + "512": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 128, + "num_warps": 2, + "num_ctas": 1, + "num_stages": 8 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_ctas": 1, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 16, + "num_ctas": 1, + "num_stages": 2 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 16, + "num_ctas": 1, + "num_stages": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_ctas": 1, + "num_stages": 2 + }, + "6144": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_ctas": 1, + "num_stages": 2 + }, + "8192": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 16, + "num_ctas": 1, + "num_stages": 2 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..48bb5f2ccb8e3c623593538461d8d8ba71f93a69 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json @@ -0,0 +1,164 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4096": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=AMD_Instinct_MI300X.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=AMD_Instinct_MI300X.json new file mode 100644 index 0000000000000000000000000000000000000000..a64d06c6d1724f736c5081a8b947fa2e6127701d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=AMD_Instinct_MI300X.json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 32, + "kpack": 2 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..2c49f359c22ac8d3b8fd3b00035b70472c34ed51 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json @@ -0,0 +1,164 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "8": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "24": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4096": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=AMD_Instinct_MI325X.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=AMD_Instinct_MI325X.json new file mode 100644 index 0000000000000000000000000000000000000000..c7db6c0cbd3faf615074fc8055ff744e528dd204 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=AMD_Instinct_MI325X.json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_A100-SXM4-80GB.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_A100-SXM4-80GB.json new file mode 100644 index 0000000000000000000000000000000000000000..dbc624731f5cb9afcdc9213183d00d1e5edd4a00 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_A100-SXM4-80GB.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..cc614e635ea57327c610ce79e99ae5339614f22e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H100_80GB_HBM3.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H100_80GB_HBM3.json new file mode 100644 index 0000000000000000000000000000000000000000..32c0c9da471cbe479044095e0ed14a0f54b73620 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H100_80GB_HBM3.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H200,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H200,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..4dd475c02a19b380efbe8f59945a0f2a41acda11 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H200,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 5 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H200.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H200.json new file mode 100644 index 0000000000000000000000000000000000000000..2ed15f30fe603c080a2e8a32b664400a50d2153e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=4096,device_name=NVIDIA_H200.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "2": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 5 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 5 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 2 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..bd2c6fbc1b941cebfe8e03f62e3044f5878db0ed --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json @@ -0,0 +1,164 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "16": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "24": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "32": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=AMD_Instinct_MI300X.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=AMD_Instinct_MI300X.json new file mode 100644 index 0000000000000000000000000000000000000000..8d7b780271854c0fbae29e92cfd3cce508ca029e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=AMD_Instinct_MI300X.json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 1, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 1, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..7a07bbf4141952c4dc6199676b1ef97d1cfabece --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json @@ -0,0 +1,164 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "16": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "24": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "32": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1536": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4096": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=AMD_Instinct_MI325X.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=AMD_Instinct_MI325X.json new file mode 100644 index 0000000000000000000000000000000000000000..3a3268cc17a84d88f0a67e20e266491ad45d1777 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=AMD_Instinct_MI325X.json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 32, + "kpack": 2 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_A100-SXM4-80GB.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_A100-SXM4-80GB.json new file mode 100644 index 0000000000000000000000000000000000000000..f578c8d0160ac3ef85b53c8539d3675455a97173 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_A100-SXM4-80GB.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..918f6839620cbab1f30b0f9383a9129c2cf2cf3d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 5 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H100_80GB_HBM3.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H100_80GB_HBM3.json new file mode 100644 index 0000000000000000000000000000000000000000..e341a67917d5177bacb3f6767e7b6d92539826ad --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H100_80GB_HBM3.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H200,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H200,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..eb817268d41208a661d2ab9526c5108d36d44085 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H200,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 5 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 5 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 5 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 3 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H200.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H200.json new file mode 100644 index 0000000000000000000000000000000000000000..0c7062aea6c4e920cdfdc9e13fc2c0fa38aceb0e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=7168,device_name=NVIDIA_H200.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 5 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 5 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 3 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..cd4fb8f11b935e401103aab5117a1d1be1799c6e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8.json @@ -0,0 +1,164 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 1, + "num_stages": 2, + "waves_per_eu": 0 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 1, + "num_stages": 2, + "waves_per_eu": 0 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4096": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=AMD_Instinct_MI300X.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=AMD_Instinct_MI300X.json new file mode 100644 index 0000000000000000000000000000000000000000..cf66868e9d57a541fe10fa9fff682f7a7c6dac97 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=AMD_Instinct_MI300X.json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 1, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 1, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..c27ca0a36594fd12a9995fffda60a9d5003425c0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8.json @@ -0,0 +1,164 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "16": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "48": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + }, + "4096": { + "BLOCK_SIZE_M": 256, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=AMD_Instinct_MI325X.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=AMD_Instinct_MI325X.json new file mode 100644 index 0000000000000000000000000000000000000000..da477b1fb15eb2064cbff78b5e47ae9c54dae7a5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=AMD_Instinct_MI325X.json @@ -0,0 +1,200 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 16, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "8": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "16": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "24": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "32": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 2, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 1 + }, + "48": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "64": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "96": { + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 4, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 4, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 2, + "waves_per_eu": 0, + "matrix_instr_nonkdim": 16, + "kpack": 2 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..34b916e574f88c65db1dac5889d74a990dc25e9b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 5 + }, + "2": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 5 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 5 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=NVIDIA_H200,dtype=fp8_w8a8.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=NVIDIA_H200,dtype=fp8_w8a8.json new file mode 100644 index 0000000000000000000000000000000000000000..96cbc111c7fffe8b0a67c22711f9a5c8f28d8b61 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/configs/E=8,N=8192,device_name=NVIDIA_H200,dtype=fp8_w8a8.json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 256, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "256": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "512": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "1024": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + }, + "1536": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 8, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "3072": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 8, + "num_stages": 4 + }, + "4096": { + "BLOCK_SIZE_M": 128, + "BLOCK_SIZE_N": 256, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 8, + "num_stages": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/fused_moe.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/fused_moe.py new file mode 100644 index 0000000000000000000000000000000000000000..02b7b65f4a025dd1e0a60e92adc22c5db9ceef0c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/fused_moe/fused_moe.py @@ -0,0 +1,2037 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Fused MoE kernel.""" +import functools +import json +import os +# torch.compile needs typing.List. It will fail torch.library.infer_schema +# otherwise +from typing import List # noqa: UP035 +from typing import Any, Callable, Optional + +import torch +import torch.nn.functional as F + +import vllm.envs as envs +import vllm.model_executor.layers.fused_moe.modular_kernel as mk +from vllm import _custom_ops as ops +from vllm.logger import init_logger +# yapf: disable +from vllm.model_executor.layers.fused_moe.config import ( + FusedMoEQuantConfig, get_config_quant_dtype) +from vllm.model_executor.layers.fused_moe.cutlass_moe import ( + _valid_cutlass_block_scaled_grouped_gemm, + run_cutlass_block_scaled_fused_experts) +# yapf: enable +from vllm.model_executor.layers.fused_moe.deep_gemm_moe import ( + _valid_deep_gemm, deep_gemm_moe_fp8) +from vllm.model_executor.layers.fused_moe.moe_align_block_size import ( + moe_align_block_size) +from vllm.model_executor.layers.fused_moe.prepare_finalize import ( + MoEPrepareAndFinalizeNoEP) +from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import ( + TopKWeightAndReduceNoOP) +from vllm.model_executor.layers.fused_moe.utils import ( + _resize_cache, moe_kernel_quantize_input, per_token_group_quant_fp8) +from vllm.model_executor.layers.quantization.utils.flashinfer_utils import ( + calculate_tile_tokens_dim) +from vllm.model_executor.layers.quantization.utils.mxfp4_utils import ( + dequant_mxfp4) +from vllm.platforms import current_platform +from vllm.triton_utils import tl, triton +from vllm.utils import direct_register_custom_op, is_torch_equal_or_newer +from vllm.utils.deep_gemm import is_blackwell_deep_gemm_e8m0_used + +from .rocm_aiter_fused_moe import is_rocm_aiter_moe_enabled + +logger = init_logger(__name__) + + +@triton.jit +def write_zeros_to_output(c_ptr, stride_cm, stride_cn, pid_n, N, offs_token, + token_mask, BLOCK_SIZE_M, BLOCK_SIZE_N, + compute_type): + accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=compute_type) + offs_cn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) + c_ptrs = c_ptr + stride_cm * offs_token[:, None] + stride_cn * offs_cn[ + None, :] + c_mask = token_mask[:, None] & (offs_cn[None, :] < N) + tl.store(c_ptrs, accumulator, mask=c_mask) + + +@triton.jit +def fused_moe_kernel_gptq_awq( + # Pointers to matrices + a_ptr, + b_ptr, + c_ptr, + b_scale_ptr, + b_zp_ptr, + topk_weights_ptr, + sorted_token_ids_ptr, + expert_ids_ptr, + num_tokens_post_padded_ptr, + # Matrix dimensions + N: tl.constexpr, + K: tl.constexpr, + EM, + num_valid_tokens, + # The stride variables represent how much to increase the ptr by when + # moving by 1 element in a particular dimension. E.g. `stride_am` is + # how much to increase `a_ptr` by to get the element one row down + # (A has M rows). + stride_am, + stride_ak, + stride_be, + stride_bk, + stride_bn, + stride_cm, + stride_cn, + stride_bse, + stride_bsk, + stride_bsn, + stride_bze, + stride_bzk, + stride_bzn, + block_k_diviable: tl.constexpr, + group_size: tl.constexpr, + # Meta-parameters + BLOCK_SIZE_M: tl.constexpr, + BLOCK_SIZE_N: tl.constexpr, + BLOCK_SIZE_K: tl.constexpr, + GROUP_SIZE_M: tl.constexpr, + MUL_ROUTED_WEIGHT: tl.constexpr, + top_k: tl.constexpr, + compute_type: tl.constexpr, + has_zp: tl.constexpr, + use_int4_w4a16: tl.constexpr, + use_int8_w8a16: tl.constexpr): + """ + Implements the fused computation for a Mixture of Experts (MOE) using + token and expert matrices. + + Key Parameters: + - A: The input tensor representing tokens with shape (*, K), where '*' can + be any shape representing batches and K is the feature dimension of + each token. + - B: The stacked MOE weight tensor with shape (E, N, K), where E is + the number of experts, K is the input feature dimension, and N is + the output feature dimension. + - C: The output cache tensor with shape (M, topk, N), where M is the + total number of tokens post padding, topk is the number of times + each token is repeated, and N is the output feature dimension. + - sorted_token_ids: A tensor containing the sorted indices of tokens, + repeated topk times and arranged by the expert index they are + assigned to. + - expert_ids: A tensor containing the indices of the expert for each + block. It determines which expert matrix from B should be used for + each block in A. + This kernel performs the multiplication of a token by its corresponding + expert matrix as determined by `expert_ids`. The sorting of + `sorted_token_ids` by expert index and padding ensures divisibility by + BLOCK_SIZE_M, which is necessary to maintain consistency in block matrix + multiplication across different blocks processed by the same expert. + """ + # ----------------------------------------------------------- + # Map program ids `pid` to the block of C it should compute. + # This is done in a grouped ordering to promote L2 data reuse. + pid = tl.program_id(axis=0) + num_pid_m = tl.cdiv(EM, BLOCK_SIZE_M) + num_pid_n = tl.cdiv(N, BLOCK_SIZE_N) + num_pid_in_group = GROUP_SIZE_M * num_pid_n + group_id = pid // num_pid_in_group + first_pid_m = group_id * GROUP_SIZE_M + group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M) + pid_m = first_pid_m + ((pid % num_pid_in_group) % group_size_m) + pid_n = (pid % num_pid_in_group) // group_size_m + + # ---------------------------------------------------------- + # Create pointers for the first blocks of A and B. + # We will advance this pointer as we move in the K direction + # and accumulate + # `a_ptrs` is a block of [BLOCK_SIZE_M, BLOCK_SIZE_K] pointers + # `b_ptrs` is a block of [BLOCK_SIZE_K, BLOCK_SIZE_N] pointers + num_tokens_post_padded = tl.load(num_tokens_post_padded_ptr) + if pid_m * BLOCK_SIZE_M >= num_tokens_post_padded: + return + offs_token_id = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M).to( + tl.int64) + offs_token = tl.load(sorted_token_ids_ptr + offs_token_id) + token_mask = offs_token < num_valid_tokens + + off_experts = tl.load(expert_ids_ptr + pid_m).to(tl.int64) + if off_experts == -1: + # ----------------------------------------------------------- + # Write back zeros to the output when the expert is not + # in the current expert parallel rank. + write_zeros_to_output(c_ptr, stride_cm, stride_cn, pid_n, N, + offs_token, token_mask, BLOCK_SIZE_M, + BLOCK_SIZE_N, compute_type) + return + + offs_bn = (pid_n * BLOCK_SIZE_N + + tl.arange(0, BLOCK_SIZE_N).to(tl.int64)) % N + offs_k = tl.arange(0, BLOCK_SIZE_K) + a_ptrs = a_ptr + (offs_token[:, None] // top_k * stride_am + + offs_k[None, :] * stride_ak) + + if use_int4_w4a16: + b_ptrs = b_ptr + off_experts * stride_be + \ + (offs_k[:, None] // 2) * stride_bk + offs_bn[None, :] * \ + stride_bn + b_shifter = (offs_k[:, None] % 2) * 4 + elif use_int8_w8a16: + b_ptrs = b_ptr + off_experts * stride_be + \ + offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn + + if not has_zp and use_int4_w4a16: + b_zp_num = 8 + if not has_zp and use_int8_w8a16: + b_zp_num = 128 + elif has_zp and use_int4_w4a16: + b_zp_shifter = (offs_bn[None, :] % 2) * 4 + + # ----------------------------------------------------------- + # Iterate to compute a block of the C matrix. + # We accumulate into a `[BLOCK_SIZE_M, BLOCK_SIZE_N]` block + # of fp32 values for higher accuracy. + # `accumulator` will be converted back to fp16 after the loop. + accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32) + for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)): + # Load the next block of A and B, generate a mask by checking the + # K dimension. + + if not block_k_diviable: + k_mask = offs_k[:, None] < K - k * BLOCK_SIZE_K + k_other = 0.0 + else: + k_mask = None + k_other = None + + a = tl.load(a_ptrs, + mask=token_mask[:, None] & + (offs_k[None, :] < K - k * BLOCK_SIZE_K), + other=0.0) + b = tl.load(b_ptrs) + if use_int4_w4a16: + b = (b >> b_shifter) & 0xF + + b_scale_ptrs = b_scale_ptr + off_experts * stride_bse + \ + offs_bn[None, :] * stride_bsn + \ + ((offs_k[:, None] + BLOCK_SIZE_K * k) // group_size) * \ + stride_bsk + b_scale = tl.load(b_scale_ptrs, mask=k_mask, other=k_other) + b_scale = b_scale.to(tl.float32) + + if has_zp and use_int4_w4a16: + offs_k_true = (offs_k[:, None] + BLOCK_SIZE_K * k) // group_size + b_zp_ptrs = b_zp_ptr + off_experts * stride_bze + \ + (offs_bn[None, :] // 2) * stride_bzn + \ + offs_k_true * stride_bzk + b_zp = tl.load(b_zp_ptrs, mask=k_mask, other=k_other) + b_zp = ((b_zp >> b_zp_shifter) & 0xF) + b_zp = b_zp.to(tl.float32) + elif has_zp and use_int8_w8a16: + offs_k_true = (offs_k[:, None] + BLOCK_SIZE_K * k) // group_size + b_zp_ptrs = b_zp_ptr + off_experts * stride_bze + \ + offs_bn[None, :] * stride_bzn + \ + offs_k_true * stride_bzk + b_zp = tl.load(b_zp_ptrs, mask=k_mask, other=k_other) + b_zp = b_zp.to(tl.float32) + + # We accumulate along the K dimension. + if has_zp: + b = ((b.to(tl.float32) - b_zp) * b_scale).to(compute_type) + else: + b = ((b.to(tl.float32) - b_zp_num) * b_scale).to(compute_type) + accumulator = tl.dot(a, b, acc=accumulator) + + # Advance the ptrs to the next K block. + a_ptrs += BLOCK_SIZE_K * stride_ak + if use_int4_w4a16: + b_ptrs += (BLOCK_SIZE_K // 2) * stride_bk + else: + b_ptrs += BLOCK_SIZE_K * stride_bk + + if MUL_ROUTED_WEIGHT: + moe_weight = tl.load(topk_weights_ptr + offs_token, + mask=token_mask, + other=0) + accumulator = accumulator * moe_weight[:, None] + + accumulator = accumulator.to(compute_type) + # ----------------------------------------------------------- + # Write back the block of the output + offs_cn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) + c_ptrs = c_ptr + stride_cm * offs_token[:, None] + stride_cn * offs_cn[ + None, :] + c_mask = token_mask[:, None] & (offs_cn[None, :] < N) + tl.store(c_ptrs, accumulator, mask=c_mask) + + +@triton.jit +def fused_moe_kernel( + # Pointers to matrices + a_ptr, + b_ptr, + c_ptr, + b_bias_ptr, + a_scale_ptr, + b_scale_ptr, + topk_weights_ptr, + sorted_token_ids_ptr, + expert_ids_ptr, + num_tokens_post_padded_ptr, + # Matrix dimensions + N, + K, + EM, + num_valid_tokens, + # The stride variables represent how much to increase the ptr by when + # moving by 1 element in a particular dimension. E.g. `stride_am` is + # how much to increase `a_ptr` by to get the element one row down + # (A has M rows). + stride_am, + stride_ak, + stride_be, + stride_bk, + stride_bn, + stride_cm, + stride_cn, + stride_asm, + stride_ask, + stride_bse, + stride_bsk, + stride_bsn, + stride_bbe, # bias expert stride + stride_bbn, # bias N stride + # Block size for block-wise quantization + group_n: tl.constexpr, + group_k: tl.constexpr, + # Meta-parameters + BLOCK_SIZE_M: tl.constexpr, + BLOCK_SIZE_N: tl.constexpr, + BLOCK_SIZE_K: tl.constexpr, + GROUP_SIZE_M: tl.constexpr, + MUL_ROUTED_WEIGHT: tl.constexpr, + top_k: tl.constexpr, + compute_type: tl.constexpr, + use_fp8_w8a8: tl.constexpr, + use_int8_w8a8: tl.constexpr, + use_int8_w8a16: tl.constexpr, + per_channel_quant: tl.constexpr, + HAS_BIAS: tl.constexpr, +): + """ + Implements the fused computation for a Mixture of Experts (MOE) using + token and expert matrices. + + Key Parameters: + - A: The input tensor representing tokens with shape (*, K), where '*' can + be any shape representing batches and K is the feature dimension of + each token. + - B: The stacked MOE weight tensor with shape (E, N, K), where E is + the number of experts, K is the input feature dimension, and N is + the output feature dimension. + - C: The output cache tensor with shape (M, topk, N), where M is the + total number of tokens post padding, topk is the number of times + each token is repeated, and N is the output feature dimension. + - sorted_token_ids: A tensor containing the sorted indices of tokens, + repeated topk times and arranged by the expert index they are + assigned to. + - expert_ids: A tensor containing the indices of the expert for each + block. It determines which expert matrix from B should be used for + each block in A. + This kernel performs the multiplication of a token by its corresponding + expert matrix as determined by `expert_ids`. The sorting of + `sorted_token_ids` by expert index and padding ensures divisibility by + BLOCK_SIZE_M, which is necessary to maintain consistency in block matrix + multiplication across different blocks processed by the same expert. + """ + # ----------------------------------------------------------- + # Map program ids `pid` to the block of C it should compute. + # This is done in a grouped ordering to promote L2 data reuse. + pid = tl.program_id(axis=0) + num_pid_m = tl.cdiv(EM, BLOCK_SIZE_M) + num_pid_n = tl.cdiv(N, BLOCK_SIZE_N) + num_pid_in_group = GROUP_SIZE_M * num_pid_n + group_id = pid // num_pid_in_group + first_pid_m = group_id * GROUP_SIZE_M + group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M) + pid_m = first_pid_m + ((pid % num_pid_in_group) % group_size_m) + pid_n = (pid % num_pid_in_group) // group_size_m + + # ---------------------------------------------------------- + # Create pointers for the first blocks of A and B. + # We will advance this pointer as we move in the K direction + # and accumulate + # `a_ptrs` is a block of [BLOCK_SIZE_M, BLOCK_SIZE_K] pointers + # `b_ptrs` is a block of [BLOCK_SIZE_K, BLOCK_SIZE_N] pointers + num_tokens_post_padded = tl.load(num_tokens_post_padded_ptr) + if pid_m * BLOCK_SIZE_M >= num_tokens_post_padded: + return + offs_token_id = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M).to( + tl.int64) + offs_token = tl.load(sorted_token_ids_ptr + offs_token_id) + token_mask = offs_token < num_valid_tokens + + off_experts = tl.load(expert_ids_ptr + pid_m).to(tl.int64) + if off_experts == -1: + # ----------------------------------------------------------- + # Write back zeros to the output when the expert is not + # in the current expert parallel rank. + write_zeros_to_output(c_ptr, stride_cm, stride_cn, pid_n, N, + offs_token, token_mask, BLOCK_SIZE_M, + BLOCK_SIZE_N, compute_type) + return + + offs_bn = (pid_n * BLOCK_SIZE_N + + tl.arange(0, BLOCK_SIZE_N).to(tl.int64)) % N + offs_k = tl.arange(0, BLOCK_SIZE_K) + a_ptrs = a_ptr + (offs_token[:, None] // top_k * stride_am + + offs_k[None, :] * stride_ak) + + b_ptrs = b_ptr + off_experts * stride_be + (offs_k[:, None] * stride_bk + + offs_bn[None, :] * stride_bn) + if use_int8_w8a16: + b_scale_ptrs = b_scale_ptr + off_experts * stride_bse + offs_bn[ + None, :] * stride_bsn + b_scale = tl.load(b_scale_ptrs) + + if use_fp8_w8a8 or use_int8_w8a8: + # block-wise + if group_k > 0 and group_n > 0: + a_scale_ptrs = a_scale_ptr + (offs_token // top_k) * stride_asm + offs_bsn = offs_bn // group_n + b_scale_ptrs = (b_scale_ptr + off_experts * stride_bse + + offs_bsn * stride_bsn) + # channel-wise + elif per_channel_quant: + b_scale_ptrs = b_scale_ptr + off_experts * stride_bse + offs_bn[ + None, :] * stride_bsn + b_scale = tl.load(b_scale_ptrs) + # Load per-token scale for activations + a_scale_ptrs = a_scale_ptr + (offs_token // top_k) * stride_asm + a_scale = tl.load(a_scale_ptrs, mask=token_mask, other=0.0)[:, + None] + # tensor-wise + else: + a_scale = tl.load(a_scale_ptr) + b_scale = tl.load(b_scale_ptr + off_experts) + if HAS_BIAS: + # bias shape: [num_experts, N] + bias_ptrs = b_bias_ptr + off_experts * stride_bbe + offs_bn * stride_bbn + bias = tl.load(bias_ptrs, mask=(offs_bn < N), other=0.0) + # ----------------------------------------------------------- + # Iterate to compute a block of the C matrix. + # We accumulate into a `[BLOCK_SIZE_M, BLOCK_SIZE_N]` block + # of fp32 values for higher accuracy. + # `accumulator` will be converted back to fp16 after the loop. + accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32) + for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)): + # Load the next block of A and B, generate a mask by checking the + # K dimension. + a = tl.load(a_ptrs, + mask=token_mask[:, None] & + (offs_k[None, :] < K - k * BLOCK_SIZE_K), + other=0.0) + b = tl.load(b_ptrs, + mask=offs_k[:, None] < K - k * BLOCK_SIZE_K, + other=0.0) + # We accumulate along the K dimension. + if use_int8_w8a16: + accumulator = tl.dot(a, b.to(compute_type), acc=accumulator) + elif use_fp8_w8a8 or use_int8_w8a8: + if group_k > 0 and group_n > 0: + k_start = k * BLOCK_SIZE_K + offs_ks = k_start // group_k + a_scale = tl.load(a_scale_ptrs + offs_ks * stride_ask, + mask=token_mask, + other=0.0) + b_scale = tl.load(b_scale_ptrs + offs_ks * stride_bsk) + + accumulator += tl.dot(a, b) * a_scale[:, + None] * b_scale[None, :] + else: + if use_fp8_w8a8: + # acc used to enable fp8_fast_accum + accumulator = tl.dot(a, b, acc=accumulator) + else: + accumulator += tl.dot(a, b) + else: + accumulator += tl.dot(a, b) + # Advance the ptrs to the next K block. + a_ptrs += BLOCK_SIZE_K * stride_ak + b_ptrs += BLOCK_SIZE_K * stride_bk + if HAS_BIAS: + accumulator = accumulator + bias[None, :] + if MUL_ROUTED_WEIGHT: + moe_weight = tl.load(topk_weights_ptr + offs_token, + mask=token_mask, + other=0) + accumulator = accumulator * moe_weight[:, None] + if use_int8_w8a16: + accumulator = (accumulator * b_scale).to(compute_type) + elif use_fp8_w8a8 or use_int8_w8a8: + if group_k > 0 and group_n > 0: + accumulator = accumulator.to(compute_type) + else: + accumulator = (accumulator * a_scale * b_scale).to(compute_type) + else: + accumulator = accumulator.to(compute_type) + + # ----------------------------------------------------------- + # Write back the block of the output + offs_cn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) + c_ptrs = c_ptr + stride_cm * offs_token[:, None] + stride_cn * offs_cn[ + None, :] + c_mask = token_mask[:, None] & (offs_cn[None, :] < N) + tl.store(c_ptrs, accumulator, mask=c_mask) + + +def invoke_fused_moe_kernel(A: torch.Tensor, + B: torch.Tensor, + C: torch.Tensor, + A_scale: Optional[torch.Tensor], + B_scale: Optional[torch.Tensor], + B_zp: Optional[torch.Tensor], + topk_weights: Optional[torch.Tensor], + sorted_token_ids: torch.Tensor, + expert_ids: torch.Tensor, + num_tokens_post_padded: torch.Tensor, + mul_routed_weight: bool, + top_k: int, + config: dict[str, Any], + compute_type: tl.dtype, + use_fp8_w8a8: bool, + use_int8_w8a8: bool, + use_int8_w8a16: bool, + use_int4_w4a16: bool, + per_channel_quant: bool, + block_shape: Optional[list[int]] = None, + B_bias: Optional[torch.Tensor] = None) -> None: + assert topk_weights is not None or not mul_routed_weight + assert topk_weights is None or topk_weights.stride(1) == 1 + assert sorted_token_ids.stride(0) == 1 + + if use_fp8_w8a8 or use_int8_w8a8: + assert B_scale is not None + assert (block_shape is None + or triton.cdiv(B.size(-2), block_shape[0]) == B_scale.size(-2)) + assert (block_shape is None + or triton.cdiv(B.size(-1), block_shape[1]) == B_scale.size(-1)) + + elif use_int8_w8a16 or use_int4_w4a16: + assert B_scale is not None + assert block_shape is None or block_shape[0] == 0 + else: + assert A_scale is None + assert B_scale is None + + M = A.size(0) + num_tokens = M * top_k + + EM = sorted_token_ids.size(0) + if A.size(0) < config["BLOCK_SIZE_M"]: + # optimize for small batch_size. + # We assume that top_ids of each token is unique, so + # so num_valid_experts <= batch_size <= BLOCK_SIZE_M, + # and we can skip some invalid blocks. + EM = min(sorted_token_ids.size(0), + A.size(0) * top_k * config['BLOCK_SIZE_M']) + grid = lambda META: (triton.cdiv(EM, META['BLOCK_SIZE_M']) * triton.cdiv( + B.size(1), META['BLOCK_SIZE_N']), ) + HAS_BIAS = B_bias is not None + if (use_int8_w8a16 or use_int4_w4a16) and \ + block_shape is not None and block_shape[1] > 0: + assert B_scale is not None and B_scale.ndim == 3 + assert B_zp is None or B_zp.ndim == 3 + + use_moe_wna16_cuda = should_moe_wna16_use_cuda( + num_valid_tokens=num_tokens, + group_size=block_shape[1], + num_experts=B.size(0), + bit=4 if use_int4_w4a16 else 8) + config = config.copy() + config.update( + get_moe_wna16_block_config(config=config, + use_moe_wna16_cuda=use_moe_wna16_cuda, + num_valid_tokens=num_tokens, + size_k=A.size(1), + size_n=B.size(1), + num_experts=B.size(1), + group_size=block_shape[1], + real_top_k=top_k, + block_size_m=config["BLOCK_SIZE_M"])) + + if use_moe_wna16_cuda: + bit = 4 if use_int4_w4a16 else 8 + ops.moe_wna16_gemm(A, C, B, B_scale, B_zp, + topk_weights if mul_routed_weight else None, + sorted_token_ids, expert_ids, + num_tokens_post_padded, top_k, + config["BLOCK_SIZE_M"], config["BLOCK_SIZE_N"], + config["BLOCK_SIZE_K"], bit) + return + + fused_moe_kernel_gptq_awq[grid]( + A, + B, + C, + B_scale, + B_zp, + topk_weights, + sorted_token_ids, + expert_ids, + num_tokens_post_padded, + B.size(1), + A.size(1), + EM, + num_tokens, + A.stride(0), + A.stride(1), + B.stride(0), + B.stride(2), + B.stride(1), + C.stride(1), + C.stride(2), + B_scale.stride(0), + B_scale.stride(2), + B_scale.stride(1), + B_zp.stride(0) if B_zp is not None else 0, + B_zp.stride(2) if B_zp is not None else 0, + B_zp.stride(1) if B_zp is not None else 0, + block_k_diviable=A.size(1) % config["BLOCK_SIZE_K"] == 0, + group_size=block_shape[1], + MUL_ROUTED_WEIGHT=mul_routed_weight, + top_k=top_k, + compute_type=compute_type, + has_zp=B_zp is not None, + use_int4_w4a16=use_int4_w4a16, + use_int8_w8a16=use_int8_w8a16, + **config, + ) + else: + config = config.copy() + BLOCK_SIZE_K = config.pop("BLOCK_SIZE_K") + if block_shape is not None: + BLOCK_SIZE_K = min(BLOCK_SIZE_K, min(block_shape[0], + block_shape[1])) + fused_moe_kernel[grid]( + A, + B, + C, + B_bias, + A_scale, + B_scale, + topk_weights, + sorted_token_ids, + expert_ids, + num_tokens_post_padded, + B.size(1), + B.size(2), + EM, + num_tokens, + A.stride(0), + A.stride(1), + B.stride(0), + B.stride(2), + B.stride(1), + C.stride(1), + C.stride(2), + A_scale.stride(0) + if A_scale is not None and A_scale.ndim == 2 else 0, + A_scale.stride(1) + if A_scale is not None and A_scale.ndim == 2 else 0, + B_scale.stride(0) + if B_scale is not None and B_scale.ndim >= 2 else 0, + B_scale.stride(2) + if B_scale is not None and B_scale.ndim == 3 else 0, + B_scale.stride(1) + if B_scale is not None and B_scale.ndim >= 2 else 0, + B_bias.stride(0) if B_bias is not None else 0, + B_bias.stride(1) if B_bias is not None else 0, + 0 if block_shape is None else block_shape[0], + 0 if block_shape is None else block_shape[1], + MUL_ROUTED_WEIGHT=mul_routed_weight, + top_k=top_k, + compute_type=compute_type, + use_fp8_w8a8=use_fp8_w8a8, + use_int8_w8a8=use_int8_w8a8, + use_int8_w8a16=use_int8_w8a16, + per_channel_quant=per_channel_quant, + HAS_BIAS=HAS_BIAS, + BLOCK_SIZE_K=BLOCK_SIZE_K, + **config, + ) + + +# Adapted from: https://github.com/sgl-project/sglang/pull/2628 +def get_config_file_name(E: int, + N: int, + dtype: Optional[str], + block_shape: Optional[list[int]] = None) -> str: + device_name = current_platform.get_device_name().replace(" ", "_") + dtype_selector = "" if not dtype else f",dtype={dtype}" + block_shape_selector = ("" if not block_shape or not all(block_shape) else + f",block_shape={block_shape}").replace(" ", "") + return f"E={E},N={N},device_name={device_name}{dtype_selector}{block_shape_selector}.json" # noqa: E501 + + +# Adapted from: https://github.com/sgl-project/sglang/pull/2628 +@functools.lru_cache +def get_moe_configs( + E: int, + N: int, + dtype: Optional[str], + block_n: Optional[int] = None, + block_k: Optional[int] = None, +) -> Optional[dict[int, Any]]: + """ + Return optimized configurations for the fused MoE kernel. + + The return value will be a dictionary that maps an irregular grid of + batch sizes to configurations of the fused_moe kernel. To evaluate the + kernel on a given batch size bs, the closest batch size in the grid should + be picked and the associated configuration chosen to invoke the kernel. + """ + + # First look up if an optimized configuration is available in the configs + # directory + block_shape = [block_n, block_k] if block_n and block_k else None + json_file_name = get_config_file_name(E, N, dtype, block_shape) + + config_file_paths = [] + + # note that we prioritize user defined config + user_defined_config_folder = envs.VLLM_TUNED_CONFIG_FOLDER + if user_defined_config_folder is not None: + user_defined_config_file_path = os.path.join( + user_defined_config_folder, json_file_name) + config_file_paths.append(user_defined_config_file_path) + + default_config_file_path = os.path.join( + os.path.dirname(os.path.realpath(__file__)), "configs", json_file_name) + config_file_paths.append(default_config_file_path) + + for config_file_path in config_file_paths: + if os.path.exists(config_file_path): + with open(config_file_path) as f: + logger.info("Using configuration from %s for MoE layer.", + config_file_path) + # If a configuration has been found, return it + return {int(key): val for key, val in json.load(f).items()} + + # If no optimized configuration is available, we will use the default + # configuration + logger.warning( + ("Using default MoE config. Performance might be sub-optimal! " + "Config file not found at %s"), config_file_paths) + return None + + +def get_moe_wna16_block_config(config: dict[str, + int], use_moe_wna16_cuda: bool, + num_valid_tokens: int, size_k: int, size_n: int, + num_experts: int, group_size: int, + real_top_k: int, block_size_m: int): + if "BLOCK_SIZE_N" in config and "BLOCK_SIZE_K" in config: + # optimal block config is set + return {} + if not use_moe_wna16_cuda: + # triton moe wna16 kernel + if num_valid_tokens // real_top_k == 1: + # if bs=1, use a smaller BLOCK_SIZE_N + return {"BLOCK_SIZE_N": 32, "BLOCK_SIZE_K": 64} + else: + return {"BLOCK_SIZE_N": 64, "BLOCK_SIZE_K": 32} + else: + # cuda moe wna16 kernel + # set default block_size 128, and increase them when num_blocks + # is too large. + block_size_n = 128 + block_size_k = 128 + if block_size_k <= group_size: + block_size_k = group_size + + num_n_blocks = size_k // block_size_k + num_k_blocks = size_n // block_size_k + num_m_blocks = (num_valid_tokens + block_size_m - 1) / block_size_m + \ + num_experts + if num_valid_tokens // real_top_k <= block_size_m: + num_m_blocks = min(num_m_blocks, num_valid_tokens) + num_blocks = num_m_blocks * num_n_blocks * num_k_blocks + + if size_k % 256 == 0 and num_blocks >= 256 and \ + block_size_k < 256: + block_size_k = 256 + num_blocks = num_blocks // (256 // block_size_k) + + if num_m_blocks <= 16 and size_k % (block_size_k * 2) == 0 and \ + size_k % (block_size_k * 2) == 0 and block_size_k <= 512 and \ + num_blocks >= 512: + block_size_k = block_size_k * 2 + num_blocks = num_blocks // 2 + + if num_blocks > 1024: + block_size_n = 256 + num_n_blocks = num_n_blocks // 2 + num_blocks = num_blocks // 2 + + if size_n <= 1024 and num_blocks >= 1024: + # The kernel performance got much better with BLOCK_SIZE_N=1024 + # when num_blocks is large, event when N is small. + # Not sure why, maybe it force the CUDA SM process only one block + # at the same time. + block_size_n = 1024 + + return {"BLOCK_SIZE_N": block_size_n, "BLOCK_SIZE_K": block_size_k} + + +def should_moe_wna16_use_cuda(num_valid_tokens: int, group_size: int, + num_experts: int, bit: int): + return current_platform.is_cuda() and bit == 4 and \ + group_size in [32, 64, 128] and num_valid_tokens / num_experts <= 6 + + +def get_default_config( + M: int, + E: int, + N: int, + K: int, + topk: int, + dtype: Optional[str], + block_shape: Optional[list[int]] = None, +) -> dict[str, int]: + if dtype == "fp8_w8a8" and block_shape is not None: + # Block-wise quant: BLOCK_SIZE_N must be divisible by block_shape[0] + # BLOCK_SIZE_K must be divisible by block_shape[1] + # num_stages=3 can cause triton.runtime.errors.OutOfResources + # on ROCm, set it to 2 instead. + config = { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": block_shape[0], + "BLOCK_SIZE_K": block_shape[1], + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 if not current_platform.is_rocm() else 2, + } + elif dtype in ["int4_w4a16", "int8_w8a16"] and block_shape is not None: + # moe wna16 kernels + # only set BLOCK_SIZE_M + # BLOCK_SIZE_N and BLOCK_SIZE_K would be set later + bit = 4 if dtype == "int4_w4a16" else 8 + use_moe_wna16_cuda = should_moe_wna16_use_cuda(M * topk, + block_shape[1], E, bit) + if use_moe_wna16_cuda: + config = {"BLOCK_SIZE_M": min(16, M)} + elif M <= 20: + config = {"BLOCK_SIZE_M": 16, "GROUP_SIZE_M": 1} + elif M <= 40: + config = {"BLOCK_SIZE_M": 32, "GROUP_SIZE_M": 1} + else: + config = {"BLOCK_SIZE_M": 64, "GROUP_SIZE_M": 1} + elif M <= E: + config = { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 64, + "GROUP_SIZE_M": 1, + } + else: + config = { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 32, + "GROUP_SIZE_M": 8, + } + return config + + +def try_get_optimal_moe_config( + w1_shape: tuple[int, ...], + w2_shape: tuple[int, ...], + top_k: int, + dtype: Optional[str], + M: int, + block_shape: Optional[list[int]] = None, +) -> dict[str, int]: + from vllm.model_executor.layers.fused_moe import get_config + override_config = get_config() + if override_config: + config = override_config + else: + # First try to load optimal config from the file + E, _, N = w2_shape + if dtype == "int4_w4a16": + N = N * 2 + block_n = block_shape[0] if block_shape else 0 + block_k = block_shape[1] if block_shape else 0 + configs = get_moe_configs(E, N, dtype, block_n, block_k) + + if configs: + # If an optimal configuration map has been found, look up the + # optimal config + config = configs[min(configs.keys(), key=lambda x: abs(x - M))] + else: + # Else use the default config + config = get_default_config(M, E, N, w1_shape[2], top_k, dtype, + block_shape) + return config + + +def vllm_topk_softmax(topk_weights: torch.Tensor, topk_indices: torch.Tensor, + token_expert_indices: torch.Tensor, + gating_output: torch.Tensor, + renormalize: bool) -> tuple[torch.Tensor, ...]: + ops.topk_softmax( + topk_weights, + topk_indices, + token_expert_indices, + gating_output, + ) + if renormalize: + topk_weights = topk_weights / topk_weights.sum(dim=-1, keepdim=True) + + return topk_weights, topk_indices + + +def dispatch_topk_func() -> Callable[..., tuple[torch.Tensor, ...]]: + if is_rocm_aiter_moe_enabled(): + from .rocm_aiter_fused_moe import rocm_aiter_topk_softmax + return rocm_aiter_topk_softmax + return vllm_topk_softmax + + +def fused_topk( + hidden_states: torch.Tensor, + gating_output: torch.Tensor, + topk: int, + renormalize: bool, + indices_type: Optional[torch.dtype] = None, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + assert hidden_states.size(0) == gating_output.size(0), ( + "Number of tokens mismatch") + + M, _ = hidden_states.size() + + topk_weights = torch.empty(M, + topk, + dtype=torch.float32, + device=hidden_states.device) + topk_ids = torch.empty( + M, + topk, + dtype=torch.int32 if indices_type is None else indices_type, + device=hidden_states.device) + token_expert_indices = torch.empty(M, + topk, + dtype=torch.int32, + device=hidden_states.device) + + gating_output_float = gating_output.float() # TODO(woosuk): Optimize this. + + topk_func = dispatch_topk_func() + topk_weights, topk_ids = topk_func(topk_weights, topk_ids, + token_expert_indices, + gating_output_float, renormalize) + + return topk_weights, topk_ids, token_expert_indices + + +# This is used by the Deepseek-V2 and Deepseek-V3 model +@torch.compile(dynamic=True, backend=current_platform.simple_compile_backend) +def grouped_topk( + hidden_states: torch.Tensor, + gating_output: torch.Tensor, + topk: int, + renormalize: bool, + num_expert_group: int = 0, + topk_group: int = 0, + scoring_func: str = "softmax", + e_score_correction_bias: Optional[torch.Tensor] = None +) -> tuple[torch.Tensor, torch.Tensor]: + + assert hidden_states.size(0) == gating_output.size(0), ( + "Number of tokens mismatch") + + if scoring_func == "softmax": + scores = torch.softmax(gating_output, dim=-1) + elif scoring_func == "sigmoid": + scores = gating_output.sigmoid() + else: + raise ValueError(f"Unsupported scoring function: {scoring_func}") + + num_token = scores.size(0) + if e_score_correction_bias is not None: + # Store original scores before applying correction bias. We use biased + # scores for expert selection but original scores for routing weights + original_scores = scores + scores = scores + e_score_correction_bias.unsqueeze(0) + group_scores = (scores.view(num_token, num_expert_group, + -1).topk(2, dim=-1)[0].sum(dim=-1)) + else: + group_scores = scores.view(num_token, num_expert_group, + -1).max(dim=-1).values # [n, n_group] + group_idx = torch.topk(group_scores, k=topk_group, dim=-1, + sorted=False)[1] # [n, top_k_group] + group_mask = torch.zeros_like(group_scores) # [n, n_group] + group_mask.scatter_(1, group_idx, 1) # [n, n_group] + score_mask = group_mask.unsqueeze(-1).expand( + num_token, num_expert_group, + scores.size(-1) // num_expert_group).reshape(num_token, -1) # [n, e] + tmp_scores = scores.masked_fill(~score_mask.bool(), + float("-inf")) # [n, e] + + if e_score_correction_bias is not None: + topk_ids = torch.topk(tmp_scores, k=topk, dim=-1, sorted=False)[1] + # Use original unbiased scores for the routing weights + topk_weights = original_scores.gather(1, topk_ids) + else: + topk_weights, topk_ids = torch.topk(tmp_scores, + k=topk, + dim=-1, + sorted=False) + + if renormalize: + topk_weights = topk_weights / topk_weights.sum(dim=-1, keepdim=True) + + return topk_weights.to(torch.float32), topk_ids.to(torch.int32) + + +def get_config_dtype_str( + dtype: torch.dtype, + use_int4_w4a16: Optional[bool] = False, + use_int8_w8a16: Optional[bool] = False, + use_fp8_w8a8: Optional[bool] = False, + use_mxfp4_w4a4: Optional[bool] = False) -> Optional[str]: + if use_fp8_w8a8: + return "fp8_w8a8" + elif use_int8_w8a16: + return "int8_w8a16" + elif use_int4_w4a16: + return "int4_w4a16" + elif use_mxfp4_w4a4: + return "mxfp4_w4a4" + elif dtype == torch.float: + # avoiding cases where kernel fails when float32 MoE + # use fp16/bfloat16 configs + return "float32" + return None + + +def inplace_fused_experts( + hidden_states: torch.Tensor, + w1: torch.Tensor, + w2: torch.Tensor, + topk_weights: torch.Tensor, + topk_ids: torch.Tensor, + activation: str = "silu", + is_act_and_mul: bool = True, + apply_router_weight_on_input: bool = False, + use_fp8_w8a8: bool = False, + use_int8_w8a8: bool = False, + use_int8_w8a16: bool = False, + use_int4_w4a16: bool = False, + use_mxfp4_w4a4: bool = False, + per_channel_quant: bool = False, + global_num_experts: int = -1, + expert_map: Optional[torch.Tensor] = None, + w1_scale: Optional[torch.Tensor] = None, + w2_scale: Optional[torch.Tensor] = None, + w1_zp: Optional[torch.Tensor] = None, + w2_zp: Optional[torch.Tensor] = None, + a1_scale: Optional[torch.Tensor] = None, + a2_scale: Optional[torch.Tensor] = None, + block_shape: Optional[List[int]] = None, #noqa: UP006 + w1_bias: Optional[torch.Tensor] = None, + w2_bias: Optional[torch.Tensor] = None) -> None: + fused_experts_impl(hidden_states, w1, w2, topk_weights, topk_ids, True, + activation, is_act_and_mul, + apply_router_weight_on_input, use_fp8_w8a8, + use_int8_w8a8, use_int8_w8a16, use_int4_w4a16, + use_mxfp4_w4a4, per_channel_quant, global_num_experts, + expert_map, w1_scale, w2_scale, w1_zp, w2_zp, a1_scale, + a2_scale, block_shape, w1_bias, w2_bias) + + +def inplace_fused_experts_fake(hidden_states: torch.Tensor, + w1: torch.Tensor, + w2: torch.Tensor, + topk_weights: torch.Tensor, + topk_ids: torch.Tensor, + activation: str = "silu", + is_act_and_mul: bool = True, + apply_router_weight_on_input: bool = False, + use_fp8_w8a8: bool = False, + use_int8_w8a8: bool = False, + use_int8_w8a16: bool = False, + use_int4_w4a16: bool = False, + use_mxfp4_w4a4: bool = False, + per_channel_quant: bool = False, + global_num_experts: int = -1, + expert_map: Optional[torch.Tensor] = None, + w1_scale: Optional[torch.Tensor] = None, + w2_scale: Optional[torch.Tensor] = None, + w1_zp: Optional[torch.Tensor] = None, + w2_zp: Optional[torch.Tensor] = None, + a1_scale: Optional[torch.Tensor] = None, + a2_scale: Optional[torch.Tensor] = None, + block_shape: Optional[list[int]] = None, + w1_bias: Optional[torch.Tensor] = None, + w2_bias: Optional[torch.Tensor] = None) -> None: + pass + + +direct_register_custom_op( + op_name="inplace_fused_experts", + op_func=inplace_fused_experts, + mutates_args=["hidden_states"], + fake_impl=inplace_fused_experts_fake, + tags=(() if is_torch_equal_or_newer("2.7.0") else + (torch.Tag.needs_fixed_stride_order, )), +) + + +def flashinfer_fused_moe_blockscale_fp8( + routing_logits: torch.Tensor, + routing_bias: torch.Tensor, + x: torch.Tensor, + w13_weight: torch.Tensor, + w13_weight_scale_inv: torch.Tensor, + w2_weight: torch.Tensor, + w2_weight_scale_inv: torch.Tensor, + global_num_experts: int, + top_k: int, + num_expert_group: int, + topk_group: int, + intermediate_size: int, + expert_offset: int, + local_num_experts: int, + block_shape: List[int], #noqa: UP006 + routed_scaling: float = 1.0) -> torch.Tensor: + from vllm.utils.flashinfer import flashinfer_trtllm_fp8_block_scale_moe + assert top_k <= global_num_experts + assert top_k <= 8 + assert topk_group <= 4 + assert global_num_experts > num_expert_group + assert global_num_experts % num_expert_group == 0 + assert global_num_experts % 4 == 0 + assert top_k < (topk_group * global_num_experts / num_expert_group) + assert block_shape == [128, 128] + + a_q, a_sf = per_token_group_quant_fp8(x, block_shape[1]) + # NOTE: scales of hidden states have to be transposed! + a_sf_t = a_sf.t().contiguous() + return flashinfer_trtllm_fp8_block_scale_moe( + routing_logits=routing_logits, + routing_bias=routing_bias, + hidden_states=a_q, + hidden_states_scale=a_sf_t, + gemm1_weights=w13_weight, + gemm1_weights_scale=w13_weight_scale_inv, + gemm2_weights=w2_weight, + gemm2_weights_scale=w2_weight_scale_inv, + num_experts=global_num_experts, + top_k=top_k, + n_group=num_expert_group, + topk_group=topk_group, + intermediate_size=intermediate_size, + local_expert_offset=expert_offset, + local_num_experts=local_num_experts, + routed_scaling_factor=routed_scaling, + tile_tokens_dim=calculate_tile_tokens_dim(x.shape[0], top_k, + global_num_experts), + routing_method_type=2, # DeepSeek-styled routing method + use_shuffled_weight=False, + ) + + +def flashinfer_fused_moe_blockscale_fp8_fake( + routing_logits: torch.Tensor, + routing_bias: torch.Tensor, + x: torch.Tensor, + w13_weight: torch.Tensor, + w13_weight_scale_inv: torch.Tensor, + w2_weight: torch.Tensor, + w2_weight_scale_inv: torch.Tensor, + global_num_experts: int, + top_k: int, + num_expert_group: int, + topk_group: int, + intermediate_size: int, + expert_offset: int, + local_num_experts: int, + block_shape: list[int], + routed_scaling: float = 1.0) -> torch.Tensor: + return torch.empty_like(x) + + +direct_register_custom_op( + op_name="flashinfer_fused_moe_blockscale_fp8", + op_func=flashinfer_fused_moe_blockscale_fp8, + mutates_args=[], + fake_impl=flashinfer_fused_moe_blockscale_fp8_fake, + tags=(torch.Tag.needs_fixed_stride_order, ), +) + + +def flashinfer_fused_moe_per_tensor_scale_fp8( + routing_logits: torch.Tensor, + routing_bias: Optional[torch.Tensor], + hidden_states: torch.Tensor, + input_scale: torch.Tensor, + gemm1_weights: torch.Tensor, + gemm2_weights: torch.Tensor, + output1_scales_scalar: torch.Tensor, + output1_scales_gate_scalar: torch.Tensor, + output2_scales_scalar: torch.Tensor, + num_experts: int, + top_k: int, + num_expert_group: Optional[int], + topk_group: Optional[int], + intermediate_size: int, + local_expert_offset: int, + local_num_experts: int, + use_routing_scales_on_input: bool, + routing_method_type: int, + routed_scaling_factor: float = 1.0) -> torch.Tensor: + num_expert_group = num_expert_group if num_expert_group is not None else 0 + topk_group = topk_group if topk_group is not None else 0 + + quant_hidden_states, _ = moe_kernel_quantize_input( + hidden_states, + input_scale, + quant_dtype=torch.float8_e4m3fn, + per_act_token_quant=False) + + from vllm.utils.flashinfer import ( + flashinfer_trtllm_fp8_per_tensor_scale_moe) + return flashinfer_trtllm_fp8_per_tensor_scale_moe( + routing_logits=routing_logits, + routing_bias=routing_bias, + hidden_states=quant_hidden_states, + gemm1_weights=gemm1_weights, + output1_scales_scalar=output1_scales_scalar, + output1_scales_gate_scalar=output1_scales_gate_scalar, + gemm2_weights=gemm2_weights, + output2_scales_scalar=output2_scales_scalar, + num_experts=num_experts, + top_k=top_k, + n_group=num_expert_group, + topk_group=topk_group, + intermediate_size=intermediate_size, + local_expert_offset=local_expert_offset, + local_num_experts=local_num_experts, + routed_scaling_factor=routed_scaling_factor, + use_routing_scales_on_input=use_routing_scales_on_input, + tile_tokens_dim=calculate_tile_tokens_dim(hidden_states.shape[0], + top_k, num_experts), + routing_method_type=routing_method_type) + + +def flashinfer_fused_moe_per_tensor_scale_fp8_fake( + routing_logits: torch.Tensor, + routing_bias: Optional[torch.Tensor], + hidden_states: torch.Tensor, + input_scale: torch.Tensor, + gemm1_weights: torch.Tensor, + gemm2_weights: torch.Tensor, + output1_scales_scalar: torch.Tensor, + output1_scales_gate_scalar: torch.Tensor, + output2_scales_scalar: torch.Tensor, + num_experts: int, + top_k: int, + num_expert_group: Optional[int], + topk_group: Optional[int], + intermediate_size: int, + local_expert_offset: int, + local_num_experts: int, + use_routing_scales_on_input: bool, + routing_method_type: int, + routed_scaling_factor: float = 1.0) -> torch.Tensor: + pass + + +direct_register_custom_op( + op_name="flashinfer_fused_moe_per_tensor_scale_fp8", + op_func=flashinfer_fused_moe_per_tensor_scale_fp8, + mutates_args=["hidden_states"], + fake_impl=flashinfer_fused_moe_per_tensor_scale_fp8_fake, + tags=(torch.Tag.needs_fixed_stride_order, ), +) + + +def outplace_fused_experts( + hidden_states: torch.Tensor, + w1: torch.Tensor, + w2: torch.Tensor, + topk_weights: torch.Tensor, + topk_ids: torch.Tensor, + activation: str = "silu", + is_act_and_mul: bool = True, + apply_router_weight_on_input: bool = False, + use_fp8_w8a8: bool = False, + use_int8_w8a8: bool = False, + use_int8_w8a16: bool = False, + use_int4_w4a16: bool = False, + use_mxfp4_w4a4: bool = False, + per_channel_quant: bool = False, + global_num_experts: int = -1, + expert_map: Optional[torch.Tensor] = None, + w1_scale: Optional[torch.Tensor] = None, + w2_scale: Optional[torch.Tensor] = None, + w1_zp: Optional[torch.Tensor] = None, + w2_zp: Optional[torch.Tensor] = None, + a1_scale: Optional[torch.Tensor] = None, + a2_scale: Optional[torch.Tensor] = None, + block_shape: Optional[List[int]] = None, #noqa: UP006 + w1_bias: Optional[torch.Tensor] = None, + w2_bias: Optional[torch.Tensor] = None, +) -> torch.Tensor: + return fused_experts_impl( + hidden_states, w1, w2, topk_weights, topk_ids, False, activation, + is_act_and_mul, apply_router_weight_on_input, use_fp8_w8a8, + use_int8_w8a8, use_int8_w8a16, use_int4_w4a16, use_mxfp4_w4a4, + per_channel_quant, global_num_experts, expert_map, w1_scale, w2_scale, + w1_zp, w2_zp, a1_scale, a2_scale, block_shape, w1_bias, w2_bias) + + +def outplace_fused_experts_fake( + hidden_states: torch.Tensor, + w1: torch.Tensor, + w2: torch.Tensor, + topk_weights: torch.Tensor, + topk_ids: torch.Tensor, + activation: str = "silu", + is_act_and_mul: bool = True, + use_fp8_w8a8: bool = False, + use_int8_w8a8: bool = False, + use_int8_w8a16: bool = False, + use_int4_w4a16: bool = False, + use_mxfp4_w4a4: bool = False, + per_channel_quant: bool = False, + global_num_experts: int = -1, + expert_map: Optional[torch.Tensor] = None, + w1_scale: Optional[torch.Tensor] = None, + w2_scale: Optional[torch.Tensor] = None, + w1_zp: Optional[torch.Tensor] = None, + w2_zp: Optional[torch.Tensor] = None, + a1_scale: Optional[torch.Tensor] = None, + a2_scale: Optional[torch.Tensor] = None, + block_shape: Optional[list[int]] = None, + w1_bias: Optional[torch.Tensor] = None, + w2_bias: Optional[torch.Tensor] = None) -> torch.Tensor: + return torch.empty_like(hidden_states) + + +direct_register_custom_op( + op_name="outplace_fused_experts", + op_func=outplace_fused_experts, + mutates_args=[], + fake_impl=outplace_fused_experts_fake, + tags=(() if is_torch_equal_or_newer("2.7.0") else + (torch.Tag.needs_fixed_stride_order, )), +) + + +def torch_vllm_inplace_fused_experts(**kwargs) -> torch.Tensor: + torch.ops.vllm.inplace_fused_experts(**kwargs) + hidden_states = kwargs['hidden_states'] + return hidden_states + + +def torch_vllm_outplace_fused_experts(**kwargs) -> torch.Tensor: + return torch.ops.vllm.outplace_fused_experts(**kwargs) + + +def dispatch_fused_experts_func(inplace: bool) -> Callable[..., torch.Tensor]: + if inplace: + return torch_vllm_inplace_fused_experts + return torch_vllm_outplace_fused_experts + + +# TODO (bnell): replace this with modular op. Can get rid of inplace/outplace +# torch ops. +def fused_experts(hidden_states: torch.Tensor, + w1: torch.Tensor, + w2: torch.Tensor, + topk_weights: torch.Tensor, + topk_ids: torch.Tensor, + inplace: bool = False, + activation: str = "silu", + is_act_and_mul: bool = True, + apply_router_weight_on_input: bool = False, + use_fp8_w8a8: bool = False, + use_int8_w8a8: bool = False, + use_int8_w8a16: bool = False, + use_int4_w4a16: bool = False, + use_mxfp4_w4a4: bool = False, + per_channel_quant: bool = False, + global_num_experts: int = -1, + expert_map: Optional[torch.Tensor] = None, + w1_scale: Optional[torch.Tensor] = None, + w2_scale: Optional[torch.Tensor] = None, + w1_zp: Optional[torch.Tensor] = None, + w2_zp: Optional[torch.Tensor] = None, + a1_scale: Optional[torch.Tensor] = None, + a2_scale: Optional[torch.Tensor] = None, + block_shape: Optional[list[int]] = None, + allow_deep_gemm: bool = False, + allow_cutlass_block_scaled_grouped_gemm: bool = False, + w1_bias: Optional[torch.Tensor] = None, + w2_bias: Optional[torch.Tensor] = None) -> torch.Tensor: + # For now, disable DeepGemm for small N (<= 512) until better + # permute/unpermute ops are available. + # However, on B200, we use DeepGemm for all cases because they only support + # E8M0 scale, which means we requantize the weight and input to the specific + # scale. Fallen back to cutlass or triton for some cases would cause + # accuracy issue. + if (allow_deep_gemm and use_fp8_w8a8 + and (is_blackwell_deep_gemm_e8m0_used() + or _valid_deep_gemm(hidden_states, w1, w2))): + assert apply_router_weight_on_input is False + assert is_act_and_mul, ( + "DeepGemm only supports is_act_and_mul=True for now.") + return deep_gemm_moe_fp8( + hidden_states=hidden_states, + w1=w1, + w2=w2, + topk_weights=topk_weights, + topk_ids=topk_ids, + inplace=inplace, + activation=activation, + global_num_experts=global_num_experts, + expert_map=expert_map, + w1_scale=w1_scale, + w2_scale=w2_scale, + a1_scale=a1_scale, + a2_scale=a2_scale, + apply_router_weight_on_input=apply_router_weight_on_input, + ) + elif (allow_cutlass_block_scaled_grouped_gemm and use_fp8_w8a8 + and _valid_cutlass_block_scaled_grouped_gemm( + w1, w2, inplace, activation, apply_router_weight_on_input, + expert_map)): + return run_cutlass_block_scaled_fused_experts( + a=hidden_states, + w1=w1, + w2=w2, + w1_scale=w1_scale, + w2_scale=w2_scale, + topk_weights=topk_weights, + topk_ids=topk_ids) + else: + return dispatch_fused_experts_func(inplace)( + hidden_states=hidden_states, + w1=w1, + w2=w2, + topk_weights=topk_weights, + topk_ids=topk_ids, + activation=activation, + is_act_and_mul=is_act_and_mul, + apply_router_weight_on_input=apply_router_weight_on_input, + use_fp8_w8a8=use_fp8_w8a8, + use_int8_w8a8=use_int8_w8a8, + use_int8_w8a16=use_int8_w8a16, + use_int4_w4a16=use_int4_w4a16, + use_mxfp4_w4a4=use_mxfp4_w4a4, + per_channel_quant=per_channel_quant, + global_num_experts=global_num_experts, + expert_map=expert_map, + w1_scale=w1_scale, + w2_scale=w2_scale, + w1_zp=w1_zp, + w2_zp=w2_zp, + a1_scale=a1_scale, + a2_scale=a2_scale, + block_shape=block_shape, + w1_bias=w1_bias, + w2_bias=w2_bias, + ) + + +def fused_experts_impl( + hidden_states: torch.Tensor, + w1: torch.Tensor, + w2: torch.Tensor, + topk_weights: torch.Tensor, + topk_ids: torch.Tensor, + inplace: bool = False, + activation: str = "silu", + is_act_and_mul: bool = True, + apply_router_weight_on_input: bool = False, + use_fp8_w8a8: bool = False, + use_int8_w8a8: bool = False, + use_int8_w8a16: bool = False, + use_int4_w4a16: bool = False, + use_mxfp4_w4a4: bool = False, + per_channel_quant: bool = False, + global_num_experts: int = -1, + expert_map: Optional[torch.Tensor] = None, + w1_scale: Optional[torch.Tensor] = None, + w2_scale: Optional[torch.Tensor] = None, + w1_zp: Optional[torch.Tensor] = None, + w2_zp: Optional[torch.Tensor] = None, + a1_scale: Optional[torch.Tensor] = None, + a2_scale: Optional[torch.Tensor] = None, + block_shape: Optional[list[int]] = None, + w1_bias: Optional[torch.Tensor] = None, + w2_bias: Optional[torch.Tensor] = None, +) -> torch.Tensor: + # Check constraints. + if use_int4_w4a16: + assert hidden_states.size(1) // 2 == w1.size(2), ( + "Hidden size mismatch") + elif use_mxfp4_w4a4: + # 16bit activation and fp4x2 packed weight + assert hidden_states.size(1) // 2 == w1.size(2), "hidden size mismatch" + else: + assert hidden_states.size(1) == w1.size(2), ( + f"Hidden size mismatch {hidden_states.size(1)} != {w1.size(2)}") + + assert topk_weights.size() == topk_ids.size(), "topk shape mismatch" + assert hidden_states.is_contiguous(), "Hidden_states must be contiguous" + assert w1.stride(-1) == 1, "Stride of last dimension must be 1" + assert w2.stride(-1) == 1, "Stride of last dimension must be 1" + assert hidden_states.dtype in [ + torch.float32, torch.float16, torch.bfloat16 + ] + + num_tokens = hidden_states.size(0) + E, N, _ = w1.size() + K = w2.size(1) + if global_num_experts == -1: + global_num_experts = E + top_k_num = topk_ids.size(1) + # We execute the fused_moe kernel in chunks to circumvent this issue: + # https://github.com/vllm-project/vllm/issues/5938 + CHUNK_SIZE = envs.VLLM_FUSED_MOE_CHUNK_SIZE + M = min(num_tokens, CHUNK_SIZE) + config_dtype = get_config_dtype_str(use_fp8_w8a8=use_fp8_w8a8, + use_int8_w8a16=use_int8_w8a16, + use_int4_w4a16=use_int4_w4a16, + use_mxfp4_w4a4=use_mxfp4_w4a4, + dtype=hidden_states.dtype) + + qtype = get_config_quant_dtype(use_fp8_w8a8=use_fp8_w8a8, + use_int8_w8a8=use_int8_w8a8, + use_int8_w8a16=use_int8_w8a16, + use_int4_w4a16=use_int4_w4a16, + use_mxfp4_w4a4=use_mxfp4_w4a4) + + get_config_func = functools.partial( + try_get_optimal_moe_config, + w1.size(), + w2.size(), + top_k_num, + config_dtype, + block_shape=block_shape, + ) + + config = get_config_func(M) + + # We can reuse the memory between these because by the time we need + # cache3, we're done with cache1 + cache13 = torch.empty(M * top_k_num * max(N, K), + device=hidden_states.device, + dtype=hidden_states.dtype) + intermediate_cache1 = cache13[:M * top_k_num * N].view(M, top_k_num, N) + intermediate_cache3 = cache13[:M * top_k_num * K].view(M, top_k_num, K) + + # This needs separate memory since it's used concurrently with cache1 + intermediate_cache2 = torch.empty((M * top_k_num, N // 2), + device=hidden_states.device, + dtype=hidden_states.dtype) + + if hidden_states.dtype == torch.bfloat16: + compute_type = tl.bfloat16 + elif hidden_states.dtype == torch.float16: + compute_type = tl.float16 + elif hidden_states.dtype == torch.float32: + compute_type = tl.float32 + else: + raise ValueError(f"Unsupported compute_type: {hidden_states.dtype}") + + if inplace: + out_hidden_states = hidden_states + else: + out_hidden_states = torch.empty_like(hidden_states) + + if use_mxfp4_w4a4: + # Weight has to be dequantized for mxfp4 emulation. + w1 = dequant_mxfp4(w1, w1_scale, hidden_states.dtype) + w1_scale = None + w2 = dequant_mxfp4(w2, w2_scale, hidden_states.dtype) + w2_scale = None + + for chunk in range((num_tokens // CHUNK_SIZE) + 1): + begin_chunk_idx, end_chunk_idx = (chunk * CHUNK_SIZE, + min((chunk + 1) * CHUNK_SIZE, + num_tokens)) + curr_hidden_states = hidden_states[begin_chunk_idx:end_chunk_idx] + tokens_in_chunk, _ = curr_hidden_states.size() + + if tokens_in_chunk == 0: + break + + if tokens_in_chunk < CHUNK_SIZE and chunk > 0: + # Adjust the intermediate cache size and config for the last + # chunk. Note that in most cases we only have one chunk + # so the cache size and config are already set correctly and + # do not need to be adjusted. + intermediate_cache1 = intermediate_cache1[:tokens_in_chunk] + intermediate_cache2 = intermediate_cache2[:tokens_in_chunk * + topk_ids.size(1)] + intermediate_cache3 = intermediate_cache3[:tokens_in_chunk] + config = get_config_func(tokens_in_chunk) + + curr_topk_ids = topk_ids[begin_chunk_idx:end_chunk_idx] + curr_topk_weights = topk_weights[begin_chunk_idx:end_chunk_idx] + qcurr_hidden_states, a1q_scale = moe_kernel_quantize_input( + A=curr_hidden_states, + A_scale=a1_scale, + quant_dtype=qtype, + per_act_token_quant=per_channel_quant, + block_shape=block_shape) + + sorted_token_ids, expert_ids, num_tokens_post_padded = ( + moe_align_block_size(curr_topk_ids, config['BLOCK_SIZE_M'], + global_num_experts, expert_map)) + + invoke_fused_moe_kernel(qcurr_hidden_states, + w1, + intermediate_cache1, + a1q_scale, + w1_scale, + w1_zp, + curr_topk_weights, + sorted_token_ids, + expert_ids, + num_tokens_post_padded, + apply_router_weight_on_input, + top_k_num, + config, + compute_type=compute_type, + use_fp8_w8a8=use_fp8_w8a8, + use_int8_w8a8=use_int8_w8a8, + use_int8_w8a16=use_int8_w8a16, + use_int4_w4a16=use_int4_w4a16, + per_channel_quant=per_channel_quant, + block_shape=block_shape, + B_bias=w1_bias) + + # Activation function with multiplication + if activation == "silu" and is_act_and_mul: + torch.ops._C.silu_and_mul(intermediate_cache2, + intermediate_cache1.view(-1, N)) + elif activation == "gelu" and is_act_and_mul: + torch.ops._C.gelu_and_mul(intermediate_cache2, + intermediate_cache1.view(-1, N)) + elif activation == "swigluoai" and is_act_and_mul: + # alpha = 1.702, limit = 7.0 + torch.ops._C.swigluoai_and_mul(intermediate_cache2, + intermediate_cache1.view(-1, N)) + # Activation function without multiplication + elif activation == "silu": + intermediate_cache2 = F.silu(intermediate_cache1.view(-1, N)) + elif activation == "gelu": + intermediate_cache2 = F.gelu(intermediate_cache1.view(-1, N)) + + else: + raise ValueError(f"Unsupported FusedMoe activation: {activation}, " + f"with is_act_and_mul={is_act_and_mul}.") + + qintermediate_cache2, a2q_scale = moe_kernel_quantize_input( + A=intermediate_cache2, + A_scale=a2_scale, + quant_dtype=qtype, + per_act_token_quant=per_channel_quant, + block_shape=block_shape) + + invoke_fused_moe_kernel(qintermediate_cache2, + w2, + intermediate_cache3, + a2q_scale, + w2_scale, + w2_zp, + curr_topk_weights, + sorted_token_ids, + expert_ids, + num_tokens_post_padded, + not apply_router_weight_on_input, + 1, + config, + compute_type=compute_type, + use_fp8_w8a8=use_fp8_w8a8, + use_int8_w8a8=use_int8_w8a8, + use_int8_w8a16=use_int8_w8a16, + use_int4_w4a16=use_int4_w4a16, + per_channel_quant=per_channel_quant, + block_shape=block_shape, + B_bias=w2_bias) + + ops.moe_sum(intermediate_cache3.view(*intermediate_cache3.size()), + out_hidden_states[begin_chunk_idx:end_chunk_idx]) + + return out_hidden_states + + +def fused_moe( + hidden_states: torch.Tensor, + w1: torch.Tensor, + w2: torch.Tensor, + gating_output: torch.Tensor, + topk: int, + renormalize: bool, + inplace: bool = False, + activation: str = "silu", + is_act_and_mul: bool = True, + use_grouped_topk: bool = False, + num_expert_group: Optional[int] = None, + topk_group: Optional[int] = None, + custom_routing_function: Optional[Callable] = None, + use_fp8_w8a8: bool = False, + use_int8_w8a8: bool = False, + use_int8_w8a16: bool = False, + use_int4_w4a16: bool = False, + use_mxfp4_w4a4: bool = False, + per_channel_quant: bool = False, + global_num_experts: int = -1, + expert_map: Optional[torch.Tensor] = None, + w1_scale: Optional[torch.Tensor] = None, + w2_scale: Optional[torch.Tensor] = None, + w1_zp: Optional[torch.Tensor] = None, + w2_zp: Optional[torch.Tensor] = None, + a1_scale: Optional[torch.Tensor] = None, + a2_scale: Optional[torch.Tensor] = None, + block_shape: Optional[list[int]] = None, + w1_bias: Optional[torch.Tensor] = None, + w2_bias: Optional[torch.Tensor] = None, +) -> torch.Tensor: + """ + This function computes a Mixture of Experts (MoE) layer using two sets of + weights, w1 and w2, and top-k gating mechanism. + + Parameters: + - hidden_states (torch.Tensor): The input tensor to the MoE layer. + - w1 (torch.Tensor): The first set of expert weights. + - w2 (torch.Tensor): The second set of expert weights. + - gating_output (torch.Tensor): The output of the gating operation + (before softmax). + - topk (int): The number of top-k experts to select. + - renormalize (bool): If True, renormalize the top-k weights to sum to 1. + - inplace (bool): If True, perform the operation in-place. + Defaults to False. + - activation (str): The activation function to apply after the first + MoE layer. + - is_act_and_mul (bool): If True, use activation-and-mul function for + activation (self-gated activation), otherwise use activation function + for activation (ungated activation). + - num_expert_group: Optional[int]: additional parameter for grouped_topk + - topk_group: Optional[int]: additional parameter for grouped_topk + - use_grouped_topk: If True, use grouped_topk instead of fused_topk + note: Deepseekv2 model uses grouped_topk + - use_fp8_w8a8 (bool): If True, use fp8 arithmetic to compute the inner + products for w1 and w2. Defaults to False. + - use_int8_w8a8 (bool): If True, use int8 arithmetic to compute the inner + products for w1 and w2. Defaults to False. + - use_int8_w8a16 (bool): If True, use matmul of int8 weight and bf16/fp16 + activation to compute the inner products for w1 and w2. + Defaults to False. + - use_int4_w4a16 (bool): If True, use matmul of int4 weight and bf16/fp16 + activation to compute the inner products for w1 and w2. + Defaults to False. + - use_mxfp4_w4a4 (bool): If True, use matmul of OCP MXFP4 weight and + OCP MXFP4 activation to compute the inner products for w1 and w2. + Defaults to False. + - global_num_experts (int): The total number of experts in the global + expert space. + - expert_map (Optional[torch.Tensor]): A tensor mapping expert indices + from the global expert space to the local expert space of the expert + parallel shard. + - w1_scale (Optional[torch.Tensor]): Optional scale to be used for + w1. + - w2_scale (Optional[torch.Tensor]): Optional scale to be used for + w2. + - a1_scale (Optional[torch.Tensor]): Optional scale to be used for + a1. + - a2_scale (Optional[torch.Tensor]): Optional scale to be used for + a2. + - block_shape: (Optional[list[int]]): Optional block size for block-wise + quantization. + + Returns: + - torch.Tensor: The output tensor after applying the MoE layer. + """ + if not is_act_and_mul: + assert inplace is False, ( + "is_act_and_mul=False is not supported with inplace=True") + + if use_grouped_topk: + assert num_expert_group is not None and topk_group is not None + topk_weights, topk_ids = grouped_topk(hidden_states, gating_output, + topk, renormalize, + num_expert_group, topk_group) + elif custom_routing_function is None: + topk_weights, topk_ids, token_expert_indices = fused_topk( + hidden_states, gating_output, topk, renormalize) + else: + topk_weights, topk_ids = custom_routing_function( + hidden_states, gating_output, topk, renormalize) + + return fused_experts(hidden_states, + w1, + w2, + topk_weights, + topk_ids, + inplace=inplace, + activation=activation, + is_act_and_mul=is_act_and_mul, + use_fp8_w8a8=use_fp8_w8a8, + use_int8_w8a8=use_int8_w8a8, + use_int8_w8a16=use_int8_w8a16, + use_int4_w4a16=use_int4_w4a16, + use_mxfp4_w4a4=use_mxfp4_w4a4, + per_channel_quant=per_channel_quant, + global_num_experts=global_num_experts, + expert_map=expert_map, + w1_scale=w1_scale, + w2_scale=w2_scale, + w1_zp=w1_zp, + w2_zp=w2_zp, + a1_scale=a1_scale, + a2_scale=a2_scale, + block_shape=block_shape, + w1_bias=w1_bias, + w2_bias=w2_bias) + + +class TritonExperts(mk.FusedMoEPermuteExpertsUnpermute): + + def __init__( + self, + use_fp8_w8a8: bool = False, + use_int8_w8a8: bool = False, + use_int8_w8a16: bool = False, + use_int4_w4a16: bool = False, + use_mxfp4_w4a4: bool = False, + per_act_token_quant: bool = False, + block_shape: Optional[list[int]] = None, + ): + super().__init__( + FusedMoEQuantConfig.make( + use_fp8_w8a8=use_fp8_w8a8, + use_int8_w8a8=use_int8_w8a8, + use_int8_w8a16=use_int8_w8a16, + use_int4_w4a16=use_int4_w4a16, + use_mxfp4_w4a4=use_mxfp4_w4a4, + per_act_token_quant=per_act_token_quant, + block_shape=block_shape, + )) + + self.use_fp8_w8a8 = use_fp8_w8a8 + self.use_int4_w4a16 = use_int4_w4a16 + self.use_int8_w8a8 = use_int8_w8a8 + self.use_int8_w8a16 = use_int8_w8a16 + self.use_mxfp4_w4a4 = use_mxfp4_w4a4 + + @property + def activation_formats( + self + ) -> tuple[mk.FusedMoEActivationFormat, mk.FusedMoEActivationFormat]: + return (mk.FusedMoEActivationFormat.Standard, + mk.FusedMoEActivationFormat.Standard) + + def supports_chunking(self) -> bool: + return True + + def supports_expert_map(self) -> bool: + return True + + def finalize_weight_and_reduce_impl(self) -> mk.TopKWeightAndReduce: + return TopKWeightAndReduceNoOP() + + def workspace_shapes( + self, + a: torch.Tensor, + aq: torch.Tensor, + M: int, + N: int, + K: int, + topk: int, + global_num_experts: int, + local_num_experts: int, + expert_tokens_meta: Optional[mk.ExpertTokensMetadata], + ) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...], torch.dtype]: + workspace1 = (M, topk, max(N // 2, K)) + workspace2 = (M, topk, max(N, K)) + output = (M, K) + return (workspace1, workspace2, output, a.dtype) + + def apply( + self, + output: torch.Tensor, + hidden_states: torch.Tensor, + w1: torch.Tensor, + w2: torch.Tensor, + topk_weights: torch.Tensor, + topk_ids: torch.Tensor, + activation: str, + global_num_experts: int, + expert_map: Optional[torch.Tensor], + w1_scale: Optional[torch.Tensor], + w2_scale: Optional[torch.Tensor], + w1_zp: Optional[torch.Tensor], + w2_zp: Optional[torch.Tensor], + a1q_scale: Optional[torch.Tensor], + a2_scale: Optional[torch.Tensor], + workspace13: torch.Tensor, + workspace2: torch.Tensor, + expert_tokens_meta: Optional[mk.ExpertTokensMetadata], + apply_router_weight_on_input: bool, + ): + # Check constraints. + if self.use_int4_w4a16: + assert hidden_states.size(-1) // 2 == w1.size(2), ( + "Hidden size mismatch") + else: + assert hidden_states.size(-1) == w1.size(2), \ + (f"Hidden size mismatch {hidden_states.size(-1)} " + f"!= {w1.size(2)}") + + assert hidden_states.is_contiguous( + ), "Hidden_states must be contiguous" + assert hidden_states.dim() == 2 + assert w1.stride(-1) == 1, "Stride of last dimension must be 1" + assert w2.stride(-1) == 1, "Stride of last dimension must be 1" + assert hidden_states.dtype in [ + torch.float32, torch.float16, torch.bfloat16, torch.float8_e4m3fn + ] + + E, num_tokens, N, K, top_k_num = mk._moe_problem_size( + hidden_states, w1, w2, topk_ids) + + if global_num_experts == -1: + global_num_experts = E + + config_dtype = get_config_dtype_str(use_fp8_w8a8=self.use_fp8_w8a8, + use_int8_w8a16=self.use_int8_w8a16, + use_int4_w4a16=self.use_int4_w4a16, + use_mxfp4_w4a4=self.use_mxfp4_w4a4, + dtype=hidden_states.dtype) + + config = try_get_optimal_moe_config( + w1.size(), + w2.size(), + top_k_num, + config_dtype, + num_tokens, + block_shape=self.block_shape, + ) + + if hidden_states.dtype == torch.bfloat16: + compute_type = tl.bfloat16 + elif hidden_states.dtype == torch.float16: + compute_type = tl.float16 + elif hidden_states.dtype == torch.float32: + compute_type = tl.float32 + elif hidden_states.dtype == torch.float8_e4m3fn: + compute_type = tl.bfloat16 + else: + raise ValueError( + f"Unsupported compute_type: {hidden_states.dtype}") + + # Note that the output tensor might be in workspace1 + intermediate_cache1 = _resize_cache(workspace2, + (num_tokens, top_k_num, N)) + intermediate_cache2 = _resize_cache(workspace13, + (num_tokens * top_k_num, N // 2)) + intermediate_cache3 = _resize_cache(workspace2, + (num_tokens, top_k_num, K)) + + sorted_token_ids, expert_ids, num_tokens_post_padded = ( + moe_align_block_size(topk_ids, config['BLOCK_SIZE_M'], + global_num_experts, expert_map)) + + invoke_fused_moe_kernel( + hidden_states, + w1, + intermediate_cache1, + a1q_scale, + w1_scale, + w1_zp, + None, # topk_weights + sorted_token_ids, + expert_ids, + num_tokens_post_padded, + False, # mul_routed_weights + top_k_num, + config, + compute_type=compute_type, + use_fp8_w8a8=self.use_fp8_w8a8, + use_int8_w8a8=self.use_int8_w8a8, + use_int8_w8a16=self.use_int8_w8a16, + use_int4_w4a16=self.use_int4_w4a16, + per_channel_quant=self.per_act_token_quant, + block_shape=self.block_shape, + B_bias=None # TODO support B_bias + ) + + self.activation(activation, intermediate_cache2, + intermediate_cache1.view(-1, N)) + + a2q_scale: Optional[torch.Tensor] = None + + qintermediate_cache2, a2q_scale = moe_kernel_quantize_input( + intermediate_cache2, a2_scale, self.quant_dtype, + self.per_act_token_quant, self.block_shape) + + invoke_fused_moe_kernel( + qintermediate_cache2, + w2, + intermediate_cache3, + a2q_scale, + w2_scale, + w2_zp, + topk_weights, + sorted_token_ids, + expert_ids, + num_tokens_post_padded, + not apply_router_weight_on_input, + 1, + config, + compute_type=compute_type, + use_fp8_w8a8=self.use_fp8_w8a8, + use_int8_w8a8=self.use_int8_w8a8, + use_int8_w8a16=self.use_int8_w8a16, + use_int4_w4a16=self.use_int4_w4a16, + per_channel_quant=self.per_act_token_quant, + block_shape=self.block_shape, + B_bias=None # TODO support B_bias + ) + + ops.moe_sum(intermediate_cache3, output) + + +def modular_triton_fused_moe( + use_fp8_w8a8: bool, + use_int8_w8a8: bool, + use_int8_w8a16: bool, + use_int4_w4a16: bool, + use_mxfp4_w4a4: bool, + per_act_token_quant: bool, + block_shape: Optional[list[int]] = None, +) -> mk.FusedMoEModularKernel: + return mk.FusedMoEModularKernel( + MoEPrepareAndFinalizeNoEP(), + TritonExperts( + use_fp8_w8a8=use_fp8_w8a8, + use_int8_w8a8=use_int8_w8a8, + use_int8_w8a16=use_int8_w8a16, + use_int4_w4a16=use_int4_w4a16, + use_mxfp4_w4a4=use_mxfp4_w4a4, + per_act_token_quant=per_act_token_quant, + block_shape=block_shape, + ), + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a8dfe3a0d71eb8d480e504a2382fb3871a202ff Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/__pycache__/abstract.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/__pycache__/abstract.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3fd5136303bc477427450b3b9bf5db4bccb84afb Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/__pycache__/abstract.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/__pycache__/mamba2_metadata.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/__pycache__/mamba2_metadata.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe40d4d474d49b4301d536bed7aa768937c5de75 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/__pycache__/mamba2_metadata.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/__pycache__/mamba_mixer2.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/__pycache__/mamba_mixer2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09d46a937b7dfa7959c34225782946414e531834 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/__pycache__/mamba_mixer2.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..693a0961a324bfc6a726fdd1d2a1c5b49acc5ddf Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/__pycache__/causal_conv1d.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/__pycache__/causal_conv1d.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb9d5c9ca7206329903382ca08ab119eba69a14e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/__pycache__/causal_conv1d.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/__pycache__/layernorm_gated.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/__pycache__/layernorm_gated.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6c260950b10cf6ad545deee8b980b99494f4d40 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/__pycache__/layernorm_gated.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/__pycache__/ssd_bmm.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/__pycache__/ssd_bmm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a59242faf62152e096dc6502874ac0ecd059dc76 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/__pycache__/ssd_bmm.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/__pycache__/ssd_chunk_scan.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/__pycache__/ssd_chunk_scan.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f73ab3c4e18e9b4a31a0338ba25db1a99c286461 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/__pycache__/ssd_chunk_scan.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/__pycache__/ssd_combined.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/__pycache__/ssd_combined.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95b52825456a06dbb04d2e339fb431f6d2242786 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/__pycache__/ssd_combined.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/causal_conv1d.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/causal_conv1d.py new file mode 100644 index 0000000000000000000000000000000000000000..b8d4bbc37105d78abe48b0faab1e1f15ae35e56c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/causal_conv1d.py @@ -0,0 +1,945 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +# Copyright (c) 2024, Tri Dao. +# Adapted from https://github.com/Dao-AILab/causal-conv1d/blob/main/causal_conv1d/causal_conv1d_interface.py + +from typing import Optional, Union + +import numpy as np +import torch + +from vllm.attention.backends.utils import PAD_SLOT_ID +from vllm.triton_utils import tl, triton + + +@triton.jit() +def _causal_conv1d_fwd_kernel( # continuous batching + # Pointers to matrices + x_ptr, # (dim, cu_seqlen) holding `batch` of actual sequences + padded sequences + w_ptr, # (dim, width) + bias_ptr, + initial_states_ptr, # conv_states_ptr + cache_indices_ptr, # conv_state_indices_ptr + has_initial_states_ptr, + query_start_loc_ptr, + batch_ptr, + token_chunk_offset_ptr, + o_ptr, # (dim, seqlen) - actually pointing to x_ptr + # Matrix dimensions + batch: tl.int32, # actually padded_batch + dim: tl.constexpr, + seqlen: tl.int32, # cu_seqlen + num_cache_lines: tl.constexpr, # added to support vLLM larger cache lines + # Strides + stride_x_seq: tl.constexpr, # stride to get to next sequence, + stride_x_dim: tl.constexpr, # stride to get to next feature-value, + stride_x_token: tl. + constexpr, # stride to get to next token (same feature-index, same sequence-index) + stride_w_dim: tl.constexpr, # stride to get to next dim-axis value + stride_w_width: tl.constexpr, # stride to get to next width-axis value + stride_istate_seq: tl.constexpr, + stride_istate_dim: tl.constexpr, + stride_istate_token: tl.constexpr, + stride_o_seq: tl.constexpr, + stride_o_dim: tl.constexpr, + stride_o_token: tl.constexpr, + # others + pad_slot_id: tl.constexpr, + # Meta-parameters + HAS_BIAS: tl.constexpr, + KERNEL_WIDTH: tl.constexpr, + SILU_ACTIVATION: tl.constexpr, + HAS_INITIAL_STATES: tl.constexpr, + HAS_CACHE: tl.constexpr, + IS_CONTINUOUS_BATCHING: tl.constexpr, + USE_PAD_SLOT: tl.constexpr, + NP2_STATELEN: tl.constexpr, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, +): + conv_states_ptr = initial_states_ptr + conv_state_indices_ptr = cache_indices_ptr + stride_conv_state_seq = stride_istate_seq + stride_conv_state_dim = stride_istate_dim + stride_conv_state_tok = stride_istate_token + state_len = KERNEL_WIDTH - 1 # can be passed via argument if it's not the same as this value + + # one program handles one chunk in a single sequence + # rather than mixing sequences - to make updating initial_states across sequences efficiently + + # single-sequence id + idx_seq = tl.load(batch_ptr + tl.program_id(0)) + chunk_offset = tl.load(token_chunk_offset_ptr + tl.program_id(0)) + + # BLOCK_N elements along the feature-dimension (channel) + idx_feats = tl.program_id(1) * BLOCK_N + tl.arange(0, BLOCK_N) + + if idx_seq == pad_slot_id: + return + + sequence_start_index = tl.load(query_start_loc_ptr + idx_seq) + sequence_end_index = tl.load(query_start_loc_ptr + idx_seq + 1) + # find the actual sequence length + seqlen = sequence_end_index - sequence_start_index + + token_offset = BLOCK_M * chunk_offset + segment_len = min(BLOCK_M, seqlen - token_offset) + + # base of the sequence + x_base = x_ptr + sequence_start_index * stride_x_token + idx_feats * stride_x_dim # [BLOCK_N,] + + if IS_CONTINUOUS_BATCHING: + # cache_idx + conv_state_batch_coord = tl.load(conv_state_indices_ptr + idx_seq).to( + tl.int64) + else: + # cache_idx + conv_state_batch_coord = idx_seq + if USE_PAD_SLOT: # noqa + if conv_state_batch_coord == pad_slot_id: + # not processing as this is not the actual sequence + return + conv_states_base = (conv_states_ptr + + (conv_state_batch_coord * stride_conv_state_seq) + + (idx_feats * stride_conv_state_dim)) # [BLOCK_N,] + + w_base = w_ptr + (idx_feats * stride_w_dim) # [BLOCK_N,] + + # Does 2 things: + # 1. READ prior-block init-state data - [done by every Triton programs] + # 2. update conv_state with new data [only by the Triton program handles chunk_offset=0] + if chunk_offset == 0: + # read from conv_states + load_init_state = False + if HAS_INITIAL_STATES: # the new HAS_INITIAL_STATES + load_init_state = tl.load(has_initial_states_ptr + idx_seq).to( + tl.int1) + if load_init_state: + # load from conv_states + prior_tokens = conv_states_base + (state_len - + 1) * stride_conv_state_tok + mask_w = idx_feats < dim + if KERNEL_WIDTH == 2: + conv_states_ptrs = prior_tokens # [BLOCK_N] + col0 = tl.load(conv_states_ptrs, mask_w, 0.0) + if KERNEL_WIDTH == 3: + conv_states_ptrs = prior_tokens # [BLOCK_N] + col1 = tl.load(conv_states_ptrs, mask_w, 0.0) + conv_states_ptrs = prior_tokens - 1 * stride_conv_state_tok # [BLOCK_N] + col0 = tl.load(conv_states_ptrs, mask_w, 0.0) + if KERNEL_WIDTH == 4: + conv_states_ptrs = prior_tokens # [BLOCK_N] + col2 = tl.load(conv_states_ptrs, mask_w, 0.0) + conv_states_ptrs = prior_tokens - 1 * stride_conv_state_tok # [BLOCK_N] + col1 = tl.load(conv_states_ptrs, mask_w, 0.0) + conv_states_ptrs = prior_tokens - 2 * stride_conv_state_tok # [BLOCK_N] + col0 = tl.load(conv_states_ptrs, mask_w, 0.0) + if KERNEL_WIDTH == 5: + conv_states_ptrs = prior_tokens # [BLOCK_N] + col3 = tl.load(conv_states_ptrs, mask_w, 0.0) + conv_states_ptrs = prior_tokens - 1 * stride_conv_state_tok # [BLOCK_N] + col2 = tl.load(conv_states_ptrs, mask_w, 0.0) + conv_states_ptrs = prior_tokens - 2 * stride_conv_state_tok # [BLOCK_N] + col1 = tl.load(conv_states_ptrs, mask_w, 0.0) + conv_states_ptrs = prior_tokens - 3 * stride_conv_state_tok # [BLOCK_N] + col0 = tl.load(conv_states_ptrs, mask_w, 0.0) + else: + # prior-tokens are zeros + if KERNEL_WIDTH >= 2: # STRATEGY1 + # first chunk and does not have prior-token, so just set to 0 + col0 = tl.zeros((BLOCK_N, ), dtype=x_ptr.dtype.element_ty) + if KERNEL_WIDTH >= 3: # STRATEGY1 + col1 = tl.zeros((BLOCK_N, ), dtype=x_ptr.dtype.element_ty) + if KERNEL_WIDTH >= 4: # STRATEGY1 + col2 = tl.zeros((BLOCK_N, ), dtype=x_ptr.dtype.element_ty) + if KERNEL_WIDTH >= 5: # STRATEGY1 + col3 = tl.zeros((BLOCK_N, ), dtype=x_ptr.dtype.element_ty) + + # STEP 2: + # here prepare data for updating conv_state + if state_len <= seqlen: # SMALL_CACHE=True (only move part of 'x' into conv_state cache) + # just read from 'x' + # copy 'x' data to conv_state + # load only 'x' data (and set 0 before 'x' if seqlen < state_len) + idx_tokens_last = (seqlen - state_len) + tl.arange( + 0, NP2_STATELEN) # [BLOCK_M] + x_ptrs = x_ptr + ( + (sequence_start_index + idx_tokens_last) * + stride_x_token)[:, None] + ( + idx_feats * stride_x_dim)[None, :] # [BLOCK_M,BLOCK_N,] + mask_x = ((idx_tokens_last >= 0)[:, None] & + (idx_tokens_last < seqlen)[:, None] & + (idx_feats < dim)[None, :] + ) # token-index # token-index # feature-index + loaded_x = tl.load(x_ptrs, mask_x, 0.0) + new_conv_state = tl.load(x_ptrs, mask_x, 0.0) + idx_tokens_conv = tl.arange(0, NP2_STATELEN) # [BLOCK_M] + conv_states_ptrs_target = conv_states_base[None, :] + ( + idx_tokens_conv * stride_conv_state_tok)[:, None] + + mask = (idx_tokens_conv < state_len)[:, None] & (idx_feats + < dim)[None, :] + tl.debug_barrier() # NOTE: use this due to bug in Triton compiler + tl.store(conv_states_ptrs_target, new_conv_state, mask) + + else: + if load_init_state: + # update conv_state by shifting left, i.e. take last few cols from conv_state + cols from 'x' + idx_tokens_conv = tl.arange(0, NP2_STATELEN) # [BLOCK_M] + + conv_states_ptrs_source = ( + conv_states_ptr + + (conv_state_batch_coord * stride_conv_state_seq) + + (idx_feats * stride_conv_state_dim)[None, :] + + ((idx_tokens_conv + seqlen) * stride_conv_state_tok)[:, + None] + ) # [BLOCK_M, BLOCK_N] + mask = ((conv_state_batch_coord < num_cache_lines) + & ((idx_tokens_conv + seqlen) < state_len)[:, None] + & (idx_feats < dim)[None, :]) + conv_state = tl.load(conv_states_ptrs_source, mask, other=0.0) + + VAL = state_len - seqlen + + x_ptrs = x_base[None, :] + ( + (idx_tokens_conv - VAL) * + stride_x_token)[:, None] # [BLOCK_M, BLOCK_N] + + mask_x = ((idx_tokens_conv - VAL >= 0)[:, None] & + (idx_tokens_conv - VAL < seqlen)[:, None] & + (idx_feats < dim)[None, :] + ) # token-index # token-index # feature-index + loaded_x = tl.load(x_ptrs, mask_x, 0.0) + + tl.debug_barrier( + ) # need this due to the bug in tl.where not enforcing this when data is the result of another tl.load + new_conv_state = tl.where( + mask, conv_state, loaded_x + ) # BUG in 'tl.where' which requires a barrier before this + conv_states_ptrs_target = conv_states_base + ( + idx_tokens_conv * + stride_conv_state_tok)[:, None] # [BLOCK_M, BLOCK_N] + mask = (idx_tokens_conv + < state_len)[:, None] & (idx_feats < dim)[None, :] + tl.store(conv_states_ptrs_target, new_conv_state, mask) + else: # load_init_state == False + # update conv_state by shifting left, BUT + # set cols prior to 'x' as zeros + cols from 'x' + idx_tokens_conv = tl.arange(0, NP2_STATELEN) # [BLOCK_M] + + VAL = state_len - seqlen + + x_ptrs = x_base[None, :] + ( + (idx_tokens_conv - VAL) * + stride_x_token)[:, None] # [BLOCK_M, BLOCK_N] + + mask_x = ((idx_tokens_conv - VAL >= 0)[:, None] & + (idx_tokens_conv - VAL < seqlen)[:, None] & + (idx_feats < dim)[None, :] + ) # token-index # token-index # feature-index + new_conv_state = tl.load(x_ptrs, mask_x, 0.0) + + conv_states_ptrs_target = conv_states_base + ( + idx_tokens_conv * + stride_conv_state_tok)[:, None] # [BLOCK_M, BLOCK_N] + mask = (idx_tokens_conv + < state_len)[:, None] & (idx_feats < dim)[None, :] + tl.store(conv_states_ptrs_target, new_conv_state, mask) + + else: # chunk_offset > 0 + # read prior-token data from `x` + load_init_state = True + prior_tokens = x_base + (token_offset - 1) * stride_x_token + mask_w = idx_feats < dim + if KERNEL_WIDTH == 2: + conv_states_ptrs = prior_tokens # [BLOCK_N] + col0 = tl.load(conv_states_ptrs, mask_w, 0.0, cache_modifier='.ca') + if KERNEL_WIDTH == 3: + conv_states_ptrs = prior_tokens # [BLOCK_N] + col1 = tl.load(conv_states_ptrs, mask_w, 0.0, cache_modifier='.ca') + conv_states_ptrs = prior_tokens - 1 * stride_x_token # [BLOCK_N] + col0 = tl.load(conv_states_ptrs, mask_w, 0.0, cache_modifier='.ca') + if KERNEL_WIDTH == 4: + conv_states_ptrs = prior_tokens # [BLOCK_N] + col2 = tl.load(conv_states_ptrs, mask_w, 0.0, cache_modifier='.ca') + conv_states_ptrs = prior_tokens - 1 * stride_x_token # [BLOCK_N] + col1 = tl.load(conv_states_ptrs, mask_w, 0.0, cache_modifier='.ca') + conv_states_ptrs = prior_tokens - 2 * stride_x_token # [BLOCK_N] + col0 = tl.load(conv_states_ptrs, mask_w, 0.0, cache_modifier='.ca') + if KERNEL_WIDTH == 5: + # ruff: noqa: F841 + conv_states_ptrs = prior_tokens # [BLOCK_N] + col3 = tl.load(conv_states_ptrs, mask_w, 0.0, cache_modifier='.ca') + conv_states_ptrs = prior_tokens - 1 * stride_x_token # [BLOCK_N] + col2 = tl.load(conv_states_ptrs, mask_w, 0.0, cache_modifier='.ca') + conv_states_ptrs = prior_tokens - 2 * stride_x_token # [BLOCK_N] + col1 = tl.load(conv_states_ptrs, mask_w, 0.0, cache_modifier='.ca') + conv_states_ptrs = prior_tokens - 3 * stride_x_token # [BLOCK_N] + col0 = tl.load(conv_states_ptrs, mask_w, 0.0, cache_modifier='.ca') + + if HAS_BIAS: + bias = bias_ptr + idx_feats + mask_bias = idx_feats < dim + acc_preload = tl.load(bias, mask=mask_bias, + other=0.0).to(tl.float32) # [BLOCK_N] + else: + acc_preload = tl.zeros((BLOCK_N, ), dtype=tl.float32) + + x_base_1d = x_base + token_offset * stride_x_token # starting of chunk + + # PRE-LOAD WEIGHTS + mask_w = idx_feats < dim + if KERNEL_WIDTH >= 2: + w_ptrs = w_base + (0 * stride_w_width) # [BLOCK_N] tensor + w_col0 = tl.load(w_ptrs, mask_w, other=0.0) + w_ptrs = w_base + (1 * stride_w_width) # [BLOCK_N] tensor + w_col1 = tl.load(w_ptrs, mask_w, other=0.0) + if KERNEL_WIDTH >= 3: + w_ptrs = w_base + (2 * stride_w_width) # [BLOCK_N] tensor + w_col2 = tl.load(w_ptrs, mask_w, other=0.0) + if KERNEL_WIDTH >= 4: + w_ptrs = w_base + (3 * stride_w_width) # [BLOCK_N] tensor + w_col3 = tl.load(w_ptrs, mask_w, other=0.0) + mask_x_1d = idx_feats < dim + for idx_token in range(segment_len): + acc = acc_preload + + matrix_w = w_col0 + matrix_x = col0 + for j in tl.static_range(KERNEL_WIDTH): + + if KERNEL_WIDTH == 2: + if j == 1: # KERNEL_WIDTH-1: + matrix_w = w_col1 + x_ptrs_1d = x_base_1d + idx_token * stride_x_token # [BLOCK_N] + matrix_x = tl.load(x_ptrs_1d, mask=mask_x_1d) + elif KERNEL_WIDTH == 3: + if j == 1: + matrix_w = w_col1 + matrix_x = col1 + elif j == 2: + matrix_w = w_col2 + x_ptrs_1d = x_base_1d + idx_token * stride_x_token # [BLOCK_N] + matrix_x = tl.load(x_ptrs_1d, mask=mask_x_1d) + elif KERNEL_WIDTH == 4: + if j == 1: + matrix_w = w_col1 + matrix_x = col1 + elif j == 2: + matrix_w = w_col2 + matrix_x = col2 + elif j == 3: + matrix_w = w_col3 + x_ptrs_1d = x_base_1d + idx_token * stride_x_token # [BLOCK_N] + matrix_x = tl.load(x_ptrs_1d, mask=mask_x_1d) + + acc += matrix_x * matrix_w # [BLOCK_N] + + if KERNEL_WIDTH == 2: + col0 = matrix_x + elif KERNEL_WIDTH == 3: + col0 = col1 + col1 = matrix_x + elif KERNEL_WIDTH == 4: + col0 = col1 + col1 = col2 + col2 = matrix_x + + if SILU_ACTIVATION: + acc = acc / (1 + tl.exp(-acc)) + mask_1d = (idx_token < segment_len) & ( + idx_feats < dim) # token-index # feature-index + o_ptrs = o_ptr + (sequence_start_index + token_offset + idx_token + ) * stride_o_token + (idx_feats * stride_o_dim) + + tl.store(o_ptrs, acc, mask=mask_1d) + + +def causal_conv1d_fn( + x: torch.Tensor, + weight: torch.Tensor, + bias: Union[torch.Tensor, None], + conv_states: torch.Tensor, + query_start_loc: torch.Tensor, + cache_indices: Optional[torch.Tensor] = None, + has_initial_state: Optional[torch.Tensor] = None, + activation: Optional[str] = "silu", + pad_slot_id: int = PAD_SLOT_ID, + metadata=None, + validate_data=False, +): + """support varlen + continuous batching when x is 2D tensor + + x: (dim,cu_seq_len) + cu_seq_len = total tokens of all seqs in that batch + sequences are concatenated from left to right for varlen + weight: (dim, width) + conv_states: (...,dim,width - 1) itype + updated inplace if provided + [it use `cache_indices` to get the index to the cache of conv_state for that sequence + + conv_state[cache_indices[i]] for seq-i - to be used as initial_state when has_initial_state[i] = True + and after that conv_state[cache_indices[i]] need to be shift-left and updated with values from 'x' + ] + query_start_loc: (batch + 1) int32 + The cumulative sequence lengths of the sequences in + the batch, used to index into sequence. prepended by 0. + if + x = [5, 1, 1, 1] <- continuous batching (batch=4) + then + query_start_loc = [0, 5, 6, 7, 8] <- the starting index of the next sequence; while the last value is + the ending index of the last sequence + [length(query_start_loc)-1 == batch] + for example: query_start_loc = torch.Tensor([0,10,16,17]), + x.shape=(dim,17) + cache_indices: (batch) int32 + indicates the corresponding state index, + like so: conv_state = conv_states[cache_indices[batch_id]] + has_initial_state: (batch) bool + indicates whether should the kernel take the current state as initial + state for the calculations + [single boolean for each sequence in the batch: True or False] + bias: (dim,) + activation: either None or "silu" or "swish" or True + pad_slot_id: int + if cache_indices is passed, lets the kernel identify padded + entries that will not be processed, + for example: cache_indices = [pad_slot_id, 1, 20, pad_slot_id] + in this case, the kernel will not process entries at + indices 0 and 3 + + out: same shape as `x` + """ + if isinstance(activation, bool) and activation: + activation = "silu" + + args = None + out = torch.empty_like(x) + if metadata is not None: + cu_seqlen = metadata.cu_seqlen + nums_dict = metadata.nums_dict + #x = metadata.x + args = nums_dict + batch_ptr = metadata.batch_ptr + token_chunk_offset_ptr = metadata.token_chunk_offset_ptr + else: + seqlens = np.diff(query_start_loc.to('cpu')) + args = seqlens + MAX_NUM_PROGRAMS = 1024 + + batch_ptr = torch.full( + (MAX_NUM_PROGRAMS, ), + PAD_SLOT_ID, + dtype=torch.int32, + device=x.device + ) # tracking which seq-idx the Triton program is handling + token_chunk_offset_ptr = torch.full( + (MAX_NUM_PROGRAMS, ), + PAD_SLOT_ID, + dtype=torch.int32, + device=x.device + ) # tracking BLOCK_M-based index in the sequence the Triton program is handling + + is_channel_last = (x.stride(0) == 1) & (x.stride(1) > 1) + dim, cu_seqlen = x.shape + _, width = weight.shape + state_len = width - 1 + np2_statelen = triton.next_power_of_2(state_len) + + padded_batch = query_start_loc.size(0) - 1 + stride_x_seq = 0 + stride_x_dim = x.stride(0) + stride_x_token = x.stride(1) + stride_w_dim = weight.stride(0) + stride_w_width = weight.stride(1) + stride_istate_seq = 0 + stride_istate_dim = 0 + stride_istate_token = 0 + num_cache_lines = 0 + if conv_states is not None: + # extensions to support vLLM: + # 1. conv_states is used to replaced initial_states + # 2. conv_states serve as a cache with num cache lines can be larger than batch size + # 3. mapping from sequence x[idx] to a cache line at index as specified via cache_indices[idx] + # 4. computation can be skipped if cache_indices[idx] == pad_slot_id + num_cache_lines = conv_states.size(0) + assert (num_cache_lines, dim, width - 1) == conv_states.shape + stride_istate_seq = conv_states.stride(0) + stride_istate_dim = conv_states.stride(1) + stride_istate_token = conv_states.stride(2) + assert stride_istate_dim == 1 + if out.dim() == 2: + stride_o_seq = 0 + stride_o_dim = out.stride(0) + stride_o_token = out.stride(1) + else: + stride_o_seq = out.stride(0) + stride_o_dim = out.stride(1) + stride_o_token = out.stride(2) + + if validate_data: + assert x.dim() == 2 + assert query_start_loc is not None + assert query_start_loc.dim() == 1 + assert x.stride(0) == 1 or x.stride(1) == 1 + if bias is not None: + assert bias.dim() == 1 + assert dim == bias.size(0) + if cache_indices is not None: + assert cache_indices.dim() == 1 + assert padded_batch == cache_indices.size(0) + if has_initial_state is not None: + assert has_initial_state.size() == (padded_batch, ) + assert conv_states is not None, "ERROR: `has_initial_state` is used, which needs also `conv_states`" + assert weight.stride(1) == 1 + assert (dim, width) == weight.shape + assert is_channel_last, "Need to run in channel-last layout" + + if metadata is None: + + def num_program(META, seqlens): + tot = 0 + + mlist = [] + offsetlist = [] # type: ignore + + nums = -(-seqlens // META["BLOCK_M"]) + + tot = nums.sum().item() + mlist = np.repeat(np.arange(len(nums)), nums) + for idx, num in enumerate(nums): + offsetlist.extend( + range(num) + ) # chunk-idx if a sequence is split into multiple chunks + + if META["batch_ptr"].nelement() < len(mlist): + newlen = len(mlist) + 1 + META["batch_ptr"].resize_(newlen).fill_(PAD_SLOT_ID) + META["token_chunk_offset_ptr"].resize_(newlen).fill_( + PAD_SLOT_ID) + + if META["batch_ptr"].nelement() >= len(mlist): + META["batch_ptr"][0:len(mlist)].copy_( + torch.from_numpy(np.array(mlist))) + META["token_chunk_offset_ptr"][0:len(mlist)].copy_( + torch.from_numpy(np.array(offsetlist))) + + META["batch_ptr"] = META["batch_ptr"].to(META["x_ptr"].device) + META["token_chunk_offset_ptr"] = META["token_chunk_offset_ptr"].to( + META["x_ptr"].device) + return tot + else: + + def num_program(META, nums_dict): + tot = nums_dict[META["BLOCK_M"]]['tot'] + + mlist = nums_dict[META["BLOCK_M"]]['mlist'] + mlist_len = nums_dict[META["BLOCK_M"]]['mlist_len'] + + offsetlist = nums_dict[META["BLOCK_M"]]['offsetlist'] + + if nums_dict[META["BLOCK_M"]]["batch_ptr"] is not None: + META["batch_ptr"] = nums_dict[META["BLOCK_M"]]["batch_ptr"] + META["token_chunk_offset_ptr"] = nums_dict[ + META["BLOCK_M"]]["token_chunk_offset_ptr"] + else: + if META["batch_ptr"].nelement() < mlist_len: + newlen = mlist_len + 1 + META["batch_ptr"].resize_(newlen).fill_(PAD_SLOT_ID) + META["token_chunk_offset_ptr"].resize_(newlen).fill_( + PAD_SLOT_ID) + + if META["batch_ptr"].nelement() >= mlist_len: + META["batch_ptr"][0:mlist_len].copy_(mlist) + META["token_chunk_offset_ptr"][0:mlist_len].copy_( + offsetlist) + return tot + + def grid(META): + return ( + num_program(META, args), + triton.cdiv(dim, META["BLOCK_N"]), + ) + + if batch_ptr.device != x.device: + batch_ptr = batch_ptr.to(x.device) + token_chunk_offset_ptr = token_chunk_offset_ptr.to(x.device) + + _causal_conv1d_fwd_kernel[grid]( + # Pointers to matrices + x, + weight, + bias, + conv_states, + cache_indices, + has_initial_state, + query_start_loc, + batch_ptr, + token_chunk_offset_ptr, + out, + # Matrix dimensions + padded_batch, + dim, + cu_seqlen, + num_cache_lines, + # stride + stride_x_seq, + stride_x_dim, + stride_x_token, + stride_w_dim, + stride_w_width, + stride_istate_seq, + stride_istate_dim, + stride_istate_token, + stride_o_seq, + stride_o_dim, + stride_o_token, + # others + pad_slot_id, + # META + HAS_BIAS=bias is not None, + KERNEL_WIDTH=width, + SILU_ACTIVATION=activation in ["silu", "swish"], + HAS_INITIAL_STATES=has_initial_state is not None, + HAS_CACHE=conv_states is not None, + IS_CONTINUOUS_BATCHING=cache_indices is not None, + USE_PAD_SLOT=pad_slot_id is not None, + NP2_STATELEN=np2_statelen, + #launch_cooperative_grid=True + BLOCK_M=8, + BLOCK_N=256, + num_stages=2, + ) + return out + + +@triton.jit() +def _causal_conv1d_update_kernel( + # Pointers to matrices + x_ptr, # (batch, dim, seqlen) + w_ptr, # (dim, width) + bias_ptr, + conv_state_ptr, + cache_seqlens_ptr, # circular buffer + conv_state_indices_ptr, + o_ptr, # (batch, dim, seqlen) + # Matrix dimensions + batch: int, + dim: tl.constexpr, + seqlen: tl.constexpr, + state_len: tl.constexpr, + num_cache_lines: tl.constexpr, # added to support vLLM larger cache lines + # Strides + stride_x_seq: tl.constexpr, + stride_x_dim: tl.constexpr, + stride_x_token: tl.constexpr, + stride_w_dim: tl.constexpr, + stride_w_width: tl.constexpr, + stride_conv_state_seq: tl.constexpr, + stride_conv_state_dim: tl.constexpr, + stride_conv_state_tok: tl.constexpr, + stride_o_seq: tl.constexpr, + stride_o_dim: tl.constexpr, + stride_o_token: tl.constexpr, + # others + pad_slot_id: tl.constexpr, + # Meta-parameters + HAS_BIAS: tl.constexpr, + KERNEL_WIDTH: tl.constexpr, + SILU_ACTIVATION: tl.constexpr, + IS_CONTINUOUS_BATCHING: tl.constexpr, + NP2_STATELEN: tl.constexpr, + USE_PAD_SLOT: tl.constexpr, + BLOCK_N: tl.constexpr, +): + # ruff: noqa: E501 + idx_seq = tl.program_id(0) + if idx_seq >= batch: + return + + # [BLOCK_N,] elements along the feature-dimension (channel) + idx_feats = tl.program_id(1) * BLOCK_N + tl.arange(0, BLOCK_N) + + if IS_CONTINUOUS_BATCHING: + # mask = idx_seq < batch + conv_state_batch_coord = tl.load(conv_state_indices_ptr + idx_seq).to( + tl.int64) + else: + conv_state_batch_coord = idx_seq + if USE_PAD_SLOT: # noqa + if conv_state_batch_coord == pad_slot_id: + # not processing as this is not the actual sequence + return + + # STEP 1: READ init_state data + conv_states_base = (conv_state_ptr + + (conv_state_batch_coord * stride_conv_state_seq) + + (idx_feats * stride_conv_state_dim)) + mask_w = idx_feats < dim + + prior_tokens = conv_states_base + if KERNEL_WIDTH >= 2: + conv_states_ptrs = prior_tokens # [BLOCK_N] + col0 = tl.load(conv_states_ptrs, mask_w, 0.0) + if KERNEL_WIDTH >= 3: + conv_states_ptrs = prior_tokens + 1 * stride_conv_state_tok # [BLOCK_N] + col1 = tl.load(conv_states_ptrs, mask_w, 0.0) + if KERNEL_WIDTH >= 4: + conv_states_ptrs = prior_tokens + 2 * stride_conv_state_tok # [BLOCK_N] + col2 = tl.load(conv_states_ptrs, mask_w, 0.0) + if KERNEL_WIDTH == 5: + conv_states_ptrs = prior_tokens + 3 * stride_conv_state_tok # [BLOCK_N] + col3 = tl.load(conv_states_ptrs, mask_w, 0.0) + + # STEP 2: assume state_len > seqlen + idx_tokens = tl.arange(0, NP2_STATELEN) # [BLOCK_M] + + conv_state_ptrs_source = ( + conv_state_ptr + (conv_state_batch_coord * stride_conv_state_seq) + + (idx_feats * stride_conv_state_dim)[None, :] + + ((idx_tokens + seqlen) * stride_conv_state_tok)[:, None] + ) # [BLOCK_M, BLOCK_N] + mask = ((conv_state_batch_coord < num_cache_lines) + & ((idx_tokens + seqlen) < state_len)[:, None] + & (idx_feats < dim)[None, :]) + conv_state = tl.load(conv_state_ptrs_source, mask, other=0.0) + + VAL = state_len - seqlen + x_base = x_ptr + (idx_seq * stride_x_seq) + (idx_feats * stride_x_dim + ) # [BLOCK_N] + + x_ptrs = x_base[None, :] + ( + (idx_tokens - VAL) * stride_x_token)[:, None] # [BLOCK_M, BLOCK_N] + + mask_x = ((idx_tokens - VAL >= 0)[:, None] & + (idx_tokens - VAL < seqlen)[:, None] & (idx_feats < dim)[None, :] + ) # token-index # token-index # feature-index + loaded_x = tl.load(x_ptrs, mask_x, 0.0) + tl.debug_barrier() + + new_conv_state = tl.where(mask, conv_state, loaded_x) + + conv_state_base = (conv_state_ptr + + (conv_state_batch_coord * stride_conv_state_seq) + + (idx_feats * stride_conv_state_dim)) # [BLOCK_N,] + conv_state_ptrs_target = conv_state_base + ( + idx_tokens * stride_conv_state_tok)[:, None] # [BLOCK_M, BLOCK_N] + mask = (idx_tokens < state_len)[:, None] & (idx_feats < dim)[None, :] + tl.store(conv_state_ptrs_target, new_conv_state, mask) + + # STEP 3: init accumulator + if HAS_BIAS: + bias = bias_ptr + idx_feats + mask_bias = idx_feats < dim + acc_preload = tl.load(bias, mask=mask_bias, + other=0.0).to(tl.float32) # [BLOCK_N] + else: + acc_preload = tl.zeros((BLOCK_N, ), dtype=tl.float32) + + # STEP 4: + # PRE-LOAD WEIGHTS + # first kernel column, configured for weights to handle BLOCK_N features in range + w_base = w_ptr + (idx_feats * stride_w_dim) # [BLOCK_N,] + mask_w = idx_feats < dim + if KERNEL_WIDTH >= 2: + w_ptrs = w_base + (0 * stride_w_width) # [BLOCK_N] tensor + w_col0 = tl.load(w_ptrs, mask_w, other=0.0) + w_ptrs = w_base + (1 * stride_w_width) # [BLOCK_N] tensor + w_col1 = tl.load(w_ptrs, mask_w, other=0.0) + if KERNEL_WIDTH >= 3: + w_ptrs = w_base + (2 * stride_w_width) # [BLOCK_N] tensor + w_col2 = tl.load(w_ptrs, mask_w, other=0.0) + if KERNEL_WIDTH >= 4: + w_ptrs = w_base + (3 * stride_w_width) # [BLOCK_N] tensor + w_col3 = tl.load(w_ptrs, mask_w, other=0.0) + + x_base_1d = x_base # starting of chunk [BLOCK_N] + mask_x_1d = idx_feats < dim + + # STEP 5: compute each token + for idx_token in tl.static_range(seqlen): + acc = acc_preload + + matrix_w = w_col0 + matrix_x = col0 + for j in tl.static_range(KERNEL_WIDTH): + if KERNEL_WIDTH == 2: + if j == 1: # KERNEL_WIDTH-1: + matrix_w = w_col1 + x_ptrs_1d = x_base_1d + idx_token * stride_x_token # [BLOCK_N] + matrix_x = tl.load(x_ptrs_1d, mask=mask_x_1d) + elif KERNEL_WIDTH == 3: + if j == 1: + matrix_w = w_col1 + matrix_x = col1 + elif j == 2: + matrix_w = w_col2 + x_ptrs_1d = x_base_1d + idx_token * stride_x_token # [BLOCK_N] + matrix_x = tl.load(x_ptrs_1d, mask=mask_x_1d) + elif KERNEL_WIDTH == 4: + if j == 1: + matrix_w = w_col1 + matrix_x = col1 + elif j == 2: + matrix_w = w_col2 + matrix_x = col2 + elif j == 3: + matrix_w = w_col3 + x_ptrs_1d = x_base_1d + idx_token * stride_x_token # [BLOCK_N] + matrix_x = tl.load(x_ptrs_1d, mask=mask_x_1d) + + acc += matrix_x * matrix_w # [BLOCK_N] + + if KERNEL_WIDTH == 2: + col0 = matrix_x + elif KERNEL_WIDTH == 3: + col0 = col1 + col1 = matrix_x + elif KERNEL_WIDTH == 4: + col0 = col1 + col1 = col2 + col2 = matrix_x + + if SILU_ACTIVATION: + acc = acc / (1 + tl.exp(-acc)) + mask_1d = (idx_token < seqlen) & (idx_feats < dim + ) # token-index # feature-index + o_ptrs = o_ptr + ( + idx_seq) * stride_o_seq + idx_token * stride_o_token + ( + idx_feats * stride_o_dim) + + tl.store(o_ptrs, acc, mask=mask_1d) + + +def causal_conv1d_update( + x: torch.Tensor, + conv_state: torch.Tensor, + weight: torch.Tensor, + bias: Optional[torch.Tensor] = None, + activation: Union[bool, str, None] = None, + cache_seqlens: Optional[torch.Tensor] = None, + conv_state_indices: Optional[torch.Tensor] = None, + pad_slot_id: int = PAD_SLOT_ID, + metadata=None, + validate_data=False, +): + """ + x: (batch, dim) or (batch, dim, seqlen) + [shape=2: single token prediction] + [shape=3: single or multiple tokens prediction] + conv_state: (..., dim, state_len), where state_len >= width - 1 + weight: (dim, width) + bias: (dim,) + cache_seqlens: (batch,), dtype int32. + If not None, the conv_state is treated as a circular buffer. + The conv_state will be updated by copying x to the conv_state + starting at the index + @cache_seqlens % state_len. + conv_state_indices: (batch,), dtype int32 + If not None, the conv_state is a larger tensor along the batch dim, + and we are selecting the batch coords specified by conv_state_indices. + Useful for a continuous batching scenario. + pad_slot_id: int + if cache_indices is passed, lets the kernel identify padded + entries that will not be processed, + for example: cache_indices = [pad_slot_id, 1 ,20 ,pad_slot_id] + in this case, the kernel will not process entries at + indices 0 and 3 + out: (batch, dim) or (batch, dim, seqlen) + """ + if validate_data: + assert cache_seqlens is None # not implemented yet - ok for vLLM + assert pad_slot_id is not None + assert x.stride(1) == 1 + if isinstance(activation, bool): + activation = "silu" if activation is True else None + elif activation is not None: + assert activation in ["silu", "swish"] + unsqueeze = x.dim() == 2 + if unsqueeze: + # make it (batch, dim, seqlen) with seqlen == 1 + x = x.unsqueeze(-1) + batch, dim, seqlen = x.shape + _, width = weight.shape + # conv_state: (..., dim, state_len), where state_len >= width - 1 + num_cache_lines, _, state_len = conv_state.size() + + if validate_data: + assert dim == weight.size(0) + assert conv_state.stride( + -2 + ) == 1, f"ERROR: expect contiguous along feat-dim of conv_state (currently stride={conv_state.stride()})" + assert state_len >= width - 1 + # when above happens, we don't shift-left to keep any records in conv_state + assert dim == conv_state.size(1) + if conv_state_indices is None: + assert conv_state.size(0) >= batch + else: + assert (batch, ) == conv_state_indices.shape + + assert num_cache_lines >= batch + assert weight.stride(1) == 1 # Need this + assert cache_seqlens is None # not needed for vLLM - circular buffer + + # adopt the strategy in vLLM that overwrite on 'x' directly, rather than creating a new tensor 'o' + out = x + stride_w_dim, stride_w_width = weight.stride() + + stride_x_seq, stride_x_dim, stride_x_token = x.stride( + ) # X (batch, dim, seqlen) + + stride_o_seq, stride_o_dim, stride_o_token = out.stride() + + stride_istate_seq, stride_istate_dim, stride_istate_token = conv_state.stride( + ) + state_len = width - 1 + np2_statelen = triton.next_power_of_2(state_len) + + def grid(META): + return ( + batch, + triton.cdiv(dim, META["BLOCK_N"]), + ) + + _causal_conv1d_update_kernel[grid]( + # Pointers to matrices + x, + weight, + bias, + conv_state, + cache_seqlens, + conv_state_indices, + out, + # Matrix dimensions + batch, + dim, + seqlen, + state_len, + num_cache_lines, + # stride + stride_x_seq, + stride_x_dim, + stride_x_token, + stride_w_dim, + stride_w_width, + stride_istate_seq, + stride_istate_dim, + stride_istate_token, + stride_o_seq, + stride_o_dim, + stride_o_token, + # others + pad_slot_id, + # META + HAS_BIAS=bias is not None, + KERNEL_WIDTH=width, + SILU_ACTIVATION=activation in ["silu", "swish"], + IS_CONTINUOUS_BATCHING=conv_state_indices is not None, + NP2_STATELEN=np2_statelen, + USE_PAD_SLOT=pad_slot_id is not None, + BLOCK_N=256, + ) + if unsqueeze: + out = out.squeeze(-1) + return out diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/mamba_ssm.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/mamba_ssm.py new file mode 100644 index 0000000000000000000000000000000000000000..838290a9f5fb2b5d51961c04dfd2b89625be4eee --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/mamba_ssm.py @@ -0,0 +1,414 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +# Copyright (c) 2024, Tri Dao, Albert Gu. +# Adapted from https://github.com/state-spaces/mamba/blob/v2.2.4/mamba_ssm/ops/triton/selective_state_update.py + +import torch +from packaging import version + +from vllm import _custom_ops as ops +from vllm.attention.backends.utils import PAD_SLOT_ID +from vllm.triton_utils import HAS_TRITON, tl, triton + +TRITON3 = HAS_TRITON and (version.parse(triton.__version__) + >= version.parse("3.0.0")) + +if TRITON3: + + @triton.jit + def softplus(dt): + dt = tl.where(dt <= 20.0, tl.math.log(tl.math.exp(dt) + 1), dt) + return dt +else: + + @triton.jit + def softplus(dt): + dt = tl.where(dt <= 20.0, tl.math.log1p(tl.exp(dt)), dt) + return dt + + +@triton.heuristics( + {"HAS_DT_BIAS": lambda args: args["dt_bias_ptr"] is not None}) +@triton.heuristics({"HAS_D": lambda args: args["D_ptr"] is not None}) +@triton.heuristics({"HAS_Z": lambda args: args["z_ptr"] is not None}) +@triton.heuristics({ + "HAS_STATE_BATCH_INDICES": + lambda args: args["state_batch_indices_ptr"] is not None +}) +@triton.heuristics( + {"BLOCK_SIZE_DSTATE": lambda args: triton.next_power_of_2(args["dstate"])}) +@triton.jit +def _selective_scan_update_kernel( + # Pointers to matrices + state_ptr, + x_ptr, + dt_ptr, + dt_bias_ptr, + A_ptr, + B_ptr, + C_ptr, + D_ptr, + z_ptr, + out_ptr, + state_batch_indices_ptr, + pad_slot_id, + # Matrix dimensions + batch, + nheads, + dim, + dstate, + nheads_ngroups_ratio, + # Strides + stride_state_batch, + stride_state_head, + stride_state_dim, + stride_state_dstate, + stride_x_batch, + stride_x_head, + stride_x_dim, + stride_dt_batch, + stride_dt_head, + stride_dt_dim, + stride_dt_bias_head, + stride_dt_bias_dim, + stride_A_head, + stride_A_dim, + stride_A_dstate, + stride_B_batch, + stride_B_group, + stride_B_dstate, + stride_C_batch, + stride_C_group, + stride_C_dstate, + stride_D_head, + stride_D_dim, + stride_z_batch, + stride_z_head, + stride_z_dim, + stride_out_batch, + stride_out_head, + stride_out_dim, + # Meta-parameters + DT_SOFTPLUS: tl.constexpr, + TIE_HDIM: tl.constexpr, + BLOCK_SIZE_M: tl.constexpr, + HAS_DT_BIAS: tl.constexpr, + HAS_D: tl.constexpr, + HAS_Z: tl.constexpr, + HAS_STATE_BATCH_INDICES: tl.constexpr, + BLOCK_SIZE_DSTATE: tl.constexpr, +): + pid_m = tl.program_id(axis=0) + pid_b = tl.program_id(axis=1) + pid_h = tl.program_id(axis=2) + + # If HAS_STATE_BATCH_INDICES is true, then the ssm state's batch coordinate + # is taken from the state_batch_indices_ptr Otherwise, the state coordinate + # is the same as the batch id. + if HAS_STATE_BATCH_INDICES: + state_batch_indices_ptr += pid_b + state_batch_idx = tl.load(state_batch_indices_ptr).to(tl.int64) + state_ptr += (state_batch_idx * stride_state_batch + + pid_h * stride_state_head) + else: + state_ptr += pid_b * stride_state_batch + pid_h * stride_state_head + + x_ptr += pid_b * stride_x_batch + pid_h * stride_x_head + dt_ptr += pid_b * stride_dt_batch + pid_h * stride_dt_head + if HAS_DT_BIAS: + dt_bias_ptr += pid_h * stride_dt_bias_head + A_ptr += pid_h * stride_A_head + B_ptr += pid_b * stride_B_batch + (pid_h // + nheads_ngroups_ratio) * stride_B_group + C_ptr += pid_b * stride_C_batch + (pid_h // + nheads_ngroups_ratio) * stride_C_group + if HAS_Z: + z_ptr += pid_b * stride_z_batch + pid_h * stride_z_head + out_ptr += pid_b * stride_out_batch + pid_h * stride_out_head + + offs_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M) + offs_n = tl.arange(0, BLOCK_SIZE_DSTATE) + state_ptrs = state_ptr + (offs_m[:, None] * stride_state_dim + + offs_n[None, :] * stride_state_dstate) + x_ptrs = x_ptr + offs_m * stride_x_dim + dt_ptrs = dt_ptr + offs_m * stride_dt_dim + if HAS_DT_BIAS: + dt_bias_ptrs = dt_bias_ptr + offs_m * stride_dt_bias_dim + if HAS_D: + D_ptr += pid_h * stride_D_head + A_ptrs = A_ptr + (offs_m[:, None] * stride_A_dim + + offs_n[None, :] * stride_A_dstate) + B_ptrs = B_ptr + offs_n * stride_B_dstate + C_ptrs = C_ptr + offs_n * stride_C_dstate + if HAS_D: + D_ptrs = D_ptr + offs_m * stride_D_dim + if HAS_Z: + z_ptrs = z_ptr + offs_m * stride_z_dim + out_ptrs = out_ptr + offs_m * stride_out_dim + mask = (offs_m[:, None] < dim) & (offs_n[None, :] < dstate) + if HAS_STATE_BATCH_INDICES: + mask &= (state_batch_idx != pad_slot_id) + state = tl.load(state_ptrs, mask=mask, other=0.0) + + x = tl.load(x_ptrs, mask=offs_m < dim, other=0.0).to(tl.float32) + if not TIE_HDIM: + dt = tl.load(dt_ptrs, mask=offs_m < dim, other=0.0).to(tl.float32) + if HAS_DT_BIAS: + dt += tl.load(dt_bias_ptrs, mask=offs_m < dim, + other=0.0).to(tl.float32) + if DT_SOFTPLUS: + dt = softplus(dt) + A = tl.load(A_ptrs, + mask=(offs_m[:, None] < dim) & (offs_n[None, :] < dstate), + other=0.0).to(tl.float32) + dA = tl.exp(A * dt[:, None]) + else: + dt = tl.load(dt_ptr).to(tl.float32) + if HAS_DT_BIAS: + dt += tl.load(dt_bias_ptr).to(tl.float32) + if DT_SOFTPLUS: + dt = softplus(dt) + A = tl.load(A_ptr).to(tl.float32) + dA = tl.exp(A * dt) # scalar, not a matrix + + B = tl.load(B_ptrs, mask=offs_n < dstate, other=0.0).to(tl.float32) + C = tl.load(C_ptrs, mask=offs_n < dstate, other=0.0).to(tl.float32) + if HAS_D: + D = tl.load(D_ptrs, mask=offs_m < dim, other=0.0).to(tl.float32) + if HAS_Z: + z = tl.load(z_ptrs, mask=offs_m < dim, other=0.0).to(tl.float32) + + dB = B[None, :] * dt[:, None] if not TIE_HDIM else B * dt + state = state * dA + dB * x[:, None] + + mask = (offs_m[:, None] < dim) & (offs_n[None, :] < dstate) + if HAS_STATE_BATCH_INDICES: + mask &= (state_batch_idx != pad_slot_id) + tl.store(state_ptrs, state, mask=mask) + out = tl.sum(state * C[None, :], axis=1) + if HAS_D: + out += x * D + if HAS_Z: + out *= z * tl.sigmoid(z) + tl.store(out_ptrs, out, mask=offs_m < dim) + + +def selective_state_update(state, + x, + dt, + A, + B, + C, + D=None, + z=None, + dt_bias=None, + dt_softplus=False, + state_batch_indices=None, + pad_slot_id=PAD_SLOT_ID, + out=None): + """ + Argument: + state: (batch, dim, dstate) or (batch, nheads, dim, dstate) + x: (batch, dim) or (batch, nheads, dim) + dt: (batch, dim) or (batch, nheads, dim) + A: (dim, dstate) or (nheads, dim, dstate) + B: (batch, dstate) or (batch, ngroups, dstate) + C: (batch, dstate) or (batch, ngroups, dstate) + D: (dim,) or (nheads, dim) + z: (batch, dim) or (batch, nheads, dim) + dt_bias: (dim,) or (nheads, dim) + pad_slot_id: int + if cache_indices is passed, lets the kernel identify padded + entries that will not be processed, + for example: cache_indices = [pad_slot_id, 1, 20, pad_slot_id] + in this case, the kernel will not process entries at + indices 0 and 3 + out: Preallocated ssm output tensor. Assume same shape as x. + In-place updated. + """ + if state.dim() == 3: + state = state.unsqueeze(1) + if x.dim() == 2: + x = x.unsqueeze(1) + if dt.dim() == 2: + dt = dt.unsqueeze(1) + if A.dim() == 2: + A = A.unsqueeze(0) + if B.dim() == 2: + B = B.unsqueeze(1) + if C.dim() == 2: + C = C.unsqueeze(1) + if D is not None and D.dim() == 1: + D = D.unsqueeze(0) + if z is not None and z.dim() == 2: + z = z.unsqueeze(1) + if dt_bias is not None and dt_bias.dim() == 1: + dt_bias = dt_bias.unsqueeze(0) + if out.dim() == 2: + out = out.unsqueeze(1) + + _, nheads, dim, dstate = state.shape + batch = x.shape[0] + + assert x.shape == (batch, nheads, dim) + assert dt.shape == x.shape + assert A.shape == (nheads, dim, dstate) + ngroups = B.shape[1] + assert nheads % ngroups == 0, "nheads must be divisible by ngroups" + assert B.shape == (batch, ngroups, dstate) + assert C.shape == B.shape + if D is not None: + assert D.shape == (nheads, dim) + if z is not None: + assert z.shape == x.shape + if dt_bias is not None: + assert dt_bias.shape == (nheads, dim) + if state_batch_indices is not None: + assert state_batch_indices.shape == (batch, ) + assert out.shape == x.shape + + grid = lambda META: (triton.cdiv(dim, META['BLOCK_SIZE_M']), batch, nheads) + z_strides = ((z.stride(0), z.stride(1), z.stride(2)) if z is not None else + (0, 0, 0)) + # We don't want autotune since it will overwrite the state + # We instead tune by hand. + BLOCK_SIZE_M, num_warps = ((32, 4) if dstate <= 16 else + ((16, 4) if dstate <= 32 else + ((8, 4) if dstate <= 64 else + ((4, 4) if dstate <= 128 else ((4, 8)))))) + tie_hdim = A.stride(-1) == 0 and A.stride(-2) == 0 and dt.stride( + -1) == 0 and dt_bias.stride(-1) == 0 + with torch.cuda.device(x.device.index): + _selective_scan_update_kernel[grid]( + state, + x, + dt, + dt_bias, + A, + B, + C, + D, + z, + out, + state_batch_indices, + pad_slot_id, + batch, + nheads, + dim, + dstate, + nheads // ngroups, + state.stride(0), + state.stride(1), + state.stride(2), + state.stride(3), + x.stride(0), + x.stride(1), + x.stride(2), + dt.stride(0), + dt.stride(1), + dt.stride(2), + *(dt_bias.stride(0), + dt_bias.stride(1)) if dt_bias is not None else 0, + A.stride(0), + A.stride(1), + A.stride(2), + B.stride(0), + B.stride(1), + B.stride(2), + C.stride(0), + C.stride(1), + C.stride(2), + *(D.stride(0), D.stride(1)) if D is not None else 0, + z_strides[0], + z_strides[1], + z_strides[2], + out.stride(0), + out.stride(1), + out.stride(2), + dt_softplus, + tie_hdim, + BLOCK_SIZE_M, + num_warps=num_warps, + ) + + +def selective_scan_fn(u, + ssm_states, + delta, + A, + B, + C, + D=None, + z=None, + delta_bias=None, + delta_softplus=False, + query_start_loc=None, + cache_indices=None, + has_initial_state=None, + pad_slot_id=PAD_SLOT_ID) -> torch.Tensor: + """ + u: (dim, total_length) for varlen or (batch, dim, seqlen) + applies changes in place. + ssm_states: (batch, dim, dstate) or (batch, nheads, dim, dstate) + applies changes in place. + delta: (dim, total_length) for varlen or (batch, dim, seqlen) + A: (dim, dstate) + B: (ngroups, dstate, total_length) for varlen or + (batch,ngroups,dstate,seqlen) + C: (ngroups, dstate, total_length) for varlen or + (batch,ngroups,dstate,seqlen) + D: (dim,) + z: (dim, total_length) for varlen or (batch, dim, seqlen) + dt_bias: (dim,) or (dim) + query_start_loc: (batch + 1) int32 + The cumulative sequence lengths of the sequences in + the batch, used to index into sequence. prepended with 0. + for example: query_start_loc = torch.Tensor([0,10,16,17]), + x.shape=(dim,17) + cache_indices: (batch) int32 + A tensor with each cell is a correspondent + input and output ssm_state index + has_initial_state: (batch) bool + A tensor populated with ones and zeros, + indicate if the ssm_state at the corresponding index should be + used as initial state. Not providing argument assumes + there's no initial state + pad_slot_id: int + if cache_indices is passed, lets the kernel identify padding entries + that will not be processed, + for example: cache_indices = [pad_slot_id, 1 ,20 ,pad_slot_id] + in this case, the kernel will not process entries at indices 0 and 3 + returns + output: (dim, total_length) for varlen or (batch, dim, seqlen) + supports inplace replacement + """ + if u.stride(-1) != 1: + u = u.contiguous() + if delta.stride(-1) != 1: + delta = delta.contiguous() + if D is not None: + D = D.contiguous() + if B.stride(-1) != 1: + B = B.contiguous() + if C.stride(-1) != 1: + C = C.contiguous() + if z is not None and z.stride(-1) != 1: + z = z.contiguous() + if B.dim() == 3 and query_start_loc is None: + B = B.unsqueeze(1) + if B.dim() == 2 and query_start_loc is not None: + B = B.unsqueeze(0) + if C.dim() == 3 and query_start_loc is None: + C = C.unsqueeze(1) + if C.dim() == 2 and query_start_loc is not None: + C = C.unsqueeze(0) + + ops.selective_scan_fwd(u, delta, A, B, C, D, z, delta_bias, delta_softplus, + query_start_loc, cache_indices, has_initial_state, + ssm_states, pad_slot_id) + + if z is None: + return delta # output written inplace to delta + else: + return z # output written inplace to z diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/ssd_bmm.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/ssd_bmm.py new file mode 100644 index 0000000000000000000000000000000000000000..11ca1255ebfb6ce633add657cf64bc0f9827361e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/ssd_bmm.py @@ -0,0 +1,262 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +# Copyright (c) 2024, Tri Dao, Albert Gu. +# Adapted from https://github.com/state-spaces/mamba/blob/v2.2.4/mamba_ssm/ops/triton/ssd_bmm.py + +# ruff: noqa: E501,SIM102 + +import math + +import torch + +from vllm.triton_utils import tl, triton + + +@triton.autotune( + configs=[ + triton.Config( + { + 'BLOCK_SIZE_M': 128, + 'BLOCK_SIZE_N': 256, + 'BLOCK_SIZE_K': 64 + }, + num_stages=3, + num_warps=8), + triton.Config( + { + 'BLOCK_SIZE_M': 64, + 'BLOCK_SIZE_N': 256, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=4), + triton.Config( + { + 'BLOCK_SIZE_M': 128, + 'BLOCK_SIZE_N': 128, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=4), + triton.Config( + { + 'BLOCK_SIZE_M': 128, + 'BLOCK_SIZE_N': 64, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=4), + triton.Config( + { + 'BLOCK_SIZE_M': 64, + 'BLOCK_SIZE_N': 128, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=4), + triton.Config( + { + 'BLOCK_SIZE_M': 128, + 'BLOCK_SIZE_N': 32, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=4), + triton.Config( + { + 'BLOCK_SIZE_M': 64, + 'BLOCK_SIZE_N': 32, + 'BLOCK_SIZE_K': 32 + }, + num_stages=5, + num_warps=2), + triton.Config( + { + 'BLOCK_SIZE_M': 32, + 'BLOCK_SIZE_N': 64, + 'BLOCK_SIZE_K': 32 + }, + num_stages=5, + num_warps=2), + triton.Config( + { + 'BLOCK_SIZE_M': 64, + 'BLOCK_SIZE_N': 64, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=2), + ], + key=['chunk_size', 'K', 'IS_CAUSAL'], +) +@triton.jit +def _bmm_chunk_fwd_kernel( + # Pointers to matrices + a_ptr, + b_ptr, + out_ptr, + seq_idx_ptr, + # Matrix dimensions + seqlen, + chunk_size, + K, + ngroups, + stride_a_batch, + stride_a_seqlen, + stride_a_head, + stride_ak, + stride_b_batch, + stride_b_seqlen, + stride_b_head, + stride_bk, + stride_out_batch, + stride_out_chunk, + stride_out_head, + stride_outm, + stride_outn, + stride_seq_idx_batch, + stride_seq_idx_seqlen, + # Meta-parameters + IS_CAUSAL: tl.constexpr, + dot_dtype: tl.constexpr, + HAS_SEQ_IDX: tl.constexpr, + BLOCK_SIZE_M: tl.constexpr, + BLOCK_SIZE_N: tl.constexpr, + BLOCK_SIZE_K: tl.constexpr, +): + pid_b = tl.program_id(axis=1) + pid_ch = tl.program_id(axis=2).to(tl.int64) + pid_c = pid_ch // ngroups + pid_h = pid_ch - pid_c * ngroups + num_pid_n = tl.cdiv(chunk_size, BLOCK_SIZE_N) + pid_m = tl.program_id(axis=0) // num_pid_n + pid_n = tl.program_id(axis=0) % num_pid_n + if IS_CAUSAL: + if pid_n * BLOCK_SIZE_N >= (pid_m + 1) * BLOCK_SIZE_M: + return + a_ptr += pid_b * stride_a_batch + pid_c * chunk_size * stride_a_seqlen + pid_h * stride_a_head + b_ptr += pid_b * stride_b_batch + pid_c * chunk_size * stride_b_seqlen + pid_h * stride_b_head + if HAS_SEQ_IDX: + seq_idx_ptr += pid_b * stride_seq_idx_batch + pid_c * chunk_size * stride_seq_idx_seqlen + + offs_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M) + offs_n = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) + offs_k = tl.arange(0, BLOCK_SIZE_K) + a_ptrs = a_ptr + (offs_m[:, None] * stride_a_seqlen + + offs_k[None, :] * stride_ak) + b_ptrs = b_ptr + (offs_k[:, None] * stride_bk + + offs_n[None, :] * stride_b_seqlen) + chunk_size_limit = min(chunk_size, seqlen - pid_c * chunk_size) + + acc = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32) + for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)): + a = tl.load(a_ptrs, + mask=(offs_m[:, None] < chunk_size_limit) & + (offs_k[None, :] < K - k * BLOCK_SIZE_K), + other=0.0).to(dot_dtype) + b = tl.load(b_ptrs, + mask=(offs_k[:, None] < K - k * BLOCK_SIZE_K) & + (offs_n[None, :] < chunk_size_limit), + other=0.0).to(dot_dtype) + acc += tl.dot(a, b) + a_ptrs += BLOCK_SIZE_K * stride_ak + b_ptrs += BLOCK_SIZE_K * stride_bk + + offs_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M) + offs_n = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) + if HAS_SEQ_IDX: + chunk_size_limit = min(chunk_size, seqlen - pid_c * chunk_size) + seq_idx_m = tl.load(seq_idx_ptr + offs_m * stride_seq_idx_seqlen, + mask=offs_m < chunk_size_limit, + other=-1) + seq_idx_n = tl.load(seq_idx_ptr + offs_n * stride_seq_idx_seqlen, + mask=offs_n < chunk_size_limit, + other=-2) + acc = tl.where(seq_idx_m[:, None] == seq_idx_n[None, :], acc, 0.0) + out = acc.to(out_ptr.dtype.element_ty) + + out_ptr += pid_b * stride_out_batch + pid_c * stride_out_chunk + pid_h * stride_out_head + out_ptrs = out_ptr + (stride_outm * offs_m[:, None] + + offs_n[None, :] * stride_outn) + tl.store(out_ptrs, + out, + mask=(offs_m[:, None] < chunk_size) & + (offs_n[None, :] < chunk_size)) + + +def _bmm_chunk_fwd(a, + b, + chunk_size, + seq_idx=None, + causal=False, + output_dtype=None): + """ + Argument: + a: (batch, seqlen, k) or (batch, seqlen, ngroups, k) + b: (batch, seqlen, k) or (batch, seqlen, ngroups, k) + seq_idx: (batch, seqlen) or None. out[i, j] for seq_idx[i] != seq_idx[j] will be zeroed out. + causal: if True, then out[i, j] for i > j will be arbitrary, only out[i, j] for i <= j are + guaranteed to be correct. + Return: + out: (batch, nchunks, chunk_size, chunk_size) or (batch, nchunks, ngroups, chunk_size, chunk_size) + """ + # Check constraints. + has_groups = a.dim() == 4 + if not has_groups: + batch, seqlen, k = a.shape + else: + batch, seqlen, ngroups, k = a.shape + assert b.shape == a.shape + if seq_idx is not None: + assert seq_idx.shape == (batch, seqlen) + if a.stride(-1) != 1 and a.stride(1) != 1: + a = a.contiguous() + if b.stride(-1) != 1 and b.stride(1) != 1: + b = b.contiguous() + nchunks = math.ceil(seqlen / chunk_size) + # Allocates output. + out_dtype = a.dtype if output_dtype is None else output_dtype + out = torch.empty( + (batch, nchunks, chunk_size, chunk_size) if not has_groups else + (batch, nchunks, ngroups, chunk_size, chunk_size), + device=a.device, + dtype=out_dtype) + dot_dtype = (tl.bfloat16 + if a.dtype == torch.bfloat16 or b.dtype == torch.bfloat16 else + (tl.float16 if a.dtype == torch.float16 + or b.dtype == torch.float16 else tl.float32)) + grid = lambda META: (triton.cdiv( + chunk_size, META['BLOCK_SIZE_M']) * triton.cdiv( + chunk_size, META['BLOCK_SIZE_N']), batch, nchunks + if not has_groups else nchunks * ngroups) + with torch.cuda.device(a.device.index): + _bmm_chunk_fwd_kernel[grid]( + a, + b, + out, + seq_idx, + seqlen, + chunk_size, + k, + ngroups if has_groups else 1, + a.stride(0), + a.stride(1), + 0 if not has_groups else a.stride(2), + a.stride(-1), + b.stride(0), + b.stride(1), + 0 if not has_groups else b.stride(2), + b.stride(-1), + out.stride(0), + out.stride(1), + 0 if not has_groups else out.stride(2), + out.stride(-2), + out.stride(-1), + *((seq_idx.stride(0), + seq_idx.stride(1)) if seq_idx is not None else (0, 0)), + causal, + dot_dtype, + HAS_SEQ_IDX=seq_idx is not None, + ) + return out diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/ssd_chunk_scan.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/ssd_chunk_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..365139e237c66c532d8339511e415e0fc6014626 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/ssd_chunk_scan.py @@ -0,0 +1,571 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +# Copyright (c) 2024, Tri Dao, Albert Gu. +# Adapted from https://github.com/state-spaces/mamba/blob/v2.2.4/mamba_ssm/ops/triton/ssd_chunk_scan.py + +# ruff: noqa: E501,SIM102 + +import torch +from packaging import version + +from vllm.triton_utils import tl, triton + +TRITON_22 = version.parse(triton.__version__) >= version.parse('2.2.0') + + +@triton.autotune( + configs=[ + triton.Config( + { + 'BLOCK_SIZE_M': 128, + 'BLOCK_SIZE_N': 256, + 'BLOCK_SIZE_K': 64 + }, + num_stages=3, + num_warps=8), + triton.Config( + { + 'BLOCK_SIZE_M': 64, + 'BLOCK_SIZE_N': 256, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=4), + triton.Config( + { + 'BLOCK_SIZE_M': 128, + 'BLOCK_SIZE_N': 128, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=4), + triton.Config( + { + 'BLOCK_SIZE_M': 128, + 'BLOCK_SIZE_N': 64, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=4), + triton.Config( + { + 'BLOCK_SIZE_M': 64, + 'BLOCK_SIZE_N': 128, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=4), + triton.Config( + { + 'BLOCK_SIZE_M': 128, + 'BLOCK_SIZE_N': 64, + 'BLOCK_SIZE_K': 64 + }, + num_stages=4, + num_warps=4), + triton.Config( + { + 'BLOCK_SIZE_M': 64, + 'BLOCK_SIZE_N': 128, + 'BLOCK_SIZE_K': 64 + }, + num_stages=4, + num_warps=4), + triton.Config( + { + 'BLOCK_SIZE_M': 128, + 'BLOCK_SIZE_N': 32, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=4), + triton.Config( + { + 'BLOCK_SIZE_M': 64, + 'BLOCK_SIZE_N': 32, + 'BLOCK_SIZE_K': 32 + }, + num_stages=5, + num_warps=2), + triton.Config( + { + 'BLOCK_SIZE_M': 32, + 'BLOCK_SIZE_N': 64, + 'BLOCK_SIZE_K': 32 + }, + num_stages=5, + num_warps=2), + triton.Config( + { + 'BLOCK_SIZE_M': 64, + 'BLOCK_SIZE_N': 64, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=2), + ], + key=['chunk_size', 'hdim', 'dstate', 'IS_CAUSAL'], +) +@triton.jit +def _chunk_scan_fwd_kernel( + # Pointers to matrices + cb_ptr, + x_ptr, + z_ptr, + out_ptr, + out_x_ptr, + dt_ptr, + dA_cumsum_ptr, + seq_idx_ptr, + C_ptr, + states_ptr, + D_ptr, + initstates_ptr, + chunk_indices_ptr, + chunk_offsets_ptr, + chunk_meta_num, + # Matrix dimensions + chunk_size, + hdim, + dstate, + batch, + seqlen, + nheads_ngroups_ratio, + # Strides + stride_cb_batch, + stride_cb_chunk, + stride_cb_head, + stride_cb_csize_m, + stride_cb_csize_k, + stride_x_batch, + stride_x_seqlen, + stride_x_head, + stride_x_hdim, + stride_z_batch, + stride_z_seqlen, + stride_z_head, + stride_z_hdim, + stride_out_batch, + stride_out_seqlen, + stride_out_head, + stride_out_hdim, + stride_dt_batch, + stride_dt_chunk, + stride_dt_head, + stride_dt_csize, + stride_dA_cs_batch, + stride_dA_cs_chunk, + stride_dA_cs_head, + stride_dA_cs_csize, + stride_seq_idx_batch, + stride_seq_idx_seqlen, + stride_C_batch, + stride_C_seqlen, + stride_C_head, + stride_C_dstate, + stride_states_batch, + stride_states_chunk, + stride_states_head, + stride_states_hdim, + stride_states_dstate, + stride_init_states_batch, + stride_init_states_head, + stride_init_states_hdim, + stride_init_states_dstate, + stride_D_head, + # Meta-parameters + IS_CAUSAL: tl.constexpr, + HAS_D: tl.constexpr, + D_HAS_HDIM: tl.constexpr, + HAS_Z: tl.constexpr, + HAS_SEQ_IDX: tl.constexpr, + BLOCK_SIZE_M: tl.constexpr, + BLOCK_SIZE_N: tl.constexpr, + BLOCK_SIZE_K: tl.constexpr, + BLOCK_SIZE_DSTATE: tl.constexpr, + IS_TRITON_22: tl.constexpr, + HAS_INITSTATES: tl.constexpr, +): + pid_bc = tl.program_id(axis=1).to(tl.int64) + pid_c = pid_bc // batch + pid_b = pid_bc - pid_c * batch + if not HAS_INITSTATES: + c_idx = pid_c + c_off = 0 + else: + c_idx = tl.load(chunk_indices_ptr + pid_c, mask=pid_c > -1, other=0) + c_off = tl.load(chunk_offsets_ptr + pid_c, mask=pid_c > -1, other=0) + + pid_h = tl.program_id(axis=2) + num_pid_n = tl.cdiv(hdim, BLOCK_SIZE_N) + pid_m = tl.program_id(axis=0) // num_pid_n + pid_n = tl.program_id(axis=0) % num_pid_n + cb_ptr += pid_b * stride_cb_batch + c_idx * stride_cb_chunk + ( + pid_h // nheads_ngroups_ratio) * stride_cb_head + x_ptr += pid_b * stride_x_batch + c_idx * chunk_size * stride_x_seqlen + pid_h * stride_x_head + dt_ptr += pid_b * stride_dt_batch + c_idx * stride_dt_chunk + pid_h * stride_dt_head + dA_cumsum_ptr += pid_b * stride_dA_cs_batch + c_idx * stride_dA_cs_chunk + pid_h * stride_dA_cs_head + C_ptr += pid_b * stride_C_batch + c_idx * chunk_size * stride_C_seqlen + ( + pid_h // nheads_ngroups_ratio) * stride_C_head + + # M-block offsets and prev states + # - logic in next block may override these if there is an active offset + offs_m = pid_m * BLOCK_SIZE_M + c_off + tl.arange(0, BLOCK_SIZE_M) + prev_states_ptr = states_ptr + pid_b * stride_states_batch + c_idx * stride_states_chunk + pid_h * stride_states_head + prev_states_hdim = stride_states_hdim + prev_states_dstate = stride_states_dstate + + chunk_size_limit = min(chunk_size, seqlen - c_idx * chunk_size) + if HAS_SEQ_IDX: + seq_idx_ptr += pid_b * stride_seq_idx_batch + c_idx * chunk_size * stride_seq_idx_seqlen + + # - we only need seq_idx_prev to be aligned to chunk boundary + seq_idx_prev = tl.load(seq_idx_ptr - stride_seq_idx_seqlen, + mask=c_idx >= 1, + other=0) + + if HAS_INITSTATES: + # if there are init states, we only need seq_idx_m to point + # what is the current seq_idx + + # get current seq idx + if (pid_m * BLOCK_SIZE_M + c_off) < chunk_size_limit: + seq_idx_m = tl.load( + seq_idx_ptr + + (pid_m * BLOCK_SIZE_M + c_off) * stride_seq_idx_seqlen, ) + + # - recall that in ssd_state_passing, for the case c_off == 0 + # i.e., the very first sequence, we made states_ptr hold its initial state + # so this edge case is taken care of + if ((c_off == 0) and + (seq_idx_prev != seq_idx_m + ) # if a seq is changed exactly on boundary + or (c_off > 0) # implies a new example (pseudo chunk) + ): + + # - replace prev_states_ptr with init_states + prev_states_ptr = initstates_ptr + seq_idx_m * stride_init_states_batch + pid_h * stride_init_states_head + prev_states_hdim = stride_init_states_hdim # override strides + prev_states_dstate = stride_init_states_dstate + + offs_n = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) + dA_cs_m = tl.load(dA_cumsum_ptr + offs_m * stride_dA_cs_csize, + mask=offs_m < chunk_size, + other=0.0).to(tl.float32) + + # - handle chunk state limit + if HAS_INITSTATES: + + # have to split this if otherwise compilation will have problems + dA_cs_m_boundary = 0.0 + + # get the c_idx for the next (logica) chunk + c_idx_n = tl.load( + chunk_indices_ptr + (pid_c + 1), + mask=pid_c > -1 and (pid_c + 1) < chunk_meta_num, + other=-1 # to trigger different chunk + ) + + # - there are things to consider + # A. if c_off > 0 then we need to move the dA_cs boundary to ensure correct + # contribution of past states + # B. if c_off_n < chunk_size_limit, then we need to adjust this so as not to + # encroach into the next sequence, where c_off_n is the offset of the next + # (logical) chunk. + # An equivalent check for B is c_idx == c_idx_n, where there is repetition in + # (logical) chunk indices. + + if (c_idx == c_idx_n) or c_off > 0: + + # get the next offset + c_off_n = tl.load(chunk_offsets_ptr + (pid_c + 1), + mask=pid_c > -1 and (pid_c + 1) < chunk_meta_num, + other=chunk_size) + + # in this case, adjust down the chunk_size_limit + if c_idx == c_idx_n: + chunk_size_limit = min(c_off_n, chunk_size_limit) + + # get the cs at the offset boundary + # - c_off == 0 is a passthrough + dA_cs_m_boundary = tl.load( + dA_cumsum_ptr + (c_off - 1) * stride_dA_cs_csize, + mask=(((c_off - 1) > -1) and ((c_off) < chunk_size)), + other=0.0).to(tl.float32) + + if HAS_SEQ_IDX: + # - handle seq idx when HAS_INITSTATES==False + if not HAS_INITSTATES: + seq_idx_m = tl.load(seq_idx_ptr + offs_m * stride_seq_idx_seqlen, + mask=offs_m < chunk_size_limit, + other=-1) + + acc = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32) + + # Without the if (pid_c > -1), with Triton 2.1.0, I get + # Assertion `!(srcMmaLayout && dstMmaLayout) && "Unexpected mma -> mm a layout conversion"' failed. + # With Triton 2.2.0, this works + if IS_TRITON_22 or c_idx > -1: + # Faster to just do 1 iteration with larger BLOCK_SIZE_K, up to block size 128 + offs_k_dstate = tl.arange( + 0, BLOCK_SIZE_DSTATE if BLOCK_SIZE_DSTATE <= 128 else BLOCK_SIZE_K) + C_ptrs = C_ptr + (offs_m[:, None] * stride_C_seqlen + + offs_k_dstate[None, :] * stride_C_dstate) + + prev_states_ptrs = prev_states_ptr + ( + offs_n[None, :] * prev_states_hdim + + offs_k_dstate[:, None] * prev_states_dstate) + if HAS_SEQ_IDX: + + if not HAS_INITSTATES: + # - this is for continuous batching where there is no init states + scale_m = tl.where(seq_idx_m == seq_idx_prev, tl.exp(dA_cs_m), + 0.0) + else: + # - if there is initstates, we will rely on prev_states, no zeroing + # required. + scale_m = tl.exp(dA_cs_m - dA_cs_m_boundary) + else: + scale_m = tl.exp(dA_cs_m) + if BLOCK_SIZE_DSTATE <= 128: + C = tl.load(C_ptrs, + mask=(offs_m[:, None] < chunk_size_limit) & + (offs_k_dstate[None, :] < dstate), + other=0.0) + + prev_states = tl.load(prev_states_ptrs, + mask=(offs_k_dstate[:, None] < dstate) & + (offs_n[None, :] < hdim), + other=0.0) + prev_states = prev_states.to(C_ptr.dtype.element_ty) + acc = tl.dot(C, prev_states) * scale_m[:, None] + else: + for k in range(0, dstate, BLOCK_SIZE_K): + C = tl.load(C_ptrs, + mask=(offs_m[:, None] < chunk_size_limit) & + (offs_k_dstate[None, :] < dstate - k), + other=0.0) + # C = (C * scale_m[:, None]).to(C_ptr.dtype.element_ty) + prev_states = tl.load( + prev_states_ptrs, + mask=(offs_k_dstate[:, None] < dstate - k) & + (offs_n[None, :] < hdim), + other=0.0) + prev_states = prev_states.to(C_ptr.dtype.element_ty) + acc += tl.dot(C, prev_states) + C_ptrs += BLOCK_SIZE_K + prev_states_ptrs += BLOCK_SIZE_K + acc *= scale_m[:, None] + + offs_k = tl.arange(0, BLOCK_SIZE_K) + c_off + cb_ptrs = cb_ptr + (offs_m[:, None] * stride_cb_csize_m + + offs_k[None, :] * stride_cb_csize_k) + x_ptrs = x_ptr + (offs_k[:, None] * stride_x_seqlen + + offs_n[None, :] * stride_x_hdim) + dt_ptrs = dt_ptr + offs_k * stride_dt_csize + dA_cumsum_ptrs = dA_cumsum_ptr + offs_k * stride_dA_cs_csize + K_MAX = chunk_size_limit if not IS_CAUSAL else min( + (pid_m + 1) * BLOCK_SIZE_M, chunk_size_limit) + for k in range(0, K_MAX, BLOCK_SIZE_K): + cb = tl.load(cb_ptrs, + mask=(offs_m[:, None] < chunk_size) & + (offs_k[None, :] < chunk_size - k), + other=0.0).to(tl.float32) + dA_cs_k = tl.load(dA_cumsum_ptrs, + mask=offs_k < chunk_size - k, + other=0.0).to(tl.float32) + # If there's seq_idx, we already set cb[i, j] = 0 for seq_idx[i] != seq_idx[j]. + # So we don't need masking wrt seq_idx here. + cb *= tl.exp(dA_cs_m[:, None] - dA_cs_k[None, :]) + dt_k = tl.load(dt_ptrs, mask=offs_k < chunk_size - k, + other=0.0).to(tl.float32) + cb *= dt_k + if IS_CAUSAL: + mask = offs_m[:, None] >= k + offs_k[None, :] + cb = tl.where(mask, cb, 0.0) + cb = cb.to(x_ptr.dtype.element_ty) + x = tl.load(x_ptrs, + mask=(offs_k[:, None] < chunk_size_limit - k) & + (offs_n[None, :] < hdim), + other=0.0) + acc += tl.dot(cb, x) + cb_ptrs += BLOCK_SIZE_K * stride_cb_csize_k + x_ptrs += BLOCK_SIZE_K * stride_x_seqlen + dt_ptrs += BLOCK_SIZE_K * stride_dt_csize + dA_cumsum_ptrs += BLOCK_SIZE_K * stride_dA_cs_csize + + offs_out_m = pid_m * BLOCK_SIZE_M + c_off + tl.arange(0, BLOCK_SIZE_M) + offs_out_n = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) + + if HAS_D: + if D_HAS_HDIM: + D = tl.load(D_ptr + pid_h * stride_D_head + offs_n, + mask=offs_n < hdim, + other=0.0).to(tl.float32) + else: + D = tl.load(D_ptr + pid_h * stride_D_head).to(tl.float32) + x_residual = tl.load(x_ptr + (offs_m[:, None] * stride_x_seqlen + + offs_n[None, :] * stride_x_hdim), + mask=(offs_m[:, None] < chunk_size_limit) & + (offs_n[None, :] < hdim), + other=0.0).to(tl.float32) + acc += x_residual * D + + if HAS_Z: + out_x_ptr += pid_b * stride_out_batch + c_idx * chunk_size * stride_out_seqlen + pid_h * stride_out_head + out_x_ptrs = out_x_ptr + (stride_out_seqlen * offs_out_m[:, None] + + offs_out_n[None, :]) + tl.store(out_x_ptrs, + acc, + mask=(offs_out_m[:, None] < chunk_size_limit) & + (offs_out_n[None, :] < hdim)) + + z_ptr += pid_b * stride_z_batch + c_idx * chunk_size * stride_z_seqlen + pid_h * stride_z_head + z_ptrs = z_ptr + (stride_z_seqlen * offs_out_m[:, None] + + stride_z_hdim * offs_out_n[None, :]) + z = tl.load(z_ptrs, + mask=(offs_out_m[:, None] < chunk_size_limit) & + (offs_out_n[None, :] < hdim), + other=0.0).to(tl.float32) + acc *= z * tl.sigmoid(z) + + out_ptr += pid_b * stride_out_batch + c_idx * chunk_size * stride_out_seqlen + pid_h * stride_out_head + out_ptrs = out_ptr + (stride_out_seqlen * offs_out_m[:, None] + + offs_out_n[None, :] * stride_out_hdim) + tl.store(out_ptrs, + acc, + mask=(offs_out_m[:, None] < chunk_size_limit) & + (offs_out_n[None, :] < hdim)) + + +def _chunk_scan_fwd( + cb, + x, + dt, + dA_cumsum, + C, + states, + D=None, + z=None, + seq_idx=None, + chunk_indices=None, + chunk_offsets=None, + initial_states=None, + out=None, +): + batch, seqlen, nheads, headdim = x.shape + _, _, nchunks, chunk_size = dt.shape + _, _, ngroups, dstate = C.shape + assert nheads % ngroups == 0 + assert C.shape == (batch, seqlen, ngroups, dstate) + assert cb.shape == (batch, nchunks, ngroups, chunk_size, chunk_size) + if z is not None: + assert z.shape == x.shape + if D is not None: + assert D.shape == (nheads, headdim) or D.shape == (nheads, ) + assert dt.shape == (batch, nheads, nchunks, chunk_size) + assert dA_cumsum.shape == (batch, nheads, nchunks, chunk_size) + assert states.shape == (batch, nchunks, nheads, headdim, dstate) + + if seq_idx is not None: + assert seq_idx.shape == (batch, seqlen) + + if initial_states is not None: + # with initial states, we need to take care of how + # seq_idx crosses the boundaries + assert batch == 1, "chunk scan only supports initial states with batch 1" + assert chunk_indices is not None and chunk_offsets is not None, \ + "chunk_indices and chunk_offsets should have been set" + else: + chunk_indices, chunk_offsets = None, None + else: + chunk_indices, chunk_offsets = None, None + + assert out.shape == x.shape + + if z is not None: + out_x = torch.empty_like(x) + assert out_x.stride() == out.stride() + else: + out_x = None + + grid = lambda META: ( + triton.cdiv(chunk_size, META['BLOCK_SIZE_M']) * triton.cdiv( + headdim, META['BLOCK_SIZE_N']), batch * nchunks + if chunk_offsets is None else len(chunk_offsets), nheads) + z_strides = ((z.stride(0), z.stride(1), z.stride(2), + z.stride(3)) if z is not None else (0, 0, 0, 0)) + _chunk_scan_fwd_kernel[grid]( + cb, + x, + z, + out, + out_x, + dt, + dA_cumsum, + seq_idx, + C, + states, + D, + initial_states, + chunk_indices, + chunk_offsets, + len(chunk_indices) if chunk_indices is not None else 0, + chunk_size, + headdim, + dstate, + batch, + seqlen, + nheads // ngroups, + cb.stride(0), + cb.stride(1), + cb.stride(2), + cb.stride(3), + cb.stride(4), + x.stride(0), + x.stride(1), + x.stride(2), + x.stride(3), + z_strides[0], + z_strides[1], + z_strides[2], + z_strides[3], + out.stride(0), + out.stride(1), + out.stride(2), + out.stride(3), + dt.stride(0), + dt.stride(2), + dt.stride(1), + dt.stride(3), + dA_cumsum.stride(0), + dA_cumsum.stride(2), + dA_cumsum.stride(1), + dA_cumsum.stride(3), + *((seq_idx.stride(0), seq_idx.stride(1)) if seq_idx is not None else + (0, 0)), + C.stride(0), + C.stride(1), + C.stride(2), + C.stride(3), + states.stride(0), + states.stride(1), + states.stride(2), + states.stride(3), + states.stride(4), + *((initial_states.stride(0), initial_states.stride(1), + initial_states.stride(2), + initial_states.stride(3)) if initial_states is not None else + (0, 0, 0, 0)), + D.stride(0) if D is not None else 0, + True, + D is not None, + D.dim() == 2 if D is not None else True, + BLOCK_SIZE_DSTATE=max(triton.next_power_of_2(dstate), 16), + HAS_Z=z is not None, + HAS_SEQ_IDX=seq_idx is not None, + IS_TRITON_22=TRITON_22, + HAS_INITSTATES=initial_states is not None, + ) + return out_x diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/ssd_chunk_state.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/ssd_chunk_state.py new file mode 100644 index 0000000000000000000000000000000000000000..ad58a9918f03c52776cca8bcd08e7fb2872c7d70 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/ssd_chunk_state.py @@ -0,0 +1,751 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +# Copyright (c) 2024, Tri Dao, Albert Gu. +# Adapted from https://github.com/state-spaces/mamba/blob/v2.2.4/mamba_ssm/ops/triton/ssd_chunk_state.py + +# ruff: noqa: E501 + +import math + +import torch + +from vllm.triton_utils import tl, triton + +from .mamba_ssm import softplus + + +@triton.autotune( + configs=[ + triton.Config({'BLOCK_SIZE_H': 1}), + triton.Config({'BLOCK_SIZE_H': 2}), + triton.Config({'BLOCK_SIZE_H': 4}), + triton.Config({'BLOCK_SIZE_H': 8}), + triton.Config({'BLOCK_SIZE_H': 16}), + triton.Config({'BLOCK_SIZE_H': 32}), + triton.Config({'BLOCK_SIZE_H': 64}), + ], + key=['chunk_size', 'nheads'], +) +@triton.jit +def _chunk_cumsum_fwd_kernel( + # Pointers to matrices + dt_ptr, + A_ptr, + dt_bias_ptr, + dt_out_ptr, + dA_cumsum_ptr, + # Matrix dimension + batch, + seqlen, + nheads, + chunk_size, + dt_min, + dt_max, + # Strides + stride_dt_batch, + stride_dt_seqlen, + stride_dt_head, + stride_A_head, + stride_dt_bias_head, + stride_dt_out_batch, + stride_dt_out_chunk, + stride_dt_out_head, + stride_dt_out_csize, + stride_dA_cs_batch, + stride_dA_cs_chunk, + stride_dA_cs_head, + stride_dA_cs_csize, + # Meta-parameters + DT_SOFTPLUS: tl.constexpr, + HAS_DT_BIAS: tl.constexpr, + BLOCK_SIZE_H: tl.constexpr, + BLOCK_SIZE_CHUNK: tl.constexpr, +): + pid_b = tl.program_id(axis=0) + + # if dt is long, may cause problems, so use 64 bit + # https://github.com/triton-lang/triton/issues/1058 + pid_c = tl.program_id(axis=1).to(tl.int64) + pid_h = tl.program_id(axis=2) + dt_ptr += pid_b * stride_dt_batch + pid_c * chunk_size * stride_dt_seqlen + dt_out_ptr += pid_b * stride_dt_out_batch + pid_c * stride_dt_out_chunk + dA_cumsum_ptr += pid_b * stride_dA_cs_batch + pid_c * stride_dA_cs_chunk + + offs_h = pid_h * BLOCK_SIZE_H + tl.arange(0, BLOCK_SIZE_H) + offs_c = tl.arange(0, BLOCK_SIZE_CHUNK) + dt_ptrs = dt_ptr + (offs_h[:, None] * stride_dt_head + + offs_c[None, :] * stride_dt_seqlen) + A_ptrs = A_ptr + offs_h * stride_A_head + dt_out_ptrs = dt_out_ptr + (offs_h[:, None] * stride_dt_out_head + + offs_c[None, :] * stride_dt_out_csize) + dA_cs_ptrs = dA_cumsum_ptr + (offs_h[:, None] * stride_dA_cs_head + + offs_c[None, :] * stride_dA_cs_csize) + chunk_size_limit = min(chunk_size, seqlen - pid_c * chunk_size) + + dt = tl.load(dt_ptrs, + mask=(offs_h[:, None] < nheads) & + (offs_c[None, :] < chunk_size_limit), + other=0.0).to(tl.float32) + if HAS_DT_BIAS: + dt_bias = tl.load(dt_bias_ptr + offs_h * stride_dt_bias_head, + mask=offs_h < nheads, + other=0.0).to(tl.float32) + dt += dt_bias[:, None] + if DT_SOFTPLUS: + dt = tl.where(dt <= 20.0, softplus(dt), dt) + # As of Triton 2.2.0, tl.clamp is not available yet + # dt = tl.clamp(dt, dt_min, dt_max) + dt = tl.minimum(tl.maximum(dt, dt_min), dt_max) + dt = tl.where( + (offs_h[:, None] < nheads) & (offs_c[None, :] < chunk_size_limit), dt, + 0.0) + tl.store(dt_out_ptrs, + dt, + mask=(offs_h[:, None] < nheads) & (offs_c[None, :] < chunk_size)) + A = tl.load(A_ptrs, mask=offs_h < nheads, other=0.0).to(tl.float32) + dA = dt * A[:, None] + dA_cs = tl.cumsum(dA, axis=1) + tl.store(dA_cs_ptrs, + dA_cs, + mask=(offs_h[:, None] < nheads) & (offs_c[None, :] < chunk_size)) + + +@triton.autotune( + configs=[ + triton.Config( + { + 'BLOCK_SIZE_M': 128, + 'BLOCK_SIZE_N': 256, + 'BLOCK_SIZE_K': 64 + }, + num_stages=3, + num_warps=8), + triton.Config( + { + 'BLOCK_SIZE_M': 64, + 'BLOCK_SIZE_N': 256, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=4), + triton.Config( + { + 'BLOCK_SIZE_M': 128, + 'BLOCK_SIZE_N': 128, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=4), + triton.Config( + { + 'BLOCK_SIZE_M': 128, + 'BLOCK_SIZE_N': 64, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=4), + triton.Config( + { + 'BLOCK_SIZE_M': 64, + 'BLOCK_SIZE_N': 128, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=4), + triton.Config( + { + 'BLOCK_SIZE_M': 128, + 'BLOCK_SIZE_N': 32, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=4), + triton.Config( + { + 'BLOCK_SIZE_M': 64, + 'BLOCK_SIZE_N': 32, + 'BLOCK_SIZE_K': 32 + }, + num_stages=5, + num_warps=2), + triton.Config( + { + 'BLOCK_SIZE_M': 32, + 'BLOCK_SIZE_N': 64, + 'BLOCK_SIZE_K': 32 + }, + num_stages=5, + num_warps=2), + triton.Config( + { + 'BLOCK_SIZE_M': 64, + 'BLOCK_SIZE_N': 64, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=2), + ], + key=['hdim', 'dstate', 'chunk_size'], +) +@triton.jit +def _chunk_state_fwd_kernel( + # Pointers to matrices + x_ptr, + b_ptr, + states_ptr, + dt_ptr, + dA_cumsum_ptr, + seq_idx_ptr, + # Matrix dimensions + hdim, + dstate, + chunk_size, + batch, + seqlen, + nheads_ngroups_ratio, + # Strides + stride_x_batch, + stride_x_seqlen, + stride_x_head, + stride_x_hdim, + stride_b_batch, + stride_b_seqlen, + stride_b_head, + stride_b_dstate, + stride_states_batch, + stride_states_chunk, + stride_states_head, + stride_states_hdim, + stride_states_dstate, + stride_dt_batch, + stride_dt_chunk, + stride_dt_head, + stride_dt_csize, + stride_dA_cs_batch, + stride_dA_cs_chunk, + stride_dA_cs_head, + stride_dA_cs_csize, + stride_seq_idx_batch, + stride_seq_idx_seqlen, + # Meta-parameters + HAS_SEQ_IDX: tl.constexpr, + BLOCK_SIZE_M: tl.constexpr, + BLOCK_SIZE_N: tl.constexpr, + BLOCK_SIZE_K: tl.constexpr, +): + pid_bc = tl.program_id(axis=1).to(tl.int64) + pid_c = pid_bc // batch + pid_b = pid_bc - pid_c * batch + pid_h = tl.program_id(axis=2) + num_pid_n = tl.cdiv(dstate, BLOCK_SIZE_N) + pid_m = tl.program_id(axis=0) // num_pid_n + pid_n = tl.program_id(axis=0) % num_pid_n + b_ptr += pid_b * stride_b_batch + pid_c * chunk_size * stride_b_seqlen + ( + pid_h // nheads_ngroups_ratio) * stride_b_head + x_ptr += pid_b * stride_x_batch + pid_c * chunk_size * stride_x_seqlen + pid_h * stride_x_head + dt_ptr += pid_b * stride_dt_batch + pid_c * stride_dt_chunk + pid_h * stride_dt_head + dA_cumsum_ptr += pid_b * stride_dA_cs_batch + pid_c * stride_dA_cs_chunk + pid_h * stride_dA_cs_head + if HAS_SEQ_IDX: + seq_idx_ptr += pid_b * stride_seq_idx_batch + pid_c * chunk_size * stride_seq_idx_seqlen + + offs_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M) + offs_n = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) + offs_k = tl.arange(0, BLOCK_SIZE_K) + x_ptrs = x_ptr + (offs_m[:, None] * stride_x_hdim + + offs_k[None, :] * stride_x_seqlen) + b_ptrs = b_ptr + (offs_n[None, :] * stride_b_dstate + + offs_k[:, None] * stride_b_seqlen) + dt_ptrs = dt_ptr + offs_k * stride_dt_csize + dA_cs_last = tl.load(dA_cumsum_ptr + + (chunk_size - 1) * stride_dA_cs_csize).to(tl.float32) + dA_cumsum_ptrs = dA_cumsum_ptr + offs_k * stride_dA_cs_csize + if HAS_SEQ_IDX: + seq_idx_ptrs = seq_idx_ptr + offs_k * stride_seq_idx_seqlen + + chunk_size_limit = min(chunk_size, seqlen - pid_c * chunk_size) + if HAS_SEQ_IDX: + seq_idx_last = tl.load(seq_idx_ptr + + (chunk_size_limit - 1) * stride_seq_idx_seqlen) + + acc = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32) + for k in range(0, chunk_size_limit, BLOCK_SIZE_K): + x = tl.load(x_ptrs, + mask=(offs_m[:, None] < hdim) & + (offs_k[None, :] < chunk_size_limit - k), + other=0.0) + b = tl.load(b_ptrs, + mask=(offs_k[:, None] < chunk_size_limit - k) & + (offs_n[None, :] < dstate), + other=0.0).to(tl.float32) + dA_cs_k = tl.load(dA_cumsum_ptrs, + mask=offs_k < chunk_size_limit - k, + other=0.0).to(tl.float32) + if HAS_SEQ_IDX: + seq_idx_k = tl.load(seq_idx_ptrs, + mask=offs_k < chunk_size_limit - k, + other=-1) + dt_k = tl.load(dt_ptrs, mask=offs_k < chunk_size_limit - k, + other=0.0).to(tl.float32) + if not HAS_SEQ_IDX: + scale = tl.exp(dA_cs_last - dA_cs_k) * dt_k + else: + scale = tl.where(seq_idx_k == seq_idx_last, + tl.exp(dA_cs_last - dA_cs_k) * dt_k, 0.0) + b *= scale[:, None] + b = b.to(x_ptr.dtype.element_ty) + acc += tl.dot(x, b) + x_ptrs += BLOCK_SIZE_K * stride_x_seqlen + b_ptrs += BLOCK_SIZE_K * stride_b_seqlen + dt_ptrs += BLOCK_SIZE_K * stride_dt_csize + dA_cumsum_ptrs += BLOCK_SIZE_K * stride_dA_cs_csize + if HAS_SEQ_IDX: + seq_idx_ptrs += BLOCK_SIZE_K * stride_seq_idx_seqlen + states = acc.to(states_ptr.dtype.element_ty) + + states_ptr += pid_b * stride_states_batch + pid_c * stride_states_chunk + pid_h * stride_states_head + offs_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M) + offs_n = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) + states_ptrs = states_ptr + (offs_m[:, None] * stride_states_hdim + + offs_n[None, :] * stride_states_dstate) + c_mask = (offs_m[:, None] < hdim) & (offs_n[None, :] < dstate) + tl.store(states_ptrs, states, mask=c_mask) + + +@triton.autotune( + configs=[ + triton.Config( + { + 'BLOCK_SIZE_M': 128, + 'BLOCK_SIZE_N': 256, + 'BLOCK_SIZE_K': 64 + }, + num_stages=3, + num_warps=8), + triton.Config( + { + 'BLOCK_SIZE_M': 64, + 'BLOCK_SIZE_N': 256, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=4), + triton.Config( + { + 'BLOCK_SIZE_M': 128, + 'BLOCK_SIZE_N': 128, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=4), + triton.Config( + { + 'BLOCK_SIZE_M': 128, + 'BLOCK_SIZE_N': 64, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=4), + triton.Config( + { + 'BLOCK_SIZE_M': 64, + 'BLOCK_SIZE_N': 128, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=4), + triton.Config( + { + 'BLOCK_SIZE_M': 128, + 'BLOCK_SIZE_N': 32, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=4), + triton.Config( + { + 'BLOCK_SIZE_M': 64, + 'BLOCK_SIZE_N': 32, + 'BLOCK_SIZE_K': 32 + }, + num_stages=5, + num_warps=2), + triton.Config( + { + 'BLOCK_SIZE_M': 32, + 'BLOCK_SIZE_N': 64, + 'BLOCK_SIZE_K': 32 + }, + num_stages=5, + num_warps=2), + triton.Config( + { + 'BLOCK_SIZE_M': 64, + 'BLOCK_SIZE_N': 64, + 'BLOCK_SIZE_K': 32 + }, + num_stages=4, + num_warps=2), + ], + key=['hdim', 'dstate', 'chunk_size'], +) +@triton.jit +def _chunk_state_varlen_kernel( + # Pointers to matrices + x_ptr, + b_ptr, + dt_ptr, + dA_cumsum_ptr, + chunk_states_ptr, + cu_seqlens_ptr, + states_ptr, + initstates_ptr, + # Matrix dimensions + hdim, + dstate, + chunk_size, + seqlen, + nheads_ngroups_ratio, + # Strides + stride_x_seqlen, + stride_x_head, + stride_x_hdim, + stride_b_seqlen, + stride_b_head, + stride_b_dstate, + stride_dt_chunk, + stride_dt_head, + stride_dt_csize, + stride_dA_cs_chunk, + stride_dA_cs_head, + stride_dA_cs_csize, + stride_chunk_states_chunk, + stride_chunk_states_head, + stride_chunk_states_hdim, + stride_chunk_states_dstate, + stride_states_batch, + stride_states_head, + stride_states_hdim, + stride_states_dstate, + stride_init_states_batch, + stride_init_states_head, + stride_init_states_hdim, + stride_init_states_dstate, + # Meta-parameters + BLOCK_SIZE_M: tl.constexpr, + BLOCK_SIZE_N: tl.constexpr, + BLOCK_SIZE_K: tl.constexpr, + HAS_INITSTATES: tl.constexpr, +): + pid_b = tl.program_id(axis=1) + pid_h = tl.program_id(axis=2) + num_pid_n = tl.cdiv(dstate, BLOCK_SIZE_N) + pid_m = tl.program_id(axis=0) // num_pid_n + pid_n = tl.program_id(axis=0) % num_pid_n + end_idx = tl.load(cu_seqlens_ptr + pid_b + 1) + pid_c = (end_idx - 1) // chunk_size + b_ptr += pid_c * chunk_size * stride_b_seqlen + ( + pid_h // nheads_ngroups_ratio) * stride_b_head + x_ptr += pid_c * chunk_size * stride_x_seqlen + pid_h * stride_x_head + dt_ptr += pid_c * stride_dt_chunk + pid_h * stride_dt_head + dA_cumsum_ptr += pid_c * stride_dA_cs_chunk + pid_h * stride_dA_cs_head + chunk_states_ptr += pid_c * stride_chunk_states_chunk + pid_h * stride_chunk_states_head + + if HAS_INITSTATES: + # if there are init states provided, we differentiate between states (which + # are boundary conditions at a chunk boundary) and initstates (which are boundary + # conditions when a new example in a cont batch starts) + initstates_ptr += pid_h * stride_init_states_head + + offs_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M) + offs_n = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) + offs_k = tl.arange(0, BLOCK_SIZE_K) + x_ptrs = x_ptr + (offs_m[:, None] * stride_x_hdim + + offs_k[None, :] * stride_x_seqlen) + b_ptrs = b_ptr + (offs_n[None, :] * stride_b_dstate + + offs_k[:, None] * stride_b_seqlen) + dt_ptrs = dt_ptr + offs_k * stride_dt_csize + dA_cs_last = tl.load(dA_cumsum_ptr + (end_idx - pid_c * chunk_size - 1) * + stride_dA_cs_csize).to(tl.float32) + dA_cumsum_ptrs = dA_cumsum_ptr + offs_k * stride_dA_cs_csize + + chunk_size_limit = end_idx - pid_c * chunk_size + start_idx = tl.load(cu_seqlens_ptr + pid_b) + start_idx_cur = tl.maximum(start_idx - pid_c * chunk_size, 0) + + acc = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32) + for k in range(0, chunk_size_limit, BLOCK_SIZE_K): + x = tl.load(x_ptrs, + mask=(offs_m[:, None] < hdim) & + (offs_k[None, :] < chunk_size_limit - k) & + (offs_k[None, :] >= start_idx_cur - k), + other=0.0) + b = tl.load(b_ptrs, + mask=(offs_k[:, None] < chunk_size_limit - k) & + (offs_n[None, :] < dstate) & + (offs_k[:, None] >= start_idx_cur - k), + other=0.0).to(tl.float32) + dA_cs_k = tl.load(dA_cumsum_ptrs, + mask=offs_k < chunk_size_limit - k, + other=0.0).to(tl.float32) + dt_k = tl.load(dt_ptrs, mask=offs_k < chunk_size_limit - k, + other=0.0).to(tl.float32) + scale = tl.where( + (offs_k >= start_idx_cur - k) & (offs_k < chunk_size_limit - k), + tl.exp(dA_cs_last - dA_cs_k) * dt_k, 0.0) + b *= scale[:, None] + b = b.to(x_ptr.dtype.element_ty) + acc += tl.dot(x, b) + x_ptrs += BLOCK_SIZE_K * stride_x_seqlen + b_ptrs += BLOCK_SIZE_K * stride_b_seqlen + dt_ptrs += BLOCK_SIZE_K * stride_dt_csize + dA_cumsum_ptrs += BLOCK_SIZE_K * stride_dA_cs_csize + + # If the sequence starts after the last chunk idx, we don't need to add the contribution from the last chunk + # If HAS_INITSTATES==True need to consider two possiblties + # - if start_idx < pid_c * chunk_size, then we need to take the past_states_ptrs + # - if state_idx >= pid * chunk_size, then we need to insert initstates + if ((start_idx < pid_c * chunk_size) # first chunk + or (HAS_INITSTATES)): + + dA_cs_boundary = 0.0 # default + + if not HAS_INITSTATES: + past_states_ptrs = chunk_states_ptr + ( + offs_m[:, None] * stride_chunk_states_hdim + + offs_n[None, :] * stride_chunk_states_dstate) + else: + + # - this seems repetitive, buts its to help the compiler + if start_idx < pid_c * chunk_size: + past_states_ptrs = chunk_states_ptr + ( + offs_m[:, None] * stride_chunk_states_hdim + + offs_n[None, :] * stride_chunk_states_dstate) + else: + past_states_ptrs = initstates_ptr + ( + pid_b * stride_init_states_batch + + offs_m[:, None] * stride_init_states_hdim + + offs_n[None, :] * stride_init_states_dstate) + + # need to adjust the boundary + if start_idx > pid_c * chunk_size: + dA_cs_boundary = tl.load(dA_cumsum_ptr + + (start_idx - pid_c * chunk_size - + 1) * stride_dA_cs_csize).to( + tl.float32) + + past_states = tl.load(past_states_ptrs, + mask=(offs_m[:, None] < hdim) & + (offs_n[None, :] < dstate), + other=0.0).to(tl.float32) + + scale = tl.exp(dA_cs_last - dA_cs_boundary) + acc += past_states * scale + + states = acc.to(states_ptr.dtype.element_ty) + + states_ptr += pid_b * stride_states_batch + pid_h * stride_states_head + offs_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M) + offs_n = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) + states_ptrs = states_ptr + (offs_m[:, None] * stride_states_hdim + + offs_n[None, :] * stride_states_dstate) + c_mask = (offs_m[:, None] < hdim) & (offs_n[None, :] < dstate) + tl.store(states_ptrs, states, mask=c_mask) + + +def _chunk_cumsum_fwd(dt, + A, + chunk_size, + dt_bias=None, + dt_softplus=False, + dt_limit=(0.0, float("inf"))): + batch, seqlen, nheads = dt.shape + assert A.shape == (nheads, ) + if dt_bias is not None: + assert dt_bias.shape == (nheads, ) + nchunks = math.ceil(seqlen / chunk_size) + dt_out = torch.empty(batch, + nheads, + nchunks, + chunk_size, + device=dt.device, + dtype=torch.float32) + dA_cumsum = torch.empty(batch, + nheads, + nchunks, + chunk_size, + device=dt.device, + dtype=torch.float32) + grid_chunk_cs = lambda META: (batch, nchunks, + triton.cdiv(nheads, META['BLOCK_SIZE_H'])) + with torch.cuda.device(dt.device.index): + _chunk_cumsum_fwd_kernel[grid_chunk_cs]( + dt, + A, + dt_bias, + dt_out, + dA_cumsum, + batch, + seqlen, + nheads, + chunk_size, + dt_limit[0], + dt_limit[1], + dt.stride(0), + dt.stride(1), + dt.stride(2), + A.stride(0), + dt_bias.stride(0) if dt_bias is not None else 0, + dt_out.stride(0), + dt_out.stride(2), + dt_out.stride(1), + dt_out.stride(3), + dA_cumsum.stride(0), + dA_cumsum.stride(2), + dA_cumsum.stride(1), + dA_cumsum.stride(3), + dt_softplus, + HAS_DT_BIAS=dt_bias is not None, + BLOCK_SIZE_CHUNK=triton.next_power_of_2(chunk_size), + ) + return dA_cumsum, dt_out + + +def _chunk_state_fwd(B, + x, + dt, + dA_cumsum, + seq_idx=None, + states=None, + states_in_fp32=True): + batch, seqlen, nheads, headdim = x.shape + _, _, nchunks, chunk_size = dt.shape + _, _, ngroups, dstate = B.shape + assert nheads % ngroups == 0 + assert B.shape == (batch, seqlen, ngroups, dstate) + assert dt.shape == (batch, nheads, nchunks, chunk_size) + assert dA_cumsum.shape == dt.shape + if seq_idx is not None: + assert seq_idx.shape == (batch, seqlen) + if states is not None: + assert states.shape == (batch, nchunks, nheads, headdim, dstate) + else: + states_dtype = torch.float32 if states_in_fp32 else B.dtype + states = torch.empty((batch, nchunks, nheads, headdim, dstate), + device=x.device, + dtype=states_dtype) + grid = lambda META: ( + triton.cdiv(headdim, META['BLOCK_SIZE_M']) * triton.cdiv( + dstate, META['BLOCK_SIZE_N']), batch * nchunks, nheads) + with torch.cuda.device(x.device.index): + _chunk_state_fwd_kernel[grid]( + x, + B, + states, + dt, + dA_cumsum, + seq_idx, + headdim, + dstate, + chunk_size, + batch, + seqlen, + nheads // ngroups, + x.stride(0), + x.stride(1), + x.stride(2), + x.stride(3), + B.stride(0), + B.stride(1), + B.stride(2), + B.stride(-1), + states.stride(0), + states.stride(1), + states.stride(2), + states.stride(3), + states.stride(4), + dt.stride(0), + dt.stride(2), + dt.stride(1), + dt.stride(3), + dA_cumsum.stride(0), + dA_cumsum.stride(2), + dA_cumsum.stride(1), + dA_cumsum.stride(3), + *((seq_idx.stride(0), + seq_idx.stride(1)) if seq_idx is not None else (0, 0)), + HAS_SEQ_IDX=seq_idx is not None, + ) + return states + + +def chunk_state_varlen(B, + x, + dt, + dA_cumsum, + cu_seqlens, + chunk_states, + initial_states=None): + total_seqlen, nheads, headdim = x.shape + _, nchunks, chunk_size = dt.shape + _, ngroups, dstate = B.shape + batch = cu_seqlens.shape[0] - 1 + cu_seqlens = cu_seqlens.contiguous() + assert nheads % ngroups == 0 + assert B.shape == (total_seqlen, ngroups, dstate) + assert dt.shape == (nheads, nchunks, chunk_size) + assert dA_cumsum.shape == dt.shape + assert chunk_states.shape == (nchunks, nheads, headdim, dstate) + + if initial_states is not None: + assert initial_states.shape == (batch, nheads, headdim, dstate) + + states = torch.empty(batch, + nheads, + headdim, + dstate, + dtype=chunk_states.dtype, + device=chunk_states.device) + grid = lambda META: (triton.cdiv(headdim, META['BLOCK_SIZE_M']) * triton. + cdiv(dstate, META['BLOCK_SIZE_N']), batch, nheads) + with torch.cuda.device(x.device.index): + _chunk_state_varlen_kernel[grid]( + x, + B, + dt, + dA_cumsum, + chunk_states, + cu_seqlens, + states, + initial_states, + headdim, + dstate, + chunk_size, + total_seqlen, + nheads // ngroups, + x.stride(0), + x.stride(1), + x.stride(2), + B.stride(0), + B.stride(1), + B.stride(2), + dt.stride(1), + dt.stride(0), + dt.stride(2), + dA_cumsum.stride(1), + dA_cumsum.stride(0), + dA_cumsum.stride(2), + chunk_states.stride(0), + chunk_states.stride(1), + chunk_states.stride(2), + chunk_states.stride(3), + states.stride(0), + states.stride(1), + states.stride(2), + states.stride(3), + *((initial_states.stride(0), initial_states.stride(1), + initial_states.stride(2), + initial_states.stride(3)) if initial_states is not None else + (0, 0, 0, 0)), + HAS_INITSTATES=initial_states is not None) + return states diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/ssd_state_passing.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/ssd_state_passing.py new file mode 100644 index 0000000000000000000000000000000000000000..a28fc9ffad71b5a4d42cc7bac70ff1c82860bb03 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/mamba/ops/ssd_state_passing.py @@ -0,0 +1,206 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +# Copyright (c) 2024, Tri Dao, Albert Gu. +# Adapted from https://github.com/state-spaces/mamba/blob/v2.2.4/mamba_ssm/ops/triton/ssd_state_passing.py + +# ruff: noqa: E501 + +import torch + +from vllm.triton_utils import tl, triton + + +@triton.autotune( + configs=[ + triton.Config({'BLOCK_SIZE': 64}), + triton.Config({'BLOCK_SIZE': 128}), + triton.Config({'BLOCK_SIZE': 256}), + triton.Config({'BLOCK_SIZE': 512}), + triton.Config({'BLOCK_SIZE': 1024}), + triton.Config({'BLOCK_SIZE': 2048}), + ], + key=['dim'], +) +@triton.jit +def _state_passing_fwd_kernel( + # Pointers to matrices + states_ptr, + out_ptr, + final_states_ptr, + dA_cs_ptr, + initstates_ptr, + seq_idx_ptr, + # Matrix dimensions + dim, + nchunks, + seqlen, + chunk_size, + # Strides + stride_states_batch, + stride_states_chunk, + stride_states_head, + stride_states_dim, + stride_out_batch, + stride_out_chunk, + stride_out_head, + stride_out_dim, + stride_final_states_batch, + stride_final_states_head, + stride_final_states_dim, + stride_dA_cs_batch, + stride_dA_cs_chunk, + stride_dA_cs_head, + stride_initstates_batch, + stride_initstates_head, + stride_initstates_dim, + stride_seq_idx_batch, + stride_seq_idx_seqlen, + # Meta-parameters + HAS_INITSTATES: tl.constexpr, + HAS_SEQ_IDX: tl.constexpr, + IS_CONT_BATCHED: tl.constexpr, + BLOCK_SIZE: tl.constexpr, +): + pid_b = tl.program_id(axis=1) + pid_h = tl.program_id(axis=2) + pid_m = tl.program_id(axis=0) + states_ptr += pid_b * stride_states_batch + pid_h * stride_states_head + dA_cs_ptr += pid_b * stride_dA_cs_batch + pid_h * stride_dA_cs_head + out_ptr += pid_b * stride_out_batch + pid_h * stride_out_head + final_states_ptr += pid_b * stride_final_states_batch + pid_h * stride_final_states_head + if HAS_INITSTATES: + initstates_ptr += pid_h * stride_initstates_head + if not IS_CONT_BATCHED: + initstates_ptr += pid_b * stride_initstates_batch + + if HAS_SEQ_IDX: + seq_idx_ptr += pid_b * stride_seq_idx_batch + + offs_m = pid_m * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) + states_ptrs = states_ptr + offs_m * stride_states_dim + out_ptrs = out_ptr + offs_m * stride_out_dim + final_states_ptrs = final_states_ptr + offs_m * stride_final_states_dim + + # - states will be the past state of the sequence that continues on the current check + if not HAS_INITSTATES: + states = tl.zeros((BLOCK_SIZE, ), dtype=tl.float32) + else: + initstates_ptr += offs_m * stride_initstates_dim + initstates_ptrs = initstates_ptr + # - for cont batches, for the first chunk mean it will be the first batch's + # init state + states = tl.load(initstates_ptrs, mask=offs_m < dim, + other=0.0).to(tl.float32) + + tl.store(out_ptrs, states, mask=offs_m < dim) + out_ptrs += stride_out_chunk + seq_idx = 0 + for c in range(nchunks): + new_states = tl.load(states_ptrs, mask=offs_m < dim, + other=0.0).to(tl.float32) + dA_cs = tl.load(dA_cs_ptr).to(tl.float32) + scale = tl.exp(dA_cs) + if HAS_SEQ_IDX: + # - the seq to pass forward is the one that is flushed to the right + # boundary. + # - that is given by seq_idx_new below. + seq_idx_new = tl.load(seq_idx_ptr + + (min((c + 1) * chunk_size, seqlen) - 1) * + stride_seq_idx_seqlen) + if HAS_INITSTATES: + if IS_CONT_BATCHED and seq_idx != seq_idx_new: + # this means in the current chunk the rightmost flushed seq + # has changed. + # - so we do not propagate the state from previous chunk + # - but rather we load that sequence's init state + initstates_ptrs = initstates_ptr + seq_idx_new * stride_initstates_batch + + # - update state with seq_idx_new's init state + states = tl.load(initstates_ptrs, + mask=offs_m < dim, + other=0.0).to(tl.float32) + else: + scale = tl.where(seq_idx_new == seq_idx, scale, 0.0) + + seq_idx = seq_idx_new + states = scale * states + new_states + if c < nchunks - 1: + tl.store(out_ptrs, states, mask=offs_m < dim) + else: + tl.store(final_states_ptrs, states, mask=offs_m < dim) + states_ptrs += stride_states_chunk + dA_cs_ptr += stride_dA_cs_chunk + out_ptrs += stride_out_chunk + + +def _state_passing_fwd( + states, + dA_chunk_cumsum, + initial_states=None, + seq_idx=None, + chunk_size=None, + out_dtype=None, + is_cont_batched=False, +): + batch, nchunks, nheads, dim = states.shape + assert dA_chunk_cumsum.shape == (batch, nheads, nchunks) + if initial_states is not None: + if is_cont_batched: + # - if cu_seqlens is provided, then the initial states + # are used for continuous batching. In which case we + # require seq_idx to be provided + assert seq_idx is not None, "" + else: + # - this is the regular batching case, where initial + # states are used are for each example of the batch. + assert initial_states.shape == (batch, nheads, dim) + + if seq_idx is not None: + assert chunk_size is not None + seqlen = seq_idx.shape[-1] + assert seq_idx.shape == (batch, seqlen) + out_dtype = states.dtype if out_dtype is None else out_dtype + out = torch.empty((batch, nchunks, nheads, dim), + device=states.device, + dtype=out_dtype) + final_states = torch.empty((batch, nheads, dim), + device=states.device, + dtype=torch.float32) + grid = lambda META: (triton.cdiv(dim, META['BLOCK_SIZE']), batch, nheads) + with torch.cuda.device(states.device.index): + _state_passing_fwd_kernel[grid]( + states, + out, + final_states, + dA_chunk_cumsum, + initial_states, + seq_idx, + dim, + nchunks, + seqlen if seq_idx is not None else 0, + chunk_size if seq_idx is not None else 0, + states.stride(0), + states.stride(1), + states.stride(2), + states.stride(3), + out.stride(0), + out.stride(1), + out.stride(2), + out.stride(3), + final_states.stride(0), + final_states.stride(1), + final_states.stride(2), + dA_chunk_cumsum.stride(0), + dA_chunk_cumsum.stride(2), + dA_chunk_cumsum.stride(1), + *((initial_states.stride(0), initial_states.stride(1), + initial_states.stride(2)) if initial_states is not None else + (0, 0, 0)), + *((seq_idx.stride(0), + seq_idx.stride(1)) if seq_idx is not None else (0, 0)), + HAS_INITSTATES=initial_states is not None, + HAS_SEQ_IDX=seq_idx is not None, + IS_CONT_BATCHED=is_cont_batched, + ) + return out, final_states diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/auto_round.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/auto_round.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a163a09d651adcda083b5c278841e1b7faa39399 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/auto_round.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/awq.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/awq.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5af040ba35e695ccf858554ff7651d93136479b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/awq.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/awq_triton.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/awq_triton.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f5e0a5fbe9030b38ed6b55c4daa25765df95f6e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/awq_triton.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/base_config.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/base_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55a38fb9a69d6c8d9040b8c44a8c06bb1381ad0e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/base_config.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/bitblas.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/bitblas.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9eac9b26b951f1a576118e9dd537f77a1a8ee816 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/bitblas.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/bitsandbytes.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/bitsandbytes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b81bd2d61ecab4ebe806292917fe8d44388e5134 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/bitsandbytes.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/experts_int8.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/experts_int8.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b99e22fee05c1c838690dccaf726f1dcec2e77d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/experts_int8.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/fbgemm_fp8.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/fbgemm_fp8.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e253dc2e715b030fdff993789f429674b9422f5 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/fbgemm_fp8.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/fp8.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/fp8.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75d8f7ea3caff0f7a29257bfa642e3814dc010d3 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/fp8.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/gguf.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/gguf.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2067d68533fe3e61d23fcbf13ff5a65aac1ba67 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/gguf.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/gptq.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/gptq.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1cc50849a4f9ebf9d3bb1df83f1da9affa914192 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/gptq.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/gptq_bitblas.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/gptq_bitblas.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..363f830cd3847d52568e50f2e9bcdced7b403f97 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/gptq_bitblas.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/gptq_marlin.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/gptq_marlin.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0fbe573b1d73fc5ec374c7767abdb190d314c41a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/gptq_marlin.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/gptq_marlin_24.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/gptq_marlin_24.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fda93f7d8cce15377cd6f57fb511be735080cbbc Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/gptq_marlin_24.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/hqq_marlin.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/hqq_marlin.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c86824b9c4ab0772fb48b5f233d4efc7cae97675 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/hqq_marlin.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/inc.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/inc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5b5bb981bcfb3298a12c0edbf1a4111b5d58a26 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/inc.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/input_quant_fp8.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/input_quant_fp8.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3f86ca3a76f57f1bce782ecfcca20f908993c17 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/input_quant_fp8.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/ipex_quant.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/ipex_quant.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..178eccca0f2dbdced060f6e6af398cf94511038d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/ipex_quant.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/kv_cache.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/kv_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1631af447152d8b5ffd11644082355ddee27645 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/kv_cache.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/marlin.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/marlin.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc354daafe5f51661df45a9030a25da548b23fe8 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/marlin.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/modelopt.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/modelopt.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb5bcffb0721415e7d81c82cd300afa12d9f3e26 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/modelopt.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/moe_wna16.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/moe_wna16.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99920316e36c5f0632d15a3dc88da032517c9d50 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/moe_wna16.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/mxfp4.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/mxfp4.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1ed1ee3bfda9845fae80bbc726bf491e379bdcd Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/mxfp4.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/neuron_quant.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/neuron_quant.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab480661120cf7bd4cb31c8d1cf7a8481fc593a6 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/neuron_quant.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/ptpc_fp8.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/ptpc_fp8.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4892a81a0609a08cf91535d74c32cae81835986e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/ptpc_fp8.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/qqq.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/qqq.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42dcded94367b4fc89d6b012c9efc8e087098921 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/qqq.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/torchao.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/torchao.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8b87fbc1d28dbbc76a07c9dd9314394a572273f Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/__pycache__/torchao.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58ac1340563c3b0adbf577e53cdd52ad38df87fa Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/__pycache__/compressed_tensors.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/__pycache__/compressed_tensors.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..880df5edf9b23d032ca747ab1bb53f890b291e0a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/__pycache__/compressed_tensors.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/__pycache__/compressed_tensors_moe.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/__pycache__/compressed_tensors_moe.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e45bd6502ccfb51472e1011a792181e52dab52a8 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/__pycache__/compressed_tensors_moe.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/compressed_tensors.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/compressed_tensors.py new file mode 100644 index 0000000000000000000000000000000000000000..637a84372990ae3b1812de899fd6e5aec8271f19 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/compressed_tensors.py @@ -0,0 +1,741 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from contextlib import suppress +from typing import TYPE_CHECKING, Any, Literal, Optional, cast + +import torch +from compressed_tensors.config import (CompressionFormat, + SparsityCompressionConfig, + SparsityStructure) +from compressed_tensors.quantization import (QuantizationArgs, + QuantizationStrategy, + QuantizationType) +from pydantic import BaseModel + +import vllm.envs as envs +from vllm.logger import init_logger +from vllm.model_executor.layers.fused_moe import FusedMoE +from vllm.model_executor.layers.linear import (LinearBase, LinearMethodBase, + UnquantizedLinearMethod) +from vllm.model_executor.layers.quantization import QuantizationMethods +from vllm.model_executor.layers.quantization.base_config import ( # noqa: E501 + QuantizationConfig, QuantizeMethodBase) +from vllm.model_executor.layers.quantization.compressed_tensors.compressed_tensors_moe import ( # noqa: E501 + CompressedTensorsMoEMethod) +from vllm.model_executor.layers.quantization.compressed_tensors.schemes import ( + W4A16SPARSE24_SUPPORTED_BITS, WNA16_SUPPORTED_BITS, CompressedTensors24, + CompressedTensorsScheme, CompressedTensorsW4A4Fp4, + CompressedTensorsW4A8Int, CompressedTensorsW4A16Fp4, + CompressedTensorsW4A16Sparse24, CompressedTensorsW8A8Fp8, + CompressedTensorsW8A8Int8, CompressedTensorsW8A16Fp8, + CompressedTensorsWNA16) +from vllm.model_executor.layers.quantization.compressed_tensors.utils import ( + find_matched_target, is_activation_quantization_format, + should_ignore_layer) +from vllm.model_executor.layers.quantization.kv_cache import BaseKVCacheMethod +from vllm.model_executor.layers.quantization.utils.quant_utils import ( + cutlass_fp4_supported) +from vllm.platforms import current_platform + +if TYPE_CHECKING: + from vllm.model_executor.models.utils import WeightsMapper + +logger = init_logger(__name__) + +__all__ = ["CompressedTensorsLinearMethod"] + +SPARSITY_CONFIG_NAME: Literal["sparsity_config"] = "sparsity_config" +QUANTIZATION_SCHEME_MAP_TYPE = dict[str, Optional[dict[str, QuantizationArgs]]] + + +class CompressedTensorsConfig(QuantizationConfig): + + def __init__( + self, + target_scheme_map: dict[str, Any], + ignore: list[str], + quant_format: str, + sparsity_scheme_map: dict[str, SparsityCompressionConfig], + sparsity_ignore_list: list[str], + kv_cache_scheme: Optional[dict[str, Any]] = None, + config: Optional[dict[str, Any]] = None, + ): + super().__init__() + self.ignore = ignore + self.quant_format = quant_format + # Map from [target -> scheme] + self.target_scheme_map = target_scheme_map + self.kv_cache_scheme = kv_cache_scheme + self.sparsity_scheme_map = sparsity_scheme_map + self.sparsity_ignore_list = sparsity_ignore_list + self.config = config + + def get_linear_method(self) -> "CompressedTensorsLinearMethod": + return CompressedTensorsLinearMethod(self) + + def get_supported_act_dtypes(cls) -> list[torch.dtype]: + return [torch.float32, torch.float16, torch.bfloat16] + + @classmethod + def get_min_capability(cls) -> int: + return 70 + + def get_name(self) -> QuantizationMethods: + return "compressed-tensors" + + def apply_vllm_mapper(self, hf_to_vllm_mapper: "WeightsMapper"): + self.target_scheme_map = hf_to_vllm_mapper.apply_dict( + self.target_scheme_map) + self.ignore = hf_to_vllm_mapper.apply_list(self.ignore) + self.sparsity_scheme_map = hf_to_vllm_mapper.apply_dict( + self.sparsity_scheme_map) + self.sparsity_ignore_list = hf_to_vllm_mapper.apply_list( + self.sparsity_ignore_list) + if self.kv_cache_scheme is not None: + self.kv_cache_scheme = hf_to_vllm_mapper.apply_dict( + self.kv_cache_scheme) + + def get_quant_method( + self, + layer: torch.nn.Module, + prefix: str, + ) -> Optional["QuantizeMethodBase"]: + from vllm.attention.layer import Attention # Avoid circular import + + # Check if the layer is skipped for quantization. + # TODO (@robertgshaw2): support module names + if should_ignore_layer(prefix, + ignore=self.ignore, + fused_mapping=self.packed_modules_mapping): + return UnquantizedLinearMethod() + if isinstance(layer, LinearBase): + scheme = self.get_scheme(layer=layer, layer_name=prefix) + if scheme is None: + return UnquantizedLinearMethod() + layer.scheme = scheme + return CompressedTensorsLinearMethod(self) + if isinstance(layer, Attention): + return CompressedTensorsKVCacheMethod(self) + if isinstance(layer, FusedMoE): + return CompressedTensorsMoEMethod.get_moe_method(self, layer) + return None + + @classmethod + def from_config(cls, config: dict[str, Any]) -> "CompressedTensorsConfig": + ignore: list[str] = cast(list[str], config.get("ignore", [])) + quant_format = cast(str, config.get("format")) + target_scheme_map = cls._quantization_scheme_map_from_config( + config=config) + sparsity_scheme_map, sparsity_ignore_list = cls._parse_sparsity_config( + config=config) + + return cls( + target_scheme_map=target_scheme_map, + ignore=ignore, + quant_format=quant_format, + sparsity_scheme_map=sparsity_scheme_map, + sparsity_ignore_list=sparsity_ignore_list, + config=config, + ) + + @classmethod + def _parse_sparsity_config( + cls, config: dict[str, Any] + ) -> tuple[dict[str, SparsityCompressionConfig], list[str]]: + """ + :param config: The `quantization_config` dictionary from config.json + :return: A tuple with two elements + 1. A dictionary mapping target layer names to their corresponding + sparsity_config + 2. A list of layer names to ignore for sparsity + """ + if not (sparsity_config := config.get(SPARSITY_CONFIG_NAME)): + return dict(), [] + + sparsity_config = SparsityCompressionConfig.model_validate( + sparsity_config) + sparse_scheme_map: dict[str, SparsityCompressionConfig] = { + target: sparsity_config + for target in sparsity_config.targets or list() + } + sparsity_ignore_list = sparsity_config.ignore or list() + return sparse_scheme_map, sparsity_ignore_list + + @classmethod + def _quantization_scheme_map_from_config( + cls, config: dict[str, Any]) -> QUANTIZATION_SCHEME_MAP_TYPE: + """ + :param config: The `quantization_config` dictionary from config.json + :return: A dictionary mapping target layer names to their corresponding + quantization_args for weights and input activations + """ + target_scheme_map: dict[str, Any] = dict() + quant_format = cast(str, config.get("format")) + + # The quant_config has multiple config_groups, each containing + # an input_activations key with details about how the activations are + # quantized, a weights key indicating how the weights are quantized, + # and a list of targets under the `targets` key, dictating which + # layers are impacted by the quantization details. The quantization + # details follow the structure defined by the QuantizationArgs + # pydantic model, which is used to verify the structure of the + # quant_config and also store the details for later use. + + config_groups = config.get("config_groups", dict()) + for _, quant_config in config_groups.items(): + targets = quant_config.get("targets") + for target in targets: + target_scheme_map[target] = {} + target_scheme_map[target][ + "weights"] = QuantizationArgs.model_validate( + quant_config.get("weights")) + + target_scheme_map[target]["input_activations"] = None + target_scheme_map[target]["format"] = quant_config.get( + "format") + format = target_scheme_map[target].get("format") + # If no per-config format defined, use global format in config + act_quant_format = is_activation_quantization_format( + format + ) if format is not None else is_activation_quantization_format( + quant_format) + if act_quant_format: + input_activations = quant_config.get("input_activations") + # The only case where we have activation quant supported + # but no input_activations provided in the config + # should be w8a16fp8 w8a16fp8 can also run for cases where + # there is an input_quant but it is ignored + if not input_activations: + assert target_scheme_map[target][ + "weights"].type == QuantizationType.FLOAT + else: + target_scheme_map[target][ + "input_activations"] = QuantizationArgs.model_validate( # noqa: E501 + quant_config.get("input_activations")) + return target_scheme_map + + @classmethod + def get_config_filenames(cls) -> list[str]: + return [] + + def _check_scheme_supported(self, + min_capability: int, + error: bool = True, + match_exact: bool = False) -> bool: + capability_tuple = current_platform.get_device_capability() + + if capability_tuple is not None: + capability = capability_tuple.to_int() + if match_exact: + supported = capability == min_capability + if error and not supported: + raise RuntimeError( + "Quantization scheme is not supported for ", + "the current GPU. Required capability: ", + f"{min_capability}. Current capability: {capability}.") + else: + supported = capability >= min_capability + if error and not supported: + raise RuntimeError( + "Quantization scheme is not supported for ", + f"the current GPU. Min capability: {min_capability}. ", + f"Current capability: {capability}.") + return supported + else: + return False + + def _is_fp4a4_nvfp4(self, weight_quant: BaseModel, input_quant: BaseModel): + + if weight_quant is None or input_quant is None: + return False + + is_tensor_group_quant = (weight_quant.strategy + == QuantizationStrategy.TENSOR_GROUP.value + and input_quant.strategy + == QuantizationStrategy.TENSOR_GROUP.value) + is_symmetric = weight_quant.symmetric and input_quant.symmetric + + is_group_size_16 = (weight_quant.group_size == 16 + and input_quant.group_size == 16) + is_float_type = (weight_quant.type == QuantizationType.FLOAT + and input_quant.type == QuantizationType.FLOAT.value) + is_4_bits = weight_quant.num_bits == 4 and input_quant.num_bits == 4 + + return (is_tensor_group_quant and is_float_type and is_4_bits + and is_group_size_16 and is_symmetric) + + def _is_fp4a16_nvfp4(self, weight_quant: BaseModel, + input_quant: BaseModel): + + is_weight_only = weight_quant is not None and input_quant is None + is_tensor_group_quant = ( + weight_quant.strategy == QuantizationStrategy.TENSOR_GROUP.value) + is_symmetric = weight_quant.symmetric + + is_group_size_16 = weight_quant.group_size == 16 + is_float_type = weight_quant.type == QuantizationType.FLOAT + is_4_bits = weight_quant.num_bits == 4 + + return (is_weight_only and is_tensor_group_quant and is_float_type + and is_4_bits and is_group_size_16 and is_symmetric) + + def _is_static_tensor_w8a8(self, weight_quant: BaseModel, + input_quant: BaseModel) -> bool: + is_8_bits = weight_quant.num_bits == input_quant.num_bits == 8 + weight_strategy = ( + weight_quant.strategy == QuantizationStrategy.TENSOR.value + or weight_quant.strategy == QuantizationStrategy.CHANNEL.value) + is_tensor = (weight_strategy and input_quant.strategy + == QuantizationStrategy.TENSOR.value) + is_static = not weight_quant.dynamic and not input_quant.dynamic + + # Both symmetric and asymmetric input quantization supported. + # Only symmetric weight quantization supported. + return is_8_bits and is_tensor and weight_quant.symmetric and is_static + + def _is_dynamic_token_w8a8(self, weight_quant: BaseModel, + input_quant: BaseModel) -> bool: + is_8_bits = weight_quant.num_bits == input_quant.num_bits == 8 + weight_strategy = ( + weight_quant.strategy == QuantizationStrategy.TENSOR.value + or weight_quant.strategy == QuantizationStrategy.CHANNEL.value) + is_token = (weight_strategy and input_quant.strategy + == QuantizationStrategy.TOKEN.value) + is_dynamic = not weight_quant.dynamic and input_quant.dynamic + + # Both symmetric and asymmetric input quantization supported. + # Only symmetric weight quantization supported. + return is_8_bits and is_token and weight_quant.symmetric and is_dynamic + + def _is_dynamic_token_w4a8_int(self, weight_quant: BaseModel, + input_quant: BaseModel) -> bool: + is_weight_4_bits = weight_quant.num_bits == 4 + is_activation_8_bits = input_quant.num_bits == 8 + weight_strategy = ( + weight_quant.strategy == QuantizationStrategy.GROUP.value + or weight_quant.strategy == QuantizationStrategy.CHANNEL.value) + is_token = (weight_strategy and input_quant.strategy + == QuantizationStrategy.TOKEN.value) + is_dynamic = not weight_quant.dynamic and input_quant.dynamic + + # Both symmetric and asymmetric input quantization supported. + # Only symmetric weight quantization supported. + return (is_weight_4_bits and is_activation_8_bits and is_token + and weight_quant.symmetric and is_dynamic) + + def _is_fp8_w8a8(self, weight_quant: BaseModel, + input_quant: BaseModel) -> bool: + # Confirm weights and activations quantized. + if weight_quant is None or input_quant is None: + return False + + # Confirm weight scheme is supported. + is_floating_point = (weight_quant.type == QuantizationType.FLOAT + and input_quant.type == QuantizationType.FLOAT) + is_symmetric_weight = weight_quant.symmetric + is_static_weight = not weight_quant.dynamic + is_per_tensor_or_channel_weight = (weight_quant.strategy in [ + QuantizationStrategy.TENSOR, QuantizationStrategy.CHANNEL + ]) + if not (is_floating_point and is_symmetric_weight and is_static_weight + and is_per_tensor_or_channel_weight): + return False + + # Dynamic quantization is always supported if weights supported. + if input_quant.dynamic: + return True + + # Confirm activation scheme is supported. + is_symmetric_activation = input_quant.symmetric + is_per_tensor_activation = ( + input_quant.strategy == QuantizationStrategy.TENSOR) + return is_symmetric_activation and is_per_tensor_activation + + def _is_fp8_w8a8_sm90(self, weight_quant: BaseModel, + input_quant: BaseModel) -> bool: + return (self._check_scheme_supported(90, error=False, match_exact=True) + and self._is_fp8_w8a8(weight_quant, input_quant)) + + def _is_fp8_w8a8_sm100(self, weight_quant: BaseModel, + input_quant: BaseModel) -> bool: + return (self._check_scheme_supported( + 100, error=False, match_exact=True) + and self._is_fp8_w8a8(weight_quant, input_quant)) + + def _is_fp8_w8a16(self, weight_quant: BaseModel, + input_quant: BaseModel) -> bool: + # Confirm weights quantized. + if weight_quant is None: + return False + + # Confirm we have floating points. + if weight_quant.type != QuantizationType.FLOAT: + return False + + # Confirm weight scheme is supported. + is_symmetric_weight = weight_quant.symmetric + is_static_weight = not weight_quant.dynamic + is_per_tensor_or_channel_weight = (weight_quant.strategy in [ + QuantizationStrategy.TENSOR, QuantizationStrategy.CHANNEL + ]) + if not (is_symmetric_weight and is_static_weight # noqa: SIM103 + and is_per_tensor_or_channel_weight): + return False + + # All conditions satisfied. + return True + + def _is_wNa16_group_channel(self, weight_quant: BaseModel, + input_quant: BaseModel) -> bool: + input_quant_none = input_quant is None + is_channel_group = ( + weight_quant.strategy == QuantizationStrategy.CHANNEL.value + or weight_quant.strategy == QuantizationStrategy.GROUP.value) + is_static = not weight_quant.dynamic + + return (is_channel_group and input_quant_none and is_static) + + def _get_scheme_from_parts( + self, + weight_quant: BaseModel, + input_quant: BaseModel, + format: Optional[str] = None) -> "CompressedTensorsScheme": + # Detect If Mixed Precision + if self._is_fp4a16_nvfp4(weight_quant, input_quant): + return CompressedTensorsW4A16Fp4() + + if self._is_wNa16_group_channel(weight_quant, input_quant): + if (self.quant_format == CompressionFormat.marlin_24.value + and weight_quant.num_bits in W4A16SPARSE24_SUPPORTED_BITS): + assert weight_quant.symmetric + return CompressedTensorsW4A16Sparse24( + strategy=weight_quant.strategy, + num_bits=weight_quant.num_bits, + group_size=weight_quant.group_size) + if (self.quant_format == CompressionFormat.pack_quantized.value + and weight_quant.num_bits in WNA16_SUPPORTED_BITS): + return CompressedTensorsWNA16( + num_bits=weight_quant.num_bits, + strategy=weight_quant.strategy, + symmetric=weight_quant.symmetric, + group_size=weight_quant.group_size, + actorder=weight_quant.actorder) + + act_quant_format = is_activation_quantization_format( + format + ) if format is not None else is_activation_quantization_format( + self.quant_format) + if act_quant_format: + if self._is_fp4a4_nvfp4(weight_quant, input_quant): + if cutlass_fp4_supported( + ) or envs.VLLM_USE_NVFP4_CT_EMULATIONS: + return CompressedTensorsW4A4Fp4() + else: + logger.warning_once( + "Current platform does not support cutlass NVFP4." + " Running CompressedTensorsW4A16Fp4.") + return CompressedTensorsW4A16Fp4( + has_input_global_scale=True) + + if self._is_fp8_w8a8(weight_quant, input_quant): + is_fp8_w8a8_supported = self._check_scheme_supported( + CompressedTensorsW8A8Fp8.get_min_capability(), error=False) + if is_fp8_w8a8_supported: + return CompressedTensorsW8A8Fp8( + strategy=weight_quant.strategy, + is_static_input_scheme=(input_quant + and not input_quant.dynamic)) + else: + # note: input_quant will be present for converted models; + # will be ignored during inference post loading + return CompressedTensorsW8A16Fp8( + strategy=weight_quant.strategy, + is_static_input_scheme=not input_quant.dynamic) + + # note: input_quant can be None + if self._is_fp8_w8a16(weight_quant, input_quant): + is_static_input_scheme = (input_quant + and not input_quant.dynamic) + return CompressedTensorsW8A16Fp8( + strategy=weight_quant.strategy, + is_static_input_scheme=is_static_input_scheme) + + if self._is_static_tensor_w8a8(weight_quant, input_quant): + return CompressedTensorsW8A8Int8( + strategy=weight_quant.strategy, + is_static_input_scheme=True, + input_symmetric=input_quant.symmetric) + + if self._is_dynamic_token_w8a8(weight_quant, input_quant): + return CompressedTensorsW8A8Int8( + strategy=weight_quant.strategy, + is_static_input_scheme=False, + input_symmetric=input_quant.symmetric) + + if self._is_dynamic_token_w4a8_int(weight_quant, input_quant): + is_static_input_scheme = (input_quant + and not input_quant.dynamic) + return CompressedTensorsW4A8Int( + num_bits=weight_quant.num_bits, + strategy=weight_quant.strategy, + group_size=weight_quant.group_size, + is_static_input_scheme=is_static_input_scheme, + input_symmetric=input_quant.symmetric) + + raise NotImplementedError( + "No compressed-tensors compatible scheme was found.") + + def get_scheme(self, + layer: torch.nn.Module, + layer_name: Optional[str] = None + ) -> Optional["CompressedTensorsScheme"]: + """ + compressed-tensors supports non uniform in the following way: + + targets of config_groups: There can be N config_groups which each + have a quantization scheme. Each config_group has a list of targets + which can be a full layer_name, a regex for a layer_name, or + an nn.Module name. + + Detect whether a layer_name is found in any target and + use the quantization scheme corresponding to the matched target + to select the CompressedTensorsScheme used for inference. + """ + + # Find the "target" in the compressed-tensors config + # that our layer conforms to. + # TODO (@robertgshaw): add compressed-tensors as dep + # so we do not have to re-write these functions + # need to make accelerate optional in ct to do this + + # Will be empty for models with only sparsity + weight_quant = input_quant = None + if self.target_scheme_map: + matched_target = find_matched_target( + layer_name=layer_name, + module=layer, + targets=self.target_scheme_map.keys(), + fused_mapping=self.packed_modules_mapping) + + scheme_dict = self.target_scheme_map[matched_target] + weight_quant = scheme_dict.get("weights") + input_quant = scheme_dict.get("input_activations") + format = scheme_dict.get("format") + + # Find the sparsity scheme of the layer + # assume that fused layers inerhit first component's sparsity scheme + sparsity_targets = (self.sparsity_scheme_map.keys() - + set(self.sparsity_ignore_list)) + sparsity_scheme: Optional[SparsityCompressionConfig] = None + with suppress(ValueError): + matched_target = find_matched_target( + layer_name=layer_name, + module=layer, + targets=sparsity_targets, + fused_mapping=self.packed_modules_mapping) + sparsity_scheme = self.sparsity_scheme_map[matched_target] + + if self.supports_cutlass_24(weight_quant=weight_quant, + input_quant=input_quant, + sparsity_scheme=sparsity_scheme): + # Have a valid sparsity scheme + # Validate layer is supported by Cutlass 2:4 Kernel + model_compression_config = (None if sparsity_scheme is None + or sparsity_scheme.format == "dense" + else self.config) + + scheme = CompressedTensors24( + quantized=weight_quant is not None or input_quant is not None, + weight_quant=weight_quant, + input_quant=input_quant, + model_compression_config=model_compression_config, + ) + elif weight_quant is None: + logger.warning_once("Acceleration for non-quantized schemes is " + "not supported by Compressed Tensors. " + "Falling back to UnquantizedLinearMethod") + return None + + else: + # Find the quant_scheme + scheme = self._get_scheme_from_parts( # type: ignore + weight_quant=weight_quant, + input_quant=input_quant, + format=format) + + # Raise error if device does not support the scheme + # (e.g. fp8 needs ada lovelace) + self._check_scheme_supported(scheme.get_min_capability()) + logger.debug("Using scheme: %s for %s", scheme.__class__.__name__, + layer_name) + return scheme + + def get_cache_scale(self, name: str) -> Optional[str]: + """ + Check whether the param name matches the format for k/v cache scales + in compressed-tensors. If this is the case, return its equivalent + param name expected by vLLM + + :param name: param name + :return: matching param name for KV cache scale in vLLM + """ + if name.endswith(".output_scale") and ".k_proj" in name: + return name.replace(".k_proj.output_scale", ".attn.k_scale") + if name.endswith(".output_scale") and ".v_proj" in name: + return name.replace(".v_proj.output_scale", ".attn.v_scale") + # If no matches, return None + return None + + @staticmethod + def supports_cutlass_24( + weight_quant: Optional[QuantizationArgs], + input_quant: Optional[QuantizationArgs], + sparsity_scheme: Optional[SparsityCompressionConfig] = None + ) -> bool: + """ + Check if the layer is supported by the Cutlass 2:4 Kernel + Conditions: + - Overarching condition: Sparsity Structure is 2:4 + - Unquantized cases are supported + - Weight only quantization is not-supported + - Supported weight quantization strategies are TENSOR and CHANNEL + - Supported input quantization strategies are TENSOR and TOKEN + - Only 8 bit quantization is supported + + :return: True if the layer is supported by the Cutlass 2:4 Kernel + False otherwise + """ + if sparsity_scheme is None: + return False + + is_valid_sparsity_structure: bool = ( + sparsity_scheme.sparsity_structure == + SparsityStructure.TWO_FOUR.value) + + valid_compressors = { + CompressionFormat.dense.value, + CompressionFormat.sparse_24_bitmask.value + } + + is_valid_sparsity = (is_valid_sparsity_structure + and sparsity_scheme.format in valid_compressors) + + if not is_valid_sparsity: + return False + + # Unquantized cases are supported + if weight_quant is None and input_quant is None: + return True + + # Weight only quantization is not-supported + if weight_quant is not None and input_quant is None: + return False + + supported_weight_quant_strategies = [ + QuantizationStrategy.TENSOR.value, + QuantizationStrategy.CHANNEL.value + ] + + assert weight_quant is not None + assert input_quant is not None + if weight_quant.strategy not in supported_weight_quant_strategies: + return False + + supported_input_quant_strategies = [ + QuantizationStrategy.TENSOR.value, QuantizationStrategy.TOKEN.value + ] + + if input_quant.strategy not in supported_input_quant_strategies: + return False + + return weight_quant.num_bits == input_quant.num_bits == 8 + + +class CompressedTensorsLinearMethod(LinearMethodBase): + + def __init__(self, quantization_config: CompressedTensorsConfig): + self.quantization_config = quantization_config + + def process_weights_after_loading(self, layer: torch.nn.Module) -> None: + layer.scheme.process_weights_after_loading(layer) + + def create_weights(self, layer: torch.nn.Module, + input_size_per_partition: int, + output_partition_sizes: list[int], input_size: int, + output_size: int, params_dtype: torch.dtype, + **extra_weight_attrs): + """ + Use the CompressedTensorsScheme associated with each layer to create + the necessary parameters for the layer. See LinearMethodBase for param + details + """ + weight_loader = extra_weight_attrs.get("weight_loader") + layer.scheme.create_weights( + layer=layer, + input_size=input_size, + input_size_per_partition=input_size_per_partition, + output_partition_sizes=output_partition_sizes, + output_size=output_size, + params_dtype=params_dtype, + weight_loader=weight_loader) + + def apply(self, + layer: torch.nn.Module, + x: torch.Tensor, + bias: Optional[torch.Tensor] = None): + """ + Use the output of create_weights and the CompressedTensorsScheme + associated with the layer to apply the forward pass with the + layer input. See LinearMethodBase for param details + + """ + + scheme = layer.scheme + if scheme is None: + raise ValueError("A scheme must be defined for each layer") + return scheme.apply_weights(layer, x, bias=bias) + + +class CompressedTensorsKVCacheMethod(BaseKVCacheMethod): + """ + Supports loading kv-cache scaling factors from compressed-tensors + checkpoints. + """ + + def __init__(self, quant_config: CompressedTensorsConfig): + self.validate_kv_cache_scheme(quant_config.kv_cache_scheme) + super().__init__(quant_config) + + @staticmethod + def validate_kv_cache_scheme(kv_cache_scheme: Optional[dict[str, Any]]): + """ + Validator for the kv cache scheme. Useful for controlling the + kv cache quantization schemes, that are being supported in vLLM + :param kv_cache_scheme: the compressed-tensors kv cache scheme + """ + if kv_cache_scheme is None: + return + + type_ = kv_cache_scheme.get("type") + num_bits = kv_cache_scheme.get("num_bits") + + if type_ != "float" and num_bits != 8: + raise NotImplementedError( + "Currently supported kv cache quantization is " + "num_bits=8, type=float, however " + f"received num_bits={num_bits}, type={type_}") + + strategy = kv_cache_scheme.get("strategy") + if strategy != "tensor": + raise NotImplementedError( + "Only support per-tensor scaling factor " + "for compressed-tensors KV cache. " + f"Expected strategy: tensor, found strategy: {strategy}") + + is_symmetric = kv_cache_scheme.get("symmetric") + if not is_symmetric: + raise NotImplementedError( + "Only support symmetric scaling factor " + "for compressed-tensors KV cache. " + f"However found symmetric: {is_symmetric}") diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/schemes/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/schemes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..734fa603ba7b966f3ee8c4540d63dc3967aa790d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/schemes/__init__.py @@ -0,0 +1,25 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from .compressed_tensors_scheme import CompressedTensorsScheme +from .compressed_tensors_w4a4_nvfp4 import CompressedTensorsW4A4Fp4 +from .compressed_tensors_w4a8_int import CompressedTensorsW4A8Int +from .compressed_tensors_w4a16_24 import (W4A16SPARSE24_SUPPORTED_BITS, + CompressedTensorsW4A16Sparse24) +from .compressed_tensors_w4a16_nvfp4 import CompressedTensorsW4A16Fp4 +from .compressed_tensors_w8a8_fp8 import CompressedTensorsW8A8Fp8 +from .compressed_tensors_w8a8_int8 import CompressedTensorsW8A8Int8 +from .compressed_tensors_w8a16_fp8 import CompressedTensorsW8A16Fp8 +from .compressed_tensors_wNa16 import (WNA16_SUPPORTED_BITS, + CompressedTensorsWNA16) + +from .compressed_tensors_24 import CompressedTensors24 # isort: skip + +__all__ = [ + "CompressedTensorsScheme", "CompressedTensorsWNA16", + "CompressedTensorsW8A16Fp8", "CompressedTensorsW4A16Sparse24", + "CompressedTensorsW8A8Int8", "CompressedTensorsW8A8Fp8", + "WNA16_SUPPORTED_BITS", "W4A16SPARSE24_SUPPORTED_BITS", + "CompressedTensors24", "CompressedTensorsW4A16Fp4", + "CompressedTensorsW4A4Fp4", "CompressedTensorsW4A8Int" +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/schemes/__pycache__/compressed_tensors_w8a16_fp8.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/schemes/__pycache__/compressed_tensors_w8a16_fp8.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b0a5dccb2dd876c8145f450fa97c445abc71922 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/schemes/__pycache__/compressed_tensors_w8a16_fp8.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_wNa16.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_wNa16.py new file mode 100644 index 0000000000000000000000000000000000000000..74787603e00295a8bf3561425473e004a9fd36f4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_wNa16.py @@ -0,0 +1,201 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from typing import Callable, Optional + +import torch +from compressed_tensors.quantization import ActivationOrdering + +from vllm.logger import init_logger +from vllm.model_executor.layers.quantization.compressed_tensors.schemes import ( + CompressedTensorsScheme) +from vllm.model_executor.layers.quantization.kernels.mixed_precision import ( + MPLinearLayerConfig, choose_mp_linear_kernel) +from vllm.model_executor.layers.quantization.utils.marlin_utils import ( + marlin_repeat_scales_on_all_ranks) +# yapf conflicts with isort for this block +# yapf: disable +from vllm.model_executor.parameter import (BasevLLMParameter, + ChannelQuantScaleParameter, + GroupQuantScaleParameter, + PackedColumnParameter, + PackedvLLMParameter, + RowvLLMParameter) +# yapf: enable +from vllm.scalar_type import scalar_types + +logger = init_logger(__name__) + +__all__ = ["CompressedTensorsWNA16"] +WNA16_SUPPORTED_TYPES_MAP = { + 4: scalar_types.uint4b8, + 8: scalar_types.uint8b128 +} +WNA16_ZP_SUPPORTED_TYPES_MAP = {4: scalar_types.uint4, 8: scalar_types.uint8} +WNA16_SUPPORTED_BITS = list(WNA16_SUPPORTED_TYPES_MAP.keys()) + + +class CompressedTensorsWNA16(CompressedTensorsScheme): + _kernel_backends_being_used: set[str] = set() + + def __init__(self, + strategy: str, + num_bits: int, + group_size: Optional[int] = None, + symmetric: Optional[bool] = True, + actorder: Optional[ActivationOrdering] = None): + + self.pack_factor = 32 // num_bits + self.strategy = strategy + self.symmetric = symmetric + self.group_size = -1 if group_size is None else group_size + self.has_g_idx = actorder == ActivationOrdering.GROUP + + if self.group_size == -1 and self.strategy != "channel": + raise ValueError("Marlin kernels require group quantization or " + "channelwise quantization, but found no group " + "size and strategy is not channelwise.") + + if num_bits not in WNA16_SUPPORTED_TYPES_MAP: + raise ValueError( + f"Unsupported num_bits = {num_bits}. " + f"Supported num_bits = {WNA16_SUPPORTED_TYPES_MAP.keys()}") + + self.quant_type = (WNA16_ZP_SUPPORTED_TYPES_MAP[num_bits] + if not self.symmetric else + WNA16_SUPPORTED_TYPES_MAP[num_bits]) + + @classmethod + def get_min_capability(cls) -> int: + # ampere and up + return 80 + + def create_weights(self, layer: torch.nn.Module, output_size: int, + input_size: int, output_partition_sizes: list[int], + input_size_per_partition: int, + params_dtype: torch.dtype, weight_loader: Callable, + **kwargs): + + output_size_per_partition = sum(output_partition_sizes) + + mp_linear_kernel_config = MPLinearLayerConfig( + full_weight_shape=(input_size, output_size), + partition_weight_shape=\ + (input_size_per_partition, output_size_per_partition), + weight_type=self.quant_type, + act_type=params_dtype, + group_size=self.group_size, + zero_points=not self.symmetric, + has_g_idx=self.has_g_idx + ) + + kernel_type = choose_mp_linear_kernel(mp_linear_kernel_config) + + if kernel_type.__name__ not in self._kernel_backends_being_used: + logger.info("Using %s for CompressedTensorsWNA16", + kernel_type.__name__) + self._kernel_backends_being_used.add(kernel_type.__name__) + + # If group_size is -1, we are in channelwise case. + group_size = self.group_size if self.group_size != -1 else input_size + row_parallel = (input_size != input_size_per_partition) + partition_scales = not marlin_repeat_scales_on_all_ranks( + self.has_g_idx, self.group_size, row_parallel) + + scales_and_zp_size = input_size // group_size + + if partition_scales: + assert input_size_per_partition % group_size == 0 + scales_and_zp_size = input_size_per_partition // group_size + + weight = PackedvLLMParameter(input_dim=1, + output_dim=0, + weight_loader=weight_loader, + packed_factor=self.pack_factor, + packed_dim=1, + data=torch.empty( + output_size_per_partition, + input_size_per_partition // + self.pack_factor, + dtype=torch.int32, + )) + + weight_scale_args = { + "weight_loader": + weight_loader, + "data": + torch.empty( + output_size_per_partition, + scales_and_zp_size, + dtype=params_dtype, + ) + } + + zeros_args = { + "weight_loader": + weight_loader, + "data": + torch.zeros( + output_size_per_partition // self.pack_factor, + scales_and_zp_size, + dtype=torch.int32, + ) + } + + if not partition_scales: + weight_scale = ChannelQuantScaleParameter(output_dim=0, + **weight_scale_args) + + if not self.symmetric: + qzeros = PackedColumnParameter(output_dim=0, + packed_dim=0, + packed_factor=self.pack_factor, + **zeros_args) + else: + weight_scale = GroupQuantScaleParameter(output_dim=0, + input_dim=1, + **weight_scale_args) + if not self.symmetric: + qzeros = PackedvLLMParameter(input_dim=1, + output_dim=0, + packed_dim=0, + packed_factor=self.pack_factor, + **zeros_args) + + # A 2D array defining the original shape of the weights + # before packing + weight_shape = BasevLLMParameter(data=torch.empty(2, + dtype=torch.int64), + weight_loader=weight_loader) + + layer.register_parameter("weight_packed", weight) + layer.register_parameter("weight_scale", weight_scale) + layer.register_parameter("weight_shape", weight_shape) + + if not self.symmetric: + layer.register_parameter("weight_zero_point", qzeros) + + # group index (for activation reordering) + if self.has_g_idx: + weight_g_idx = RowvLLMParameter(data=torch.empty( + input_size_per_partition, + dtype=torch.int32, + ), + input_dim=0, + weight_loader=weight_loader) + layer.register_parameter("weight_g_idx", weight_g_idx) + + self.kernel = kernel_type(mp_linear_kernel_config, + w_q_param_name="weight_packed", + w_s_param_name="weight_scale", + w_zp_param_name="weight_zero_point", + w_gidx_param_name="weight_g_idx") + + # Checkpoints are serialized in compressed-tensors format, which is + # different from the format the kernel may want. Handle repacking here. + def process_weights_after_loading(self, layer: torch.nn.Module) -> None: + self.kernel.process_weights_after_loading(layer) + + def apply_weights(self, layer: torch.nn.Module, x: torch.Tensor, + bias: Optional[torch.Tensor]) -> torch.Tensor: + return self.kernel.apply_weights(layer, x, bias) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/triton_scaled_mm.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/triton_scaled_mm.py new file mode 100644 index 0000000000000000000000000000000000000000..d926b4c12db14cac5703af5efd27f85b29113d00 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/triton_scaled_mm.py @@ -0,0 +1,206 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from typing import Optional + +import torch + +from vllm.triton_utils import tl, triton + + +def is_weak_contiguous(x: torch.Tensor): + strides = x.stride() + sizes = x.shape + is_not_transpose = strides[0] == 1 and (strides[1] >= max(1, sizes[0])) + is_transpose = strides[1] == 1 and (strides[0] >= max(1, sizes[1])) + return is_transpose or is_not_transpose + + +@triton.jit +def scaled_mm_kernel(a_ptr, b_ptr, scale_a_ptr, scale_b_ptr, c_ptr, bias_ptr, + M, N, K, stride_am, stride_ak, stride_bk, stride_bn, + stride_cm, stride_cn, ACCUMULATOR_DTYPE: tl.constexpr, + BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, + BLOCK_SIZE_K: tl.constexpr, + BLOCK_SIZE_SCALE_A: tl.constexpr, + BLOCK_SIZE_SCALE_B: tl.constexpr): + pid = tl.program_id(axis=0) + + num_pid_n = tl.cdiv(N, BLOCK_SIZE_N) + + pid_m = pid // num_pid_n + pid_n = pid % num_pid_n + + accumulator_dtype = ACCUMULATOR_DTYPE + accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), + dtype=accumulator_dtype) + + # NOTE: Some tensor inputs are so large, they will cause int32 overflow + # so it is necessary to use tl.int64 for all the offsets, else SEGV will + # eventually occur. + + # Offsets and masks. + offsets_am = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M).to(tl.int64) + masks_am = offsets_am < M + + offsets_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N).to(tl.int64) + masks_bn = offsets_bn < N + + offsets_k = tl.arange(0, BLOCK_SIZE_K).to(tl.int64) + offsets_a = (stride_am * offsets_am[:, None] + + stride_ak * offsets_k[None, :]) + offsets_b = (stride_bk * offsets_k[:, None] + + stride_bn * offsets_bn[None, :]) + + # NOTE: BLOCK_SIZE_SCALE_A could be 1 or BLOCK_SIZE_M, so need to create + # appropriate offsets and masks for each case. Same goes for + # BLOCK_SIZE_SCALE_B. + offsets_scale_am = (tl.arange(0, BLOCK_SIZE_SCALE_A) + + (BLOCK_SIZE_SCALE_A > 1) * pid_m * BLOCK_SIZE_M) + masks_scale_am = offsets_scale_am < M + + offsets_scale_bn = (tl.arange(0, BLOCK_SIZE_SCALE_B) + + (BLOCK_SIZE_SCALE_B > 1) * pid_n * BLOCK_SIZE_N) + masks_scale_bn = offsets_scale_bn < N + + a_ptrs = a_ptr + offsets_a + b_ptrs = b_ptr + offsets_b + + scale_a_ptrs = scale_a_ptr + offsets_scale_am + scale_b_ptrs = scale_b_ptr + offsets_scale_bn + + for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)): + masks_k = offsets_k < K + masks_a = masks_am[:, None] & masks_k[None, :] + a = tl.load(a_ptrs, mask=masks_a) + + masks_b = masks_k[:, None] & masks_bn[None, :] + b = tl.load(b_ptrs, mask=masks_b) + + # Accumulate results. + accumulator = tl.dot(a, b, accumulator, out_dtype=accumulator_dtype) + + offsets_k += BLOCK_SIZE_K + a_ptrs += BLOCK_SIZE_K * stride_ak + b_ptrs += BLOCK_SIZE_K * stride_bk + + # Apply scale at end. + masks_scale_a = masks_scale_am[:, None] & (tl.arange(0, 1) < 1)[:, None] + scale_a = tl.load(scale_a_ptrs[:, None], masks_scale_a) + # Need to broadcast to the appropriate size, if scale_a is already + # (BLOCK_SIZE_M, 1) then it will broadcast to its own shape. Same goes + # for scale_b below. + scale_a = scale_a.broadcast_to((BLOCK_SIZE_M, 1)) + accumulator = scale_a * accumulator.to(tl.float32) + + masks_scale_b = masks_scale_bn[:, None] & (tl.arange(0, 1) < 1)[None, :] + scale_b = tl.load(scale_b_ptrs[:, None], masks_scale_b) + scale_b = scale_b.broadcast_to((BLOCK_SIZE_N, 1)) + accumulator = scale_b.T * accumulator.to(tl.float32) + + # Convert to output format. + c = accumulator.to(c_ptr.type.element_ty) + + # Add bias, it's already in output format, so add it after conversion. + if bias_ptr: + offsets_bias = offsets_bn + bias_ptrs = bias_ptr + offsets_bias + bias_mask = offsets_bias < N + bias = tl.load(bias_ptrs, bias_mask) + c += bias + + # Save output + offs_cm = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M).to(tl.int64) + offs_cn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N).to(tl.int64) + offs_cm = offs_cm.to(tl.int64) + offs_cn = offs_cn.to(tl.int64) + c_ptrs = (c_ptr + stride_cm * offs_cm[:, None] + + stride_cn * offs_cn[None, :]) + c_mask = (offs_cm[:, None] < M) & (offs_cn[None, :] < N) + + tl.store(c_ptrs, c, mask=c_mask) + + +# input - [M, K] +# weight - [K, N] +def triton_scaled_mm(input: torch.Tensor, + weight: torch.Tensor, + scale_a: torch.Tensor, + scale_b: torch.Tensor, + out_dtype: type[torch.dtype], + bias: Optional[torch.Tensor] = None, + block_size_m: int = 32, + block_size_n: int = 32, + block_size_k: int = 32, + use_heuristic=True) -> torch.Tensor: + M, K = input.shape + N = weight.shape[1] + + assert N > 0 and K > 0 and M > 0 + assert weight.shape[0] == K + assert input.dtype == weight.dtype + + scale_a = scale_a.reshape(-1, 1) if scale_a.dim() <= 1 else scale_a + scale_b = scale_b.reshape(-1, 1) if scale_b.dim() <= 1 else scale_b + + assert scale_a.dtype == scale_b.dtype and scale_a.is_floating_point() + assert scale_a.shape[1] == 1 and (scale_a.shape[0] == 1 + or scale_a.shape[0] == M) + assert scale_b.shape[1] == 1 and (scale_b.shape[0] == 1 + or scale_b.shape[0] == N) + assert out_dtype.is_floating_point + assert bias is None or bias.is_floating_point() + assert is_weak_contiguous(input) + assert is_weak_contiguous(weight) + + grid = lambda META: (triton.cdiv(M, META['BLOCK_SIZE_M']) * triton.cdiv( + N, META['BLOCK_SIZE_N']), ) + + result = torch.empty((M, N), dtype=out_dtype, device=input.device) + + has_scalar = lambda x: x.shape[0] == 1 and x.shape[1] == 1 + + if use_heuristic: + is_small_N = N < 8192 + next_power_of_2_M = max(32, triton.next_power_of_2(M)) + if next_power_of_2_M <= 32: + tile_shape = (64, 64, 256) if is_small_N else (64, 128, 256) + elif next_power_of_2_M <= 64: + tile_shape = (64, 64, 256) + elif next_power_of_2_M <= 128: + tile_shape = (64, 128, 128) + else: + tile_shape = (128, 128, 128) + + block_size_m, block_size_n, block_size_k = tile_shape + + block_size_sa = 1 if has_scalar(scale_a) else block_size_m + block_size_sb = 1 if has_scalar(scale_b) else block_size_n + + accumulator_dtype = tl.float32 if input.is_floating_point() else tl.int32 + + # A = input, B = weight, C = result + # A = M x K, B = K x N, C = M x N + scaled_mm_kernel[grid](input, + weight, + scale_a, + scale_b, + result, + bias, + M, + N, + K, + input.stride(0), + input.stride(1), + weight.stride(0), + weight.stride(1), + result.stride(0), + result.stride(1), + accumulator_dtype, + BLOCK_SIZE_M=block_size_m, + BLOCK_SIZE_N=block_size_n, + BLOCK_SIZE_K=block_size_k, + BLOCK_SIZE_SCALE_A=block_size_sa, + BLOCK_SIZE_SCALE_B=block_size_sb) + + return result.to(out_dtype) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..099d8613fc1a73db206d3e8fc7056ac2d5d1bf1f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/compressed_tensors/utils.py @@ -0,0 +1,216 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from collections.abc import Iterable, Mapping +from types import MappingProxyType +from typing import Optional + +import regex as re +from compressed_tensors import CompressionFormat +from torch.nn import Module + + +def is_activation_quantization_format(format: str) -> bool: + _ACTIVATION_QUANTIZATION_FORMATS = [ + CompressionFormat.naive_quantized.value, + CompressionFormat.int_quantized.value, + CompressionFormat.float_quantized.value, + CompressionFormat.nvfp4_pack_quantized.value + ] + return format in _ACTIVATION_QUANTIZATION_FORMATS + + +def should_ignore_layer( + layer_name: Optional[str], + ignore: Iterable[str] = tuple(), + fused_mapping: Mapping[str, list[str]] = MappingProxyType({}) +) -> bool: + if layer_name is None: + return False + + # layer_name = model.layers.0.self_attn.qkv_proj + # proj_name = qkv_proj + proj_name = layer_name.split(".")[-1] + + # Fused layers like gate_up_proj or qkv_proj will not be fused + # in the safetensors checkpoint. So, we convert the name + # from the fused version to unfused + check to make sure that + # each shard of the fused layer has the same scheme. + if proj_name in fused_mapping and layer_name not in ignore: + shard_proj_names = fused_mapping[proj_name] + + # Convert fused_name --> [shard_names] + shard_names = [ + layer_name.replace(proj_name, shard_proj_name) + for shard_proj_name in shard_proj_names + ] + + # Layer should be ignored if shards are ignored. + should_ignore_layer = None + for shard_name in shard_names: + should_ignore_shard = check_equal_or_regex_match( + layer_name=shard_name, targets=ignore) + + # If shard_idx=0, set layer ignore to match shard. + if should_ignore_layer is None: + should_ignore_layer = should_ignore_shard + + # If shard_idx=1+ confirm scheme matches prior shards. + elif should_ignore_shard != should_ignore_layer: + raise ValueError(f"Found a different quantization schemes for " + f"{shard_proj_names} in {layer_name}. vLLM " + "requires all to use the same scheme.") + + # Unfused layers like down_proj and o_proj will match + # the safetensors checkpoint already. + else: + should_ignore_layer = check_equal_or_regex_match(layer_name=layer_name, + targets=ignore) + + assert should_ignore_layer is not None + return should_ignore_layer + + +def check_equal_or_regex_match(layer_name: str, + targets: Iterable[str]) -> bool: + """ + Checks whether a layer_name is exactly equal or a regex match for + if target starts with 're:' to any target in list. + """ + for target in targets: + if _is_equal_or_regex_match(layer_name, target): + return True + return False + + +def find_matched_target( + layer_name: Optional[str], + module: Module, + targets: Iterable[str], + fused_mapping: Mapping[str, list[str]] = MappingProxyType({}) +) -> str: + """ + Helper function to look up which "target" in the compressed-tensors + config that a layer corresponds to. + + Recall that a compressed-tensors configs has a concept of + config_groups, where each layer can be quantized with with a different + scheme. + + targets in each config_group will be a list of either layer names + (or regexes corresponding to layer names) or names of torch Modules. + + First, we try to match the layer_name with a target + Second, we try to match the module's name with a target + Third, we try to map the layer_name to a list of fused module names. + *All* component module names must match in order for a match to be + successful. A successful match returns the first component target + + :param layer_name: layer name + :param module: torch.nn.Module + :param targets: list of targets to match the layer against + :param fused_mapping: map from fused layer names to its components + :param fused_strategy: either "all" or "any". If using "all", fused + layers match if "all" of its components match + """ + + if layer_name is None: + layer_name = "" + + matched_target = ( + _find_first_match(layer_name, targets) + or _find_first_match(module.__class__.__name__, targets, True) + or _match_fused_layer(layer_name, targets, fused_mapping)) + + if matched_target is None: + raise ValueError( + f"Unable to find matching target for {layer_name} in the " + "compressed-tensors config.") + + return matched_target + + +def _find_first_match(value: str, + targets: Iterable[str], + check_contains: bool = False) -> Optional[str]: + """ + Returns first element of target that matches value either + exactly or as a regex after 're:'. If check_contains is set to True, + additionally checks if the target string is contained within the value. + + :param value: string to compare the list of targets against + :param targets: list of targets to match the layer against + :param check_contains: whether or not to do a substring match + """ + + for target in targets: + if _is_equal_or_regex_match(value, + target, + check_contains=check_contains): + return target + return None + + +def _is_equal_or_regex_match(value: str, + target: str, + check_contains: bool = False) -> bool: + """ + Checks whether a value is exactly equal or a regex match for target + if target starts with 're:'. If check_contains is set to True, + additionally checks if the target string is contained within the value. + """ + + if target.startswith("re:"): + pattern = target[3:] + if re.match(pattern, value): + return True + elif check_contains: + if target.lower() in value.lower(): + return True + elif target == value: + return True + return False + + +def _match_fused_layer( + layer_name: str, target_layers: Iterable[str], + fused_mapping: Mapping[str, list[str]]) -> Optional[str]: + """ + Match a fused layer name to its corresponding individual layer in + target_layers. Returns first value in fused_mapping which matches targets + + Implements an "all" matching strategy where a fused layer matches iff + "all" of its components match + + :param layer_name: layer name + :param target_layers: list of targets to match the layer against + :param fused_mapping: map from fused layer names to its components + + Examples: + layer_name = "model.layers.0.self_attn.qkv_proj" + target_layers = ["model.layers.0.self_attn.q_proj", + "model.layers.0.self_attn.k_proj", + "model.layers.0.self_attn.v_proj"] + """ + # find layer_name in mapping + fused = next((key for key in fused_mapping if layer_name.endswith(key)), + None) + if fused is None: + return None + + # expand path of unfused components + unfused_paths = [ + layer_name.replace(fused, unfused) for unfused in fused_mapping[fused] + ] + + # for each unfused component, find a match in targets + unfused_matches: list[Optional[str]] = [] + for unfused in unfused_paths: + for target in target_layers: + if _is_equal_or_regex_match(unfused, target): + unfused_matches.append(target) + break + else: + unfused_matches.append(None) + + return unfused_matches[0] if all(unfused_matches) else None diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/kernels/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/kernels/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3eb3f5fedecc1289b2ec6f41c69e3d2a2a9213b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/kernels/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/kernels/mixed_precision/exllama.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/kernels/mixed_precision/exllama.py new file mode 100644 index 0000000000000000000000000000000000000000..fef333e862d5a85d095b3e8a6f2683dadca0f820 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/kernels/mixed_precision/exllama.py @@ -0,0 +1,143 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from typing import Optional + +import torch + +from vllm import _custom_ops as ops +from vllm.model_executor.layers.quantization.utils.quant_utils import ( + pack_quantized_values_into_int32) +from vllm.model_executor.parameter import (BasevLLMParameter, + permute_param_layout_) +from vllm.scalar_type import scalar_types + +from .MPLinearKernel import MPLinearKernel, MPLinearLayerConfig + + +class ExllamaLinearKernel(MPLinearKernel): + SUPPORTED_QUANT_TYPES = [scalar_types.uint4b8, scalar_types.uint8b128] + # In theory supports `scalar_types.uint2b2, scalar_types.uint3b4` too but + # currently untested so not added to the list + + @classmethod + def get_min_capability(cls) -> int: + return 60 + + @classmethod + def can_implement(cls, + c: MPLinearLayerConfig) -> tuple[bool, Optional[str]]: + if c.has_g_idx and\ + c.partition_weight_shape[0] != c.full_weight_shape[0]: + return False, "Act reordering currently not supported by Exllama, "\ + "when the input features are partitioned across "\ + "devices" + + if c.partition_weight_shape[1] % (32 // c.weight_type.size_bits) != 0: + return False, "Output features must be a multiple of the pack " \ + "factor (32 / num_bits) so that we can correctly " \ + "pack the zero points" + + if c.act_type != torch.float16: + return False, "Exllama only supports float16 activations" + + if c.weight_type not in cls.SUPPORTED_QUANT_TYPES: + return False, f"Quant type ({c.weight_type}) not supported by "\ + "Exllama, supported types are: "\ + f"{cls.SUPPORTED_QUANT_TYPES}" + + if c.full_weight_shape[0] % c.group_size != 0: + return False, f"Group size ({c.group_size}) does not evenly divide"\ + " the number of input features "\ + f"({c.full_weight_shape[0]})" + + return True, None + + def process_weights_after_loading(self, layer: torch.nn.Module): + c = self.config + + # For Exllama, we need to set a zero-point tensor if there is not one + if not c.zero_points: + self.w_zp_name = "qzeros" + device = getattr(layer, self.w_q_name).device + groups = c.partition_weight_shape[0] // c.group_size + out_features = c.partition_weight_shape[1] + + if c.weight_type.has_bias(): + # if the type has a bias we have to create a zeros tensor that + # contains the bias values repeated for each group (-1 due to + # a bug in the original GPTQ checkpoint format leading to + # exllama kernel adding 1 to the zero points during inference) + # Documentation of the bug can be found here: + # https://garden.danieldk.eu/GPTQ-Checkpoint-Format + zeros = torch.full((groups, out_features), + c.weight_type.bias - 1, + dtype=torch.int32, + device=device) + else: + raise NotImplementedError( + "A 0 zero-point is not supported by Exllama due to " + "a bug in the original GPTQ checkpoint format leading to " + "exllama kernel adding 1 to the zero points during " + "inference") + zeros = pack_quantized_values_into_int32(zeros, + c.weight_type, + packed_dim=1) + setattr(layer, self.w_zp_name, + torch.nn.Parameter(zeros, requires_grad=False)) + + if c.has_g_idx: + + def transform_w_g_idx(x): + # Exllama wants the permutation array instead of the group + # indices + return torch.argsort(x).to(torch.int) + + self._transform_param(layer, self.w_gidx_name, transform_w_g_idx) + else: + self.w_gidx_name = "g_idx" + empty_g_idx = torch.nn.Parameter(torch.empty((0, ), + dtype=torch.int, + device=device), + requires_grad=False) + setattr(layer, self.w_gidx_name, empty_g_idx) + + def transform_w_q(x): + assert isinstance(x, BasevLLMParameter) + assert self.w_gidx_name is not None + g_idx = getattr(layer, self.w_gidx_name) + + permute_param_layout_(x, input_dim=0, output_dim=1, packed_dim=0) + x_cont = x.data.contiguous() + ops.gptq_shuffle(x_cont, g_idx, c.weight_type.size_bits) + return x_cont + + def transform_w_s(x): + assert isinstance(x, BasevLLMParameter) + permute_param_layout_(x, input_dim=0, output_dim=1) + x.data = x.data.contiguous() + return x.to(dtype=c.act_type) + + # Repack weights and scales for Machete + self._transform_param(layer, self.w_q_name, transform_w_q) + self._transform_param(layer, self.w_s_name, transform_w_s) + + def apply_weights(self, + layer: torch.nn.Module, + x: torch.Tensor, + bias: Optional[torch.Tensor] = None) -> torch.Tensor: + c = self.config + + x_2d = x.reshape(-1, x.shape[-1]) + out_shape = x.shape[:-1] + (c.partition_weight_shape[1], ) + + w_q, w_s, w_zp, w_g_idx = self._get_weight_params(layer) + + assert w_zp is not None, "Zero points are required by Exllama" + assert w_g_idx is not None, "Group index is required by Exllama" + output = ops.gptq_gemm(x_2d, w_q, w_zp, w_s, w_g_idx, True, + c.weight_type.size_bits) + + if bias is not None: + output.add_(bias) + return output.reshape(out_shape) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/quark/utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/quark/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..99f5ec15933abc95382ebd8243e85059f64beb1b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/quark/utils.py @@ -0,0 +1,105 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from collections.abc import Iterable, Mapping +from types import MappingProxyType +from typing import Any, Optional + +import regex as re + + +def deep_compare(dict1: Any, dict2: Any) -> bool: + if type(dict1) is not type(dict2): + return False + if isinstance(dict1, dict): + if dict1.keys() != dict2.keys(): + return False + return all(deep_compare(dict1[k], dict2[k]) for k in dict1) + elif isinstance(dict1, list): + return set(dict1) == set(dict2) + else: + return dict1 == dict2 + + +def should_ignore_layer( + layer_name: Optional[str], + ignore: Iterable[str], + fused_mapping: Mapping[str, list[str]] = MappingProxyType({}) +) -> bool: + if layer_name is None: + return False + + # layer_name = model.layers.0.self_attn.qkv_proj + # proj_name = qkv_proj + proj_name = layer_name.split(".")[-1] + + # Fused layers like gate_up_proj or qkv_proj will not be fused + # in the safetensors checkpoint. So, we convert the name + # from the fused version to unfused + check to make sure that + # each shard of the fused layer has the same scheme. + if proj_name in fused_mapping: + shard_proj_names = fused_mapping[proj_name] + + # Convert fused_name --> [shard_names] + shard_names = [ + layer_name.replace(proj_name, shard_proj_name) + for shard_proj_name in shard_proj_names + ] + + # Layer should be ignored if shards are ignored. + should_ignore_layer = None + for shard_name in shard_names: + should_ignore_shard = check_equal_or_regex_match( + layer_name=shard_name, targets=ignore) + + # If shard_idx=0, set layer ignore to match shard. + if should_ignore_layer is None: + should_ignore_layer = should_ignore_shard + + # If shard_idx=1+ confirm scheme matches prior shards. + elif should_ignore_shard != should_ignore_layer: + raise ValueError(f"Found a different quantization schemes for " + f"{shard_proj_names} in {layer_name}. vLLM " + "requires all to use the same scheme.") + + # Unfused layers like down_proj and o_proj will match + # the safetensors checkpoint already. + else: + should_ignore_layer = check_equal_or_regex_match(layer_name=layer_name, + targets=ignore) + + assert should_ignore_layer is not None + return should_ignore_layer + + +def check_equal_or_regex_match(layer_name: str, + targets: Iterable[str]) -> bool: + """ + Checks whether a layer_name is exactly equal or a regex match for + if target starts with 're:' to any target in list. + """ + for target in targets: + if _is_equal_or_regex_match(layer_name, target): + return True + return False + + +def _is_equal_or_regex_match(value: str, + target: str, + check_contains: bool = False) -> bool: + """ + Checks whether a value is exactly equal or a regex match for target + if target starts with 're:'. If check_contains is set to True, + additionally checks if the target string is contained within the value. + """ + + if target.startswith("re:"): + pattern = target[3:] + if re.match(pattern, value): + return True + elif check_contains: + if target.lower() in value.lower(): + return True + elif target == value: + return True + return False diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/allspark_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/allspark_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1992b4d201478ca1062f8d6ac4867c8968985dd8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/allspark_utils.py @@ -0,0 +1,52 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +import torch + +from vllm.platforms import current_platform +from vllm.scalar_type import ScalarType, scalar_types + +ALLSPARK_AMPERE_M_CUBLAS_THRESHOLD = 1024 +ALLSPARK_SUPPORTED_QUANT_TYPES = [scalar_types.uint8b128] +ALLSPARK_AMPERE_N_ALIGN = 16 +ALLSPARK_AMPERE_K_ALIGN = 16 + + +def check_allspark_supported_dtype_shape(input_size_per_partition: int, + output_size_per_partition: int, + group_size: int, + weight_dtype: ScalarType, + act_dtype: torch.dtype): + capability_tuple = current_platform.get_device_capability() + device_capability = (-1 if capability_tuple is None else + capability_tuple.to_int()) + + # For Ampere GPU + if device_capability >= 80 and device_capability < 90: + if group_size != -1: + return False, \ + "For Ampere GPU, AllSpark does not support group_size "\ + f"= {group_size}. Only group_size = -1 are supported." + + if weight_dtype not in ALLSPARK_SUPPORTED_QUANT_TYPES: + return False, "For Ampere GPU, AllSpark does not support "\ + f"quant type ({weight_dtype}). Only quant type "\ + f"({ALLSPARK_SUPPORTED_QUANT_TYPES}) are supported." + + if input_size_per_partition % ALLSPARK_AMPERE_K_ALIGN != 0 \ + or output_size_per_partition % ALLSPARK_AMPERE_N_ALIGN != 0: + return False, \ + "AllSpark needs input_size_per_partition % "\ + f"{ALLSPARK_AMPERE_K_ALIGN} = 0 and "\ + f"output_size_per_partition % {ALLSPARK_AMPERE_N_ALIGN} = 0 "\ + "for Ampere GPU optimized kernels." + + if act_dtype != torch.float16 and act_dtype != torch.bfloat16: + return False, \ + "AllSpark only supports act_dtype = float16 or bfloat16,"\ + f"for Ampere GPU, but got act_dtype = {act_dtype}." + else: + return False, "AllSpark currently does not support "\ + f"device_capability = {device_capability}." + + return True, None diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/configs/N=7168,K=2048,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/configs/N=7168,K=2048,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json new file mode 100644 index 0000000000000000000000000000000000000000..5acea242cc0ad094cba8ee5f568ff88afb1b41ae --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/configs/N=7168,K=2048,device_name=NVIDIA_H200,dtype=fp8_w8a8,block_shape=[128,128].json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 8, + "num_stages": 4 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 5 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 5 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/configs/N=7168,K=2304,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/configs/N=7168,K=2304,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json new file mode 100644 index 0000000000000000000000000000000000000000..58cdd93e90b8c29bc7a211861711565dbeeb529a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/configs/N=7168,K=2304,device_name=NVIDIA_H100_80GB_HBM3,dtype=fp8_w8a8,block_shape=[128,128].json @@ -0,0 +1,146 @@ +{ + "1": { + "BLOCK_SIZE_M": 16, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "2": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 4 + }, + "4": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "8": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 4 + }, + "16": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "24": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "32": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "48": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "64": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 32, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 4 + }, + "96": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "128": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 4 + }, + "256": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 3 + }, + "512": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 16, + "num_warps": 4, + "num_stages": 3 + }, + "1024": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "1536": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "2048": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + }, + "3072": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 1, + "num_warps": 4, + "num_stages": 3 + }, + "4096": { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "BLOCK_SIZE_K": 128, + "GROUP_SIZE_M": 64, + "num_warps": 4, + "num_stages": 3 + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/configs/N=7168,K=8192,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/configs/N=7168,K=8192,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json new file mode 100644 index 0000000000000000000000000000000000000000..d86b349f9c42329872c400d393bf4d7125fba782 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/configs/N=7168,K=8192,device_name=AMD_Instinct_MI325X,dtype=fp8_w8a8,block_shape=[128,128].json @@ -0,0 +1,164 @@ +{ + "1": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 16, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "2": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 16, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "4": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 16, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "8": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 32, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "16": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 8, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "24": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 16, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "32": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 32, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "48": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 8, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "64": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 8, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "96": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 1, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "128": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 1, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "256": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 1, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "512": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 1, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "1024": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 32, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "1536": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 1, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "2048": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 32, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "3072": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 32, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "4096": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 128, + "GROUP_SIZE_M": 32, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/configs/N=8192,K=1536,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/configs/N=8192,K=1536,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json new file mode 100644 index 0000000000000000000000000000000000000000..e4716875871fe9abeaf462d06d7471780f5d4b69 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/configs/N=8192,K=1536,device_name=AMD_Instinct_MI300X,dtype=fp8_w8a8,block_shape=[128,128].json @@ -0,0 +1,164 @@ +{ + "1": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 1, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "2": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 16, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "4": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 8, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "8": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 16, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "16": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 16, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "24": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 8, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "32": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 16, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "48": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 8, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "64": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 32, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "96": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 32, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 1, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "128": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 32, + "GROUP_SIZE_M": 1, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "256": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 1, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "512": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 1, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "1024": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 1, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "1536": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 1, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "2048": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 1, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "3072": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 1, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + }, + "4096": { + "BLOCK_SIZE_K": 128, + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": 64, + "GROUP_SIZE_M": 1, + "kpack": 1, + "matrix_instr_nonkdim": 16, + "num_warps": 4 + } +} \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/fp8_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/fp8_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2fb7ef29e4684b9b3a4788a93ca5baf33a50ccb9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/fp8_utils.py @@ -0,0 +1,805 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +# Adapted from https://github.com/sgl-project/sglang/pull/2575 +import functools +import json +import os +from collections.abc import Sequence +from typing import Any, Callable, Optional, Union + +import torch + +import vllm.envs as envs +from vllm import _custom_ops as ops +from vllm.logger import init_logger +from vllm.model_executor.layers.quantization.utils.quant_utils import ( + group_broadcast) +from vllm.model_executor.layers.quantization.utils.w8a8_utils import ( + CUTLASS_BLOCK_FP8_SUPPORTED) +from vllm.platforms import current_platform +from vllm.triton_utils import tl, triton +from vllm.utils import cdiv, direct_register_custom_op, has_deep_gemm +from vllm.utils.deep_gemm import is_blackwell_deep_gemm_e8m0_used + +logger = init_logger(__name__) + + +def is_fp8(x: Union[torch.dtype, torch.Tensor]) -> bool: + if isinstance(x, torch.Tensor): + x = x.dtype + return x == torch.float8_e4m3fn or x == torch.float8_e4m3fnuz + + +def cutlass_scaled_mm( + A: torch.Tensor, + B: torch.Tensor, + As: torch.Tensor, + Bs: torch.Tensor, + block_size: list[int], + output_dtype: torch.dtype = torch.float16, +) -> torch.Tensor: + return ops.cutlass_scaled_mm(A, + B.T, + out_dtype=output_dtype, + scale_a=As, + scale_b=Bs.T) + + +def rocm_aiter_gemm_w8a8_blockscale_impl( + A: torch.Tensor, + B: torch.Tensor, + As: torch.Tensor, + Bs: torch.Tensor, + block_size: list[int], + output_dtype: torch.dtype = torch.float16, +) -> torch.Tensor: + import aiter as rocm_aiter + + return rocm_aiter.gemm_a8w8_blockscale(A, B, As, Bs, dtype=output_dtype) + + +def rocm_aiter_gemm_w8a8_blockscale_fake( + A: torch.Tensor, + B: torch.Tensor, + As: torch.Tensor, + Bs: torch.Tensor, + block_size: list[int], + output_dtype: torch.dtype = torch.float16, +) -> torch.Tensor: + + m = A.shape[0] + n = B.shape[0] + Y = torch.empty(m, n, dtype=output_dtype, device=A.device) + return Y + + +if current_platform.is_rocm(): + direct_register_custom_op( + op_name="rocm_aiter_gemm_w8a8_blockscale", + op_func=rocm_aiter_gemm_w8a8_blockscale_impl, + mutates_args=[], + fake_impl=rocm_aiter_gemm_w8a8_blockscale_fake, + dispatch_key=current_platform.dispatch_key, + ) + if (envs.VLLM_ROCM_USE_AITER and envs.VLLM_ROCM_USE_AITER_LINEAR + and current_platform.is_fp8_fnuz()): + + import aiter as rocm_aiter + from aiter import get_hip_quant + + aiter_per1x128_quant = get_hip_quant(rocm_aiter.QuantType.per_1x128) + + +def dispatch_w8a8_blockscale_func( + use_cutlass: bool, use_aiter_and_is_supported: bool +) -> Callable[[ + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + list[int], + torch.dtype, +], torch.Tensor]: + if use_cutlass: + return cutlass_scaled_mm + if (use_aiter_and_is_supported): + return torch.ops.vllm.rocm_aiter_gemm_w8a8_blockscale + return w8a8_block_fp8_matmul + + +def should_use_deepgemm(output_dtype: torch.dtype, weight: torch.Tensor): + """ + Check if DeepGEMM should be used based on the output dtype and weight shape. + DeepGEMM is only supported for bfloat16 output dtype and weights with shape + divisible by 128. + """ + + return (current_platform.is_cuda() + and current_platform.is_device_capability(90) and has_deep_gemm() + and envs.VLLM_USE_DEEP_GEMM and output_dtype == torch.bfloat16 + and weight.shape[0] % 128 == 0 and weight.shape[1] % 128 == 0) + + +# TODO fix ROCm->Triton custom path: +# https://github.com/vllm-project/vllm/issues/14397 +def apply_w8a8_block_fp8_linear( + input: torch.Tensor, + weight: torch.Tensor, + block_size: list[int], + weight_scale: torch.Tensor, + input_scale: Optional[torch.Tensor] = None, + bias: Optional[torch.Tensor] = None, + cutlass_block_fp8_supported: bool = CUTLASS_BLOCK_FP8_SUPPORTED, + use_aiter_and_is_supported: bool = False, +) -> torch.Tensor: + assert input_scale is None + # View input as 2D matrix for fp8 methods + input_2d = input.view(-1, input.shape[-1]) + output_shape = [*input.shape[:-1], weight.shape[0]] + output_dtype = input.dtype + + if should_use_deepgemm(output_dtype, weight): + + input_2d = input.view(-1, input.shape[-1]) + output_shape = [*input.shape[:-1], weight.shape[0]] + + q_input, x_scale = per_token_group_quant_fp8( + input_2d, + block_size[1], + column_major_scales=True, + ) + + import vllm.model_executor.layers.quantization.deepgemm # noqa: F401 + output = torch.ops.vllm.w8a8_block_fp8_matmul_deepgemm( + q_input, + weight, + x_scale, + weight_scale, + block_size, + output_dtype=output_dtype) + if bias is not None: + output += bias + return output.to(dtype=output_dtype).view(*output_shape) + + if current_platform.is_cuda(): + if current_platform.has_device_capability(100): + + use_cutlass = cutlass_block_fp8_supported and ( + cdiv(weight.shape[0], 128) == weight_scale.shape[0] + and cdiv(weight.shape[1], 128) == weight_scale.shape[1]) + else: + # TODO: update this after switching to public sm90 block scale gemm + # as it also supports weight.shape % 128 != 0 + use_cutlass = cutlass_block_fp8_supported and ( + weight.shape[0] % 128 == 0 and weight.shape[1] % 128 == 0) + else: + use_cutlass = False + + w8a8_blockscale_func = dispatch_w8a8_blockscale_func( + use_cutlass, use_aiter_and_is_supported) + if use_cutlass: + q_input, x_scale = per_token_group_quant_fp8( + input_2d, block_size[1], column_major_scales=use_cutlass) + output = w8a8_blockscale_func(q_input, weight, x_scale, weight_scale, + block_size, input.dtype) + + else: + if use_aiter_and_is_supported: + q_input, x_scale = aiter_per1x128_quant( + input_2d.contiguous(), quant_dtype=rocm_aiter.dtypes.fp8) + else: + q_input, x_scale = per_token_group_quant_fp8( + input_2d, block_size[1], column_major_scales=use_cutlass) + + output = w8a8_blockscale_func(q_input, weight, x_scale, weight_scale, + block_size, input.dtype) + + if bias is not None: + output = output + bias + return output.to(dtype=input.dtype).view(*output_shape) + + +def apply_w8a8_block_fp8_linear_fake( + input: torch.Tensor, + weight: torch.Tensor, + block_size: list[int], + weight_scale: torch.Tensor, + input_scale: Optional[torch.Tensor] = None, + bias: Optional[torch.Tensor] = None, + cutlass_block_fp8_supported: bool = CUTLASS_BLOCK_FP8_SUPPORTED, + use_aiter_and_is_supported: bool = False, +) -> torch.Tensor: + output_shape = [*input.shape[:-1], weight.shape[0]] + return torch.empty(output_shape, dtype=input.dtype, device=input.device) + + +if not current_platform.is_cpu(): + direct_register_custom_op( + op_name="apply_w8a8_block_fp8_linear", + op_func=apply_w8a8_block_fp8_linear, + mutates_args=[], + fake_impl=apply_w8a8_block_fp8_linear_fake, + ) + + +def input_to_float8( + x: torch.Tensor, + dtype: Optional[torch.dtype] = None +) -> tuple[torch.Tensor, torch.Tensor]: + """This function quantizes input values to float8 values " + "with tensor-wise quantization.""" + dtype = current_platform.fp8_dtype() if dtype is None else dtype + finfo = torch.finfo(dtype) + min_val, max_val = x.aminmax() + amax = torch.maximum(min_val.abs(), max_val.abs()).clamp(min=1e-12) + scale = finfo.max / amax + x_scl_sat = (x * scale).clamp(min=finfo.min, max=finfo.max) + return x_scl_sat.to(dtype).contiguous(), scale.float().reciprocal() + + +def block_quant_to_tensor_quant( + x_q_block: torch.Tensor, + x_s: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor]: + """This function converts block-wise quantization to tensor-wise + quantization. The inputs are block-wise quantization tensor `x_q_block`, + block-wise quantization scale and the block size. + The outputs are tensor-wise quantization tensor and tensor-wise + quantization scale. Note only float8 is supported for now. + """ + x_dq_block = group_broadcast(x_q_block, x_s) + x_q_tensor, scale = input_to_float8(x_dq_block, dtype=x_q_block.dtype) + return x_q_tensor, scale + + +@triton.jit +def _per_token_group_quant_fp8( + # Pointers to inputs and output + y_ptr, + y_q_ptr, + y_s_ptr, + group_size, + # Num columns of y + y_num_columns, + y_row_stride, + # Avoid to divide zero + eps, + # Information for float8 + fp8_min, + fp8_max, + use_ue8m0: tl.constexpr, + # Meta-parameters + BLOCK: tl.constexpr, +): + """A Triton-accelerated function to perform per-token-group + quantization on a tensor. + This function converts the tensor values into float8 values. + """ + groups_per_row = y_num_columns // group_size + + # Map the program id to the row of X and Y it should compute. + g_id = tl.program_id(0) + row = g_id // groups_per_row + row_g_id = g_id % groups_per_row + + # Ensure offset calculations use int64 to prevent overflow + y_ptr_offset = (row.to(tl.int64) * y_row_stride) + (row_g_id.to(tl.int64) * + group_size) + y_ptr += y_ptr_offset + + y_q_ptr_offset = g_id.to(tl.int64) * group_size + y_q_ptr += y_q_ptr_offset + y_s_ptr += g_id + + cols = tl.arange(0, BLOCK) # N <= BLOCK + mask = cols < group_size + + y = tl.load(y_ptr + cols, mask=mask, other=0.0).to(tl.float32) + # Quant + _absmax = tl.maximum(tl.max(tl.abs(y)), eps) + scale_raw = _absmax / fp8_max + y_s = tl.math.exp2(tl.ceil(tl.log2(scale_raw))) if use_ue8m0 else scale_raw + y_q = tl.clamp(y / y_s, fp8_min, fp8_max).to(y_q_ptr.dtype.element_ty) + + tl.store(y_q_ptr + cols, y_q, mask=mask) + tl.store(y_s_ptr, y_s) + + +@triton.jit +def _per_token_group_quant_fp8_colmajor( + # Pointers to inputs and output + y_ptr, + y_q_ptr, + y_s_ptr, + group_size, + # Num columns of y + y_num_columns, + y_row_stride, + # Stride from one column to the next of y_s + y_s_col_stride, + # Avoid to divide zero + eps, + # Information for float8 + fp8_min, + fp8_max, + use_ue8m0: tl.constexpr, + # Meta-parameters + BLOCK: tl.constexpr, +): + """A Triton-accelerated function to perform per-token-group + quantization on a tensor. + This function converts the tensor values into float8 values. + """ + groups_per_row = y_num_columns // group_size + + # Map the program id to the row of X and Y it should compute. + g_id = tl.program_id(0) + row = g_id // groups_per_row + row_g_id = g_id % groups_per_row + + # Ensure offset calculations use int64 to prevent overflow + y_ptr_offset = (row.to(tl.int64) * y_row_stride) + (row_g_id.to(tl.int64) * + group_size) + y_ptr += y_ptr_offset + + y_q_ptr_offset = g_id.to(tl.int64) * group_size + y_q_ptr += y_q_ptr_offset + + # Convert g_id the flattened block coordinate to 2D so we can index + # into the output y_scales matrix + blocks_per_row = y_num_columns // group_size + scale_col = g_id % blocks_per_row + scale_row = g_id // blocks_per_row + # Ensure offset calculation uses int64 for y_s_ptr + y_s_ptr_offset = (scale_col.to(tl.int64) * y_s_col_stride) + scale_row.to( + tl.int64) + y_s_ptr += y_s_ptr_offset + + cols = tl.arange(0, BLOCK) # group_size <= BLOCK + mask = cols < group_size + + y = tl.load(y_ptr + cols, mask=mask, other=0.0).to(tl.float32) + # Quant + _absmax = tl.maximum(tl.max(tl.abs(y)), eps) + scale_raw = _absmax / fp8_max + y_s = tl.math.exp2(tl.ceil(tl.log2(scale_raw))) if use_ue8m0 else scale_raw + y_q = tl.clamp(y / y_s, fp8_min, fp8_max).to(y_q_ptr.dtype.element_ty) + + tl.store(y_q_ptr + cols, y_q, mask=mask) + tl.store(y_s_ptr, y_s) + + +def per_token_group_quant_fp8( + x: torch.Tensor, + group_size: int, + eps: float = 1e-10, + dtype: Optional[torch.dtype] = None, + column_major_scales: bool = False, + out_q: Optional[torch.Tensor] = None, + use_ue8m0: Optional[bool] = None, +) -> tuple[torch.Tensor, torch.Tensor]: + """Function to perform per-token-group quantization on an input tensor `x`. + It converts the tensor values into signed float8 values and returns the + quantized tensor along with the scaling factor used for quantization. + Args: + x: The input tensor with ndim >= 2. + group_size: The group size used for quantization. + eps: The minimum to avoid dividing zero. + dtype: The dype of output tensor. Note that only `torch.float8_e4m3fn` + is supported for now. + column_major_scales: Outputs scales in column major. + out_q: Optional output tensor. If not provided, function will create. + Returns: + tuple[torch.Tensor, torch.Tensor]: The quantized tensor and the + scaling factor. + """ + if use_ue8m0 is None: + use_ue8m0 = is_blackwell_deep_gemm_e8m0_used() + dtype = current_platform.fp8_dtype() if dtype is None else dtype + assert (x.shape[-1] % group_size == 0), ( + f"the last dimension of `x` {x.shape[-1]} must be divisible " + f"by `group_size` {group_size}") + assert x.stride(-1) == 1, "`x` groups must be contiguous" + + finfo = torch.finfo(dtype) + fp8_min = finfo.min + fp8_max = finfo.max + + assert out_q is None or out_q.shape == x.shape + x_q = out_q + if x_q is None: + x_q = torch.empty_like(x, device=x.device, dtype=dtype) + + # Allocate the scale tensor in either row- or column-major format. + if column_major_scales: + shape = (x.shape[-1] // group_size, ) + x.shape[:-1] + x_s = torch.empty(shape, device=x.device, + dtype=torch.float32).permute(-1, -2) + else: + shape = x.shape[:-1] + (x.shape[-1] // group_size, ) + x_s = torch.empty(shape, device=x.device, dtype=torch.float32) + + # prefer CUDA kernel if available + if current_platform.is_cuda() and x.is_contiguous(): + torch.ops._C.per_token_group_fp8_quant(x, x_q, x_s, group_size, eps, + fp8_min, fp8_max, use_ue8m0) + return x_q, x_s + + # TRITON FALLBACK + M = x.numel() // group_size + N = group_size + BLOCK = triton.next_power_of_2(N) + # heuristics for number of warps + num_warps = min(max(BLOCK // 256, 1), 8) + num_stages = 1 + if column_major_scales: + _per_token_group_quant_fp8_colmajor[(M, )]( + x, + x_q, + x_s, + group_size, + x.shape[1], + x.stride(0), + x_s.stride(1), + eps, + fp8_min=fp8_min, + fp8_max=fp8_max, + use_ue8m0=use_ue8m0, + BLOCK=BLOCK, + num_warps=num_warps, + num_stages=num_stages, + ) + else: + _per_token_group_quant_fp8[(M, )]( + x, + x_q, + x_s, + group_size, + x.shape[1], + x.stride(0), + eps, + fp8_min=fp8_min, + fp8_max=fp8_max, + use_ue8m0=use_ue8m0, + BLOCK=BLOCK, + num_warps=num_warps, + num_stages=num_stages, + ) + + return x_q, x_s + + +@triton.jit +def _w8a8_block_fp8_matmul( + # Pointers to inputs and output + A, + B, + C, + As, + Bs, + # Shape for matmul + M, + N, + K, + # Block size for block-wise quantization + group_n, + group_k, + # Stride for inputs and output + stride_am, + stride_ak, + stride_bk, + stride_bn, + stride_cm, + stride_cn, + stride_As_m, + stride_As_k, + stride_Bs_k, + stride_Bs_n, + # Meta-parameters + BLOCK_SIZE_M: tl.constexpr, + BLOCK_SIZE_N: tl.constexpr, + BLOCK_SIZE_K: tl.constexpr, + GROUP_SIZE_M: tl.constexpr, +): + """Triton-accelerated function used to perform linear operations (dot + product) on input tensors `A` and `B` with block-wise quantization, and + store the result in output tensor `C`. + """ + + pid = tl.program_id(axis=0) + num_pid_m = tl.cdiv(M, BLOCK_SIZE_M) + num_pid_n = tl.cdiv(N, BLOCK_SIZE_N) + num_pid_in_group = GROUP_SIZE_M * num_pid_n + group_id = pid // num_pid_in_group + first_pid_m = group_id * GROUP_SIZE_M + group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M) + pid_m = first_pid_m + (pid % group_size_m) + pid_n = (pid % num_pid_in_group) // group_size_m + + offs_am = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M + offs_bn = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N + offs_k = tl.arange(0, BLOCK_SIZE_K) + a_ptrs = A + (offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak) + b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn) + + As_ptrs = As + offs_am * stride_As_m + offs_bsn = offs_bn // group_n + Bs_ptrs = Bs + offs_bsn * stride_Bs_n + + accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32) + for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)): + a = tl.load(a_ptrs, + mask=offs_k[None, :] < K - k * BLOCK_SIZE_K, + other=0.0) + b = tl.load(b_ptrs, + mask=offs_k[:, None] < K - k * BLOCK_SIZE_K, + other=0.0) + + k_start = k * BLOCK_SIZE_K + offs_ks = k_start // group_k + a_s = tl.load(As_ptrs + offs_ks * stride_As_k) + b_s = tl.load(Bs_ptrs + offs_ks * stride_Bs_k) + + accumulator += tl.dot(a, b) * a_s[:, None] * b_s[None, :] + a_ptrs += BLOCK_SIZE_K * stride_ak + b_ptrs += BLOCK_SIZE_K * stride_bk + + if C.dtype.element_ty == tl.bfloat16: + c = accumulator.to(tl.bfloat16) + elif C.dtype.element_ty == tl.float16: + c = accumulator.to(tl.float16) + else: + c = accumulator.to(tl.float32) + + offs_cm = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M) + offs_cn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) + c_ptrs = C + stride_cm * offs_cm[:, None] + stride_cn * offs_cn[None, :] + c_mask = (offs_cm[:, None] < M) & (offs_cn[None, :] < N) + tl.store(c_ptrs, c, mask=c_mask) + + +@functools.lru_cache +def get_w8a8_block_fp8_configs(N: int, K: int, block_n: int, + block_k: int) -> Optional[dict[int, Any]]: + """ + Return optimized configurations for the w8a8 block fp8 kernel. + The return value will be a dictionary that maps an irregular grid of + batch sizes to configurations of the w8a8 block fp8 kernel. To evaluate the + kernel on a given batch size bs, the closest batch size in the grid should + be picked and the associated configuration chosen to invoke the kernel. + """ + + # First look up if an optimized configuration is available in the configs + # directory + device_name = current_platform.get_device_name().replace(" ", "_") + json_file_name = f"N={N},K={K},device_name={device_name},dtype=fp8_w8a8,block_shape=[{block_n},{block_k}].json" # noqa: E501 + + config_file_path = os.path.join( + os.path.dirname(os.path.realpath(__file__)), "configs", json_file_name) + if os.path.exists(config_file_path): + with open(config_file_path) as f: + logger.info( + "Using configuration from %s for W8A8 Block FP8 kernel.", + config_file_path, + ) + # If a configuration has been found, return it + return {int(key): val for key, val in json.load(f).items()} + + # If no optimized configuration is available, we will use the default + # configuration + logger.warning( + "Using default W8A8 Block FP8 kernel config. Performance might " + "be sub-optimal! Config file not found at %s", + config_file_path, + ) + return None + + +def w8a8_block_fp8_matmul( + A: torch.Tensor, + B: torch.Tensor, + As: torch.Tensor, + Bs: torch.Tensor, + block_size: list[int], + output_dtype: torch.dtype = torch.float16, +) -> torch.Tensor: + """This function performs matrix multiplication with block-wise + quantization. + It takes two input tensors `A` and `B` with scales `As` and `Bs`. + The output is returned in the specified `output_dtype`. + Args: + A: The input tensor, e.g., activation. + B: The input tensor, e.g., weight. + As: The per-token-group quantization scale for `A`. + Bs: The per-block quantization scale for `B`. + block_size: The block size for per-block quantization. It should + be 2-dim, e.g., [128, 128]. + output_dytpe: The dtype of the returned tensor. + Returns: + torch.Tensor: The result of matmul. + """ + assert len(block_size) == 2 + block_n, block_k = block_size[0], block_size[1] + + assert A.shape[-1] == B.shape[-1] + assert A.shape[:-1] == As.shape[:-1] and A.is_contiguous() + assert triton.cdiv(A.shape[-1], block_k) == As.shape[-1] + M = A.numel() // A.shape[-1] + + assert B.ndim == 2 and Bs.ndim == 2 + N, K = B.shape + assert triton.cdiv(N, block_n) == Bs.shape[0] + assert triton.cdiv(K, block_k) == Bs.shape[1] + + C_shape = A.shape[:-1] + (N, ) + C = A.new_empty(C_shape, dtype=output_dtype) + + configs = get_w8a8_block_fp8_configs(N, K, block_size[0], block_size[1]) + if configs: + # Get the optimal config if there is one + config = configs[min(configs.keys(), key=lambda x: abs(x - M))] + else: + # Default config + # Block-wise quant: BLOCK_SIZE_N must be divisible by block_size[0] + # BLOCK_SIZE_K must be divisible by block_size[1] + config = { + "BLOCK_SIZE_M": 64, + "BLOCK_SIZE_N": block_size[0], + "BLOCK_SIZE_K": block_size[1], + "GROUP_SIZE_M": 32, + "num_warps": 4, + "num_stages": 2, + } + + def grid(META): + return (triton.cdiv(M, META["BLOCK_SIZE_M"]) * + triton.cdiv(N, META["BLOCK_SIZE_N"]), ) + + _w8a8_block_fp8_matmul[grid]( + A, + B, + C, + As, + Bs, + M, + N, + K, + block_n, + block_k, + A.stride(-2), + A.stride(-1), + B.stride(1), + B.stride(0), + C.stride(-2), + C.stride(-1), + As.stride(-2), + As.stride(-1), + Bs.stride(1), + Bs.stride(0), + **config, + ) + + return C + + +# Taken from https://github.com/deepseek-ai/DeepGEMM/blob/0c88cd01392c1073c7049a97d6328c7bba9b3947 +# TODO(wentao): remove this function when DeepGEMM exposes this function +def get_tma_aligned_size(x: int, element_size: int) -> int: + """ + Global memory address of TMA must be 16-byte aligned. + Since we use column-major layout for the LHS scaling tensor, + the M-axis of the LHS scaling tensor needs to be padded to a multiple of + 16 bytes. + + Arguments: + x: original M-axis shape of the LHS scaling tensor. + element_size: element size of the LHS scaling tensor. + + Returns: + M-axis shape of the LHS scaling tensor after padding. + """ + tma_alignment_bytes = 16 + assert tma_alignment_bytes % element_size == 0 + alignment = tma_alignment_bytes // element_size + return cdiv(x, alignment) * alignment + + +# Taken from https://github.com/deepseek-ai/DeepGEMM/blob/0c88cd01392c1073c7049a97d6328c7bba9b3947 +# TODO(wentao): remove this function when DeepGEMM exposes this function +def get_col_major_tma_aligned_tensor(x: torch.Tensor) -> torch.Tensor: + """ + Returns TMA-aligned transposed format of the input tensor. `torch.transpose` + will be called if necessary. + If the input tensor is already column-major layout and 16-byte aligned along + the M axis (thus meets the requirement of LHS scaling tensor in + DeepGEMM), this function will do nothing. + + Arguments: + x: usually the LHS scaling tensor in GEMM. + + Returns: + The LHS scaling tensor of TMA-aligned transposed format. + """ + # NOTES: for the extreme performance, you may rewrite/fuse this function in + # CUDA + assert x.dim() in (2, 3) + remove_dim = False + m, n = x.shape[-2], x.shape[-1] + aligned_m = get_tma_aligned_size(m, x.element_size()) + if x.dim() == 2: + if x.stride(0) == 1 and x.stride(1) == aligned_m: + return x + x, remove_dim = x.unsqueeze(0), True + + b = x.shape[0] + + # The last kernel gives a column-major TMA aligned layout + if x.stride(0) == aligned_m * n and x.stride(1) == 1 and x.stride( + 2) == aligned_m: + return x.squeeze(0) if remove_dim else x + + # Normal layout requires transposing + aligned_x = torch.transpose( + torch.empty((b, n, aligned_m), device=x.device, dtype=x.dtype), 1, 2) + aligned_x[:, :m, :] = x + aligned_x = aligned_x[:, :m, :] + return aligned_x.squeeze(0) if remove_dim else aligned_x + + +def requant_weight_ue8m0_inplace( + weight: torch.Tensor, + weight_scale: torch.Tensor, + block_size: Sequence[int] = (128, 128), +) -> None: + """Re-quantise *weight* so that its per-block scaling factors are in the + UE8M0 (power-of-two) format expected by the new DeepGEMM kernels inplace. + + Args: + weight: Block-quantised weight tensor stored in ``torch.float8_e4m3fn``. + Expected shape ``(..., M, K)``. + weight_scale: Corresponding per-block scale tensor (``torch.float32``) + with shape ``(..., M // block_size[0], K // block_size[1])``. + block_size: 2-element iterable ``[block_m, block_k]`` describing the + block quantisation granularity. + """ + if weight.numel() == 0: + return + + if weight.dtype != torch.float8_e4m3fn: + raise ValueError("Expected *weight* to be torch.float8_e4m3fn, got " + f"{weight.dtype} instead.") + + from vllm.utils.deep_gemm import per_block_cast_to_fp8 + + block_m, block_k = int(block_size[0]), int(block_size[1]) + + # Flatten leading dimensions so we can iterate over the last two dims. + leading_shape = weight.shape[:-2] + if len(leading_shape) == 0: + w_view = weight.unsqueeze(0) + s_view = weight_scale.unsqueeze(0) + else: + w_view = weight.reshape(-1, weight.shape[-2], weight.shape[-1]) + s_view = weight_scale.reshape(-1, *weight_scale.shape[-2:]) + + num_mats = w_view.size(0) + for idx in range(num_mats): + w_q = w_view[idx] + s_old = s_view[idx] + + # De-quantise with the *old* scaling factors (float32). + m_cur, k_cur = w_q.shape + s_float = s_old.to(torch.float32) + # Expand scales along rows and cols by block size, then crop. + s_exp_r = torch.repeat_interleave(s_float, block_m, dim=0) + s_exp = torch.repeat_interleave(s_exp_r, block_k, dim=1) + s_exp = s_exp[:m_cur, :k_cur] + w_dq = w_q.to(torch.float32) * s_exp + # Re-quantise using power-of-two scaling (UE8M0). + w_requant, s_requant = per_block_cast_to_fp8(w_dq, [block_m, block_k], + use_ue8m0=True) + + # Write back the results in-place. + w_q.copy_(w_requant) + s_old.copy_(s_requant) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/marlin_utils_fp8.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/marlin_utils_fp8.py new file mode 100644 index 0000000000000000000000000000000000000000..511e19545d5ae32bca03cfa09c7ef7692da9a799 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/marlin_utils_fp8.py @@ -0,0 +1,345 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from typing import Optional + +import torch + +import vllm._custom_ops as ops +from vllm.logger import init_logger +from vllm.model_executor.layers.quantization.utils.marlin_utils import ( + USE_FP32_REDUCE_DEFAULT, marlin_make_workspace_new, marlin_permute_bias, + marlin_permute_scales, should_use_atomic_add_reduce) +from vllm.platforms import current_platform +from vllm.scalar_type import scalar_types + +logger = init_logger(__name__) + + +def is_fp8_marlin_supported(): + return current_platform.has_device_capability(80) + + +def fp8_fused_exponent_bias_into_scales(scales): + fp8_exponent = 4 + if scales.dtype == torch.half: + target_exponent = 5 + elif scales.dtype == torch.bfloat16: + target_exponent = 8 + # exponent_bias_fp16 = 2 ** 4 - 2 ** 3 = 8 + # exponent_bias_bf16 = 2 ** 7 - 2 ** 3 = 120 + exponent_bias = 2**(target_exponent - 1) - 2**(fp8_exponent - 1) + s = torch.ones_like(scales) * 2 + s = s**exponent_bias + return scales * s + + +def apply_fp8_marlin_linear( + input: torch.Tensor, + weight: torch.Tensor, + weight_scale: torch.Tensor, + workspace: torch.Tensor, + size_n: int, + size_k: int, + bias: Optional[torch.Tensor], + use_fp32_reduce: bool = USE_FP32_REDUCE_DEFAULT) -> torch.Tensor: + # For GPUs that lack FP8 hardware support, we can leverage the + # Marlin kernel for fast weight-only FP8 quantization + + reshaped_x = input.reshape(-1, input.shape[-1]) + out_shape = input.shape[:-1] + (size_n, ) + + use_atomic_add = should_use_atomic_add_reduce(m=reshaped_x.size(0), + n=size_n, + k=size_k, + device=input.device, + dtype=input.dtype) + + output = ops.gptq_marlin_gemm(a=reshaped_x, + c=None, + b_q_weight=weight, + b_bias=bias, + b_scales=weight_scale, + global_scale=None, + b_zeros=None, + g_idx=None, + perm=None, + workspace=workspace, + b_q_type=scalar_types.float8_e4m3fn, + size_m=reshaped_x.size(0), + size_n=size_n, + size_k=size_k, + use_atomic_add=use_atomic_add, + use_fp32_reduce=use_fp32_reduce) + + return output.reshape(out_shape) + + +def prepare_fp8_layer_for_marlin(layer: torch.nn.Module, + size_k_first: bool = True) -> None: + logger.warning_once( + "Your GPU does not have native support for FP8 computation but " + "FP8 quantization is being used. Weight-only FP8 compression will " + "be used leveraging the Marlin kernel. This may degrade " + "performance for compute-heavy workloads.") + + part_size_n = layer.output_size_per_partition + part_size_k = layer.input_size_per_partition + weight_block_size = getattr(layer, "weight_block_size", None) + + if size_k_first: + assert layer.weight.shape == (part_size_k, part_size_n) + else: + assert layer.weight.shape == (part_size_n, part_size_k) + + device = layer.weight.device + + # WORKSPACE + layer.workspace = marlin_make_workspace_new(device) + + # WEIGHT + # Repack weights to marlin format + perm = torch.empty(0, dtype=torch.int, device=device) + qweight = pack_fp8_to_int32(layer.weight, size_k_first) + if not size_k_first: + qweight = qweight.T.contiguous() + + marlin_qweight = ops.gptq_marlin_repack(b_q_weight=qweight, + perm=perm, + size_k=part_size_k, + size_n=part_size_n, + num_bits=8) + layer.weight = torch.nn.Parameter(marlin_qweight, requires_grad=False) + + # WEIGHT SCALES + # Permute scales + if "weight_scale" in dir(layer): + scales = layer.weight_scale.to(layer.orig_dtype) + elif "weight_scale_inv" in dir(layer): + scales = layer.weight_scale_inv.to(layer.orig_dtype) + del layer.weight_scale_inv + + group_size = -1 if weight_block_size is None else weight_block_size[1] + + # marlin kernel only support channel-wise and group-wise quantization + # we need to convert the scales + if weight_block_size is None: + if scales.nelement() == 1: + # tensor-wise quantization -> channel-wise quantization + # (1, 1) =>(repeat)=> (1, size_n) + scales = scales.view(1, 1).repeat_interleave(part_size_n, 1) + elif scales.nelement() > 1 and scales.nelement() != part_size_n: + assert part_size_n % scales.nelement() == 0 + s_size = scales.nelement() + # tensor-wise quantization (for gate-up proj) + # -> channel-wise quantization + # (1, s_size) =>(repeat)=> (1, size_n) + scales = scales.view(1, s_size) + scales = scales.repeat_interleave(part_size_n // s_size, 1) + else: + # channel-wise quantization + # (1, size_n) + scales = scales.view(1, part_size_n) + else: + # block-wise quantization -> group-wise quantization + # (size_k // block_size[1], ceil(size_n / block_size[0])) + # =>(repeat)=> (size_k // block_size[1], size_n) + if not size_k_first: + scales = scales.T.contiguous() + block_n = weight_block_size[0] + scales = scales.repeat_interleave(block_n, 1) + # size_n may not divisible by block_size[0] + scales = scales[:, :part_size_n] + + marlin_scales = marlin_permute_scales(s=scales, + size_k=part_size_k, + size_n=part_size_n, + group_size=group_size) + marlin_scales = fp8_fused_exponent_bias_into_scales(marlin_scales) + layer.weight_scale = torch.nn.Parameter(marlin_scales, requires_grad=False) + + if hasattr(layer, "bias") and layer.bias is not None: + assert layer.bias.shape == (part_size_n, ) + bias = marlin_permute_bias(layer.bias) + layer.bias = torch.nn.Parameter(bias, requires_grad=False) + + +def prepare_moe_fp8_layer_for_marlin(layer: torch.nn.Module, + size_k_first: bool = True) -> None: + logger.warning_once( + "Your GPU does not have native support for FP8 computation but " + "FP8 quantization is being used. Weight-only FP8 compression will " + "be used leveraging the Marlin kernel. This may degrade " + "performance for compute-heavy workloads.") + + e = layer.num_experts + k = layer.hidden_size + n = layer.intermediate_size_per_partition + weight_block_size = getattr(layer, "weight_block_size", None) + + # WORKSPACE + device = layer.w13_weight.device + layer.workspace = marlin_make_workspace_new(device, 4) + perm = torch.empty(0, dtype=torch.int, device=device) + + # WEIGHT + # Repack weights to marlin format + for name in ["w13_weight", "w2_weight"]: + weight = getattr(layer, name) + tensor_list = [] + if "w13" in name: + size_n, size_k = n * 2, k + else: + size_n, size_k = k, n + + if size_k_first: + assert weight.shape == (e, size_k, size_n) + else: + assert weight.shape == (e, size_n, size_k) + + for i in range(e): + qweight = pack_fp8_to_int32(weight[i], size_k_first) + if not size_k_first: + qweight = qweight.T.contiguous() + + marlin_qweight = ops.gptq_marlin_repack(b_q_weight=qweight, + perm=perm, + size_k=size_k, + size_n=size_n, + num_bits=8) + tensor_list.append(marlin_qweight) + + weight = torch.cat([x.unsqueeze(0) for x in tensor_list], 0) + weight = torch.nn.Parameter(weight, requires_grad=False) + + setattr(layer, name, weight) + + # WEIGHT SCALES + # Permute scales + group_size = -1 if weight_block_size is None else weight_block_size[1] + + for name in ["w13", "w2"]: + if name + "_weight_scale" in dir(layer): + new_name = name + "_weight_scale" + scales = getattr(layer, new_name).to(layer.orig_dtype) + delattr(layer, new_name) + elif name + "_weight_scale_inv" in dir(layer): + new_name = name + "_weight_scale_inv" + scales = getattr(layer, new_name).to(layer.orig_dtype) + delattr(layer, new_name) + + tensor_list = [] + if "w13" in name: + size_n, size_k = n * 2, k + else: + size_n, size_k = k, n + + # marlin kernel only support channel-wise and group-wise quantization + # we need to convert the scales + if weight_block_size is None: + if scales.nelement() == e: + # tensor-wise quantization -> channel-wise quantization + # (e, 1, 1) =>(repeat)=> (e, 1, size_n) + scales = scales.view(e, 1, 1).repeat_interleave(size_n, 2) + elif scales.nelement() > e and scales.nelement() != e * size_n: + assert (e * size_n) % scales.nelement() == 0 + s_size = scales.nelement() // e + # tensor-wise quantization (for gate-up proj) + # -> channel-wise quantization + # (e, 1, s_size) =>(repeat)=> (e, 1, size_n) + scales = scales.view(e, 1, s_size) + scales = scales.repeat_interleave(size_n // s_size, 2) + else: + # channel-wise quantization + # (e, 1, size_n) + scales = scales.view(e, 1, size_n) + else: + # block-wise quantization -> group-wise quantization + # (e, size_k // block_size[1], ceil(size_n / block_size[0])) + # =>(repeat)=> (e, size_k // block_size[1], size_n) + if not size_k_first: + scales = scales.permute(0, 2, 1) + block_n = weight_block_size[0] + scales = scales.repeat_interleave(block_n, 2) + # size_n may not divisible by block_size[0] + scales = scales[..., :size_n].contiguous() + + for i in range(e): + marlin_scales = marlin_permute_scales(s=scales[i], + size_k=size_k, + size_n=size_n, + group_size=group_size) + tensor_list.append(marlin_scales) + + scales = torch.cat([x.unsqueeze(0) for x in tensor_list], 0) + scales = fp8_fused_exponent_bias_into_scales(scales) + scales = torch.nn.Parameter(scales, requires_grad=False) + + setattr(layer, name + "_weight_scale", scales) + + # BIAS + # Permute bias + for name in ["w13_bias", "w2_bias"]: + if not hasattr(layer, name): + continue + bias = getattr(layer, name).to(layer.orig_dtype) + + tensor_list = [] + for i in range(e): + expert_bias = bias[i] + + tensor_list.append(marlin_permute_bias(expert_bias)) + + bias = torch.cat([x.unsqueeze(0) for x in tensor_list], 0) + bias = torch.nn.Parameter(bias, requires_grad=False) + setattr(layer, name, bias) + + +def pack_fp8_to_int32(fp8_tensor: torch.Tensor, + size_k_first: bool = True) -> torch.Tensor: + """ + Repack FP8 weights to gptq format (packed int32 elements) + """ + assert fp8_tensor.dtype == torch.float8_e4m3fn + assert fp8_tensor.ndim == 2 + + fp8_tensor = fp8_tensor.T if size_k_first else fp8_tensor + fp8_tensor = fp8_tensor.contiguous() + # fp8_tensor is contiguous and have shape (N, K) now + # with `.view(torch.int32)`, it become (N, K // 4) + int32_tensor = fp8_tensor.view(torch.int32) + return int32_tensor.T.contiguous() if size_k_first else int32_tensor + + +def marlin_quant_fp8_torch(weight, group_size): + size_n, size_k = weight.shape + device = weight.device + + if group_size != -1: + scales = weight.view(size_n, -1, group_size).abs().max(-1)[0] / 448 + repeated_scales = scales.repeat_interleave(group_size, 1) + fp8_weight = (weight / repeated_scales).to(torch.float8_e4m3fn) + weight_ref = fp8_weight.to(weight.dtype) * repeated_scales + else: + scales = weight.view(size_n, 1, group_size).abs().max(-1)[0] / 448 + repeated_scales = scales.repeat_interleave(size_k, 1) + fp8_weight = (weight / repeated_scales).to(torch.float8_e4m3fn) + weight_ref = fp8_weight.to(weight.dtype) * repeated_scales + + packed_weight = pack_fp8_to_int32(fp8_weight, False).T.contiguous() + marlin_qweight = ops.gptq_marlin_repack( + b_q_weight=packed_weight, + perm=torch.empty(0, dtype=torch.int, device=device), + size_k=size_k, + size_n=size_n, + num_bits=8, + ) + + marlin_scales = marlin_permute_scales(s=scales.T, + size_k=size_k, + size_n=size_n, + group_size=group_size) + + marlin_scales = fp8_fused_exponent_bias_into_scales(marlin_scales) + + return weight_ref.T, marlin_qweight, marlin_scales diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/marlin_utils_test.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/marlin_utils_test.py new file mode 100644 index 0000000000000000000000000000000000000000..b2c228c242532af12a6ad5f5a068c963ce491615 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/marlin_utils_test.py @@ -0,0 +1,165 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Utility functions used for tests and benchmarks""" + +from typing import Optional + +import numpy as np +import torch + +from vllm.scalar_type import ScalarType + +from .marlin_utils import (GPTQ_MARLIN_TILE, marlin_permute_scales, + marlin_zero_points) +from .quant_utils import (get_pack_factor, gptq_quantize_weights, + quantize_weights, sort_weights) + + +class MarlinWorkspace: + + def __init__(self, out_features, min_thread_n, max_parallel): + assert (out_features % min_thread_n == 0), ( + "out_features = {} is undivisible by min_thread_n = {}".format( + out_features, min_thread_n)) + + max_workspace_size = ((out_features // min_thread_n) * max_parallel) + + self.scratch = torch.zeros(max_workspace_size, + dtype=torch.int, + device="cuda") + + +def marlin_permute_weights(q_w, size_k, size_n, perm, tile=GPTQ_MARLIN_TILE): + assert q_w.shape == (size_k, size_n) + assert size_k % tile == 0, f"size_k = {size_k}, tile = {tile}" + assert size_n % tile == 0, f"size_k = {size_n}, tile = {tile}" + + # Permute weights to 16x64 marlin tiles + q_w = q_w.reshape((size_k // tile, tile, size_n // tile, tile)) + q_w = q_w.permute((0, 2, 1, 3)) + q_w = q_w.reshape((size_k // tile, size_n * tile)) + + q_w = q_w.reshape((-1, perm.numel()))[:, perm].reshape(q_w.shape) + + return q_w + + +def marlin_weights(q_w, size_k, size_n, num_bits, perm): + # Permute + q_w = marlin_permute_weights(q_w, size_k, size_n, perm) + + # Pack + pack_factor = get_pack_factor(num_bits) + orig_device = q_w.device + + q_w = q_w.cpu().numpy().astype(np.uint32) + + q_packed = np.zeros((q_w.shape[0], q_w.shape[1] // pack_factor), + dtype=np.uint32) + for i in range(pack_factor): + q_packed |= q_w[:, i::pack_factor] << num_bits * i + + q_packed = torch.from_numpy(q_packed.astype(np.int32)).to(orig_device) + + return q_packed + + +def get_weight_perm(num_bits: int): + perm_list: list[int] = [] + for i in range(32): + perm1: list[int] = [] + col = i // 4 + for block in [0, 1]: + for row in [ + 2 * (i % 4), + 2 * (i % 4) + 1, + 2 * (i % 4 + 4), + 2 * (i % 4 + 4) + 1, + ]: + perm1.append(16 * row + col + 8 * block) + for j in range(4): + perm_list.extend([p + 256 * j for p in perm1]) + + perm = np.array(perm_list) + + if num_bits == 4: + interleave = np.array([0, 2, 4, 6, 1, 3, 5, 7]) + elif num_bits == 8: + interleave = np.array([0, 2, 1, 3]) + else: + raise Exception("num_bits must be 4 or 8, got {}".format(num_bits)) + + perm = perm.reshape((-1, len(interleave)))[:, interleave].ravel() + perm = torch.from_numpy(perm) + return perm + + +def marlin_quantize(w: torch.Tensor, + quant_type: ScalarType, + group_size: int, + act_order: bool, + test_perm: Optional[torch.Tensor] = None): + size_k, size_n = w.shape + num_bits = quant_type.size_bits + + # Normalize group_size + if group_size == -1: + group_size = size_k + assert group_size <= size_k + + # Quantize (and apply act_order if provided) + w_ref, q_w, s, g_idx, rand_perm = gptq_quantize_weights( + w, quant_type, group_size, act_order, test_perm) + + # For act_order, sort the "weights" and "g_idx" so that group ids are + # increasing + sort_indices = torch.empty(0, dtype=torch.int, device=w.device) + if act_order: + q_w, g_idx, sort_indices = sort_weights(q_w, g_idx) + + # Reformat to marlin + weight_perm = get_weight_perm(num_bits) + marlin_q_w = marlin_weights(q_w, size_k, size_n, num_bits, weight_perm) + marlin_s = marlin_permute_scales(s, size_k, size_n, group_size) + + # Create result + res_list = [w_ref, marlin_q_w, marlin_s, g_idx, sort_indices, rand_perm] + for i in range(len(res_list)): + res_list[i] = res_list[i].to(w.device) + + return res_list + + +def awq_marlin_quantize(w: torch.Tensor, quant_type: ScalarType, + group_size: int): + size_k, size_n = w.shape + + # Normalize group_size + if group_size == -1: + group_size = size_k + assert group_size <= size_k + + # Detect num groups + assert size_k % group_size == 0 + num_groups = size_k // group_size + + # Quantize with zp + w_ref, q_w, s, zp = quantize_weights(w, + quant_type, + group_size, + zero_points=True) + + # Reformat to marlin + weight_perm = get_weight_perm(quant_type.size_bits) + marlin_q_w = marlin_weights(q_w, size_k, size_n, quant_type.size_bits, + weight_perm) + marlin_s = marlin_permute_scales(s, size_k, size_n, group_size) + marlin_zp = marlin_zero_points(zp, num_groups, size_n, + quant_type.size_bits) + + # Create result + res_list = [w_ref, marlin_q_w, marlin_s, marlin_zp] + for i in range(len(res_list)): + res_list[i] = res_list[i].to(w.device) + + return res_list diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/marlin_utils_test_24.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/marlin_utils_test_24.py new file mode 100644 index 0000000000000000000000000000000000000000..1c93c364679dae9d92da80ec5e7d5c19b2250657 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/marlin_utils_test_24.py @@ -0,0 +1,464 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Utility functions used for tests and benchmarks""" + +import random + +import numpy +import torch + +from vllm.scalar_type import ScalarType + +from .marlin_utils_test import marlin_weights +from .quant_utils import gptq_quantize_weights + + +# This is PyTorch implementation of main part of reorder_meta() +# function, from tools/util/include/cutlass/util/host_reorder.h file +# of CUTLASS source tree. Furthermore, CUTLASS template for sparse +# GEMM decides upon layout of this matrix, and at the moment for the +# sparse GEMM executed on tensor cores, this is layout described by +# ColumnMajorInterleaved<2> data structure, in +# include/cutlass/layout/matrix.h of CUTLASS source tree. The +# reordering of meta matrix into meta_reordered matrix calculated +# according to these segments of CUTLASS code is re-implemented here. +# Note that this calculation produces offsets for scattering metadata +# matrix elements into reordered metadata matrix elements (or, +# equivalently, for gathering reordered metadata matrix element back +# into metadata matrix elements). +def _calculate_meta_reordering_scatter_offsets(m, meta_ncols, meta_dtype, + device): + dst_rows = torch.arange(0, m, device=device)[:, None].repeat(1, meta_ncols) + dst_cols = torch.arange(0, meta_ncols, device=device).repeat(m, 1) + + # Reorder the rows, then swizzle the 2x2 blocks. + group_x = 64 + group_y = 32 if meta_dtype.itemsize == 2 else 16 + + dst_rows = (dst_rows // group_x * group_x + (dst_rows % 2) * 2 + + (dst_rows % 8) // 4 + ((dst_rows % group_y) % 4) // 2 * 32 + + ((dst_rows % group_x) // 8) * 4) + + topright = ((dst_rows % 2 == 0) & (dst_cols % 2 == 1)).to(torch.int8) + bottomleft = ((dst_rows % 2 == 1) & (dst_cols % 2 == 0)).to(torch.int8) + dst_rows += topright - bottomleft + dst_cols -= topright - bottomleft + + # Assumed that meta tensor is to be stored in CUTLASS + # InterleavedColumnMajor layout, and reverse engineered + # corresponding code to store values into this tensor. + interleave = 2 + cols_maj = dst_cols // interleave + cols_min = dst_cols % interleave + return (cols_maj * m * interleave + dst_rows * interleave + + cols_min).view(-1) + + +# This function converts dense matrix into sparse semi-structured +# representation, producing "compressed" matrix, in the layout used by +# CUTLASS backend, and corresponding metadata matrix. +def sparse_semi_structured_from_dense_cutlass(dense): + if dense.dim() != 2: + raise RuntimeError( + f"Expected 2-dimensional dense tensor, got {dense.dim()}-dimensional tensor" # noqa: E501 + ) + + m, k = dense.shape + device = dense.device + + meta_dtype = torch.int8 + if dense.dtype == torch.int8: + meta_dtype = torch.int32 + elif dense.dtype in [torch.half, torch.bfloat16, torch.float, torch.int32]: + meta_dtype = torch.int16 + else: + raise RuntimeError(f"Invalid datatype {dense.dtype} of dense matrix") + quadbits_per_meta_elem = meta_dtype.itemsize * 8 // 4 + if quadbits_per_meta_elem not in (4, 8): + raise RuntimeError( + "Invalid number of elements per meta element calculated") + + if meta_dtype == torch.int32: + if m % 16 != 0: + raise RuntimeError( + f"Number of rows of dense matrix {m} must be divisible by 16") + else: + if m % 32 != 0: + raise RuntimeError( + f"Number of rows of dense matrix {m} must be divisible by 32") + if k % (4 * quadbits_per_meta_elem) != 0: + raise RuntimeError( + f"Number of columns of dense matrix {k} must be divisible by {4 * quadbits_per_meta_elem}" # noqa: E501 + ) + + if dense.dtype != torch.float: + ksparse = 4 + dense_4 = dense.view(-1, k // ksparse, ksparse) + m0, m1, m2, m3 = (dense_4 != 0).unbind(-1) + else: + ksparse = 2 + dense_2 = dense.view(-1, k // ksparse, ksparse) + m0, m2 = m1, m3 = (dense_2 != 0).unbind(-1) + meta_ncols = k // (ksparse * quadbits_per_meta_elem) + + # Encoding quadruples of True/False values as follows: + # [True, True, False, False] -> 0b0100 + # [True, False, True, False] -> 0b1000 + # [False, True, True, False] -> 0b1001 + # [True, False, False, True ] -> 0b1100 + # [False, True, False, True ] -> 0b1101 + # [False, False, True, True ] -> 0b1110 + # Thus, lower two bits in the encoding are index of the True value + # at the lowest index in the quadruple, and the higher two bits in + # the encoding are index of the other True value in the quadruple. + # In case there are less than two True values, than False value or + # values at some index or indices are considered True for the + # encoding. In case there are more than two True values, then the + # excess True value(s) at some indices are considered False for + # the encoding. The exact encodings used for these cases are as + # follows: + # [False, False, False, False] -> 0b1110 + # [False, False, False, True ] -> 0b1110 + # [False, False, True, False] -> 0b1110 + # [False, True, False, False] -> 0b1001 + # [False, True, True, True ] -> 0b1101 + # [True, False, False, False] -> 0b1000 + # [True, False, True, True ] -> 0b1100 + # [True, True, False, True ] -> 0b0100 + # [True, True, True, False] -> 0b0100 + # [True, True, True, True ] -> 0b0100 + # These particular encodings are chosen, with the help of Espresso + # logic minimizer software, for the purpose of minimization of + # corresponding Boolean functions, that translate non-zero flags + # into encoding bits. Note also possible choices for the first + # and last of these encodings were limited only to (0b0100, + # 0b1110), in order to produce valid encodings for 1:2 sparsity + # case. + + expr0 = m0 & m1 + expr1 = ~m0 & m1 + expr2 = ~m0 & ~m1 + bit0 = expr1 + bit1 = expr2 + bit2 = expr0 | expr2 | m3 + bit3 = expr1 | ~m1 + idxs0 = bit0 | (bit1.to(torch.int64) << 1) + idxs1 = bit2 | (bit3.to(torch.int64) << 1) + + if dense.dtype != torch.float: + sparse0 = dense_4.gather( + -1, idxs0.unsqueeze(-1)) # type: ignore[possibly-undefined] + sparse1 = dense_4.gather(-1, idxs1.unsqueeze(-1)) + sparse = torch.stack((sparse0, sparse1), dim=-1).view(m, k // 2) + else: + sparse = dense_2.gather(-1, + idxs0.unsqueeze(-1) // 2).view( + m, + k // 2) # type: ignore[possibly-undefined] + + meta_4 = idxs0 | (idxs1 << 2) + meta_n = meta_4.view( + (-1, meta_ncols, quadbits_per_meta_elem)).to(meta_dtype) + + if quadbits_per_meta_elem == 4: + meta = (meta_n[:, :, 0] + | (meta_n[:, :, 1] << 4) + | (meta_n[:, :, 2] << 8) + | (meta_n[:, :, 3] << 12)) + elif quadbits_per_meta_elem == 8: + meta = (meta_n[:, :, 0] + | (meta_n[:, :, 1] << 4) + | (meta_n[:, :, 2] << 8) + | (meta_n[:, :, 3] << 12) + | (meta_n[:, :, 4] << 16) + | (meta_n[:, :, 5] << 20) + | (meta_n[:, :, 6] << 24) + | (meta_n[:, :, 7] << 28)) + + # Reorder meta tensor elements. + meta_reordered = meta.new_empty( + (m * meta_ncols, )) # type: ignore[possibly-undefined] + meta_offsets = _calculate_meta_reordering_scatter_offsets( + m, meta_ncols, meta_dtype, device) + meta_reordered.scatter_(0, meta_offsets, meta.view(-1)) + + return (sparse, meta_reordered.view(m, meta_ncols)) + + +# This function performs reverse of the function above - it +# reconstructs dense matrix from a pair of "compressed" matrix, given +# in the layout used by CUTLASS backend, and accompanying metadata +# matrix. +def sparse_semi_structured_to_dense_cutlass(sparse, meta_reordered): + if sparse.dim() != 2: + raise RuntimeError( + f"Expected 2-dimensional sparse tensor, got {sparse.dim()}-dimensional tensor" # noqa: E501 + ) + + m, k = sparse.shape + device = sparse.device + + if meta_reordered.dim() != 2: + raise RuntimeError( + f"Expected 2-dimensional meta tensor, got {meta_reordered.dim()}-dimensional tensor" # noqa: E501 + ) + if meta_reordered.device != device: + raise RuntimeError( + f"Expected meta matrix to be on {device} device, got matrix on {meta_reordered.device} device" # noqa: E501 + ) + + meta_dtype = meta_reordered.dtype + if meta_dtype not in (torch.int16, torch.int32): + raise RuntimeError(f"Invalid datatype {meta_dtype} of meta matrix") + quadbits_per_meta_elem = meta_dtype.itemsize * 8 // 4 + + ksparse = 4 if sparse.dtype != torch.float else 2 + + meta_nrows, meta_ncols = meta_reordered.shape + if meta_nrows != m: + raise RuntimeError( + f"Number of rows of meta matrix {meta_nrows} must be equal to number of columns of spase matrix {m}" # noqa: E501 + ) + if meta_ncols * ksparse * quadbits_per_meta_elem != 2 * k: + raise RuntimeError( + f"Number of columns of sparse matrix {k} different from the {meta_ncols * ksparse * quadbits_per_meta_elem // 2}, " # noqa: E501 + "expected according to the number of columns of meta matrix") + + # Undo meta tensor elements reordering. + meta_offsets = _calculate_meta_reordering_scatter_offsets( + m, meta_ncols, meta_dtype, device) + meta = torch.gather(meta_reordered.view(-1), 0, + meta_offsets).view(m, meta_ncols) + + # Unpack sparse tensor back to original dense tensor, using + # information provided by meta tensor. Note that torch.float + # datatype is handled pretty much the same as + # torch.half/torch.bfloat16, as metadata for a pair of torch.float + # value is encoded as if underlying 8 bytes contain four + # torch.half/torch.bfloat16 values, where either first two or last + # two are zeros. + meta_2 = torch.empty( + (m, meta_ncols, 2 * quadbits_per_meta_elem), + dtype=meta_dtype, + device=device, + ) + if quadbits_per_meta_elem == 4: + meta_2[:, :, 0] = meta & 0b11 + meta_2[:, :, 1] = (meta >> 2) & 0b11 + meta_2[:, :, 2] = (meta >> 4) & 0b11 + meta_2[:, :, 3] = (meta >> 6) & 0b11 + meta_2[:, :, 4] = (meta >> 8) & 0b11 + meta_2[:, :, 5] = (meta >> 10) & 0b11 + meta_2[:, :, 6] = (meta >> 12) & 0b11 + meta_2[:, :, 7] = (meta >> 14) & 0b11 + elif quadbits_per_meta_elem == 8: + meta_2[:, :, 0] = meta & 0b11 + meta_2[:, :, 1] = (meta >> 2) & 0b11 + meta_2[:, :, 2] = (meta >> 4) & 0b11 + meta_2[:, :, 3] = (meta >> 6) & 0b11 + meta_2[:, :, 4] = (meta >> 8) & 0b11 + meta_2[:, :, 5] = (meta >> 10) & 0b11 + meta_2[:, :, 6] = (meta >> 12) & 0b11 + meta_2[:, :, 7] = (meta >> 14) & 0b11 + meta_2[:, :, 8] = (meta >> 16) & 0b11 + meta_2[:, :, 9] = (meta >> 18) & 0b11 + meta_2[:, :, 10] = (meta >> 20) & 0b11 + meta_2[:, :, 11] = (meta >> 22) & 0b11 + meta_2[:, :, 12] = (meta >> 24) & 0b11 + meta_2[:, :, 13] = (meta >> 26) & 0b11 + meta_2[:, :, 14] = (meta >> 28) & 0b11 + meta_2[:, :, 15] = (meta >> 30) & 0b11 + + dense_offsets = meta_2.view(-1) + ( + torch.arange(0, 2 * m * k // ksparse, device=device) * 4).view( + -1, 1).repeat(1, 2).view(-1) + + dense = torch.zeros((m * 2 * k, ), dtype=sparse.dtype, device=device) + if sparse.dtype != torch.float: + # dense.scatter_(0, dense_offsets, sparse.view(-1)) + dense.scatter_(0, dense_offsets, sparse.reshape(-1)) + else: + dense.view(torch.half).scatter_(0, dense_offsets, + sparse.view(torch.half).view(-1)) + + return dense.view(m, 2 * k) + + +def mask_creator(tensor): + """ + Class for creating N:M sparsity masks. + Masks will be created using the N:M ratio, where for every block of + M weights, N will be pruned based on ranked weight value. Each mask + will correspond to the given tensor. + + :param N: The number of weights in a group to keep + :param M: The size of a weight group + """ + N = 2 + M = 4 + + mask = None + # for i, tensor in enumerate(tensors): + if tensor.numel() % M != 0: + raise ValueError( + f"Tensor of size {tensor.shape} can't be evenly divided into " + f"{M} groups") + + num_groups = tensor.numel() // M + + # N:M sparsity for linear layers + tensor_temp = tensor.detach().abs().reshape(num_groups, M) + index = torch.argsort(tensor_temp, dim=1)[:, :int(M - N)] + + w_b = torch.ones(tensor_temp.shape, device=tensor_temp.device) + mask = w_b.scatter_(dim=1, index=index, value=0).reshape(tensor.shape) + + return mask + + +def inject_24(w, size_k, size_n): + assert w.shape == (size_k, size_n) + + mask = mask_creator(w.t()).t().cuda().bool() + + return (mask * w).contiguous(), mask.contiguous() + + +def check_24(w, num_rows_to_sample=50, _verbose=False): + BLOCK_SIZE = 4 + MAX_NON_ZEROS = 2 + + w = w.t().contiguous() + + print("check_24: w.shape = {}".format(w.shape)) + + num_rows, num_cols = w.shape + sampled_row_idxs = random.choices(range(num_rows), k=num_rows_to_sample) + if _verbose: + print(f"Sampled row idxs = {sampled_row_idxs}") + + total_segments = 0 + non_24_segments = 0 + for i in sampled_row_idxs: + for j in range(0, num_cols - BLOCK_SIZE, BLOCK_SIZE): + total_segments += 1 + block = w[i, j:j + BLOCK_SIZE] + num_nonzero = torch.count_nonzero(block) + if num_nonzero > MAX_NON_ZEROS: + print("i = {} j = {} block = {}".format(i, j, block)) + non_24_segments += 1 + + print(f"{non_24_segments} / {total_segments} do not have 2:4 structure.") + + +def compress_quantized_24_weight(q_24, size_k, size_n, wtype: ScalarType): + assert q_24.shape == (size_k, size_n) + + # Remove bias to normalize over 0 + q_24_no_zp = q_24 - wtype.bias + + # Compress + q_24_no_zp = q_24_no_zp.t().contiguous() + q_24_no_zp_comp, meta = sparse_semi_structured_from_dense_cutlass( + q_24_no_zp) + q_24_no_zp_comp = q_24_no_zp_comp.t().contiguous() + + # Restore bias + q_24_comp = q_24_no_zp_comp + wtype.bias + + # Resize meta to its actual shape (without moving any data) + meta = meta.resize_(meta.shape[1] // 2, meta.shape[0] * 2) + + return q_24_comp, meta + + +def get_scale_perms_24(): + scale_perm: list[int] = [] + for i in range(8): + scale_perm.extend([i * 8 + j for j in [0, 4, 1, 5, 2, 6, 3, 7]]) + scale_perm_single: list[int] = [] + for i in range(8): + scale_perm_single.extend([8 * i + j for j in [0, 1, 2, 3, 4, 5, 6, 7]]) + return scale_perm, scale_perm_single + + +def get_weight_perm_24(num_bits: int): + perm_list: list[int] = [] + for i in range(32): + perm1: list[int] = [] + col = i // 4 + col_o = col // 2 + for block in [0, 1]: + for row in [ + 2 * (i % 4), + 2 * (i % 4) + 1, + 2 * (i % 4 + 4), + 2 * (i % 4 + 4) + 1, + ]: + perm1.append(16 * row + col_o * 256 + 8 * (col % 2) + + 4 * block) + for j in range(4): + perm_list.extend([p + 1 * j for p in perm1]) + perm = numpy.array(perm_list) + + if num_bits == 4: + interleave = numpy.array([0, 2, 4, 6, 1, 3, 5, 7]) + elif num_bits == 8: + interleave = numpy.array([0, 2, 1, 3]) + else: + raise ValueError("num_bits must be 4 or 8, got {}".format(num_bits)) + + perm = perm.reshape((-1, len(interleave)))[:, interleave].ravel() + perm = torch.from_numpy(perm) + return perm + + +def marlin_permute_scales_24(s: torch.Tensor, size_k: int, size_n: int, + group_size: int) -> torch.Tensor: + + scale_perm, scale_perm_single = get_scale_perms_24() + if group_size < size_k and group_size != -1: + s = s.reshape((-1, len(scale_perm)))[:, scale_perm] + else: + s = s.reshape((-1, len(scale_perm_single)))[:, scale_perm_single] + s = s.reshape((-1, size_n)).contiguous() + + return s + + +def marlin_24_quantize( + w: torch.Tensor, + quant_type: ScalarType, + group_size: int, +): + size_k, size_n = w.shape + + # Normalize group_size + if group_size == -1: + group_size = size_k + assert group_size <= size_k + + # Inject 2:4 sparsity + w_24, mask_24 = inject_24(w, size_k, size_n) + + # Quantize + w_24_ref, q_w_24, s, g_idx, rand_perm = gptq_quantize_weights( + w_24, quant_type, group_size, act_order=False) + + # Compress quantized weight + q_w_24_comp, meta = compress_quantized_24_weight(q_w_24, size_k, size_n, + quant_type) + size_k_comp = size_k // 2 + + # Reformat to marlin + weight_perm = get_weight_perm_24(quant_type.size_bits) + marlin_24_q_w_comp = marlin_weights(q_w_24_comp, size_k_comp, size_n, + quant_type.size_bits, weight_perm) + marlin_24_s = marlin_permute_scales_24(s, size_k, size_n, group_size) + + # Create result + res_list = [w_24_ref, marlin_24_q_w_comp, meta, marlin_24_s] + for i in range(len(res_list)): + res_list[i] = res_list[i].to(w.device) + + return res_list diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/nvfp4_moe_support.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/nvfp4_moe_support.py new file mode 100644 index 0000000000000000000000000000000000000000..21af74c6b72b5f093aae07b6457eedd74a28a0fa --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/quantization/utils/nvfp4_moe_support.py @@ -0,0 +1,59 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +from dataclasses import dataclass + +import vllm.envs as envs +from vllm.logger import init_logger +from vllm.model_executor.layers.quantization.utils.flashinfer_fp4_moe import ( + is_flashinfer_fp4_cutlass_moe_available) +from vllm.model_executor.layers.quantization.utils.marlin_utils_fp4 import ( + is_fp4_marlin_supported) +from vllm.model_executor.layers.quantization.utils.quant_utils import ( + cutlass_fp4_supported) + +__all__ = ["detect_nvfp4_moe_support", "NvFp4Support"] + +_logger = init_logger(__name__) + + +@dataclass(frozen=True) +class NvFp4Support: + """Result container for NV-FP4 capability probing.""" + + cutlass_supported: bool + allow_flashinfer: bool + use_marlin: bool + + +def detect_nvfp4_moe_support(class_name: str = "") -> NvFp4Support: + """Detect platform support for NV-FP4 fused-MoE path""" + cutlass_supported = cutlass_fp4_supported() + + allow_flashinfer = (cutlass_supported + and is_flashinfer_fp4_cutlass_moe_available()) + + if allow_flashinfer: + _logger.info_once("Using FlashInfer kernels for %s.", class_name + or "NVFP4 path") + else: + if envs.VLLM_USE_FLASHINFER_MOE_FP4: + _logger.warning_once( + "FlashInfer kernels unavailable for %s on current platform.", + class_name or "NVFP4 path", + ) + + use_marlin = False + if not cutlass_supported: + if is_fp4_marlin_supported(): + use_marlin = True + _logger.info_once("Falling back to Marlin FP4 MoE kernel.") + else: + raise ValueError( + "Current platform does not support NVFP4 quantization. " + "Please use Blackwell GPUs or enable FlashInfer.") + + return NvFp4Support( + cutlass_supported=cutlass_supported, + allow_flashinfer=allow_flashinfer, + use_marlin=use_marlin, + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/rotary_embedding/__pycache__/linear_scaling_rope.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/rotary_embedding/__pycache__/linear_scaling_rope.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a552390e0f814b56076cf09019378593d5ec70b0 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/rotary_embedding/__pycache__/linear_scaling_rope.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/rotary_embedding/__pycache__/llama4_vision_rope.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/rotary_embedding/__pycache__/llama4_vision_rope.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b9cd64318a3a2f5ae0b83a1460406703f7086c6 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/rotary_embedding/__pycache__/llama4_vision_rope.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/rotary_embedding/__pycache__/ntk_scaling_rope.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/rotary_embedding/__pycache__/ntk_scaling_rope.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0890f7bfa3b256bf397b6d2a6138cdbd03655f0a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/layers/rotary_embedding/__pycache__/ntk_scaling_rope.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/model_loader/__pycache__/weight_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/model_loader/__pycache__/weight_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3db8933a1d799944ffb11e98520990a74a72426 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/model_loader/__pycache__/weight_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/aimv2.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/aimv2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a07c1a43a0e7849b2e7bca60d539ed4173b5186 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/aimv2.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/baichuan.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/baichuan.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..857c1cdfe645c6a786b8e0b70ff9e9c29db29537 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/baichuan.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/clip.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/clip.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f869678142313813a97b8bae466ce7b5df1de6b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/clip.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/dbrx.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/dbrx.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d07f6f5807fb29fb33d40f9d5b48e7647e9a12e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/dbrx.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/deepseek.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/deepseek.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e5b7d6662fa82b9d4138ad49ca152760fc181a2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/deepseek.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/dots1.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/dots1.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e007f77c7cd5329070681ff3726f3199f2af3273 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/dots1.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/ernie45_moe.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/ernie45_moe.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c30666188a0814719faba5bd2aa7b96aae4e3c5 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/ernie45_moe.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/fairseq2_llama.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/fairseq2_llama.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..263f3da0f49db8a60a08931de79e2f28385c4b12 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/fairseq2_llama.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/falcon.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/falcon.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84a03195e414d1ea3a3fd872fc7de0788ca2bb75 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/falcon.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/falcon_h1.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/falcon_h1.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75337851b39b070fd67d6a951d9f54296fd8061d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/falcon_h1.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/fuyu.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/fuyu.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43b6caa7ac3f0c7618f8d4d30181d0a3a080e9a0 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/fuyu.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/glm4_1v.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/glm4_1v.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5113148a8238d86b2086c9ce8d7cced4a7ae0f23 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/glm4_1v.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/glm4_moe.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/glm4_moe.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24987675820852290acf525886082a93ce0cd2f8 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/glm4_moe.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/glm4v.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/glm4v.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0dab0c02c054a4cf72392f3b92f4fdee286b6437 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/glm4v.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/gpt2.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/gpt2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b71932e6aa34ffc94cd03a920076b6a50bcdf19 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/gpt2.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/gpt_bigcode.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/gpt_bigcode.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2808a142df9b85367cc2d35d5d413d104bd92da Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/gpt_bigcode.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/gpt_neox.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/gpt_neox.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3439790ec0da72ea362ac383e9e71cd6d743429 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/gpt_neox.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/gritlm.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/gritlm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26b58aac6f14da7ec53dc9b37713a5e2821dcf13 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/gritlm.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/grok1.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/grok1.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4c24359155892aaae640d87275987dbdad8e681 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/grok1.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/hunyuan_v1.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/hunyuan_v1.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec8b91b8cdacd5728a973f4c73cdeebad1a003b9 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/hunyuan_v1.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/idefics2_vision_model.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/idefics2_vision_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82e180557c14a3a254bc8b335f5ee416e23b433e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/idefics2_vision_model.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/interfaces.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/interfaces.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8c37f0a71115f961d1a4d0b295ea3ab7de9da06 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/interfaces.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/interfaces_base.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/interfaces_base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7570ffab6b46d72e7fdb73dae34d02cd01cde75 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/interfaces_base.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/intern_vit.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/intern_vit.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38f9f69abd70ee6c0f3970e9343a70f088e5ba0a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/intern_vit.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/interns1.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/interns1.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33229d969894e38d08b5827039f6b06ba262ca02 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/interns1.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/interns1_vit.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/interns1_vit.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4735c22f00fa7d9521013b41ed889d5c862433c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/interns1_vit.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/internvl.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/internvl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1948d4ab122827eeaf883d0c6973ef3ac4262988 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/internvl.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/jina_vl.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/jina_vl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3137e40aae768e4ef170b36a1459b62c6d4a85d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/jina_vl.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/keye.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/keye.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23d356d4b24927851c19ecb3d1708519fa07b680 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/keye.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/kimi_vl.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/kimi_vl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8d8945aa627b73bf3698b4fc8c3c1078250fd99 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/kimi_vl.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/llama.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/llama.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be9b715b0cf3566ec861558a5dc53a865a28eda2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/llama.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/llama4.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/llama4.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1600dbdbe87b60c1b101943fba579d112ec97479 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/llama4.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/llama_eagle.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/llama_eagle.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa895f96dbe1db681a2d0b757ee2eca701c7675d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/llama_eagle.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/llava.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/llava.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfa3c8860d0c3a78a661259a3fdff9efa3563c9c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/llava.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/llava_next_video.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/llava_next_video.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e238ff5563a1f88e51d06d4bd504c1f43bb37de3 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/llava_next_video.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/llava_onevision.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/llava_onevision.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c63717a31ff75241eab865ee5f96e11a15674a89 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/llava_onevision.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mamba_cache.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mamba_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41bc30e704500060aa4a6c60d9f0218d25449c56 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mamba_cache.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/medusa.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/medusa.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..955beec523ba2a72aa9a126583bac6fc30628d5c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/medusa.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mimo.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mimo.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8970cb9fed6a5acf3ec2b2e6092c17439019d64d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mimo.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mimo_mtp.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mimo_mtp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13c705f0edd1db21110a64a188bd39ae0eccedd4 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mimo_mtp.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minicpm.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minicpm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ad367ca5acc2b32450e857d3e2b6630b894ba6c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minicpm.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minicpm3.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minicpm3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f9a69c65d9ee8b72b1463fd40f8b1715dbd0e76 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minicpm3.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minicpm_eagle.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minicpm_eagle.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1aa8706aaf9ed3a023a5b4580031b81f1ecadef9 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minicpm_eagle.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minicpmo.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minicpmo.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06253b6bec79a144fe45610866df9c0bae3559b8 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minicpmo.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minicpmv.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minicpmv.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18ae4a346277ca65897efe0eacc0875470d27d95 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minicpmv.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minimax_cache.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minimax_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59d1c1af04e33d9d0e85cafa39bd72d2a9ea9e91 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minimax_cache.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minimax_text_01.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minimax_text_01.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a7de838884858a7d54a71a36505b07299ac197e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minimax_text_01.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minimax_vl_01.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minimax_vl_01.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..573961a3e20dd55d847aed3b2a06746705026e6f Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/minimax_vl_01.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mistral3.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mistral3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6efdb97e79367b6aea25b4705e6b12c0b9bc5d2a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mistral3.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mixtral_quant.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mixtral_quant.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c111379b9346ce51e0c5efd859d1c88e4782c9e5 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mixtral_quant.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mllama.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mllama.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f369e864f7cc1582f37451c2119139f0ecc95cd Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mllama.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mlp_speculator.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mlp_speculator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4d7c58743e766143337243f72a8911180987237 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mlp_speculator.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/modernbert.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/modernbert.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19e48e685717c27467618df0aecfacc05a2fd139 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/modernbert.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/molmo.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/molmo.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76b48de8c7e35f8f92f0b3a86d217e1d92617a67 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/molmo.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/moonvit.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/moonvit.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..267339872fb194f87b25170634ff79b5f0587f7f Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/moonvit.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mpt.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mpt.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a1c1202a1a0ab25c0b89950cb5163193bb80a80 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/mpt.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/nemotron.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/nemotron.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5483f2edb13d0d7be6a81da3d130db4e5da13e4 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/nemotron.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/nemotron_h.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/nemotron_h.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f7373404053a584d3ff4790803686738a1803a6 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/nemotron_h.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/nemotron_nas.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/nemotron_nas.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..550df39d7327fa3b5bc6b54c7f7515a37747a4d8 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/nemotron_nas.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/nemotron_vl.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/nemotron_vl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..562817727f49192f4fba674991fc29520277d7b1 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/nemotron_vl.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/nvlm_d.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/nvlm_d.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c979f88e76495a784bfff2636c77e1d61dea5a99 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/nvlm_d.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/olmo.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/olmo.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bea76c7a5494be5635a1a68c4b9122d8810b4ab3 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/olmo.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/olmo2.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/olmo2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21e9db913d2c27fb268486ff35f0664fe333373f Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/olmo2.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/olmoe.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/olmoe.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23cacefdc29390f442595692f0af54076c74cf77 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/olmoe.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/opt.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/opt.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0398aeec95523f5c7a57f1e884cc2659e508332 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/opt.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/orion.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/orion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..498cc3f0901670ea3500e4653484d113ff55bdf6 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/orion.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/ovis.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/ovis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..891cdd46e7e288317022ca611d1ff2ae50233d7d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/ovis.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/paligemma.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/paligemma.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4bcf3810678124d1d2b18e00785c88d67ac786a8 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/paligemma.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/persimmon.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/persimmon.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db2e8c40be7299e6ffa2e6bdad9473f758022678 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/persimmon.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9eb98ce9827a5e456fc86c3fb30c8fe1b21293e2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi3.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17c749a8a4e24eceb990741bfcf312076b81f99b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi3.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi3v.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi3v.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4901117cdf3d77c2ee56d299d77e21d548ea4fa0 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi3v.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi4_multimodal.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi4_multimodal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76d274d93e33ebb06cb1ebffab4779c00b3e225d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi4_multimodal.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi4flash.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi4flash.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e95a3f718db890cac79f413ea159cec1a95f396e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi4flash.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi4mm.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi4mm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..547fe0176c1f5a561fe8a5135c561bd8c2f22b8c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi4mm.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi4mm_audio.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi4mm_audio.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7826ee2cd6775de90d50a9c9ec9d6d5b443922df Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi4mm_audio.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi4mm_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi4mm_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31ec971649fc67286c499413a7179bf66b6cd6d7 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phi4mm_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phimoe.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phimoe.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..181c66a458c352486b3ec39b0dbd5674b83ee0a0 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/phimoe.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/pixtral.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/pixtral.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..833c1f55c97e7782c3103e42488f818f721a6452 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/pixtral.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d91c8fabe54d8f5d69963b54e035437ec49f0268 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen2.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abbd97b77393ba70309717ed82c0efe26ab7bfdb Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen2.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen2_5_omni_thinker.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen2_5_omni_thinker.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db87712e8074b50b64bd7be07548a975f95bf3dc Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen2_5_omni_thinker.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen2_5_vl.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen2_5_vl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28789ee7296235af1c429200997b7f060e0f12e1 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen2_5_vl.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen2_audio.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen2_audio.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8ad8088fa81a05cbeb5afb3b28c48c929c90517 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen2_audio.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen2_moe.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen2_moe.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9e4ad4d8652fe7cdf1013698606cf28875b8e41 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen2_moe.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen2_rm.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen2_rm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..761e66732ed3dce58c668eb6ec29361854c385f8 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen2_rm.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen2_vl.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen2_vl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1407662ac0d37e0bc93971b61c199248d7b64d7c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen2_vl.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen3.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1829a2d0b5624c92ef8e681cae5a54d0f1f57960 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen3.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen3_moe.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen3_moe.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc5e30a3f7f159872b567c1b84cfdcf496bc9344 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/qwen3_moe.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/registry.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/registry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf06c329078c3183692caaa627ac21a8fbaafca6 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/registry.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/roberta.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/roberta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1394ac8be24534130731c0132aefed7533e433d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/roberta.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/siglip.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/siglip.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ee23a1ecb384149ee233371f80e919e203be577 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/siglip.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/skyworkr1v.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/skyworkr1v.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71fb1db2adb9161081865afcbf832d5322b56071 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/skyworkr1v.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/smolvlm.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/smolvlm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a2b260b53f78e1125709f6aecc4a2d6700168e9 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/smolvlm.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/solar.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/solar.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36b3d1903a1aab767eb974b0b4bc6e805fddcf31 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/solar.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/stablelm.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/stablelm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b53e3738dc4895ecc23480193ffe97c122013be Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/stablelm.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/starcoder2.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/starcoder2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d7d07ee398fc4997c0dc70f8cb706fe3f9e581f Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/starcoder2.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/step3_text.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/step3_text.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21739bb0de7cb328f5b0ed4831b06c775c9da490 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/step3_text.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/step3_vl.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/step3_vl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38d8212921094cf5e94f068da92c0dd6a9917271 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/step3_vl.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/tarsier.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/tarsier.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e5d5fca622cb791e8df8e524b042e9e68ef8111 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/tarsier.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/telechat2.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/telechat2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d698b55b0e6703e746788369e514cfc79450799c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/telechat2.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/teleflm.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/teleflm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d0a0d99a7264f62795e2775ac9d405c46abbed8 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/teleflm.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/transformers.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/transformers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b551c0c32b3fcebfdc8994cd1b2cf50a00cc84d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/transformers.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/ultravox.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/ultravox.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9e4a39eca5d36d8d364029ffff6ee0e6080c222 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/ultravox.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0981f47e3268367e4cbf364dfbd18aca6b29aaeb Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/vision.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/vision.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51c12c308bfbf43c2c804b8164812630405ed954 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/vision.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/voxtral.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/voxtral.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e564a33b826c466d61f101f9a101d917eef39118 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/voxtral.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/whisper.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/whisper.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4859f320ae18c32720575679c123115ecde6b7af Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/whisper.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/zamba2.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/zamba2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34b0a515df9c3a363ca4e40bf6d0821f87014504 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/models/__pycache__/zamba2.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/warmup/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/warmup/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..055da646e608a5281fc19b15a1cd1d903786feca Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/warmup/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/warmup/__pycache__/deep_gemm_warmup.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/warmup/__pycache__/deep_gemm_warmup.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43a02c5615dfba9c4b478d965b43b7dacf928273 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/warmup/__pycache__/deep_gemm_warmup.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/warmup/__pycache__/kernel_warmup.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/warmup/__pycache__/kernel_warmup.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a410871e7dad4d2a5a94149c5a116f958b450f67 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/model_executor/warmup/__pycache__/kernel_warmup.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28f00e8daea851822cd2bbe8ac8519a188f63e3f Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/audio.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/audio.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af7e932b803eb1ffe4c07e9120bdcc51af9d2695 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/audio.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/base.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef115d10f9a7fb9938d4e2b3fa4dc6c6c035ede5 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/base.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/cache.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6f934caf062f2dd05bfa000dd73f7f3c5d91cb1 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/cache.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/hasher.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/hasher.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abae59982efb7bcf1a9e8936ba88999bc049df3f Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/hasher.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/image.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/image.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9810dd83a9d50e1ce7a408825d39e982eba7cb15 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/image.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/inputs.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/inputs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab48eb018973c2042c70ab1d7171118e8064a5f8 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/inputs.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/parse.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/parse.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c244897794ec68d565410b120ffa0c79e4f8b399 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/parse.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/processing.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/processing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..857649d50046acaba39a61a0b9b3f73924b47bb7 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/processing.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/profiling.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/profiling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc41cd5f379af42e9a436d0affb921871b7a2036 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/profiling.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/registry.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/registry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c764994dd4f3726cc9f20c48d5af4940cd9230b3 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/registry.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/video.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/video.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99533263e1b4836c0f69ad6e71f879f1ea1e1cbb Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/multimodal/__pycache__/video.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/platforms/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/platforms/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb0db5e8ce0252c170bd00d4a7e3677463bd70a9 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/platforms/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/platforms/__pycache__/cpu.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/platforms/__pycache__/cpu.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..521cdb16f360b7c03c5e4fe6c60d35c1ff406812 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/platforms/__pycache__/cpu.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/platforms/__pycache__/cuda.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/platforms/__pycache__/cuda.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72f5e7e8054292e823c3a1e0a817ad91f3bdd705 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/platforms/__pycache__/cuda.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/platforms/__pycache__/neuron.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/platforms/__pycache__/neuron.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d03cacab7c9f5b4b320acf4d5a6c87afc9b2316 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/platforms/__pycache__/neuron.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/platforms/__pycache__/rocm.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/platforms/__pycache__/rocm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51a52740a83b23abc01f3343ed17e7494094a6cf Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/platforms/__pycache__/rocm.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/plugins/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/plugins/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65b0ec99b99f9208bb83c36f273ab5055b936a05 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/plugins/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/plugins/lora_resolvers/README.md b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/plugins/lora_resolvers/README.md new file mode 100644 index 0000000000000000000000000000000000000000..48f27dddea07ed4f23abc331dd1b9e7c6147ab0d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/plugins/lora_resolvers/README.md @@ -0,0 +1,16 @@ +# LoRA Resolver Plugins + +This directory contains vLLM general plugins for dynamically discovering and loading LoRA adapters +via the LoRAResolver plugin framework. + +Note that `VLLM_ALLOW_RUNTIME_LORA_UPDATING` must be set to true to allow LoRA resolver plugins +to work, and `VLLM_PLUGINS` must be set to include the desired resolver plugins. + +## lora_filesystem_resolver + +This LoRA Resolver is installed with vLLM by default. +To use, set `VLLM_PLUGIN_LORA_CACHE_DIR` to a local directory. When vLLM receives a request +for a LoRA adapter `foobar` it doesn't currently recognize, it will look in that local directory +for a subdirectory `foobar` containing a LoRA adapter. If such an adapter exists, it will +load that adapter, and then service the request as normal. That adapter will then be available +for future requests as normal. diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/plugins/lora_resolvers/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/plugins/lora_resolvers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/plugins/lora_resolvers/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/plugins/lora_resolvers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4f775bd64740f32074a2413dfa98b5f4e8c6b8c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/plugins/lora_resolvers/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/plugins/lora_resolvers/__pycache__/filesystem_resolver.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/plugins/lora_resolvers/__pycache__/filesystem_resolver.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8616392649c08656549a44953f3908f7993b5a1b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/plugins/lora_resolvers/__pycache__/filesystem_resolver.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/plugins/lora_resolvers/filesystem_resolver.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/plugins/lora_resolvers/filesystem_resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..b999d07a6eb74f05b11ae12d88c03e238fbd6437 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/plugins/lora_resolvers/filesystem_resolver.py @@ -0,0 +1,50 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +import json +import os +from typing import Optional + +import vllm.envs as envs +from vllm.lora.request import LoRARequest +from vllm.lora.resolver import LoRAResolver, LoRAResolverRegistry + + +class FilesystemResolver(LoRAResolver): + + def __init__(self, lora_cache_dir: str): + self.lora_cache_dir = lora_cache_dir + + async def resolve_lora(self, base_model_name: str, + lora_name: str) -> Optional[LoRARequest]: + lora_path = os.path.join(self.lora_cache_dir, lora_name) + if os.path.exists(lora_path): + adapter_config_path = os.path.join(self.lora_cache_dir, lora_name, + "adapter_config.json") + if os.path.exists(adapter_config_path): + with open(adapter_config_path) as file: + adapter_config = json.load(file) + if adapter_config["peft_type"] == "LORA" and adapter_config[ + "base_model_name_or_path"] == base_model_name: + lora_request = LoRARequest(lora_name=lora_name, + lora_int_id=abs( + hash(lora_name)), + lora_path=lora_path) + return lora_request + return None + + +def register_filesystem_resolver(): + """Register the filesystem LoRA Resolver with vLLM""" + + lora_cache_dir = envs.VLLM_LORA_RESOLVER_CACHE_DIR + if lora_cache_dir: + if not os.path.exists(lora_cache_dir) or not os.path.isdir( + lora_cache_dir): + raise ValueError( + "VLLM_LORA_RESOLVER_CACHE_DIR must be set to a valid directory \ + for Filesystem Resolver plugin to function") + fs_resolver = FilesystemResolver(lora_cache_dir) + LoRAResolverRegistry.register_resolver("Filesystem Resolver", + fs_resolver) + + return diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/profiler/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/profiler/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72d6009386a0727a8e7cbac97885cffcffbd65d3 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/profiler/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/profiler/__pycache__/layerwise_profile.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/profiler/__pycache__/layerwise_profile.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40b4db6153b672306d2aae2a34cb66bfa3994436 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/profiler/__pycache__/layerwise_profile.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/profiler/__pycache__/utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/profiler/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f37f0f07807ae70eaf1c88294eb7cf16dae6fc39 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/profiler/__pycache__/utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/ray/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/ray/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5dd790c594f5e08fe7de3d50d35bd246c9a48fb Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/ray/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/ray/__pycache__/lazy_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/ray/__pycache__/lazy_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cabee7941786e215b53a7b61a994fafbbc15bddb Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/ray/__pycache__/lazy_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/ray/__pycache__/ray_env.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/ray/__pycache__/ray_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b605363487423e11b660766bac220a4287e4636 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/ray/__pycache__/ray_env.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8380ffa258514147c8929ecb742920d1cddddce Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/abs_reasoning_parsers.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/abs_reasoning_parsers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40052e6cee56a376987836b14610db75f98aa0c5 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/abs_reasoning_parsers.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/deepseek_r1_reasoning_parser.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/deepseek_r1_reasoning_parser.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b06bedbaae56151f29ad9d487547762653fcf278 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/deepseek_r1_reasoning_parser.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/glm4_moe_reasoning_parser.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/glm4_moe_reasoning_parser.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..571542ebd6b54c085349480cdb3af26ace2a7c84 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/glm4_moe_reasoning_parser.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/gptoss_reasoning_parser.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/gptoss_reasoning_parser.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a5dbafd4a4bfb3154d538e153e1d69b3b09500f Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/gptoss_reasoning_parser.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/hunyuan_a13b_reasoning_parser.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/hunyuan_a13b_reasoning_parser.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4f592e3c93d4f0a364da24c7fa4a3d5e9c71f5b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/hunyuan_a13b_reasoning_parser.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/mistral_reasoning_parser.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/mistral_reasoning_parser.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a334859726b6ab847ee8d468088996b7d0180fb3 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/mistral_reasoning_parser.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/qwen3_reasoning_parser.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/qwen3_reasoning_parser.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d83b5aeb37070f0b77e6c745c468a90cd72ae1db Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/qwen3_reasoning_parser.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/step3_reasoning_parser.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/step3_reasoning_parser.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61f6d4074a84f7cfe4910a5aa225c991657b09e0 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/reasoning/__pycache__/step3_reasoning_parser.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..039a48460a18e62de67650bfeca4e152c9b4a5d9 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/config.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a555177a2a2c5c8fb902e36ae4c40847244bba3a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/config.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/detokenizer.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/detokenizer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2bae73cfcb4bf65561baa3baa91146d1e40b4821 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/detokenizer.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/dynamic_module.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/dynamic_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5589621d704a020f0d677660bcdef83c730641ad Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/dynamic_module.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/s3_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/s3_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d97eb216d4f22cd55356ee5cc3d61281be98bc61 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/s3_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/tokenizer.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/tokenizer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1e5d4b8a0cdc078d0661d93433f912d80cf6030 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/tokenizer.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aca6630621a5bf421521245146f8dba548cbc9e3 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/__pycache__/utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/chat_templates/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/chat_templates/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2783d12a22147279e95309885ce583605e45fb9a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/chat_templates/__init__.py @@ -0,0 +1,5 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +from .registry import get_chat_template_fallback_path + +__all__ = ["get_chat_template_fallback_path"] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/chat_templates/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/chat_templates/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9464c33d8f6b682fe2d0a3c6dc943a47e291cff7 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/chat_templates/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/chat_templates/__pycache__/registry.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/chat_templates/__pycache__/registry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d71e1f3e2f3b721e338936ceb0f5737c97a8d78 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/chat_templates/__pycache__/registry.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/chat_templates/registry.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/chat_templates/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..e0ef7f0999d4771351e6061e408c61ffb94c02ee --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/chat_templates/registry.py @@ -0,0 +1,60 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +from pathlib import Path +from typing import Callable, Optional, Union + +from vllm.logger import init_logger + +logger = init_logger(__file__) + +CHAT_TEMPLATES_DIR = Path(__file__).parent + +ChatTemplatePath = Union[Path, Callable[[str], Optional[Path]]] + + +def _get_qwen_chat_template_fallback( + tokenizer_name_or_path: str) -> Optional[Path]: + if tokenizer_name_or_path.endswith("-Chat"): + return CHAT_TEMPLATES_DIR / "template_chatml.jinja" + + return CHAT_TEMPLATES_DIR / "template_basic.jinja" + + +# yapf: disable +_MODEL_TYPE_TO_CHAT_TEMPLATE_FALLBACK: dict[str, ChatTemplatePath] = { + "blip-2": CHAT_TEMPLATES_DIR / "template_blip2.jinja", + "chameleon": CHAT_TEMPLATES_DIR / "template_basic.jinja", + "deepseek_vl_v2": CHAT_TEMPLATES_DIR / "template_deepseek_vl2.jinja", + "florence2": CHAT_TEMPLATES_DIR / "template_basic.jinja", + "fuyu": CHAT_TEMPLATES_DIR / "template_fuyu.jinja", + "paligemma": CHAT_TEMPLATES_DIR / "template_basic.jinja", + "qwen": _get_qwen_chat_template_fallback, +} +# yapf: enable + + +def register_chat_template_fallback_path( + model_type: str, + chat_template: ChatTemplatePath, +) -> None: + if model_type in _MODEL_TYPE_TO_CHAT_TEMPLATE_FALLBACK: + logger.warning( + "Model type %s already has a chat template registered. " + "It will be overwritten by the new chat template %s.", model_type, + chat_template) + + _MODEL_TYPE_TO_CHAT_TEMPLATE_FALLBACK[model_type] = chat_template + + +def get_chat_template_fallback_path( + model_type: str, + tokenizer_name_or_path: str, +) -> Optional[Path]: + chat_template = _MODEL_TYPE_TO_CHAT_TEMPLATE_FALLBACK.get(model_type) + if callable(chat_template): + chat_template = chat_template(tokenizer_name_or_path) + + if chat_template is None: + return None + + return chat_template diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/chat_templates/template_basic.jinja b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/chat_templates/template_basic.jinja new file mode 100644 index 0000000000000000000000000000000000000000..3fa2cccc240644154f1f79f2b0906cffae9b2f3d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/chat_templates/template_basic.jinja @@ -0,0 +1,3 @@ +{%- for message in messages -%} + {{- message['content'] -}} +{%- endfor -%} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/chat_templates/template_fuyu.jinja b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/chat_templates/template_fuyu.jinja new file mode 100644 index 0000000000000000000000000000000000000000..ec337d0c64477d6b8712fe8af9271bee84517920 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/chat_templates/template_fuyu.jinja @@ -0,0 +1,3 @@ +{%- for message in messages -%} + {{- message['content'] + '\n' -}} +{%- endfor -%} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8339c55bcf8080e4a7e83ad2160349c6b3aeac4d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/__init__.py @@ -0,0 +1,51 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +""" +Model configs may be defined in this directory for the following reasons: + +- There is no configuration file defined by HF Hub or Transformers library. +- There is a need to override the existing config to support vLLM. +""" + +from vllm.transformers_utils.configs.chatglm import ChatGLMConfig +from vllm.transformers_utils.configs.deepseek_vl2 import DeepseekVLV2Config +from vllm.transformers_utils.configs.eagle import EAGLEConfig +# RWConfig is for the original tiiuae/falcon-40b(-instruct) and +# tiiuae/falcon-7b(-instruct) models. Newer Falcon models will use the +# `FalconConfig` class from the official HuggingFace transformers library. +from vllm.transformers_utils.configs.falcon import RWConfig +from vllm.transformers_utils.configs.jais import JAISConfig +from vllm.transformers_utils.configs.kimi_vl import KimiVLConfig +from vllm.transformers_utils.configs.medusa import MedusaConfig +from vllm.transformers_utils.configs.mlp_speculator import MLPSpeculatorConfig +from vllm.transformers_utils.configs.moonvit import MoonViTConfig +from vllm.transformers_utils.configs.nemotron import NemotronConfig +from vllm.transformers_utils.configs.nemotron_h import NemotronHConfig +from vllm.transformers_utils.configs.nemotron_vl import Nemotron_Nano_VL_Config +from vllm.transformers_utils.configs.ovis import OvisConfig +from vllm.transformers_utils.configs.speculators.base import SpeculatorsConfig +from vllm.transformers_utils.configs.step3_vl import (Step3TextConfig, + Step3VisionEncoderConfig, + Step3VLConfig) +from vllm.transformers_utils.configs.ultravox import UltravoxConfig + +__all__ = [ + "ChatGLMConfig", + "DeepseekVLV2Config", + "EAGLEConfig", + "RWConfig", + "JAISConfig", + "MedusaConfig", + "MLPSpeculatorConfig", + "MoonViTConfig", + "KimiVLConfig", + "NemotronConfig", + "NemotronHConfig", + "Nemotron_Nano_VL_Config", + "OvisConfig", + "SpeculatorsConfig", + "UltravoxConfig", + "Step3VLConfig", + "Step3VisionEncoderConfig", + "Step3TextConfig", +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0b55c47a35ec48b2fadc95b0dd5025abb4eb5f4 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/__pycache__/eagle.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/__pycache__/eagle.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86c647918a63e2fc3ef6a65a97a172c7d8cc863b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/__pycache__/eagle.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/__pycache__/kimi_vl.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/__pycache__/kimi_vl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..709f2606334c190932abfae07581310e902a0905 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/__pycache__/kimi_vl.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/__pycache__/mistral.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/__pycache__/mistral.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..241feb9322926c2be09f1baad859690f6e079dc3 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/__pycache__/mistral.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/__pycache__/nemotron.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/__pycache__/nemotron.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64a001d3b15a8d40b44556dc7b9c93732db4cedf Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/__pycache__/nemotron.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/__pycache__/nemotron_vl.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/__pycache__/nemotron_vl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31e0b8c9c40398d6f9bdb62676974e66ba93e4e7 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/__pycache__/nemotron_vl.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/chatglm.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/chatglm.py new file mode 100644 index 0000000000000000000000000000000000000000..176d2b8f63fe46ff97e8f4b75a5d54829ffd022c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/chatglm.py @@ -0,0 +1,72 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +# Adapted from +# https://github.com/zai-org/ChatGLM2-6B +from transformers import PretrainedConfig + + +class ChatGLMConfig(PretrainedConfig): + model_type = "chatglm" + attribute_map = { + "num_hidden_layers": "num_layers", + "n_head_kv": "multi_query_group_num", + } + + def __init__(self, + num_layers=28, + padded_vocab_size=65024, + hidden_size=4096, + ffn_hidden_size=13696, + kv_channels=128, + num_attention_heads=32, + seq_length=2048, + hidden_dropout=0.0, + attention_dropout=0.0, + layernorm_epsilon=1e-5, + rmsnorm=True, + apply_residual_connection_post_layernorm=False, + post_layer_norm=True, + add_bias_linear=False, + add_qkv_bias=False, + interleaved_qkv=False, + bias_dropout_fusion=True, + multi_query_attention=False, + multi_query_group_num=1, + apply_query_key_layer_scaling=True, + attention_softmax_in_fp32=True, + fp32_residual_connection=False, + quantization_bit=0, + pre_seq_len=None, + prefix_projection=False, + **kwargs): + self.num_layers = num_layers + self.vocab_size = padded_vocab_size + self.padded_vocab_size = padded_vocab_size + self.hidden_size = hidden_size + self.ffn_hidden_size = ffn_hidden_size + self.kv_channels = kv_channels + self.num_attention_heads = num_attention_heads + self.seq_length = seq_length + # It is to be compatible with long lora. + self.max_position_embeddings = seq_length + self.hidden_dropout = hidden_dropout + self.attention_dropout = attention_dropout + self.layernorm_epsilon = layernorm_epsilon + self.rmsnorm = rmsnorm + self.apply_residual_connection_post_layernorm = ( + apply_residual_connection_post_layernorm) + self.post_layer_norm = post_layer_norm + self.add_bias_linear = add_bias_linear + self.add_qkv_bias = add_qkv_bias + self.bias_dropout_fusion = bias_dropout_fusion + self.multi_query_attention = multi_query_attention + self.multi_query_group_num = multi_query_group_num + self.apply_query_key_layer_scaling = apply_query_key_layer_scaling + self.attention_softmax_in_fp32 = attention_softmax_in_fp32 + self.fp32_residual_connection = fp32_residual_connection + self.quantization_bit = quantization_bit + self.pre_seq_len = pre_seq_len + self.prefix_projection = prefix_projection + self.interleaved_qkv = interleaved_qkv + super().__init__(**kwargs) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/deepseek_vl2.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/deepseek_vl2.py new file mode 100644 index 0000000000000000000000000000000000000000..957d638318410e36fa3684549be09aaf86455a20 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/deepseek_vl2.py @@ -0,0 +1,216 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +# adapted from https://github.com/deepseek-ai/DeepSeek-VL2/blob/faf18023f24b962b32d9f0a2d89e402a8d383a78/deepseek_vl2/models/modeling_deepseek_vl_v2.py#L115-L268 + +from transformers.configuration_utils import PretrainedConfig + + +class VisionEncoderConfig(PretrainedConfig): + model_type: str = "vision" + + model_name: str = "vit_so400m_patch14_siglip_384.webli" + image_size: int = 384 + patch_size: int = 16 + width: int = 1024 + layers: int = 24 + heads: int = 16 + mlp_ratio: int = 4 + global_pool: str = "map" + ignore_head: bool = True + class_token: bool = False + num_classes: int = 0 + use_checkpoint: bool = False + weight_init: str = "skip" + deterministic: bool = False + num_recomputing_layers: int = 0 + + def __init__(self, + model_name: str = "vit_so400m_patch14_siglip_384.webli", + image_size: int = 384, + patch_size: int = 16, + width: int = 1024, + layers: int = 24, + heads: int = 16, + mlp_ratio: int = 4, + global_pool: str = "map", + ignore_head: bool = True, + class_token: bool = False, + num_classes: int = 0, + use_checkpoint: bool = False, + **kwargs): + self.model_name = model_name + self.image_size = image_size + self.patch_size = patch_size + self.width = width + self.layers = layers + self.heads = heads + self.mlp_ratio = mlp_ratio + self.global_pool = global_pool + self.ignore_head = ignore_head + self.class_token = class_token + self.num_classes = num_classes + self.use_checkpoint = use_checkpoint + + super().__init__(**kwargs) + + +class MlpProjectorConfig(PretrainedConfig): + model_type = "mlp_projector" + projector_type: str = "downsample_mlp_gelu" + input_dim: int = 1152 + n_embed: int = 2048 + depth: int = 2 + mlp_ratio: int = 1 + downsample_ratio: int = 2 + token_pooling: bool = False + + def __init__(self, + projector_type: str = "downsample_mlp_gelu", + input_dim: int = 1152, + n_embed: int = 2048, + depth: int = 2, + mlp_ratio: int = 1, + downsample_ratio: int = 2, + **kwargs): + self.projector_type = projector_type + self.input_dim = input_dim + self.n_embed = n_embed + self.depth = depth + self.mlp_ratio = mlp_ratio + self.downsample_ratio = downsample_ratio + + super().__init__(**kwargs) + + +class DeepseekV2Config(PretrainedConfig): + + model_type = "deepseek_v2" + keys_to_ignore_at_inference = ["past_key_values"] + + def __init__( + self, + vocab_size=102400, + hidden_size=4096, + intermediate_size=11008, + moe_intermediate_size=1407, + num_hidden_layers=30, + num_attention_heads=32, + num_key_value_heads=32, + n_shared_experts=None, + n_routed_experts=None, + ep_size=1, + routed_scaling_factor=1.0, + kv_lora_rank=512, + q_lora_rank=1536, + qk_rope_head_dim=64, + v_head_dim=128, + qk_nope_head_dim=128, + topk_method='gready', + n_group=None, + topk_group=None, + num_experts_per_tok=None, + moe_layer_freq=1, + first_k_dense_replace=0, + norm_topk_prob=False, + scoring_func='softmax', + aux_loss_alpha=0.001, + seq_aux=True, + hidden_act="silu", + max_position_embeddings=2048, + initializer_range=0.02, + rms_norm_eps=1e-6, + use_cache=True, + pad_token_id=None, + bos_token_id=100000, + eos_token_id=100001, + pretraining_tp=1, + tie_word_embeddings=False, + rope_theta=10000.0, + rope_scaling=None, + attention_bias=False, + attention_dropout=0.0, + use_mla=True, + **kwargs, + ): + self.vocab_size = vocab_size + self.max_position_embeddings = max_position_embeddings + self.hidden_size = hidden_size + self.intermediate_size = intermediate_size + self.moe_intermediate_size = moe_intermediate_size + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.n_shared_experts = n_shared_experts + self.n_routed_experts = n_routed_experts + self.ep_size = ep_size + self.routed_scaling_factor = routed_scaling_factor + self.kv_lora_rank = kv_lora_rank + self.q_lora_rank = q_lora_rank + self.qk_rope_head_dim = qk_rope_head_dim + self.v_head_dim = v_head_dim + self.qk_nope_head_dim = qk_nope_head_dim + self.topk_method = topk_method + self.n_group = n_group + self.topk_group = topk_group + self.num_experts_per_tok = num_experts_per_tok + self.moe_layer_freq = moe_layer_freq + self.first_k_dense_replace = first_k_dense_replace + self.norm_topk_prob = norm_topk_prob + self.scoring_func = scoring_func + self.aux_loss_alpha = aux_loss_alpha + self.seq_aux = seq_aux + # for backward compatibility + if num_key_value_heads is None: + num_key_value_heads = num_attention_heads + + self.num_key_value_heads = num_key_value_heads + self.hidden_act = hidden_act + self.initializer_range = initializer_range + self.rms_norm_eps = float(rms_norm_eps) + self.pretraining_tp = pretraining_tp + self.use_cache = use_cache + self.rope_theta = rope_theta + self.rope_scaling = rope_scaling + self.attention_bias = attention_bias + self.attention_dropout = attention_dropout + self.use_mla = use_mla + + super().__init__( + pad_token_id=pad_token_id, + bos_token_id=bos_token_id, + eos_token_id=eos_token_id, + tie_word_embeddings=tie_word_embeddings, + **kwargs, + ) + + +class DeepseekVLV2Config(PretrainedConfig): + model_type = "deepseek_vl_v2" + vision_config: VisionEncoderConfig + projector_config: MlpProjectorConfig + + tile_tag: str = "2D" + global_view_pos: str = "head" + candidate_resolutions: tuple[tuple[int, int]] = ((384, 384), ) + + def __init__(self, + tile_tag: str = "tile_tag", + global_view_pos: str = "head", + candidate_resolutions: tuple[tuple[int, + int]] = ((384, 384), ), + **kwargs): + super().__init__(**kwargs) + + vision_config = kwargs.get("vision_config", {}) + self.vision_config = VisionEncoderConfig(**vision_config) + + projector_config = kwargs.get("projector_config", {}) + self.projector_config = MlpProjectorConfig(**projector_config) + + language_config = kwargs.get("language_config", {}) + self.text_config = DeepseekV2Config(**language_config) + + self.tile_tag = tile_tag + self.global_view_pos = global_view_pos + self.candidate_resolutions = candidate_resolutions + self.vocab_size = self.text_config.vocab_size diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/eagle.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/eagle.py new file mode 100644 index 0000000000000000000000000000000000000000..bc249c5836034933aad0fbc8bda90fca3294927e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/eagle.py @@ -0,0 +1,82 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +import os +from typing import Optional, Union + +from transformers import AutoConfig, PretrainedConfig + +from vllm.transformers_utils.configs.deepseek_vl2 import DeepseekV2Config + + +class EAGLEConfig(PretrainedConfig): + model_type = "eagle" + + def __init__(self, + model: Union[PretrainedConfig, dict, None] = None, + truncated_vocab_size: Optional[int] = None, + method: Optional[str] = 'eagle', + **kwargs): + + model_config: Union[PretrainedConfig, DeepseekV2Config, None] + if isinstance(model, dict): + archs = model.get("architectures", []) + target_archs = ["DeepseekV2ForCausalLM", "DeepseekV3ForCausalLM"] + if any(target_arch in archs for target_arch in target_archs): + # AutoConfig does not support DeepSeek MoE models yet + model_config = DeepseekV2Config(**model) + else: + model_config = AutoConfig.for_model(**model) + else: + model_config = model + + for k, v in kwargs.items(): + if k != "architectures" and k != "model_type" and hasattr( + model_config, k): + setattr(model_config, k, v) + + self.model = model_config + + if self.model is None: + self.truncated_vocab_size = None + else: + self.truncated_vocab_size = self.model.vocab_size if \ + truncated_vocab_size is None else truncated_vocab_size + + # Eagle model name should follow naming convention of + # LlamaForCausalLM -> EagleLlamaForCausalLM + # LlamaForCausalLM -> Eagle3LlamaForCausalLM + if method == "eagle": + assert self.model is not None, \ + "model should not be None when method is eagle" + kwargs["architectures"] = [ + f"Eagle{arch}" if not arch.startswith("Eagle") \ + else arch for arch in self.model.architectures + ] + elif method == "eagle3": + assert self.model is not None, \ + "model should not be None when method is eagle3" + kwargs["architectures"] = [ + arch if arch.startswith("Eagle3") or arch.endswith("Eagle3") + else f"Eagle3{arch}" for arch in self.model.architectures + ] + else: + raise ValueError(f"Invalid method {method}. \ + Supported methods are eagle and eagle3.") + + super().__init__(**kwargs) + + if self.model is not None: + for k, v in self.model.to_dict().items(): + if k not in kwargs: + setattr(self, k, v) + + @classmethod + def from_pretrained( + cls, + pretrained_model_name_or_path: Union[str, os.PathLike], + **kwargs, + ) -> "EAGLEConfig": + config_dict, kwargs = cls.get_config_dict( + pretrained_model_name_or_path, **kwargs) + return cls.from_dict(config_dict, **kwargs) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/falcon.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/falcon.py new file mode 100644 index 0000000000000000000000000000000000000000..2f5400463d91adf86cd9767a5fba17c825fee8ac --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/falcon.py @@ -0,0 +1,90 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +# Adapted from +# https://huggingface.co/tiiuae/falcon-7b/blob/main/configuration_RW.py +# Copyright 2023 The vLLM team. +# Copyright 2022 the Big Science Workshop and HuggingFace Inc. team. +# All rights reserved. +# +# 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. +"""Falcon configuration""" +from transformers.configuration_utils import PretrainedConfig + + +class RWConfig(PretrainedConfig): + model_type = "falcon" + keys_to_ignore_at_inference = ["past_key_values"] + attribute_map = { + "num_hidden_layers": "n_layer", + "num_attention_heads": "n_head", + "num_kv_heads": "n_head_kv", + } + + def __init__( + self, + vocab_size=250880, + hidden_size=64, + n_layer=2, + n_head=8, + layer_norm_epsilon=1e-5, + initializer_range=0.02, + use_cache=True, + bos_token_id=1, + eos_token_id=2, + hidden_dropout=0.0, + attention_dropout=0.0, + multi_query=True, + n_head_kv=None, + alibi=False, + bias=False, + parallel_attn=False, + new_decoder_architecture=False, + **kwargs, + ) -> None: + self.vocab_size = vocab_size + # Backward compatibility with n_embed kwarg + n_embed = kwargs.pop("n_embed", None) + self.hidden_size = hidden_size if n_embed is None else n_embed + self.n_layer = n_layer + self.n_head = n_head + self.layer_norm_epsilon = layer_norm_epsilon + self.initializer_range = initializer_range + self.use_cache = use_cache + self.hidden_dropout = hidden_dropout + self.attention_dropout = attention_dropout + + self.bos_token_id = bos_token_id + self.eos_token_id = eos_token_id + self.multi_query = multi_query + self.n_head_kv = 1 if n_head_kv is None else n_head_kv + self.alibi = alibi + self.bias = bias + self.parallel_attn = parallel_attn + self.new_decoder_architecture = new_decoder_architecture + + if self.hidden_size == 8192: + # Hack for falcon-40b + self.new_decoder_architecture = True + + super().__init__(bos_token_id=bos_token_id, + eos_token_id=eos_token_id, + **kwargs) + + @property + def head_dim(self): + return self.hidden_size // self.n_head + + @property + def rotary(self): + return not self.alibi diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/kimi_vl.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/kimi_vl.py new file mode 100644 index 0000000000000000000000000000000000000000..ae8dac0f381d658879c82b4fcaad3f97ca46a049 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/kimi_vl.py @@ -0,0 +1,37 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +# Adapted from https://huggingface.co/moonshotai/Kimi-VL-A3B-Instruct/blob/main/configuration_kimi_vl.py +from typing import Optional, Union + +from transformers.configuration_utils import PretrainedConfig + +from vllm.transformers_utils.configs.deepseek_vl2 import DeepseekV2Config +from vllm.transformers_utils.configs.moonvit import MoonViTConfig + + +class KimiVLConfig(PretrainedConfig): + model_type = "kimi_vl" + + def __init__(self, + vision_config: Optional[Union[dict, MoonViTConfig]] = None, + text_config: Optional[Union[dict, DeepseekV2Config]] = None, + ignore_index: int = -100, + media_placeholder_token_id: int = 163605, + pad_token_id: int = 0, + **kwargs): + if vision_config is None: + vision_config = MoonViTConfig() + elif isinstance(vision_config, dict): + vision_config = MoonViTConfig(**vision_config) + self.vision_config = vision_config + + if text_config is None: + text_config = DeepseekV2Config() + elif isinstance(text_config, dict): + text_config = DeepseekV2Config(**text_config) + self.text_config = text_config + + self.ignore_index = ignore_index + self.media_placeholder_token_id = media_placeholder_token_id + + super().__init__(pad_token_id=pad_token_id, **kwargs) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/medusa.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/medusa.py new file mode 100644 index 0000000000000000000000000000000000000000..9ba52956a8e8efc80a59c90f7f66a07234da690b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/medusa.py @@ -0,0 +1,63 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +import os +from typing import Optional, Union + +from transformers import PretrainedConfig + + +class MedusaConfig(PretrainedConfig): + model_type = "medusa" + + def __init__(self, + hidden_size: int = 4096, + vocab_size: int = 32001, + num_heads: int = 5, + num_hidden_layers: int = 1, + max_paths: int = 64, + topk: int = 10, + truncated_vocab_size: Optional[int] = None, + **kwargs): + + self.hidden_size = hidden_size + self.vocab_size = vocab_size + self.num_heads = num_heads + self.num_hidden_layers = num_hidden_layers + self.max_paths = max_paths + self.topk = topk + self.max_seq_len = int(2**20) + self.truncated_vocab_size = vocab_size if truncated_vocab_size is None\ + else truncated_vocab_size + if "architectures" not in kwargs: + kwargs["architectures"] = ["MedusaModel"] + + super().__init__(**kwargs) + + @classmethod + def from_pretrained( + cls, + pretrained_model_name_or_path: Union[str, os.PathLike], + **kwargs, + ) -> "MedusaConfig": + config_dict, kwargs = cls.get_config_dict( + pretrained_model_name_or_path, **kwargs) + for k in list(config_dict.keys()): + if 'num' in k: + if 'heads' in k: + config_dict["num_heads"] = config_dict.pop(k) + elif 'layers' in k: + config_dict["num_hidden_layers"] = config_dict.pop(k) + return cls.from_dict(config_dict, **kwargs) + + @property + def num_attention_heads(self): + return 0 + + @property + def num_lookahead_tokens(self): + return self.num_heads + + @num_lookahead_tokens.setter + def num_lookahead_tokens(self, num_lookahead_tokens: int): + self.num_heads = num_lookahead_tokens diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/mistral.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/mistral.py new file mode 100644 index 0000000000000000000000000000000000000000..8a9c660b882fd4f877ede8157920ee6fc3d42ae6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/mistral.py @@ -0,0 +1,164 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +from typing import Any + +from transformers import PretrainedConfig, WhisperConfig + +from vllm.logger import init_logger + +logger = init_logger(__name__) + + +def adapt_config_dict(config_dict: dict[str, Any], + **kwargs) -> PretrainedConfig: + config_dict.update(kwargs) + config_dict = _remap_general_mistral_args(config_dict) + + if bool(config_dict.get("quantization")): + config_dict = _remap_mistral_quantization_args(config_dict) + + if bool(config_dict.get("moe")): + config_dict["architectures"] = ["MixtralForCausalLM"] + else: + config_dict["architectures"] = ["MistralForCausalLM"] + + if bool(config_dict.get("yarn")): + config_dict = _remap_mistral_yarn_args(config_dict) + + is_vision = ((config_dict.get("multimodal") + or {}).get("vision_encoder_args") + or config_dict.get("vision_encoder")) + is_audio = bool( + ((config_dict.get("multimodal") or {}).get("whisper_model_args") + or {}).get("encoder_args")) + + assert not (is_vision and is_audio), \ + "Vision and audio are mutually exclusive" + + if is_vision: + config_dict = _remap_mistral_vision_args(config_dict) + if is_audio: + config_dict = _remap_mistral_audio_args(config_dict) + + config = PretrainedConfig.from_dict(config_dict) + + logger.debug("Initialized config %s", config) + + return config + + +def _remap_mistral_vision_args(config: dict) -> dict: + if config.get("multimodal"): + vision_config = config.pop("multimodal") + else: + vision_config = config.pop("vision_encoder") + + quant_config = config.get("quantization_config") + config = { + "model_type": "pixtral", + "architectures": ["PixtralForConditionalGeneration"], + "text_config": PretrainedConfig.from_dict(config), + "vision_config": PretrainedConfig.from_dict(vision_config), + } + if quant_config: + config["quantization_config"] = quant_config + return config + + +def _remap_mistral_yarn_args(config: dict) -> dict: + # Direct remaps: yarn.X -> rope_scaling.Y + # Source keys are from mistral.model.args.YarnArgs + _map = { + "beta": "beta_fast", + "alpha": "beta_slow", + } + yarn_config = config.get("yarn") or {} + renamed_yarn_config = {_map.get(k, k): v for k, v in yarn_config.items()} + config["rope_scaling"] = { + "rope_type": "yarn", + "mscale_all_dim": 1, # We hardcoded this to 1 + **renamed_yarn_config + } + return config + + +def _remap_general_mistral_args(config: dict) -> dict: + # Mistral key -> HF key + config_mapping = { + "dim": "hidden_size", + "norm_eps": "rms_norm_eps", + "n_kv_heads": "num_key_value_heads", + "n_layers": "num_hidden_layers", + "n_heads": "num_attention_heads", + "hidden_dim": "intermediate_size", + } + # HF key -> (Mistral key, default value) + top_level_mapping_with_default = { + "model_type": ("model_type", "transformer"), + "hidden_act": ("activation", "silu"), + "tie_word_embeddings": ("tied_embeddings", False), + "max_seq_len": ("max_seq_len", 128_000), + "max_position_embeddings": ("max_position_embeddings", 128_000), + } + + for key, new_key in config_mapping.items(): + if key in config: + config[new_key] = config.pop(key) + + for new_key, (key, + default_value) in top_level_mapping_with_default.items(): + config[new_key] = config.pop(key, default_value) + + return config + + +def _remap_mistral_quantization_args(config: dict) -> dict: + quantization = config.get("quantization", {}) + if quantization.get("qformat_weight") == "fp8_e4m3": + # This maps to the FP8 static per-tensor quantization scheme + quantization_config = { + "quant_method": "fp8", + "activation_scheme": "static" + } + elif quantization.get("quant_method") == "compressed-tensors": + # Pass through the quantization config to compressed-tensors + quantization_config = quantization + else: + raise ValueError( + f"Found unknown quantization='{quantization}' in config") + + config["quantization_config"] = quantization_config + + return config + + +def _remap_mistral_audio_args(config: dict) -> dict: + whisper_args = config["multimodal"].pop("whisper_model_args") + encoder_args = whisper_args["encoder_args"] + downsample_args = whisper_args["downsample_args"] + + quant_config = config.get("quantization_config") + config = { + "model_type": + "whixtral", + "architectures": ["VoxtralForConditionalGeneration"], + "text_config": + PretrainedConfig.from_dict(config), + "audio_config": + WhisperConfig( + num_mel_bins=encoder_args["audio_encoding_args"]["num_mel_bins"], + window_size=encoder_args["audio_encoding_args"]["window_size"], + sampling_rate=encoder_args["audio_encoding_args"]["sampling_rate"], + hop_length=encoder_args["audio_encoding_args"]["hop_length"], + downsample_factor=downsample_args["downsample_factor"], + d_model=encoder_args["dim"], + encoder_layers=encoder_args["n_layers"], + encoder_ffn_dim=encoder_args["hidden_dim"], + encoder_attention_heads=encoder_args["n_heads"], + vocab_size=encoder_args["vocab_size"], + max_source_positions=encoder_args["max_source_positions"], + ) + } + if quant_config: + config["quantization_config"] = quant_config + return config diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/moonvit.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/moonvit.py new file mode 100644 index 0000000000000000000000000000000000000000..a6f712f3d60059875980e02acaf99a365985f92a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/moonvit.py @@ -0,0 +1,33 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +# Adapted from https://huggingface.co/moonshotai/Kimi-VL-A3B-Instruct/blob/main/configuration_kimi_vl.py +from transformers.configuration_utils import PretrainedConfig + + +class MoonViTConfig(PretrainedConfig): + model_type = "moonvit" + + def __init__( + self, + patch_size: int = 14, + init_pos_emb_height: int = 64, + init_pos_emb_width: int = 64, + num_attention_heads: int = 16, + num_hidden_layers: int = 27, + hidden_size: int = 1152, + intermediate_size: int = 4304, + merge_kernel_size: tuple[int, int] = (2, 2), + **kwargs, + ): + super().__init__(**kwargs) + self.patch_size = patch_size + # Positional embedding config + self.init_pos_emb_height = init_pos_emb_height + self.init_pos_emb_width = init_pos_emb_width + # Transformer config + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.hidden_size = hidden_size + self.intermediate_size = intermediate_size + # Patch merger config + self.merge_kernel_size = merge_kernel_size diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/nemotron.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/nemotron.py new file mode 100644 index 0000000000000000000000000000000000000000..9a7243b1262c0e2ccfae4a43906d21dc5ccb4991 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/nemotron.py @@ -0,0 +1,205 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +# Copyright 2024 HuggingFace Inc. team. All rights reserved. +# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. +# +# 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. +"""Nemotron model configuration""" + +from transformers import PretrainedConfig +from transformers.utils import logging + +logger = logging.get_logger(__name__) + + +class NemotronConfig(PretrainedConfig): + r""" + This is the configuration class to store the configuration of a + [`NemotronModel`]. It is used to instantiate an Nemotron model + according to the specified arguments, defining the model architecture. + Instantiating a configuration with the defaults will yield a similar + configuration to that of the Nemotron-8B. + + Configuration objects inherit from [`PretrainedConfig`] and can be + used to control the model outputs. Read the documentation from + [`PretrainedConfig`] for more information. + + + Args: + vocab_size (`int`, *optional*, defaults to 256000): + Vocabulary size of the Nemotron model. Defines the number of + different tokens that can be represented by the + `inputs_ids` passed when calling [`NemotronModel`] + hidden_size (`int`, *optional*, defaults to 6144): + Dimension of the hidden representations. + intermediate_size (`int`, *optional*, defaults to 24576): + Dimension of the MLP representations. + num_hidden_layers (`int`, *optional*, defaults to 32): + Number of hidden layers in the Transformer decoder. + num_attention_heads (`int`, *optional*, defaults to 48): + Number of attention heads for each attention layer in the + Transformer decoder. + head_dim (`int`, *optional*): + Projection weights dimension in multi-head attention. Set to + hidden_size // num_attention_heads if None + num_key_value_heads (`int`, *optional*): + This is the number of key_value heads that should be used to + implement Grouped Query Attention. If + `num_key_value_heads=num_attention_heads`, the model will use + Multi Head Attention (MHA), if + `num_key_value_heads=1 the model will use Multi Query Attention + (MQA) otherwise GQA is used. When converting a multi-head + checkpoint to a GQA checkpoint, each group key and value + head should be constructed by meanpooling all the original + heads within that group. For more details checkout + [this paper](https://arxiv.org/pdf/2305.13245.pdf). If it + is not specified, will default to `num_attention_heads`. + hidden_act (`str` or `function`, *optional*, defaults to `"relu2"`): + The non-linear activation function (function or string) in the + decoder. + max_position_embeddings (`int`, *optional*, defaults to 4096): + The maximum sequence length that this model might ever be used + with. + initializer_range (`float`, *optional*, defaults to 0.0134): + The standard deviation of the truncated_normal_initializer for + initializing all weight matrices. + norm_eps (`float`, *optional*, defaults to 1e-05): + The epsilon used by the normalization layers. + use_cache (`bool`, *optional*, defaults to `True`): + Whether or not the model should return the last key/values + attentions (not used by all models). Only relevant if + `config.is_decoder=True`. + pad_token_id (`int`, *optional*): + Padding token id. + bos_token_id (`int`, *optional*, defaults to 2): + Beginning of stream token id. + eos_token_id (`int`, *optional*, defaults to 3): + End of stream token id. + tie_word_embeddings (`bool`, *optional*, defaults to `False`): + Whether to tie weight embeddings + rope_theta (`float`, *optional*, defaults to 10000.0): + The base period of the RoPE embeddings. + partial_rotary_factor (`float`, *optional*, defaults to 0.5): + Percentage of the query and keys which will have rotary embedding. + attention_bias (`bool`, *optional*, defaults to `False`): + Whether to use a bias in the query, key, value and output + projection layers during self-attention. + attention_dropout (`float`, *optional*, defaults to 0.0): + The dropout ratio for the attention probabilities. + mlp_bias (`bool`, *optional*, defaults to `False`): + Whether to use a bias in up_proj and down_proj layers in the MLP + layers. + + ```python + >>> from transformers import NemotronModel, NemotronConfig + >>> # Initializing a Nemotron nemotron-15b style configuration + >>> configuration = NemotronConfig() + >>> # Initializing a model from the nemotron-15b style configuration + >>> model = NemotronModel(configuration) + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "nemotron" + keys_to_ignore_at_inference = ["past_key_values"] + + def __init__( + self, + vocab_size=256000, + hidden_size=6144, + intermediate_size=24576, + num_hidden_layers=32, + num_attention_heads=48, + head_dim=None, + num_key_value_heads=None, + hidden_act="relu2", + max_position_embeddings=4096, + initializer_range=0.0134, + norm_eps=1e-5, + use_cache=True, + pad_token_id=None, + bos_token_id=2, + eos_token_id=3, + tie_word_embeddings=False, + rope_theta=10000.0, + rope_scaling=None, + partial_rotary_factor=0.5, + attention_bias=False, + attention_dropout=0.0, + mlp_bias=False, + **kwargs, + ): + self.vocab_size = vocab_size + self.max_position_embeddings = max_position_embeddings + self.hidden_size = hidden_size + self.intermediate_size = intermediate_size + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + head_dim = head_dim or kwargs.get("kv_channels") + self.head_dim = head_dim if head_dim is not None else ( + hidden_size // num_attention_heads) + + # for backward compatibility + if num_key_value_heads is None: + num_key_value_heads = num_attention_heads + + self.num_key_value_heads = num_key_value_heads + self.hidden_act = hidden_act + self.initializer_range = initializer_range + self.norm_eps = norm_eps + self.use_cache = use_cache + self.rope_theta = rope_theta + self.rope_scaling = rope_scaling + # for backward compatibility + partial_rotary_factor = kwargs.get("rope_percent") or kwargs.get( + "rope_percentage") or partial_rotary_factor + self.partial_rotary_factor = partial_rotary_factor + self._rope_scaling_validation() + self.attention_bias = attention_bias + self.attention_dropout = attention_dropout + self.mlp_bias = mlp_bias + + super().__init__( + pad_token_id=pad_token_id, + bos_token_id=bos_token_id, + eos_token_id=eos_token_id, + tie_word_embeddings=tie_word_embeddings, + **kwargs, + ) + + def _rope_scaling_validation(self): + """ + Validate the `rope_scaling` configuration. + """ + if self.rope_scaling is None: + return + + if not isinstance(self.rope_scaling, dict) or len( + self.rope_scaling) != 2: + raise ValueError( + "`rope_scaling` must be a dictionary with two fields, " + f"`type` and `factor`, got {self.rope_scaling}") + rope_scaling_type = self.rope_scaling.get("type", None) + rope_scaling_factor = self.rope_scaling.get("factor", None) + if rope_scaling_type is None or rope_scaling_type not in [ + "linear", "dynamic" + ]: + raise ValueError( + "`rope_scaling`'s type field must be one of ['linear', " + f"'dynamic'], got {rope_scaling_type}") + if rope_scaling_factor is None or not isinstance( + rope_scaling_factor, float) or rope_scaling_factor <= 1.0: + raise ValueError( + "`rope_scaling`'s factor field must be a float > 1, got " + f"{rope_scaling_factor}") \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/nemotron_h.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/nemotron_h.py new file mode 100644 index 0000000000000000000000000000000000000000..027f2911543f5a14fdb6643d4b69a8ba8c409c5a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/nemotron_h.py @@ -0,0 +1,259 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +# Copyright 2024 HuggingFace Inc. team. All rights reserved. +# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +# +# 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. +"""NemotronH model configuration""" + +import regex as re +from transformers.configuration_utils import PretrainedConfig +from transformers.utils import logging + +logger = logging.get_logger(__name__) + + +class NemotronHConfig(PretrainedConfig): + r""" + This is the configuration class to store the configuration of a + [`NemotronHModel`]. It is used to instantiate a NemotronH model according + to the specified arguments, defining the model architecture. Instantiating + a configuration with the defaults will yield a similar configuration to + that of the NemotronH-v0.1 model. + Args: + vocab_size (`int`, *optional*, defaults to 131072): + Vocabulary size of the NemotronH model. Defines the number of + different tokens that can be represented by the `inputs_ids` + passed when calling [`NemotronHModel`] + tie_word_embeddings (`bool`, *optional*, defaults to `False`): + Whether the model's input and output word embeddings should be + tied. Note that this is only relevant if the model has a output + word embedding layer. + hidden_size (`int`, *optional*, defaults to 4096): + Dimension of the hidden representations. + intermediate_size (`int`, *optional*, defaults to 21504): + Dimension of the MLP representations. + num_hidden_layers (`int`, *optional*, defaults to 52): + Number of hidden layers in the Transformer encoder. + hybrid_override_pattern (`str`, *optional*, defaults to + `"M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M-"`): + The pattern of the hybrid model. The pattern is a string of + characters where each character represents + M: Mamba2, *: Attention, -: MLP + num_attention_heads (`int`, *optional*, defaults to 32): + Number of attention heads for each attention layer in the + Transformer encoder. + attention_head_dim (`int`, *optional*, defaults to 128): + Dimension of each attention head. + num_key_value_heads (`int`, *optional*, defaults to 8): + This is the number of key_value heads that should be used to + implement Grouped Query Attention. If + `num_key_value_heads=num_attention_heads`, the model will use + Multi Head Attention (MHA), if `num_key_value_heads=1` the model + will use Multi Query Attention (MQA) otherwise GQA is used. + mlp_hidden_act (`str`, *optional*, defaults to "relu2"): + The non-linear activation function in the MLP layers. + attention_bias (`bool`, *optional*, defaults to `False`): + Whether to use bias in attention layers. + mlp_bias (`bool`, *optional*, defaults to `False`): + Whether to use bias in MLP layers. + use_bias (`bool`, *optional*, defaults to `False`): + Whether to use bias in the model. + initializer_range (`float`, *optional*, defaults to 0.02): + The standard deviation of the truncated_normal_initializer for + initializing all weight matrices. + layer_norm_epsilon (`float`, *optional*, defaults to 1e-5): + The epsilon used by the layer normalization layers. + residual_in_fp32 (`bool`, *optional*, defaults to `False`): + Whether or not residuals should be in `float32`. If set to `False` + residuals will keep the same `dtype` as the rest of the model. + use_cache (`bool`, *optional*, defaults to `True`): + Whether or not the model should return the last key/values + attentions (not used by all models). Only relevant if + `config.is_decoder=True`. + num_logits_to_keep (`int` or `None`, *optional*, defaults to 1): + Number of prompt logits to calculate during generation. If `None`, + all logits will be calculated. If an integer value, only last + `num_logits_to_keep` logits will be calculated. + pad_token_id (`int`, *optional*, defaults to 0): + The id of the padding token. + bos_token_id (`int`, *optional*, defaults to 1): + The id of the "beginning-of-sequence" token. + eos_token_id (`int`, *optional*, defaults to 2): + The id of the "end-of-sequence" token. + sliding_window (`int`, *optional*, defaults to None): + Sliding window attention window size. + max_position_embeddings (`int`, *optional*, defaults to 4096): + The maximum sequence length that this model might ever be used + with. + attention_dropout (`float`, *optional*, defaults to 0.0): + The dropout ratio for the attention probabilities. + hidden_dropout (`float`, *optional*, defaults to 0.0): + The dropout ratio for the hidden states. + use_mamba_kernels (`bool`, *optional*, defaults to `True`): + Flag indicating whether or not to use the fast mamba kernels. + These are available only if `mamba-ssm` and `causal-conv1d` + are installed, and the mamba modules are running on a CUDA device. + ssm_state_size (`int`, *optional*, defaults to 128): + The dimension of the mamba state space latents. + mamba_num_heads (`int`, *optional*, defaults to 128): + Number of heads in Mamba layers. + mamba_n_groups (`int`, *optional*, defaults to 8): + Number of groups in Mamba layers. + mamba_head_dim (`int`, *optional*, defaults to 64): + Dimension of each Mamba head. + mamba_d_conv (`int`, *optional*, defaults to 4): + The size of the mamba convolution kernel. + mamba_expand (`int`, *optional*, defaults to 2): + Expanding factor used to determine the mamba intermediate size. + mamba_hidden_act (`str`, *optional*, defaults to "silu"): + The non-linear activation function in the Mamba layers. + mamba_dt_min (`float`, *optional*, defaults to 0.001): + Minimum value for the time step in Mamba. + mamba_dt_max (`float`, *optional*, defaults to 0.1): + Maximum value for the time step in Mamba. + mamba_dt_limit (`tuple`, *optional*, defaults to (0.0, float("inf"))): + Limits for the time step in Mamba. + mamba_dt_init_floor (`float`, *optional*, defaults to 1e-4): + Floor value for time step initialization in Mamba. + mamba_conv_bias (`bool`, *optional*, defaults to `True`): + Whether to use bias in the convolution layer of the mamba mixer + block. + mamba_proj_bias (`bool`, *optional*, defaults to `False`): + Whether to use bias in the input and output projections of the + mamba mixer block. + mamba_chunk_size (`int`, *optional*, defaults to 256): + Size of chunks for Mamba processing. + rescale_prenorm_residual (`bool`, *optional*, defaults to `True`): + Whether to rescale the pre-normalization residual connections. + """ + + model_type = "nemotron_h" + keys_to_ignore_at_inference = ["past_key_values"] + + def __init__( + self, + vocab_size=131072, + tie_word_embeddings=False, + hidden_size=4096, + intermediate_size=21504, + num_hidden_layers=52, + hybrid_override_pattern="M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M-", + num_attention_heads=32, + head_dim=128, + num_key_value_heads=8, # nemo: num_query_groups + mlp_hidden_act="relu2", + attention_bias=False, + mlp_bias=False, + use_bias=False, + initializer_range=0.02, # nemo: init_method_std + layer_norm_epsilon=1e-5, # nemo: layernorm_epsilon + residual_in_fp32=False, # Megatron Core default value + use_cache=True, + num_logits_to_keep=1, + pad_token_id=0, + bos_token_id=1, + eos_token_id=2, + sliding_window=None, + max_position_embeddings=4096, + attention_dropout=0.0, + hidden_dropout=0.0, # * ADDED + use_mamba_kernels=True, + ssm_state_size=128, # mamba_state_size + mamba_num_heads=128, + mamba_n_groups=8, # nemo: mamba_ssm_ngroups = num_heads + mamba_head_dim=64, + mamba_d_conv=4, + mamba_expand=2, + mamba_hidden_act="silu", + mamba_dt_min=0.001, + mamba_dt_max=0.1, + mamba_dt_limit=(0.0, float("inf")), + mamba_dt_init_floor=1e-4, + mamba_conv_bias=True, + mamba_proj_bias=False, + mamba_chunk_size=256, + rescale_prenorm_residual=True, + **kwargs, + ): + self.vocab_size = vocab_size + self.tie_word_embeddings = tie_word_embeddings + self.hidden_size = hidden_size + self.intermediate_size = intermediate_size + self.num_hidden_layers = num_hidden_layers + self.hybrid_override_pattern = hybrid_override_pattern + self.num_attention_heads = num_attention_heads + self.head_dim = head_dim + self.sliding_window = sliding_window + self.max_position_embeddings = max_position_embeddings + self.attention_dropout = attention_dropout + self.hidden_dropout = hidden_dropout + + # Validate hybrid_override_pattern + # M: Mamba2, *: Attention, -: MLP + assert len(self.hybrid_override_pattern) == self.num_hidden_layers, ( + "hybrid_override_pattern must have same length as " + "num_hidden_layers") + assert re.match(r"^[*-M]+$", self.hybrid_override_pattern), ( + "hybrid_override_pattern must only contain characters " + "'M', '*', or '-'") + + # for backward compatibility + if num_key_value_heads is None: + num_key_value_heads = num_attention_heads + + self.num_key_value_heads = num_key_value_heads + self.mlp_hidden_act = mlp_hidden_act + self.attention_bias = attention_bias + self.mlp_bias = mlp_bias + self.use_bias = use_bias + self.initializer_range = initializer_range + self.layer_norm_epsilon = layer_norm_epsilon + self.residual_in_fp32 = residual_in_fp32 + + self.use_cache = use_cache + self.num_logits_to_keep = num_logits_to_keep + + self.use_mamba_kernels = use_mamba_kernels + self.n_groups = mamba_n_groups + self.mamba_head_dim = mamba_head_dim + self.ssm_state_size = ssm_state_size + self.mamba_num_heads = mamba_num_heads + self.conv_kernel = mamba_d_conv + self.expand = mamba_expand + self.mamba_hidden_act = mamba_hidden_act + self.time_step_min = mamba_dt_min + self.time_step_max = mamba_dt_max + self.time_step_limit = mamba_dt_limit + self.time_step_floor = mamba_dt_init_floor + self.use_conv_bias = mamba_conv_bias + self.mamba_proj_bias = mamba_proj_bias + self.chunk_size = mamba_chunk_size + self.rescale_prenorm_residual = rescale_prenorm_residual + + super().__init__( + pad_token_id=pad_token_id, + bos_token_id=bos_token_id, + eos_token_id=eos_token_id, + tie_word_embeddings=tie_word_embeddings, + **kwargs, + ) + + @property + def layers_block_type(self): + return [ + "mamba" if self.hybrid_override_pattern[i] == "M" else + "attention" if self.hybrid_override_pattern[i] == "*" else "mlp" + for i in range(self.num_hidden_layers) + ] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/nemotron_vl.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/nemotron_vl.py new file mode 100644 index 0000000000000000000000000000000000000000..6a642f26b82a2804dd4439bfb44ceed078a5434f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/nemotron_vl.py @@ -0,0 +1,56 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +# yapf: disable +# ruff: noqa: E501 +# Adapted from +# https://huggingface.co/nvidia/Llama-3.1-Nemotron-Nano-VL-8B-V1/blob/main/configuration.py +# -------------------------------------------------------- +# Adapted from https://huggingface.co/OpenGVLab/InternVL2-Llama3-76B under MIT License +# LICENSE is in incl_licenses directory. +# -------------------------------------------------------- + +from transformers import LlamaConfig +from transformers.configuration_utils import PretrainedConfig +from transformers.dynamic_module_utils import get_class_from_dynamic_module + + +class Nemotron_Nano_VL_Config(PretrainedConfig): + model_type = 'Llama_Nemotron_Nano_VL' + is_composition = True + + def __init__( + self, + vision_config=None, + llm_config=None, + force_image_size=None, + downsample_ratio=0.5, + template=None, + ps_version='v1', + image_tag_type="internvl", + projector_hidden_size=4096, + vit_hidden_size=1280, + **kwargs + ): + super().__init__(**kwargs) + + if vision_config is not None: + assert "auto_map" in vision_config and "AutoConfig" in vision_config["auto_map"] + vision_auto_config = get_class_from_dynamic_module(*vision_config["auto_map"]["AutoConfig"].split("--")[::-1]) + self.vision_config = vision_auto_config(**vision_config) + else: + self.vision_config = PretrainedConfig() + + if llm_config is None: + self.text_config = LlamaConfig() + else: + self.text_config = LlamaConfig(**llm_config) + + # Assign configuration values + self.force_image_size = force_image_size + self.downsample_ratio = downsample_ratio + self.template = template # TODO move out of here and into the tokenizer + self.ps_version = ps_version # Pixel shuffle version + self.image_tag_type = image_tag_type # TODO: into the tokenizer too? + self.projector_hidden_size = projector_hidden_size + self.vit_hidden_size = vit_hidden_size diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/speculators/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/speculators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..208f01a7cb5ee04c88d276fec2082cd4e830884b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/speculators/__init__.py @@ -0,0 +1,2 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/speculators/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/speculators/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..412cee5cf05cbfee019b1fef51361108be4d3e31 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/speculators/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/speculators/__pycache__/algos.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/speculators/__pycache__/algos.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19159b1fe1096617573a58a2b0f31f56b42ced83 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/speculators/__pycache__/algos.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/step3_vl.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/step3_vl.py new file mode 100644 index 0000000000000000000000000000000000000000..fe3c72de69d2809eaefd07af83893de9b86c9812 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/configs/step3_vl.py @@ -0,0 +1,123 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +from typing import Any, Optional, Union + +from transformers.configuration_utils import PretrainedConfig + + +class Step3VisionEncoderConfig(PretrainedConfig): + model_type = "step3_vision_encoder" + + def __init__( + self, + hidden_size=1792, + intermediate_size=3072, + output_hidden_size=4096, + num_hidden_layers=63, + num_attention_heads=16, + num_channels=3, + image_size=728, + patch_size=14, + hidden_act="quick_gelu", + layer_norm_eps=1e-5, + **kwargs, + ): + self.hidden_size = hidden_size + self.intermediate_size = intermediate_size + self.output_hidden_size = output_hidden_size + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.num_channels = num_channels + self.patch_size = patch_size + self.image_size = image_size + self.layer_norm_eps = layer_norm_eps + self.hidden_act = hidden_act + super().__init__(**kwargs) + + +class Step3TextConfig(PretrainedConfig): + model_type = "step3_text" + architectures = ["Step3TextForCausalLM"] + + def __init__( + self, + hidden_size: int = 7168, + intermediate_size: int = 18432, + num_attention_heads: int = 64, + num_attention_groups: int = 1, + num_hidden_layers: int = 61, + max_seq_len: int = 65536, + vocab_size: int = 128815, + rms_norm_eps: float = 1e-5, + moe_intermediate_size: int = 5120, + moe_num_experts: int = 48, + moe_top_k: int = 3, + rope_theta: float = 500000, + rope_scaling: Optional[dict[str, Any]] = None, + max_position_embedding: int = 65536, + share_expert_dim: int = 5120, + share_q_dim: int = 2048, + head_dim: int = 256, + norm_expert_weight: bool = False, + moe_layers_enum: tuple[int, + ...] = (4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, + 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, + 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, + 55, 56, 57, 58, 59), + **kwargs, + ) -> None: + self.hidden_size = hidden_size + self.intermediate_size = intermediate_size + self.num_attention_heads = num_attention_heads + self.num_attention_groups = num_attention_groups + self.num_hidden_layers = num_hidden_layers + self.max_seq_len = max_seq_len + self.vocab_size = vocab_size + self.rms_norm_eps = rms_norm_eps + self.moe_intermediate_size = moe_intermediate_size + self.moe_num_experts = moe_num_experts + self.moe_top_k = moe_top_k + self.rope_theta = rope_theta + self.rope_scaling = rope_scaling + self.max_position_embedding = max_position_embedding + self.share_expert_dim = share_expert_dim + self.share_q_dim = share_q_dim + self.head_dim = head_dim + self.norm_expert_weight = norm_expert_weight + self.moe_layers_enum = moe_layers_enum + + super().__init__(**kwargs) + + +class Step3VLConfig(PretrainedConfig): + model_type = "step3_vl" + + def __init__( + self, + vision_config: Optional[Union[dict, Step3VisionEncoderConfig]] = None, + text_config: Optional[Union[dict, Step3TextConfig]] = None, + understand_projector_stride: int = 1, + projector_bias: bool = True, + image_token_id: int = 128001, + **kwargs, + ) -> None: + if vision_config is None: + vision_config = Step3VisionEncoderConfig() + elif isinstance(vision_config, dict): + vision_config = Step3VisionEncoderConfig(**vision_config) + self.vision_config = vision_config + + if text_config is None: + text_config = Step3TextConfig() + elif isinstance(text_config, dict): + text_config = Step3TextConfig(**text_config) + self.text_config = text_config + + self.understand_projector_stride = understand_projector_stride + self.projector_bias = projector_bias + self.hidden_size = text_config.hidden_size + self.image_token_id = image_token_id + + super().__init__(**kwargs) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/processors/__pycache__/ovis.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/processors/__pycache__/ovis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c34c6a0abecf40e2946e88b9822c27036d54dbf Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/processors/__pycache__/ovis.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/processors/deepseek_vl2.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/processors/deepseek_vl2.py new file mode 100644 index 0000000000000000000000000000000000000000..5896bde312657ebc652b488969900a08eac36e1d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/processors/deepseek_vl2.py @@ -0,0 +1,363 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +# yapf: disable +# ruff: noqa: E501 +# coding=utf-8 +# adapted from https://github.com/deepseek-ai/DeepSeek-VL2/blob/ff23960c5cf9e6874b44be38af930cfb0ccbb620/deepseek_vl2/models/processing_deepseek_vl_v2.py +# Copyright (c) 2023-2024 DeepSeek. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy of +# this software and associated documentation files (the "Software"), to deal in +# the Software without restriction, including without limitation the rights to +# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +# the Software, and to permit persons to whom the Software is furnished to do so, +# subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +import math + +import torch +import torchvision.transforms as T +from PIL import Image, ImageOps +from transformers import AutoProcessor, BatchFeature, LlamaTokenizerFast +from transformers.processing_utils import ProcessorMixin + + +class ImageTransform: + + def __init__(self, + mean: tuple[float, float, float] = (0.5, 0.5, 0.5), + std: tuple[float, float, float] = (0.5, 0.5, 0.5), + normalize: bool = True): + self.mean = mean + self.std = std + self.normalize = normalize + + transform_pipelines = [T.ToTensor()] + + if normalize: + transform_pipelines.append(T.Normalize(mean, std)) + + self.transform = T.Compose(transform_pipelines) + + def __call__(self, pil_img: Image.Image): + x = self.transform(pil_img) + return x + + +class DeepseekVLV2Processor(ProcessorMixin): + tokenizer_class = ("LlamaTokenizer", "LlamaTokenizerFast") + attributes = ["tokenizer"] + + def __init__( + self, + tokenizer: LlamaTokenizerFast, + candidate_resolutions: tuple[tuple[int, int]], + patch_size: int, + downsample_ratio: int, + image_mean: tuple[float, float, float] = (0.5, 0.5, 0.5), + image_std: tuple[float, float, float] = (0.5, 0.5, 0.5), + normalize: bool = True, + image_token: str = "", + pad_token: str = "<|▁pad▁|>", + add_special_token: bool = False, + sft_format: str = "deepseek", + mask_prompt: bool = True, + ignore_id: int = -100, + **kwargs, + ): + + self.candidate_resolutions = candidate_resolutions + self.image_size = candidate_resolutions[0][0] + self.patch_size = patch_size + self.image_mean = image_mean + self.image_std = image_std + self.normalize = normalize + self.downsample_ratio = downsample_ratio + + self.image_transform = ImageTransform(mean=image_mean, std=image_std, normalize=normalize) + self.tokenizer = tokenizer + self.tokenizer.padding_side = 'left' # must set this,padding side with make a difference in batch inference + + # add the pad_token as special token to use 'tokenizer.pad_token' and 'tokenizer.pad_token_id' + if tokenizer.pad_token is None: + self.tokenizer.add_special_tokens({'pad_token': pad_token}) + + # add image token + image_token_id = self.tokenizer.vocab.get(image_token) + if image_token_id is None: + special_tokens = [image_token] + special_tokens_dict = {"additional_special_tokens": special_tokens} + self.tokenizer.add_special_tokens(special_tokens_dict) + self.image_token_id = self.tokenizer.vocab.get(image_token) + + # add five special tokens for grounding-related tasks + # <|ref|>, <|/ref|>, <|det|>, <|/det|>, <|grounding|> + special_tokens = ['<|ref|>', '<|/ref|>', '<|det|>', '<|/det|>', '<|grounding|>'] + special_tokens_dict = {"additional_special_tokens": special_tokens} + self.tokenizer.add_special_tokens(special_tokens_dict) + + # add special tokens for SFT data + special_tokens = ["<|User|>", "<|Assistant|>"] + special_tokens_dict = {"additional_special_tokens": special_tokens} + self.tokenizer.add_special_tokens(special_tokens_dict) + + self.image_token = image_token + self.pad_token = pad_token + self.add_special_token = add_special_token + self.sft_format = sft_format + self.mask_prompt = mask_prompt + self.ignore_id = ignore_id + + super().__init__( + tokenizer, + **kwargs, + ) + + def select_best_resolution(self, image_size): + # used for cropping + original_width, original_height = image_size + best_fit = None + max_effective_resolution = 0 + min_wasted_resolution = float("inf") + + for width, height in self.candidate_resolutions: + scale = min(width / original_width, height / original_height) + downscaled_width, downscaled_height = int( + original_width * scale), int(original_height * scale) + effective_resolution = min(downscaled_width * downscaled_height, + original_width * original_height) + wasted_resolution = (width * height) - effective_resolution + + if effective_resolution > max_effective_resolution or ( + effective_resolution == max_effective_resolution + and wasted_resolution < min_wasted_resolution): + max_effective_resolution = effective_resolution + min_wasted_resolution = wasted_resolution + best_fit = (width, height) + + return best_fit + + @property + def bos_id(self): + return self.tokenizer.bos_token_id + + @property + def eos_id(self): + return self.tokenizer.eos_token_id + + @property + def pad_id(self): + return self.tokenizer.pad_token_id + + def encode(self, text: str, bos: bool = True, eos: bool = False): + t = self.tokenizer.encode(text, add_special_tokens=False) + + if bos: + t = [self.bos_id] + t + if eos: + t = t + [self.eos_id] + + return t + + def decode(self, t: list[int], **kwargs) -> str: + return self.tokenizer.decode(t, **kwargs) + + def process_one( + self, + prompt: str, + images: list[Image.Image], + inference_mode: bool = True, + **kwargs, + ): + """ + + Args: + prompt (str): the formatted prompt; + conversations (list[dict]): conversations with a list of messages; + images (list[ImageType]): the list of images; + inference_mode (bool): if True, then remove the last eos token; + system_prompt (str): the system prompt; + **kwargs: + + Returns: + outputs (BaseProcessorOutput): the output of the processor, + - input_ids (torch.LongTensor): [N + image tokens] + - target_ids (torch.LongTensor): [N + image tokens] + - pixel_values (torch.FloatTensor): [n_patches, 3, H, W] + - image_id (int): the id of the image token + - num_image_tokens (list[int]): the number of image tokens + """ + + assert (prompt is not None and images is not None + ), "prompt and images must be used at the same time." + + sft_format = prompt + tokenized_str, images_list, images_seq_mask, images_spatial_crop, num_image_tokens = self.tokenize_with_images( + sft_format, images, bos=True, eos=True, cropping=len(images) <= 2) + masked_tokenized_str = [] + for token_index in tokenized_str: + if token_index != self.image_token_id: + masked_tokenized_str.append(token_index) + else: + masked_tokenized_str.append(self.ignore_id) + + assert len(tokenized_str) == len(images_seq_mask) == len(masked_tokenized_str), \ + (f"tokenized_str's length {len(tokenized_str)}, input_ids' length {len(masked_tokenized_str)}, " + f"imags_seq_mask's length {len(images_seq_mask)}, are not equal") + + input_ids = torch.LongTensor(tokenized_str) + target_ids = torch.LongTensor(masked_tokenized_str) + images_seq_mask = torch.tensor(images_seq_mask, dtype=torch.bool) + + # set input_ids < 0 | input_ids == self.image_token_id as ignore_id + target_ids[(input_ids < 0) | + (input_ids == self.image_token_id)] = self.ignore_id + input_ids[input_ids < 0] = self.pad_id + + if inference_mode: + # Remove the ending eos token + assert input_ids[-1] == self.eos_id + input_ids = input_ids[:-1] + target_ids = target_ids[:-1] + images_seq_mask = images_seq_mask[:-1] + + if len(images_list) == 0: + pixel_values = torch.zeros((1, 3, self.image_size, self.image_size)) + images_spatial_crop = torch.zeros((1, 2), dtype=torch.long) + else: + pixel_values = torch.stack(images_list, dim=0) + images_spatial_crop = torch.tensor(images_spatial_crop, dtype=torch.long) + + input_ids = input_ids.unsqueeze(0) + + prepare = BatchFeature( + data=dict( + input_ids=input_ids, + pixel_values=pixel_values, + images_seq_mask=images_seq_mask, + images_spatial_crop=images_spatial_crop, + num_image_tokens=num_image_tokens, + ), + tensor_type="pt", + ) + return prepare + + def __call__( + self, + *, + text: str, + images: list[Image.Image], + inference_mode: bool = True, + **kwargs, + ): + """ + + Args: + text (str): the formatted prompt; + images (list[ImageType]): the list of images; + inference_mode (bool): if True, then remove the last eos token; + **kwargs: + + Returns: + outputs (BaseProcessorOutput): the output of the processor, + - input_ids (torch.LongTensor): [N + image tokens] + - images (torch.FloatTensor): [n_images, 3, H, W] + - image_id (int): the id of the image token + - num_image_tokens (list[int]): the number of image tokens + """ + + prepare = self.process_one( + prompt=text, + images=images, + inference_mode=inference_mode, + ) + + return prepare + + def tokenize_with_images( + self, + conversation: str, + images: list[Image.Image], + bos: bool = True, + eos: bool = True, + cropping: bool = True, + ): + """Tokenize text with tags.""" + assert conversation.count(self.image_token) == len(images) + text_splits = conversation.split(self.image_token) + images_list, images_seq_mask, images_spatial_crop = [], [], [] + num_image_tokens = [] + tokenized_str = [] + for text_sep, image in zip(text_splits, images): + """encode text_sep""" + tokenized_sep = self.encode(text_sep, bos=False, eos=False) + tokenized_str += tokenized_sep + images_seq_mask += [False] * len(tokenized_sep) + + """select best resolution for anyres""" + if cropping: + best_width, best_height = self.select_best_resolution(image.size) + else: + best_width, best_height = self.image_size, self.image_size + + """process the global view""" + global_view = ImageOps.pad(image, (self.image_size, self.image_size), + color=tuple(int(x * 255) for x in self.image_transform.mean)) + images_list.append(self.image_transform(global_view)) + + """process the local views""" + local_view = ImageOps.pad(image, (best_width, best_height), + color=tuple(int(x * 255) for x in self.image_transform.mean)) + for i in range(0, best_height, self.image_size): + for j in range(0, best_width, self.image_size): + images_list.append( + self.image_transform(local_view.crop((j, i, j + self.image_size, i + self.image_size)))) + + """record height / width crop num""" + num_width_tiles, num_height_tiles = best_width // self.image_size, best_height // self.image_size + images_spatial_crop.append([num_width_tiles, num_height_tiles]) + + """add image tokens""" + h = w = math.ceil((self.image_size // self.patch_size) / self.downsample_ratio) + # global views tokens h * (w + 1), 1 is for line separator + tokenized_image = [self.image_token_id] * h * (w + 1) + # add a separator between global and local views + tokenized_image += [self.image_token_id] + # local views tokens, (num_height_tiles * h) * (num_width_tiles * w + 1) + tokenized_image += [self.image_token_id] * (num_height_tiles * h) * (num_width_tiles * w + 1) + + tokenized_str += tokenized_image + images_seq_mask += [True] * len(tokenized_image) + num_image_tokens.append(len(tokenized_image)) + + """process the last text split""" + tokenized_sep = self.encode(text_splits[-1], bos=False, eos=False) + tokenized_str += tokenized_sep + images_seq_mask += [False] * len(tokenized_sep) + + """add the bos and eos tokens""" + if bos: + tokenized_str = [self.bos_id] + tokenized_str + images_seq_mask = [False] + images_seq_mask + if eos: + tokenized_str = tokenized_str + [self.eos_id] + images_seq_mask = images_seq_mask + [False] + + assert len(tokenized_str) == len( + images_seq_mask), f"tokenize_with_images func: tokenized_str's length {len(tokenized_str)} is not equal to imags_seq_mask's length {len(images_seq_mask)}" + + return tokenized_str, images_list, images_seq_mask, images_spatial_crop, num_image_tokens + + +AutoProcessor.register("DeepseekVLV2Processor", DeepseekVLV2Processor) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/processors/ovis.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/processors/ovis.py new file mode 100644 index 0000000000000000000000000000000000000000..557d251c45f3b27850c1cc8ea0301fa511d27117 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/processors/ovis.py @@ -0,0 +1,420 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +# yapf: disable +# ruff: noqa: E501 +# coding=utf-8 +# adapted from https://github.com/AIDC-AI/Ovis/blob/35ab51a1a1e3542fa6db260a1084cefbc8f164bb/ovis/vllm/processing_ovis.py +# Copyright 2025 The Qwen Team and The HuggingFace Inc. team. All rights reserved. +# +# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX +# and OPT implementations in this library. It has been modified from its +# original forms to accommodate minor architectural differences compared +# to GPT-NeoX and OPT used by the Meta AI team that trained the model. +# +# 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. +from functools import cached_property +from typing import Union + +import PIL +import torch +from transformers import AutoProcessor, BatchFeature +from transformers.image_utils import ImageInput +from transformers.processing_utils import (ProcessingKwargs, ProcessorMixin, + Unpack) +from transformers.tokenization_utils_base import PreTokenizedInput, TextInput + +from vllm.multimodal.image import convert_image_mode + +__all__ = ['OvisProcessor'] +IGNORE_ID = -100 + +class OvisProcessorKwargs(ProcessingKwargs, total=False): # type: ignore[call-arg] + _defaults = { + "text_kwargs": { + "padding": False, + }, + "images_kwargs": { + 'max_partition':9, + 'covering_threshold':0.9, + 'convert_to_rgb':True, + 'return_tensors':'pt'}, + } + + + +class OvisProcessor(ProcessorMixin): + r""" + Constructs a Ovis processor which wraps a Ovis image processor and a Qwen2 tokenizer into a single processor. + [`OvisProcessor`] offers all the functionalities of [`Qwen2VLImageProcessor`] and [`Qwen2TokenizerFast`]. See the + [`~OvisProcessor.__call__`] and [`~OvisProcessor.decode`] for more information. + Args: + image_processor ([`Qwen2VLImageProcessor`], *optional*): + The image processor is a required input. + tokenizer ([`Qwen2TokenizerFast`], *optional*): + The tokenizer is a required input. + chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages + in a chat into a tokenizable string. + """ + + attributes = ["image_processor", "tokenizer"] + valid_kwargs = ["chat_template", "image_pad_token", "image_segment_len"] + + image_processor_class = "AutoImageProcessor" + tokenizer_class = "AutoTokenizer" + + def __init__( + self, + image_processor=None, + tokenizer=None, + chat_template=None, + image_pad_token=None, + image_segment_len=255, + **kwargs, + ): + self.image_token = "" + self.image_pad_token = image_pad_token + self.image_segment_len = image_segment_len + super().__init__(image_processor, tokenizer, chat_template=chat_template) + + @cached_property + def extra_special_tokens(self): + image_pad_token_id = self.tokenizer.get_vocab()[self.image_pad_token] + extra_special_tokens = { + "image_token": -200, + "image_atom": -300, + "image_start": -301, + "image_prefix": -302, + "image_col_sep": -303, + "image_row_sep": -304, + "image_end": -305, + 'image_pad': image_pad_token_id, + } + return extra_special_tokens + + def __call__( + self, + images: ImageInput = None, + text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None, + **kwargs: Unpack[OvisProcessorKwargs], + ) -> BatchFeature: + """ + Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text` + and `kwargs` arguments to Qwen2TokenizerFast's [`~Qwen2TokenizerFast.__call__`] if `text` is not `None` to encode + the text. To prepare the vision inputs, this method forwards the `vision_infos` and `kwrags` arguments to + Qwen2VLImageProcessor's [`~Qwen2VLImageProcessor.__call__`] if `vision_infos` is not `None`. + Args: + images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`): + The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch + tensor. Both channels-first and channels-last formats are supported. + text (`str`, `list[str]`, `list[list[str]]`): + The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings + (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set + `is_split_into_words=True` (to lift the ambiguity with a batch of sequences). + videos (`np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`): + The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch + tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported. + return_tensors (`str` or [`~utils.TensorType`], *optional*): + If set, will return tensors of a particular framework. Acceptable values are: + - `'tf'`: Return TensorFlow `tf.constant` objects. + - `'pt'`: Return PyTorch `torch.Tensor` objects. + - `'np'`: Return NumPy `np.ndarray` objects. + - `'jax'`: Return JAX `jnp.ndarray` objects. + Returns: + [`BatchFeature`]: A [`BatchFeature`] with the following fields: + - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`. + - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when + `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not + `None`). + - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`. + - **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`. + - **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`. + - **video_grid_thw** -- List of video 3D grid in LLM. Returned when `videos` is not `None`. + - **second_per_grid_ts** -- List of video seconds per time grid. Returned when `videos` is not `None`. + """ + output_kwargs = self._merge_kwargs( + OvisProcessorKwargs, + tokenizer_init_kwargs=self.tokenizer.init_kwargs, + **kwargs, + ) + + # Process all images first + image_features = {} + if images is not None: + processed_images = [] + image_placeholders_list = [] + grids = [] + + # Process each image + for image in images if isinstance(images, list) else [images]: + pixel_values, image_placeholders, grid = self.preprocess_image( + image=image, **output_kwargs["images_kwargs"] + ) + processed_images.append(pixel_values) + image_placeholders_list.append(image_placeholders) + grids.append(grid) + + # assign all processed images + if processed_images: + image_features["image_placeholders"] = image_placeholders_list + + # Process text input + if text is not None: + + if not isinstance(text, list): + text = [text] + + tokenized_batched_text = self._tokenize_with_image_symbol(text) + image_token_id = self.get_token_value("image_token") + replaced_ids_list = [] + idx = 0 + for ids_tensor in tokenized_batched_text: + if image_token_id in ids_tensor and "image_placeholders" in image_features: + if idx < len(image_features["image_placeholders"]): + # Converts in list for ease of use + ids_list = ids_tensor.tolist() + + new_ids = [] + + # replace placeholders + for i, token_id in enumerate(ids_list): + if token_id == image_token_id: + placeholder_ids = image_features["image_placeholders"][idx] + new_ids.extend(placeholder_ids) + idx += 1 + else: + new_ids.append(token_id) + + # Converts back to tensors + ids_tensor = torch.tensor(new_ids, dtype=torch.long) + else: + raise RuntimeError( + 'Mismatch between the images you provided and the number of placeholder present in the text') + + replaced_ids_list.append(ids_tensor) + + if replaced_ids_list: + replaced_and_tokenized_ids = torch.stack(replaced_ids_list) + else: + replaced_and_tokenized_ids = torch.tensor([], dtype=torch.long) + + # Create the output with text features + output = BatchFeature( + data={ + "input_ids": replaced_and_tokenized_ids, + } + ) + + # Add image features if present + if image_features: + output["pixel_values"] = processed_images + output['grids'] = grids + + return output + + # If only images were provided + return BatchFeature(data=image_features) + + def _tokenize_with_image_symbol(self, text_list: list[str]) -> torch.LongTensor: + batch_token_ids = [] + for text in text_list: + text_chunks = [self.tokenizer(chunk, add_special_tokens=False).input_ids for chunk in + text.split(self.image_token)] + token_ids = [] + num_chuck = len(text_chunks) + for i, chunk in enumerate(text_chunks): + token_ids.extend(chunk) + if i < num_chuck - 1: + token_ids.append(self.get_token_value("image_token")) + batch_token_ids.append(token_ids) + return torch.tensor(batch_token_ids, dtype=torch.long) + + def get_image_size(self): + size = self.image_processor.size + if 'shortest_edge' in size: + width = height = size['shortest_edge'] + elif "height" in size and "width" in size: + width = size['width'] + height = size['height'] + else: + raise ValueError( "Can't parse image size from image_processor config.") + return height, width + + def get_token_value(self, tok): + return self.extra_special_tokens[tok] + + def construct_image_indicators(self, grid): + image_placeholders = [self.get_token_value('image_start'), + self.get_token_value('image_atom'), + self.get_token_value('image_prefix')] + if grid[0] * grid[1] > 1: + for r in range(grid[0]): + for c in range(grid[1]): + image_placeholders.append(self.get_token_value('image_atom') ) + if c < grid[1] - 1: + image_placeholders.append(self.get_token_value('image_col_sep')) + if r < grid[0] - 1: + image_placeholders.append(self.get_token_value('image_row_sep')) + image_placeholders.append(self.get_token_value('image_end')) + return image_placeholders + + def construct_image_placeholders(self, grid): + + image_placeholders = self.construct_image_indicators(grid) + + image_atom_token_id = self.get_token_value('image_atom') + # Extract the padding token ID from tokenizer + image_padding_token_id = self.get_token_value('image_pad') + + # Create a new list with padding tokens inserted + padded_placeholder_tokens = [] + for token in image_placeholders: + padded_placeholder_tokens.append(image_padding_token_id) + if token == image_atom_token_id: + padded_placeholder_tokens.extend([image_padding_token_id] * self.image_segment_len) + return padded_placeholder_tokens + + def preprocess_image(self, image: PIL.Image.Image, max_partition, covering_threshold, convert_to_rgb, return_tensors): + def _preprocess(img: PIL.Image.Image, side): + # first resize and preprocess + w, h = img.size + if w == h: + new_width = new_height = side + elif w > h: + new_width = side + new_height = int(h / w * new_width) + else: + new_height = side + new_width = int(w / h * new_height) + new_size = dict(height=new_height, width=new_width) + pixel_values = self.image_processor.preprocess(img, size=new_size, return_tensors=return_tensors)['pixel_values'] + + # then pad to square + square_values = torch.zeros([1, 3, side, side], dtype=pixel_values.dtype, device=pixel_values.device) + new_height, new_width = pixel_values.shape[2:] + if new_height == new_width: + square_values[:, :, :, :] = pixel_values + elif new_height > new_width: + from_index = (side - new_width) // 2 + square_values[:, :, :, from_index:from_index + new_width] = pixel_values + else: + from_index = (side - new_height) // 2 + square_values[:, :, from_index:from_index + new_height, :] = pixel_values + + return square_values + + def _partition(img, grid) -> list[tuple[int, int, int, int]]: + w, h = img.size + row_height = h // grid[0] + col_width = w // grid[1] + + partition = [] + for row in range(grid[0]): + for col in range(grid[1]): + left = col * col_width + upper = row * row_height + right = w if col == grid[1] - 1 else (col + 1) * col_width + lower = h if row == grid[0] - 1 else (row + 1) * row_height + partition.append((left, upper, right, lower)) + + return partition + + def _covering_area(left, upper, right, lower, side): + w = right - left + h = lower - upper + w, h = max(w, h), min(w, h) + if w > side: + h = h / w * side + w = side + return w * h + + def _get_best_grid(img, side): + img_area = img.size[0] * img.size[1] + + candidate_grids = [] + for i in range(1, max_partition + 1): + for j in range(1, max_partition + 1): + if i * j <= max_partition: + candidate_grids.append((i, j)) + + all_grids = [] + good_grids = [] + for grid in candidate_grids: + partition = _partition(img, grid) + covering_ratio = sum([_covering_area(*p, side) for p in partition]) / img_area + assert covering_ratio <= 1.0 + all_grids.append((grid, covering_ratio)) + if covering_ratio > covering_threshold: + good_grids.append((grid, covering_ratio)) + + if len(good_grids) > 0: + # pick the good partition with minimum #sub_images and break the tie using covering_ratio + return sorted(good_grids, key=lambda x: (x[0][0] * x[0][1], -x[1]))[0][0] + else: + # pick the partition with maximum covering_ratio and break the tie using #sub_images + return sorted(all_grids, key=lambda x: (-x[1], x[0][0] * x[0][1]))[0][0] + + if convert_to_rgb: + image = convert_image_mode(image, 'RGB') + + + sides = self.get_image_size() + if sides[0] != sides[1]: + raise ValueError('get_image_size() returns non-square size') + side = sides[0] + grid = _get_best_grid(image, side) + partition = _partition(image, grid) + crops = [image.crop(p) for p in partition] + if len(crops) > 1: + crops.insert(0, image) + pixel_values = torch.cat([_preprocess(crop, side) for crop in crops], dim=0) + image_placeholders = self.construct_image_placeholders(grid) + return pixel_values, image_placeholders, grid + + def batch_decode(self, *args, **kwargs): + """ + This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please + refer to the docstring of this method for more information. + """ + return self.tokenizer.batch_decode(*args, **kwargs) + + def decode(self, *args, **kwargs): + """ + This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to + the docstring of this method for more information. + """ + return self.tokenizer.decode(*args, **kwargs) + + def post_process_image_text_to_text(self, generated_outputs): + """ + Post-process the output of the model to decode the text. + Args: + generated_outputs (`torch.Tensor` or `np.ndarray`): + The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)` + or `(sequence_length,)`. + Returns: + `list[str]`: The decoded text. + """ + return self.tokenizer.batch_decode( + generated_outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False + ) + + @property + def model_input_names(self): + tokenizer_input_names = self.tokenizer.model_input_names + image_processor_input_names = self.image_processor.model_input_names + names_from_processor = list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) + return names_from_processor + ["second_per_grid_ts"] + + +AutoProcessor.register("OvisProcessor", OvisProcessor) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/tokenizers/mistral.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/tokenizers/mistral.py new file mode 100644 index 0000000000000000000000000000000000000000..4dd8b2439b3f5b04405ece0aa4cfb32d90cf6347 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/transformers_utils/tokenizers/mistral.py @@ -0,0 +1,516 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +import os +from pathlib import Path +from typing import TYPE_CHECKING, Any, Optional, Union, cast + +import huggingface_hub +import regex as re +from huggingface_hub import HfApi, hf_hub_download +from transformers.tokenization_utils_base import BatchEncoding + +from vllm.logger import init_logger +from vllm.transformers_utils.tokenizer_base import TokenizerBase +from vllm.utils import is_list_of + +if TYPE_CHECKING: + # make sure `mistral_common` is lazy imported, + # so that users who only use non-mistral models + # will not be bothered by the dependency. + from mistral_common.protocol.instruct.request import ChatCompletionRequest + from mistral_common.tokens.tokenizers.mistral import ( + MistralTokenizer as PublicMistralTokenizer) + + from vllm.entrypoints.chat_utils import ChatCompletionMessageParam + +logger = init_logger(__name__) + + +def maybe_serialize_tool_calls(request: "ChatCompletionRequest"): + # SEE: https://github.com/vllm-project/vllm/pull/9951 + # Credits go to: @gcalmettes + # NOTE: There is currently a bug in pydantic where attributes + # declared as iterables are replaced in in the instances by + # pydantic-core ValidatorIterator instance. In particular, this + # affects tool_calls defined in ChatCompletionAssistantMessageParam + # model: + # see: + # - https://github.com/pydantic/pydantic/issues/9467 + # As a result, tool_calls from assistant messages are never + # deserialized in the request object if the tool_calls iterator is + # not consumed. This affect messages passed to the MistralTokenizer + # since no chat template is applied and therefore the tools_calls + # iterator is not directly consumed. + # Issue is tracked on Pydantic side, with resolution planned for + # v2.11 release. In the meantime, the official workaround is to + # consume the iterator so the tool_calls are correctly deserialized + # in the OpenAI ChatCompletionAssistantMessageParam object + # https://github.com/pydantic/pydantic/issues/9467#issuecomment-2442097291 # noqa: E501 + # Official Pydantic Issues: + # - https://github.com/pydantic/pydantic/issues/9541 + # TODO: remove when pydantic v2.11 is released + for i, message in enumerate(request.messages): + if message.get("role") == 'assistant': + tool_calls_validator = message.get("tool_calls", ().__iter__()) + validated_tool_calls = [] + while True: + try: + tool_call = next(tool_calls_validator) # type: ignore + validated_tool_calls.append(tool_call) + except StopIteration: + break + + request.messages[i]["tool_calls"] = validated_tool_calls + + +def truncate_tool_call_ids(request: "ChatCompletionRequest"): + """Truncates tool call IDs for Mistral's ID requirements.""" + for i, message in enumerate(request.messages): + if message.get("role") == 'assistant': + tool_calls = message.get("tool_calls", []) + for tool_call in tool_calls: + if len(tool_call["id"]) > 9: + logger.warning( + "Truncating tool call ID: %s to %s", + tool_call["id"], + tool_call["id"][-9:], + ) + tool_call["id"] = tool_call["id"][-9:] + + request.messages[i]["tool_calls"] = tool_calls + + elif message.get("role") in {"tool_results", "tool"}: + if "tool_call_id" in message: + tool_call_id = message["tool_call_id"] + + if len(tool_call_id) > 9: + logger.warning( + "Truncating tool_call_id: %s to %s", + tool_call_id, + tool_call_id[-9:], + ) + tool_call_id = tool_call_id[-9:] + request.messages[i]["tool_call_id"] = tool_call_id + + +def validate_request_params(request: "ChatCompletionRequest"): + if (request.skip_special_tokens is not None + and not request.skip_special_tokens): + raise ValueError("skip_special_tokens=False is not supported " + "for Mistral tokenizers.") + + +def list_local_repo_files(repo_id: str, revision: Optional[str]) -> list[str]: + repo_cache = os.path.join( + huggingface_hub.constants.HF_HUB_CACHE, + huggingface_hub.constants.REPO_ID_SEPARATOR.join( + ["models", *repo_id.split("/")])) + + if revision is None: + revision_file = os.path.join(repo_cache, "refs", "main") + if os.path.isfile(revision_file): + with open(revision_file) as file: + revision = file.read() + + if revision: + revision_dir = os.path.join(repo_cache, "snapshots", revision) + if os.path.isdir(revision_dir): + return os.listdir(revision_dir) + + return [] + + +def find_tokenizer_file(files: list[str]): + file_pattern = re.compile( + r"^tokenizer\.model\.v.*$|^tekken\.json$|^tokenizer\.mm\.model\.v.*$") + + matched_files = [file for file in files if file_pattern.match(file)] + if len(matched_files) > 1: + raise OSError( + f"Found {len(matched_files)} files matching the " + f"pattern: `{file_pattern.pattern}`. Make sure only one Mistral " + f"tokenizer is present in {files}.") + elif len(matched_files) == 0: + raise OSError( + f"Found {len(matched_files)} files matching the " + f"pattern: `{file_pattern.pattern}`. Make sure that a Mistral " + f"tokenizer is present in {files}.") + + return matched_files[0] + + +def _aggregate_content(content: list) -> list[dict[str, Any]]: + aggregated_content: list[dict[str, Any]] = [] + for chunk in content: + if chunk.get("type" + ) == "text" and aggregated_content and aggregated_content[ + -1].get("type") == "text": + aggregated_content[-1]["text"] += "\n\n" + chunk.get("text") + else: + aggregated_content.append(chunk) + if len(aggregated_content) == 1 and aggregated_content[0].get( + "type") == "text": + content = aggregated_content[0]["text"] + return content + + +def make_mistral_chat_completion_request( + messages: list["ChatCompletionMessageParam"], + tools: Optional[list[dict[str, + Any]]] = None) -> "ChatCompletionRequest": + last_message = cast(dict[str, Any], messages[-1]) + if last_message["role"] == "assistant": + last_message["prefix"] = True + + # mistral-common requires AssistantMessage content to be string [1]. + # + # [1]: https://github.com/mistralai/mistral-common/blob/f4a06998b75ed78bbf5aaf569590b772ea26c9f6/src/mistral_common/protocol/instruct/messages.py#L80 + for message in messages: + # Remove reasoning_content as unsupported by Mistral + _ = message.pop("reasoning_content", None) # type: ignore + + # Convert list text content to string + if message.get("role") in ("assistant", "tool"): + content: Any = message.get("content") + if isinstance(content, list): + content = _aggregate_content(content) + message["content"] = content + + # The Mistral client, in comparison to the OpenAI client, requires the + # "parameters" dict and the "description" string to be present + # even if they are empty. + if tools: + for function in [ + tool["function"] for tool in tools + if tool["type"] == "function" + ]: + if function.get("parameters") is None: + function["parameters"] = {} + if function.get("description") is None: + function["description"] = "" + + from mistral_common.protocol.instruct.request import ChatCompletionRequest + return ChatCompletionRequest(messages=messages, + tools=tools) # type: ignore[type-var] + + +class MistralTokenizer(TokenizerBase): + + def __init__(self, tokenizer: "PublicMistralTokenizer") -> None: + self.mistral = tokenizer + self.instruct = tokenizer.instruct_tokenizer + _mistral_version_str = self.instruct.tokenizer.version.value + self.version: int = int(_mistral_version_str.split("v")[-1]) + + tokenizer_ = tokenizer.instruct_tokenizer.tokenizer + from mistral_common.tokens.tokenizers.tekken import ( + SpecialTokenPolicy, Tekkenizer) + self.is_tekken = isinstance(tokenizer_, Tekkenizer) + from mistral_common.tokens.tokenizers.sentencepiece import ( + SentencePieceTokenizer) + self.is_spm = isinstance(tokenizer_, SentencePieceTokenizer) + if self.is_tekken: + # Make sure special tokens will not raise + tokenizer_.special_token_policy = SpecialTokenPolicy.IGNORE + elif self.is_spm: + pass + else: + raise TypeError(f"Unsupported tokenizer: {type(tokenizer_)}") + + self._vocab = tokenizer_.vocab() + # Convert to a dict[str, int] to match protocol, but this is a lossy + # conversion. There may be multiple token ids that decode to the same + # string due to partial UTF-8 byte sequences being converted to � + self._vocab_dict = { + token: idx + for idx, token in enumerate(self._vocab) + } + self.tokenizer = tokenizer_ + self._max_token_id = self.vocab_size - 1 + + @classmethod + def from_pretrained(cls, + path_or_repo_id: str, + *, + revision: Optional[str] = None) -> "MistralTokenizer": + if not Path(path_or_repo_id).exists(): + assert len(path_or_repo_id.split("/")) == 2, ( + "You have either provided a non-existent path: " + "{path_or_repo_id} or an invalid HF Hub repo id.") + tokenizer_file = cls._download_mistral_tokenizer_from_hf( + path_or_repo_id, revision) + elif Path(path_or_repo_id).is_dir(): + tokenizer_file_name = find_tokenizer_file( + os.listdir(path_or_repo_id)) + tokenizer_file = str(Path(path_or_repo_id) / tokenizer_file_name) + else: + assert Path( + path_or_repo_id).is_file(), f"Invalid path: {path_or_repo_id}" + tokenizer_file = str(Path(path_or_repo_id)) + + from mistral_common.tokens.tokenizers.mistral import ( + MistralTokenizer as PublicMistralTokenizer) + mistral_tokenizer = PublicMistralTokenizer.from_file(tokenizer_file) + return cls(mistral_tokenizer) + + @staticmethod + def _download_mistral_tokenizer_from_hf(tokenizer_name: str, + revision: Optional[str]) -> str: + try: + hf_api = HfApi() + files = hf_api.list_repo_files(repo_id=tokenizer_name, + revision=revision) + except ConnectionError as exc: + files = list_local_repo_files(repo_id=tokenizer_name, + revision=revision) + + if len(files) == 0: + raise exc + + filename = find_tokenizer_file(files) + + tokenizer_file = hf_hub_download(tokenizer_name, + filename=filename, + revision=revision) + return tokenizer_file + + # the following attributes are set to fit vLLM's design and are used + # by the guided structured output backends. + @property + def all_special_tokens_extended(self) -> list[str]: + from mistral_common.tokens.tokenizers.base import SpecialTokens + + # tekken defines its own extended special tokens list + if hasattr(self.tokenizer, "SPECIAL_TOKENS"): + special_tokens = self.tokenizer.SPECIAL_TOKENS + else: + special_tokens = list(SpecialTokens) + return [ + s.value if isinstance(s, SpecialTokens) else s + for s in special_tokens + ] + + @property + def all_special_tokens(self) -> list[str]: + return self.all_special_tokens_extended + + @property + def all_special_ids(self) -> list[int]: + return [ + self.all_special_tokens.index(t) for t in self.all_special_tokens + ] + + @property + def bos_token_id(self) -> int: + return self.tokenizer.bos_id + + @property + def eos_token_id(self) -> int: + return self.tokenizer.eos_id + + @property + def sep_token(self) -> str: + raise NotImplementedError() + + @property + def pad_token(self) -> str: + raise NotImplementedError() + + @property + def is_fast(self) -> bool: + return True + + @property + def vocab_size(self) -> int: + return len(self._vocab) + + @property + def max_token_id(self) -> int: + return self._max_token_id + + def __len__(self) -> int: + return self.vocab_size + + def __call__( + self, + text: Union[str, list[str], list[int]], + text_pair: Optional[str] = None, + add_special_tokens: bool = False, + truncation: bool = False, + max_length: Optional[int] = None, + ): + input_ids: Union[list[int], list[list[int]]] + # For list[str], original prompt text + if is_list_of(text, str): + input_ids_: list[list[int]] = [] + for p in text: + each_input_ids = self.encode_one(p, truncation, max_length) + input_ids_.append(each_input_ids) + input_ids = input_ids_ + # For list[int], apply chat template output, already tokens. + elif is_list_of(text, int): + input_ids = text + # For str, single prompt text + else: + input_ids = self.encode_one(text, truncation, max_length) + return BatchEncoding({"input_ids": input_ids}) + + def get_vocab(self) -> dict[str, int]: + # NB: the dictionary form of the vocabulary collapses token ids that map + # to the same string but have different bytes + return self._vocab_dict + + def get_added_vocab(self) -> dict[str, int]: + # Mistral tokenizers have no added vocabulary + return {} + + def encode_one( + self, + text: str, + truncation: bool = False, + max_length: Optional[int] = None, + ) -> list[int]: + # Mistral Tokenizers should not add special tokens + input_ids = self.encode(text) + + if truncation: + input_ids = input_ids[:max_length] + return input_ids + + def encode(self, + text: str, + truncation: Optional[bool] = None, + max_length: Optional[int] = None, + add_special_tokens: Optional[bool] = None) -> list[int]: + # `encode` should only be used for prompt completion + # it should never be used for chat_completion. + # For chat completion use `apply_chat_template` + if add_special_tokens is not None: + return self.tokenizer.encode(text, + bos=add_special_tokens, + eos=add_special_tokens) + else: + return self.tokenizer.encode(text, bos=True, eos=False) + + def apply_chat_template(self, + messages: list["ChatCompletionMessageParam"], + tools: Optional[list[dict[str, Any]]] = None, + **kwargs) -> list[int]: + + request = make_mistral_chat_completion_request(messages, tools) + encoded = self.mistral.encode_chat_completion(request) + + # encode-decode to get clean prompt + return encoded.tokens + + def convert_tokens_to_string(self, tokens: list[str]) -> str: + from mistral_common.tokens.tokenizers.base import SpecialTokens + if self.is_tekken: + tokens = [ + t for t in tokens + if (t is SpecialTokens.tool_calls + or t not in self.tokenizer._all_special_tokens) + ] + + if any(isinstance(t, bytes) for t in tokens): + # we need to encode and decode all tokens again + shift = self.tokenizer.num_special_tokens + + def _token_to_id(t: str): + t_bytes = t.encode("utf-8") \ + if not isinstance(t, bytes) else t + try: + return shift + \ + self.tokenizer._tekken_token2id_nospecial[t_bytes] + except KeyError: + logger.warning( + "Failed to convert token %s to id," + " replacing with ", t_bytes) + return self.tokenizer.unk_id + + ids = [_token_to_id(t) for t in tokens] + decoded = self.tokenizer.decode(ids) + else: + decoded = "".join(tokens) + else: + # make sure certain special tokens like Tool calls are + # not decoded + special_tokens = {SpecialTokens.tool_calls} + regular_tokens: list[str] = [] + decoded_list = [] + + for token in tokens: + if token in special_tokens: + if regular_tokens: + decoded_list.append( + self.tokenizer.decode(regular_tokens)) + regular_tokens = [] + decoded_list.append(token) + else: + regular_tokens.append(token) + + if regular_tokens: + decoded_list.append( + self.tokenizer.decode(regular_tokens)) # type: ignore + + decoded = ''.join(decoded_list) + + return decoded + + # WARN: Outlines logits processors can overwrite this method. + # See: guided_decoding/outlines_logits_processors.py::_adapt_tokenizer + # for more. + def decode(self, + ids: Union[list[int], int], + skip_special_tokens: bool = True) -> str: + assert ( + skip_special_tokens + ), "skip_special_tokens=False is not supported for Mistral tokenizers." + + if isinstance(ids, int): + ids = [ids] + return self.tokenizer.decode(ids) + + def convert_ids_to_tokens( + self, + ids: list[int], + skip_special_tokens: bool = True, + ) -> list[str]: + from mistral_common.tokens.tokenizers.base import SpecialTokens + from mistral_common.tokens.tokenizers.instruct import ( + InstructTokenizerV13) + + # TODO(Patrick) - potentially allow special tokens to not be skipped + assert ( + skip_special_tokens + ), "skip_special_tokens=False is not supported for Mistral tokenizers." + + assert self.is_tekken or self.is_spm, type(self.tokenizer) + + if self.is_tekken: + # skip special tokens except tool call and think tokens + non_skip_special_tokens = { + self.tokenizer.get_control_token(SpecialTokens.tool_calls) + } + if isinstance(self.instruct, InstructTokenizerV13): + if self.instruct.BEGIN_THINK: + non_skip_special_tokens.add(self.instruct.BEGIN_THINK) + if self.instruct.END_THINK: + non_skip_special_tokens.add(self.instruct.END_THINK) + ids = [ + i for i in ids if i > self.tokenizer.num_special_tokens + or i in non_skip_special_tokens + ] + + tokens = [self.tokenizer.id_to_piece(id) for id in ids] + + if any("�" in t for t in tokens) and self.is_tekken: + # if a decoded token contains the replacement character, then the + # token has an incomplete UTF-8 character so we must use bytes + # See: https://github.com/vllm-project/vllm/pull/8640 + # https://github.com/vllm-project/vllm/pull/9625 + # if underlying tokenizeir is sentencepiece, we just add "�" + tokens = [self.tokenizer.id_to_byte_piece(id) for id in ids] + + return tokens diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/usage/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/usage/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b00e525112b3e180db328bc941f08ba1f77fcf14 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/usage/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/__pycache__/outputs.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/__pycache__/outputs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8a881bb7d49bfa1157bfe89e86ed86ef6bd06c6 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/__pycache__/outputs.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/attention/backends/mla/common.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/attention/backends/mla/common.py new file mode 100644 index 0000000000000000000000000000000000000000..f2610671f769e6c4b309c5d4246568cad8b086fa --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/attention/backends/mla/common.py @@ -0,0 +1,1206 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +""" +# MLA Common Components + +This file implements common components for MLA implementations. + +First we define: + +Sq as Q sequence length +Skv as KV sequence length + +MLA has two possible ways of computing, a data-movement friendly approach and a +compute friendly approach, we generally want to use the compute friendly +approach for "prefill" (i.e. the ratio Sq / Skv is "small", is near 1) +and the data-movement friendly approach for "decode" (i.e. the ratio +Sq / Skv is "large"). + +NOTE what we deem small and large is currently determined by if its labelled +prefill or decode by the scheduler, but this is something we should probably +tune. + +Main reference: DeepseekV2 paper, and FlashInfer Implementation +(https://arxiv.org/abs/2405.04434 and https://github.com/flashinfer-ai/flashinfer/pull/551). + +Deepseek's MLA attention works the following way: +* Use a single latent vector to represent the per-token entry of the KV cache. +* For decode (i.e. the memory friendly approach) the attention "simulates" a +multi-head attention, while the compute is similar to multi-query attention. + +Below is example of both paths assuming batchsize = 1 + +## More Extent Definitions: + +C Context length, `Skv - Sq` +H hidden size +N number of attention heads +Lq latent dimension for Q 1536 in DSV3 +Lkv latent dimension for K/V 512 in DSV3 +P nope dimension, no rope. 128 in DSV3 +R rope dimension, goes through rope. 64 in DSV3 +V V head dim. 128 in DSV3 + +## Vector/Matrix Definitions + +h_t hidden states (input to attention) shape [Sq, H] +q_c latent/compressed Q shape [Sq, Lq] +q_nope uncompressed Q (no-rope) shape [Sq, N, P] +q_pe uncompressed Q (rope) shape [Sq, N, R] +kv_c latent/compressed KV shape [Skv, Lkv] +k_pe decoupled k position embeddings shape [Skv, R] +new_kv_c new kv_c from current iter shape [Sq, Lkv] +new_k_pe new k_pe from current iter shape [Sq, R] +cache_kv_c cached k_c from previous iters shape [C, Lkv] +cache_k_pe cached k_pe from previous iters shape [C, R] +W_DQ project h_t to q_c shape [H, Lq] +W_UQ project q_c to q_nope shape [Lq, N * P] +W_QR project q_c to q_pe shape [Lq, N * R] +W_DKV project h_t to kv_c shape [H, Lkv] +W_UK project kv_c to k_nope shape [Lkv, N, P] +W_KR project h_t to k_pe shape [H, R] +W_UV project kv_c to v shape [Lkv, N, V] +W_O project v to h_t shape [N * V, H] + + +## Compute Friendly Approach (i.e. "_forward_prefill"): + +q_c = h_t @ W_DQ +q_nope = (q_c @ W_UQ).view(Sq, N, P) +q_pe = RoPE(q_c @ W_QR).view(Sq, N, R) +new_kv_c = h_t @ W_DKV +new_k_pe = RoPE(h_t @ W_KR) +kv_c = torch.cat([new_kv_c, cache_kv_c], dim=0) +k_pe = torch.cat([new_k_pe, cache_k_pe], dim=0) +k_nope = (kv_c @ W_UK.view(Lkv, N * P)).view(Skv, N, P) +v = (kv_c @ W_UV.view(Lkv, N * V)).view(Skv, N, V) + +// MHA with QK headdim = P + R +// V headdim = V +// spda_o shape [Sq, N, V] +spda_o = scaled_dot_product_attention( + torch.cat([q_nope, q_pe], dim=-1), + torch.cat([k_nope, k_pe.unsqueeze(1).expand(-1, N, -1)], dim=-1), + v +) +return spda_o @ W_O + +NOTE: in the actual code, + `kv_b_proj` is [W_UK; W_UV] concatenated per head + `q_b_proj` is [W_UQ; W_QR] concatenated per head + `out_proj` is W_O + + +## Data-Movement Friendly Approach (i.e. "_forward_decode"): + +Runtime +q_c = h_t @ W_DQ +q_nope = (q_c @ W_UQ).view(-1, N, P) +ql_nope = einsum("snh,lnh->snl", q, W_UK) +q_pe = RoPE(q_c @ W_QR).view(Sq, N, R) +new_kv_c = h_t @ W_DKV +new_k_pe = RoPE(h_t @ W_KR) +kv_c = torch.cat([new_kv_c, cache_kv_c], dim=0) +k_pe = torch.cat([new_k_pe, cache_k_pe], dim=0) + +// MQA with QK headdim = Lkv + R +// V headdim = Lkv +// spda_o shape [Sq, N, Lkv] +// NOTE: this is less compute-friendly since Lkv > P +// but is more data-movement friendly since its MQA vs MHA +spda_o = scaled_dot_product_attention( + torch.cat([ql_nope, q_pe], dim=-1), + torch.cat([kv_c, k_pe], dim=-1), + kv_c +) + +o = einsum("snl,lnv->snv", spda_o.reshape(-1, N, Lkv), W_UV) +return o.view(-1, N * V) @ self.num_heads @ W_O + + +## Chunked Prefill + +For chunked prefill we want to use the compute friendly algorithm. We are +assuming sufficiently large Sq / Skv ratio, in the future may want to switch to +the data-movement friendly approach if the chunk (i.e. `Sq`) is small. + +However, the compute-friendly approach can potentially run out of memory if Skv +is large due to: `k_nope = (kv_c @ W_UK).view(Skv, N, P)` + +To mitigate this, we chunk the computation of attention with respect to the +current context (i.e. `cache_kv_c` and `cache_k_pe`) so that we can used a +fixed workspace size. + +The chunked prefill approach is as follows: + +MCC Max chunk of context to process per iter, computed dynamically, + used to bound the memory usage + +q_c = h_t @ W_DQ +q_nope = (q_c @ W_UQ).view(Sq, N, P) +q_pe = RoPE(q_c @ W_QR).view(Sq, N, R) +new_kv_c = h_t @ W_DKV +new_k_pe = RoPE(h_t @ W_KR) +new_k_nope = (new_kv_c @ W_UK.view(Lkv, N * P)).view(Sq, N, P) +new_v = (new_kv_c @ W_UV.view(Lkv, N * V)).view(Sq, N, V) + +// MHA between queries and new KV +// with QK headdim = P + R +// V headdim = V +// curr_o shape [Sq, N, V] +// curr_lse shape [N, Sq], this is just order FA returns +curr_o, curr_lse = scaled_dot_product_attention( + torch.cat([q_nope, q_pe], dim=-1), + torch.cat([new_k_nope, new_k_pe.unsqueeze(1).expand(-1, N, -1)], dim=-1), + new_v, + casual=True, + return_softmax_lse=True +) + +// Compute attention with the already existing context +for chunk_idx in range(cdiv(C, MCC)): + chunk_start = chunk_idx * MCC + chunk_end = min(chunk_start + MCC, C) + Sc = chunk_end - chunk_start + cache_kv_c_chunk = cache_kv_c[chunk_start:chunk_end] + cache_k_pe_chunk = cache_k_pe[chunk_start:chunk_end] + cache_k_nope_chunk = (cache_kv_c_chunk @ W_UK).view(-1, N, P) + cache_v_chunk = (cache_kv_c_chunk @ W_UV).view(-1, N, V) + + chunk_o, chunk_lse = scaled_dot_product_attention( + torch.cat([q_nope, q_pe], dim=-1), + torch.cat([cache_k_nope_chunk, + cache_k_pe_chunk.unsqueeze(1).expand(-1, N, -1)], + dim=-1), + cache_v_chunk, + casual=False, + return_softmax_lse=True + ) + + curr_o, curr_lse = merge_attn_states( + suffix_output=curr_o, + suffix_lse=curr_lse, + prefix_output=chunk_o, + prefix_lse=chunk_lse, + ) + +return curr_o @ W_O +""" + +import functools +from abc import abstractmethod +from dataclasses import dataclass, field +from typing import ClassVar, Generic, Optional, TypeVar, Union + +import torch + +import vllm.envs as envs +from vllm import _custom_ops as ops +from vllm.attention.backends.abstract import (AttentionBackend, AttentionLayer, + AttentionMetadata, + MLAAttentionImpl) +from vllm.attention.backends.utils import get_mla_dims +from vllm.attention.ops.merge_attn_states import merge_attn_states +from vllm.attention.utils.fa_utils import get_flash_attn_version +from vllm.config import VllmConfig +from vllm.logger import init_logger +from vllm.model_executor.layers.linear import (ColumnParallelLinear, + LinearBase, + UnquantizedLinearMethod) +from vllm.platforms import current_platform +from vllm.utils import cdiv, round_down +from vllm.utils.flashinfer import has_nvidia_artifactory +from vllm.v1.attention.backends.utils import (AttentionMetadataBuilder, + CommonAttentionMetadata, + get_per_layer_parameters, + infer_global_hyperparameters, + split_decodes_and_prefills) +from vllm.v1.kv_cache_interface import AttentionSpec + +try: + from vllm.vllm_flash_attn import flash_attn_varlen_func + is_vllm_fa = True +except ImportError: + # For rocm use upstream flash attention + if current_platform.is_rocm(): + from flash_attn import flash_attn_varlen_func + is_vllm_fa = False + +try: + from flashinfer import BatchPrefillWithRaggedKVCacheWrapper + from flashinfer.prefill import ( # noqa: F401 + cudnn_batch_prefill_with_kv_cache) + flashinfer_available = True +except ImportError: + flashinfer_available = False + +logger = init_logger(__name__) + +CUDNN_WORKSPACE_SIZE = 12800 + + +class MLACommonBackend(AttentionBackend): + + accept_output_buffer: bool = True + + @staticmethod + def get_name() -> str: + return "TRITON_MLA_VLLM_V1" + + @staticmethod + def get_metadata_cls() -> type["AttentionMetadata"]: + return MLACommonMetadata + + @staticmethod + def get_builder_cls() -> type["MLACommonMetadataBuilder"]: + return MLACommonMetadataBuilder + + @staticmethod + def get_kv_cache_shape( + num_blocks: int, + block_size: int, + num_kv_heads: int, # assumed to be 1 for MLA + head_size: int, + ) -> tuple[int, ...]: + return (num_blocks, block_size, head_size) + + @classmethod + def get_supported_dtypes(cls) -> list[torch.dtype]: + return [torch.float16, torch.bfloat16] + + @classmethod + def get_supported_head_sizes(cls) -> list[int]: + return [576] + + @classmethod + def validate_head_size(cls, head_size: int) -> None: + supported_head_sizes = cls.get_supported_head_sizes() + if head_size not in supported_head_sizes: + attn_type = cls.__name__.removesuffix("Backend") + raise ValueError( + f"Head size {head_size} is not supported by {attn_type}. " + f"Supported head sizes are: {supported_head_sizes}. " + "Set VLLM_ATTENTION_BACKEND=FLEX_ATTENTION to use " + "FlexAttention backend which supports all head sizes.") + + +@dataclass +class MLACommonPrefillMetadata: + """ Prefill Specific Metadata """ + + @dataclass + class ChunkedContextMetadata: + # New for MLA (compared to FlashAttention) + # For handling chunked prefill + cu_seq_lens: torch.Tensor + starts: torch.Tensor + seq_tot: list[int] + max_seq_lens: list[int] + seq_lens: torch.Tensor + workspace: torch.Tensor + + block_table: torch.Tensor + query_start_loc: torch.Tensor + max_query_len: int + chunked_context: Optional[ChunkedContextMetadata] = None + + +@dataclass +class FlashInferPrefillMetadata(MLACommonPrefillMetadata): + prefill_main: Optional['BatchPrefillWithRaggedKVCacheWrapper'] = None + prefill_chunks: list['BatchPrefillWithRaggedKVCacheWrapper'] = field( + default_factory=list) + + +@dataclass +class CudnnPrefillMetadata(MLACommonPrefillMetadata): + + class ChunkedContextMetadata( + MLACommonPrefillMetadata.ChunkedContextMetadata): + seq_lens: torch.Tensor + + query_seq_lens: Optional[torch.Tensor] = None + cudnn_workspace: Optional[torch.Tensor] = None + + +@dataclass +class MLACommonDecodeMetadata: + block_table: torch.Tensor + seq_lens: torch.Tensor + + +D = TypeVar("D", bound=MLACommonDecodeMetadata) + + +@dataclass +class MLACommonMetadata(Generic[D]): + """Metadata for MLACommon. + + NOTE: Please read the comment at the top of the file before trying to + understand this class + """ + # NOTE(sang): Definition of context_len, query_len, and seq_len. + # |---------- N-1 iteration --------| + # |---------------- N iteration ---------------------| + # |- tokenA -|......................|-- newTokens ---| + # |---------- context_len ----------| + # |-------------------- seq_len ---------------------| + # |-- query_len ---| + + num_reqs: int + max_query_len: int + + num_actual_tokens: int # Number of tokens excluding padding. + query_start_loc: torch.Tensor + slot_mapping: torch.Tensor + + # New for MLA (compared to FlashAttention) + # For handling prefill decode split + num_decodes: int + num_decode_tokens: int + num_prefills: int + + # The dimension of the attention heads + head_dim: Optional[int] = None + + decode: Optional[D] = None + prefill: Optional[Union[MLACommonPrefillMetadata, + FlashInferPrefillMetadata, + CudnnPrefillMetadata]] = None + + def __post_init__(self): + if self.head_dim is not None: + MLACommonBackend.validate_head_size(self.head_dim) + + +M = TypeVar("M", bound=MLACommonMetadata) + + +def use_flashinfer_prefill() -> bool: + # For blackwell default to flashinfer prefill if its available since + # it is faster than FA2. + return (flashinfer_available and not envs.VLLM_USE_CUDNN_PREFILL + and current_platform.is_device_capability(100)) + + +def use_cudnn_prefill() -> bool: + return (flashinfer_available and envs.VLLM_USE_CUDNN_PREFILL + and current_platform.is_device_capability(100) + and has_nvidia_artifactory()) + + +# Currently 394MB, this can be tuned based on GEMM sizes used. +# Chosen to be the same as sglang: +# https://github.com/sgl-project/sglang/blob/766392c6bda2558b61ce6d1c1bfd8081a549e1f1/python/sglang/global_config.py#L37 +FLASHINFER_WORKSPACE_BUFFER_SIZE = 394 * 1024 * 1024 + + +class MLACommonMetadataBuilder(AttentionMetadataBuilder[M]): + """ + NOTE: Please read the comment at the top of the file before trying to + understand this class + """ + reorder_batch_threshold: ClassVar[int] = 1 + + def __init__(self, + kv_cache_spec: AttentionSpec, + layer_names: list[str], + vllm_config: VllmConfig, + device: torch.device, + metadata_cls: Optional[type[M]] = None): + self.metadata_cls = metadata_cls \ + if metadata_cls is not None else MLACommonMetadata + self.kv_cache_spec = kv_cache_spec + self.device = device + scheduler_config = vllm_config.scheduler_config + self.model_config = vllm_config.model_config + cache_config = vllm_config.cache_config + parallel_config = vllm_config.parallel_config + self.chunked_prefill_enabled = scheduler_config.chunked_prefill_enabled + self.num_heads = self.model_config.get_num_attention_heads( + parallel_config) + self.mla_dims = get_mla_dims(self.model_config) + self.aot_schedule = current_platform.is_cuda() + + # Dont try to access the runner on AMD + if self.aot_schedule: + self.page_size = self.kv_cache_spec.block_size + + if self.chunked_prefill_enabled: + self.chunked_prefill_workspace_size = min( + # Max sure there is enough for 8 full length request or at least + # 4 pages of cache per request + max( + 8 * self.model_config.max_model_len, 4 * + scheduler_config.max_num_seqs * cache_config.block_size), + # For long-context models try not to over-allocate limiting + # kv-cache space, limiting it to 64k tokens, + # which would result in the workspace being: + # 2*(576)*(64*1024) = 144mb + # (assuming 576 MLA head dim, and fp16) + # which would result in up-projected context being + # 2*(192*128)*(64*1024) = 3gb + # (assuming 192 QK head dim, 128 heads, and fp16) + 128 * 1024) + assert self.chunked_prefill_workspace_size >= \ + scheduler_config.max_num_seqs * cache_config.block_size + self.chunked_prefill_workspace = torch.empty( + (self.chunked_prefill_workspace_size, + self.model_config.get_head_size()), + dtype=self.model_config.dtype, + device=device, + ) + + self._use_cudnn_prefill = use_cudnn_prefill() + self._use_fi_prefill = use_flashinfer_prefill() + self.prefill_metadata_cls = ( + FlashInferPrefillMetadata + if self._use_fi_prefill else CudnnPrefillMetadata + if self._use_cudnn_prefill else MLACommonPrefillMetadata) + + if self._use_fi_prefill: + self._workspace_buffer = torch.empty( + FLASHINFER_WORKSPACE_BUFFER_SIZE, + dtype=torch.uint8, + device=device) + + self._fi_prefill_main: Optional[ + BatchPrefillWithRaggedKVCacheWrapper] = None + self._fi_prefill_chunks: list[ + BatchPrefillWithRaggedKVCacheWrapper] = [] + + self._global_hyperparameters = infer_global_hyperparameters( + get_per_layer_parameters(vllm_config, layer_names, + MLACommonImpl)) + + if self._use_cudnn_prefill: + self.cudnn_workspace = torch.empty( + CUDNN_WORKSPACE_SIZE * scheduler_config.max_num_seqs, + dtype=torch.int8, + device=device, + ) + + def _build_fi_prefill_wrappers(self, prefill: FlashInferPrefillMetadata): + qo_indptr = prefill.query_start_loc + + has_context = False + if prefill.chunked_context is not None: + chunked_context = prefill.chunked_context + has_context = True + + if self._fi_prefill_main is None: + self._fi_prefill_main = BatchPrefillWithRaggedKVCacheWrapper( + self._workspace_buffer, "NHD", backend="cutlass") + + if has_context: + num_chunks = chunked_context.cu_seq_lens.shape[0] + # Allocate more prefill chunk wrappers if needed + if len(self._fi_prefill_chunks) < num_chunks: + for _ in range(len(self._fi_prefill_chunks), num_chunks): + self._fi_prefill_chunks.append( + BatchPrefillWithRaggedKVCacheWrapper( + self._workspace_buffer, "NHD", backend="cutlass")) + assert num_chunks <= len(self._fi_prefill_chunks) + + # In MLA, the non-latent num_qo_heads == num_kv_heads + num_qo_heads = self.num_heads + num_kv_heads = num_qo_heads + + # Sanity: Verify that num_kv_heads == 1 since it is latent space + assert self.kv_cache_spec.num_kv_heads == 1 + + # Get non-latent head_dim_qk and head_dim_vo + head_dim_qk = (self.mla_dims.qk_nope_head_dim + + self.mla_dims.qk_rope_head_dim) + head_dim_vo = self.mla_dims.v_head_dim + + # For main run, qo_indptr == kv_indptr + kv_indptr = qo_indptr.clone() + + # Prepare main prefill + self._fi_prefill_main.plan( + qo_indptr=qo_indptr, + kv_indptr=kv_indptr, + num_qo_heads=num_qo_heads, + num_kv_heads=num_kv_heads, + head_dim_qk=head_dim_qk, + head_dim_vo=head_dim_vo, + causal=True, # This is main run + sm_scale=self._global_hyperparameters.sm_scale, + window_left=self._global_hyperparameters.window_left, + logits_soft_cap=self._global_hyperparameters.logits_soft_cap, + q_data_type=self.model_config.dtype, + kv_data_type=self.kv_cache_spec.dtype, + ) + + # Prepare context prefills + if has_context: + for i in range(num_chunks): + kv_indptr_chunk = chunked_context.cu_seq_lens[i] + + self._fi_prefill_chunks[i].plan( + qo_indptr=qo_indptr, + kv_indptr=kv_indptr_chunk, + num_qo_heads=num_qo_heads, + num_kv_heads=num_kv_heads, + head_dim_qk=head_dim_qk, + head_dim_vo=head_dim_vo, + causal=False, # This is context run + sm_scale=self._global_hyperparameters.sm_scale, + window_left=self._global_hyperparameters.window_left, + logits_soft_cap=self._global_hyperparameters. + logits_soft_cap, + q_data_type=self.model_config.dtype, + kv_data_type=self.kv_cache_spec.dtype, + ) + + prefill.prefill_main = self._fi_prefill_main + prefill.prefill_chunks = self._fi_prefill_chunks + + def _build_decode(self, block_table_tensor: torch.Tensor, + seq_lens: torch.Tensor): + return MLACommonDecodeMetadata( + block_table=block_table_tensor, + seq_lens=seq_lens, + ) + + def build_for_cudagraph_capture( + self, common_attn_metadata: CommonAttentionMetadata) -> M: + """ + This method builds the metadata for full cudagraph capture. + Currently, only decode is supported for full cudagraphs with MLA. + """ + m = common_attn_metadata + assert m.num_reqs == m.num_actual_tokens, \ + "MLA only supports decode-only full CUDAGraph capture. " \ + "Make sure all cudagraph capture sizes <= max_num_seq." + + assert m.max_query_len == 1 # decode-only + + return self.build(0, m) + + def build(self, + common_prefix_len: int, + common_attn_metadata: CommonAttentionMetadata, + fast_build: bool = False) -> M: + num_reqs = common_attn_metadata.num_reqs + num_tokens = common_attn_metadata.num_actual_tokens + max_query_len = common_attn_metadata.max_query_len + + # Note(simon): be careful about the CPU <> GPU memory movement in this + # function. We should avoid GPU -> CPU sync as much as possible because + # it blocks on all previous kernels. + device = self.device + block_table_tensor = common_attn_metadata.block_table_tensor + slot_mapping = common_attn_metadata.slot_mapping + + query_start_loc = common_attn_metadata.query_start_loc + query_start_loc_cpu = common_attn_metadata.query_start_loc_cpu + seq_lens = common_attn_metadata.seq_lens + + query_seq_lens_cpu = query_start_loc_cpu[1:] - query_start_loc_cpu[:-1] + + num_computed_tokens_cpu = (common_attn_metadata.seq_lens_cpu - + query_seq_lens_cpu) + + num_decodes, num_prefills, num_decode_tokens, num_prefill_tokens = \ + split_decodes_and_prefills(common_attn_metadata) + + assert num_decodes + num_prefills == num_reqs + assert num_decode_tokens + num_prefill_tokens == num_tokens + + prefill_metadata = None + if num_prefills > 0: + reqs_start = num_decodes # prefill_start + + context_lens_cpu = num_computed_tokens_cpu[reqs_start:num_reqs] + max_context_len_cpu = context_lens_cpu.max().item() + num_prefills_with_context_cpu = (context_lens_cpu > 0).sum().item() + prefill_query_start_loc = query_start_loc[ + reqs_start:] - query_start_loc[reqs_start] + + chunked_context_metadata = None + if self.chunked_prefill_enabled and num_prefills > 0 \ + and max_context_len_cpu > 0: + # NOTE: it is recommend you read the `Chunked Prefill` section + # in the comment at the top of the file before trying to + # understand the following code + + # currently we allocate an equal amount of workspace for each + # prefill in the batch, we could probably use a more advanced + # algorithm here and allocate more workspace to prefills with + # longer context lengths + max_context_chunk = (self.chunked_prefill_workspace_size // + num_prefills_with_context_cpu) + + if self.aot_schedule: + # align max_context_chunk to page_size by rounding down, + # currently the `gather_cache` kernel cannot handle + # `context_chunk_starts` that are not aligned to page_size + max_context_chunk = round_down(max_context_chunk, + self.page_size) + + assert max_context_chunk > 0 + num_chunks = cdiv(max_context_len_cpu, max_context_chunk) + + # if `max_context_chunk = 256`, `num_chunks = 3`, and + # `num_prefills_with_context = 4`, create a tensor that looks + # like + # [[0, 0, 0, 0], [256, 256, 256, 256], [512, 512, 512, 512]] + # Note(simon): this is done in CPU because of downstream's + # of `to_list`. + chunk_starts = \ + torch.arange(num_chunks, dtype=torch.int32) \ + .unsqueeze(1).expand(-1, num_prefills) \ + * max_context_chunk + chunk_ends = torch.min(context_lens_cpu.unsqueeze(0), + chunk_starts + max_context_chunk) + chunk_seq_lens = (chunk_ends - chunk_starts).clamp(min=0) + + cu_seq_lens_cpu = torch.zeros(num_chunks, + num_prefills + 1, + dtype=torch.int32, + pin_memory=True) + torch.cumsum(chunk_seq_lens, + dim=1, + out=cu_seq_lens_cpu[:, 1:], + dtype=torch.int32) + + chunked_context_metadata_cls = \ + CudnnPrefillMetadata.ChunkedContextMetadata \ + if self._use_cudnn_prefill else \ + MLACommonPrefillMetadata.ChunkedContextMetadata + + chunked_context_metadata = \ + chunked_context_metadata_cls( + cu_seq_lens=cu_seq_lens_cpu.to(device, non_blocking=True), + starts=chunk_starts.to(device, non_blocking=True), + seq_tot=chunk_seq_lens.sum(dim=1).tolist(), + max_seq_lens=chunk_seq_lens.max(dim=1).values.tolist(), + seq_lens=chunk_seq_lens, + workspace=self.chunked_prefill_workspace, + ) + + if self._use_cudnn_prefill: + chunked_context_metadata.seq_lens = chunk_seq_lens + + assert max(chunked_context_metadata.max_seq_lens) <= \ + self.chunked_prefill_workspace_size + + prefill_metadata = self.prefill_metadata_cls( + block_table=block_table_tensor[reqs_start:, ...], + query_start_loc=prefill_query_start_loc, + max_query_len=max_query_len, + chunked_context=chunked_context_metadata, + ) + + if self._use_cudnn_prefill: + assert isinstance(prefill_metadata, CudnnPrefillMetadata) + prefill_metadata.query_seq_lens = prefill_query_start_loc[1:] \ + - prefill_query_start_loc[:-1] + prefill_metadata.cudnn_workspace = self.cudnn_workspace + + decode_metadata = None + if num_decodes > 0: + decode_metadata = self._build_decode( + block_table_tensor=block_table_tensor[:num_decodes, ...], + seq_lens=seq_lens[:num_decodes], + ) + + attn_metadata = self.metadata_cls( + num_reqs=common_attn_metadata.num_reqs, + max_query_len=common_attn_metadata.max_query_len, + num_actual_tokens=num_tokens, + query_start_loc=query_start_loc, + slot_mapping=slot_mapping, + head_dim=self.model_config.get_head_size(), + # MLACommonMetadata Chunk prefill specific + num_decodes=num_decodes, + num_decode_tokens=num_decode_tokens, + num_prefills=num_prefills, + prefill=prefill_metadata, + decode=decode_metadata, + ) + + if self._use_fi_prefill and num_prefills > 0: + assert isinstance(attn_metadata.prefill, FlashInferPrefillMetadata) + self._build_fi_prefill_wrappers(attn_metadata.prefill) + + return attn_metadata + + +class MLACommonImpl(MLAAttentionImpl[M], Generic[M]): + """ + NOTE: Please read the comment at the top of the file before trying to + understand this class + """ + + def __init__( + self, + num_heads: int, + head_size: int, + scale: float, + num_kv_heads: int, + alibi_slopes: Optional[list[float]], + sliding_window: Optional[int], + kv_cache_dtype: str, + logits_soft_cap: Optional[float], + attn_type: str, + kv_sharing_target_layer_name: Optional[str], + # MLA Specific Arguments + q_lora_rank: Optional[int], + kv_lora_rank: int, + qk_nope_head_dim: int, + qk_rope_head_dim: int, + qk_head_dim: int, + v_head_dim: int, + kv_b_proj: ColumnParallelLinear, + ) -> None: + if kv_sharing_target_layer_name is not None: + raise NotImplementedError("KV sharing is not supported for MLA") + + self.num_heads = num_heads + self.head_size = head_size + self.scale = float(scale) + self.num_kv_heads = num_kv_heads + self.kv_cache_dtype = kv_cache_dtype + + self.q_lora_rank = q_lora_rank + self.kv_lora_rank = kv_lora_rank + self.qk_nope_head_dim = qk_nope_head_dim + self.qk_rope_head_dim = qk_rope_head_dim + self.qk_head_dim = qk_head_dim + self.v_head_dim = v_head_dim + self.kv_b_proj = kv_b_proj + + if use_flashinfer_prefill(): + logger.debug_once("Using FlashInfer prefill for MLA") + self._run_prefill_context_chunk = self._run_prefill_context_chunk_fi + self._run_prefill_new_tokens = self._run_prefill_new_tokens_fi + self._pad_v = False + elif use_cudnn_prefill(): + logger.debug_once("Using CUDNN prefill for MLA") + self._run_prefill_context_chunk = \ + self._run_prefill_context_chunk_cudnn + self._run_prefill_new_tokens = self._run_prefill_new_tokens_cudnn + self._pad_v = False + else: # Use FlashAttention + logger.debug_once("Using FlashAttention prefill for MLA") + self._run_prefill_context_chunk = self._run_prefill_context_chunk_fa + self._run_prefill_new_tokens = self._run_prefill_new_tokens_fa + + # Handle the differences between the flash_attn_varlen from + # flash_attn and the one from vllm_flash_attn. The former is used on + # RoCM and the latter has an additional parameter to control + # FA2 vs FA3 + self.flash_attn_varlen_func = flash_attn_varlen_func + self.vllm_flash_attn_version = get_flash_attn_version() + if self.vllm_flash_attn_version is not None: + self.flash_attn_varlen_func = \ + functools.partial(flash_attn_varlen_func, + fa_version=self.vllm_flash_attn_version) + + # For MLA the v head dim is smaller than qk head dim so we pad out + # v with 0s to match the qk head dim for attention backends that do + # not support different headdims + # We don't need to pad V if we are on a hopper system with FA3 + self._pad_v = self.vllm_flash_attn_version is None or not ( + self.vllm_flash_attn_version == 3 + and current_platform.get_device_capability()[0] == 9) + + def _flash_attn_varlen_diff_headdims(self, + q, + k, + v, + return_softmax_lse=False, + softmax_scale=None, + **kwargs): + maybe_padded_v = v + if self._pad_v: + maybe_padded_v = torch.nn.functional.pad( + v, [0, q.shape[-1] - v.shape[-1]], value=0) + + if is_vllm_fa: + kwargs["return_softmax_lse"] = return_softmax_lse + else: + # ROCm leverages the upstream flash_attn, which takes a parameter + # called "return_attn_probs" instead of return_softmax_lse + kwargs["return_attn_probs"] = return_softmax_lse + + attn_out = self.flash_attn_varlen_func( + q=q, + k=k, + v=maybe_padded_v, + softmax_scale=softmax_scale, + **kwargs, + ) + + # Unpack the output if there is multiple results + lse = None + if isinstance(attn_out, tuple): + attn_out, lse = attn_out[0], attn_out[1] + + # Remain consistent with old `flash_attn_varlen_func` where there + # is only one output tensor if `return_softmax_lse` is False. + if return_softmax_lse: + return attn_out, lse + return attn_out + + def _run_prefill_new_tokens_fa(self, prefill: MLACommonPrefillMetadata, q, + k, v, return_softmax_lse): + return self._flash_attn_varlen_diff_headdims( + q=q, + k=k, + v=v, + cu_seqlens_q=prefill.query_start_loc, + cu_seqlens_k=prefill.query_start_loc, + max_seqlen_q=prefill.max_query_len, + max_seqlen_k=prefill.max_query_len, + softmax_scale=self.scale, + causal=True, + return_softmax_lse=return_softmax_lse, + ) + + def _run_prefill_new_tokens_fi(self, prefill: MLACommonPrefillMetadata, q, + k, v, return_softmax_lse): + assert isinstance(prefill, FlashInferPrefillMetadata) + assert prefill.prefill_main is not None + return prefill.prefill_main.run( + q=q, + k=k, + v=v, + return_lse=return_softmax_lse, + ) + + def _run_prefill_new_tokens_cudnn(self, prefill: MLACommonPrefillMetadata, + q, k, v, return_softmax_lse): + assert isinstance(prefill, CudnnPrefillMetadata) + assert prefill.query_seq_lens is not None + output, lse = cudnn_batch_prefill_with_kv_cache( + q=q, + k_cache=k, + v_cache=v, + scale=self.scale, + workspace_buffer=prefill.cudnn_workspace, + max_token_per_sequence=prefill.max_query_len, + max_sequence_kv=prefill.max_query_len, + actual_seq_lens_q=prefill.query_seq_lens.view(-1, 1, 1, 1), + actual_seq_lens_kv=prefill.query_seq_lens.view(-1, 1, 1, 1), + causal=True, + return_lse=True, # do not support False for now + is_cuda_graph_compatible= + True, #Indicates actual_seq_lens are on GPU or CPU. + ) + if return_softmax_lse: + return output, lse + return output + + def _run_prefill_context_chunk_fa(self, prefill: MLACommonPrefillMetadata, + chunk_idx: int, q, k, v): + assert prefill.chunked_context is not None + return self._flash_attn_varlen_diff_headdims( + q=q, + k=k, + v=v, + cu_seqlens_q=prefill.query_start_loc, + cu_seqlens_k=prefill.chunked_context.cu_seq_lens[chunk_idx], + max_seqlen_q=prefill.max_query_len, + max_seqlen_k=prefill.chunked_context.max_seq_lens[chunk_idx], + softmax_scale=self.scale, + causal=False, # Context is unmasked + return_softmax_lse=True, + ) + + def _run_prefill_context_chunk_fi(self, prefill: MLACommonPrefillMetadata, + chunk_idx: int, q, k, v): + assert isinstance(prefill, FlashInferPrefillMetadata) + return prefill.prefill_chunks[chunk_idx].run( + q=q, + k=k, + v=v, + return_lse=True, + ) + + def _run_prefill_context_chunk_cudnn(self, + prefill: MLACommonPrefillMetadata, + chunk_idx: int, q, k, v): + assert isinstance(prefill, CudnnPrefillMetadata) + assert prefill.chunked_context is not None + assert prefill.chunked_context.seq_lens[chunk_idx] is not None + assert prefill.query_seq_lens is not None + return cudnn_batch_prefill_with_kv_cache( + q=q, + k_cache=k, + v_cache=v, + scale=self.scale, + workspace_buffer=prefill.cudnn_workspace, + max_token_per_sequence=prefill.max_query_len, + max_sequence_kv=prefill.chunked_context.max_seq_lens[chunk_idx], + actual_seq_lens_q=prefill.query_seq_lens.view(-1, 1, 1, 1), + actual_seq_lens_kv=prefill.chunked_context.seq_lens[chunk_idx]. + view(-1, 1, 1, 1), + causal=False, + return_lse=True, + is_cuda_graph_compatible= + True, #Indicates actual_seq_lens are on GPU or CPU. + ) + + def _v_up_proj(self, x): + # Convert from (B, N, L) to (N, B, L) + x = x.view(-1, self.num_heads, self.kv_lora_rank).transpose(0, 1) + # Multiply (N, B, L) x (N, L, V) -> (N, B, V) + x = torch.bmm(x, self.W_UV) + # Convert from (N, B, V) to (B, N * V) + return x.transpose(0, 1).reshape(-1, self.num_heads * self.v_head_dim) + + def process_weights_after_loading(self, act_dtype: torch.dtype): + + def get_layer_weight(layer): + WEIGHT_NAMES = ("weight", "qweight", "weight_packed") + for attr in WEIGHT_NAMES: + if hasattr(layer, attr): + return getattr(layer, attr) + raise AttributeError( + f"Layer '{layer}' has no recognized weight attribute:" + f" {WEIGHT_NAMES}.") + + def get_and_maybe_dequant_weights(layer: LinearBase): + if not isinstance(layer.quant_method, UnquantizedLinearMethod): + # NOTE: This should only be used offline, since it's O(N^3) + eye = torch.eye(layer.input_size_per_partition, + dtype=act_dtype, + device=get_layer_weight(layer).device) + dequant_weights = layer.quant_method.apply(layer, + eye, + bias=None) + del eye + # standardize to (output, input) + return dequant_weights.T + return layer.weight + + # we currently do not have quantized bmm's which are needed for + # `W_UV` and `W_UK_T`, we we just store fp16/bf16 copies and perform + # the bmm's in 16-bit, the extra memory overhead of this is fairly low + kv_b_proj_weight = get_and_maybe_dequant_weights(self.kv_b_proj).T + assert kv_b_proj_weight.shape == ( + self.kv_lora_rank, + self.num_heads * (self.qk_nope_head_dim + self.v_head_dim)), ( + f"{kv_b_proj_weight.shape=}, " + f"{self.kv_lora_rank=}, " + f"{self.num_heads=}, " + f"{self.qk_nope_head_dim=}, " + f"{self.v_head_dim=}") + kv_b_proj_weight = kv_b_proj_weight.view( + self.kv_lora_rank, + self.num_heads, + self.qk_nope_head_dim + self.v_head_dim, + ) + + W_UK, W_UV = kv_b_proj_weight.split( + [self.qk_nope_head_dim, self.v_head_dim], dim=-1) + + # Convert from (L, N, V) to (N, L, V) + self.W_UV = W_UV.transpose(0, 1) + # Convert from (L, N, P) to (N, P, L) + self.W_UK_T = W_UK.permute(1, 2, 0) + + def _compute_prefill_context( + self, + q: torch.Tensor, + kv_c_and_k_pe_cache: torch.Tensor, + attn_metadata: MLACommonMetadata, + ): + assert attn_metadata.prefill is not None + prefill_metadata = attn_metadata.prefill + assert prefill_metadata.chunked_context is not None + + output = None + iters = len(prefill_metadata.chunked_context.seq_tot) + workspace = prefill_metadata.chunked_context.workspace + + for i in range(iters): + toks = prefill_metadata.chunked_context.seq_tot[i] + + ops.gather_cache( + src_cache=kv_c_and_k_pe_cache, + dst=workspace, + block_table=prefill_metadata.block_table, + cu_seq_lens=prefill_metadata.chunked_context.cu_seq_lens[i], + batch_size=attn_metadata.num_prefills, + seq_starts=prefill_metadata.chunked_context.starts[i], + ) + + kv_c_normed = workspace[:toks]\ + [..., :self.kv_lora_rank] + k_pe = workspace[:toks]\ + [..., self.kv_lora_rank:].unsqueeze(1) + + kv_nope = self.kv_b_proj(kv_c_normed)[0].view( \ + -1, self.num_heads, self.qk_nope_head_dim + self.v_head_dim) + k_nope, v = kv_nope\ + .split([self.qk_nope_head_dim, self.v_head_dim], dim=-1) + + k = torch.cat((k_nope, k_pe.expand((*k_nope.shape[:-1], -1))), + dim=-1) + + attn_output, attn_softmax_lse = self._run_prefill_context_chunk( + prefill=prefill_metadata, + chunk_idx=i, + q=q, + k=k, + v=v, + ) + + if output is None: + output = attn_output + output_lse = attn_softmax_lse + else: + output_tmp = torch.empty_like(output) + output_lse_tmp = torch.empty_like(output_lse) + merge_attn_states( + output=output_tmp, + output_lse=output_lse_tmp, + prefix_output=output, + prefix_lse=output_lse, + suffix_output=attn_output, + suffix_lse=attn_softmax_lse, + ) + output = output_tmp + output_lse = output_lse_tmp + + return output, output_lse + + def _forward_prefill( + self, + q: torch.Tensor, + kv_c_normed: torch.Tensor, + k_pe: torch.Tensor, + kv_c_and_k_pe_cache: torch.Tensor, + attn_metadata: MLACommonMetadata, + ) -> torch.Tensor: + assert attn_metadata.prefill is not None + + has_context = attn_metadata.prefill.chunked_context is not None + kv_nope = self.kv_b_proj(kv_c_normed)[0].view(\ + -1, self.num_heads, self.qk_nope_head_dim + self.v_head_dim) + k_nope, v = kv_nope\ + .split([self.qk_nope_head_dim, self.v_head_dim], dim=-1) + + k = torch.cat((k_nope, k_pe.expand((*k_nope.shape[:-1], -1))), dim=-1) + + output = self._run_prefill_new_tokens( + prefill=attn_metadata.prefill, + q=q, + k=k, + v=v, + return_softmax_lse=has_context, + ) + + if has_context: + suffix_output, suffix_lse = output + context_output, context_lse = self._compute_prefill_context( \ + q, kv_c_and_k_pe_cache, attn_metadata) + + output = torch.empty_like(suffix_output) + merge_attn_states( + output=output, + prefix_output=context_output, + prefix_lse=context_lse, + suffix_output=suffix_output, + suffix_lse=suffix_lse, + ) + + # unpad if necessary + if self._pad_v: + output = output[..., :v.shape[-1]] + + return output.flatten(start_dim=-2) + + @abstractmethod + def _forward_decode( + self, + ql_nope: torch.Tensor, + q_pe: torch.Tensor, + kv_c_and_k_pe_cache: torch.Tensor, + attn_metadata: M, + ) -> torch.Tensor: + raise NotImplementedError + + def forward( + self, + layer: AttentionLayer, + q: torch.Tensor, + k_c_normed: torch.Tensor, # key in unified attn + k_pe: torch.Tensor, # value in unified attn + kv_cache: torch.Tensor, + attn_metadata: M, + output: Optional[torch.Tensor] = None, + output_scale: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + assert output is not None, "Output tensor must be provided." + + if output_scale is not None: + raise NotImplementedError( + "fused output quantization is not yet supported" + " for MLACommonImpl") + + if attn_metadata is None: + # The zero fill is required when used with DP + EP + # to ensure all ranks within a DP group compute the + # same expert outputs. + return output.fill_(0) + + num_actual_toks = attn_metadata.num_actual_tokens + + # Inputs and outputs may be padded for CUDA graphs + output_padded = output + output = output[:num_actual_toks, ...] + q = q[:num_actual_toks, ...] + k_c_normed = k_c_normed[:num_actual_toks, ...] + k_pe = k_pe[:num_actual_toks, ...] + + assert attn_metadata.num_decodes is not None and \ + attn_metadata.num_prefills is not None and \ + attn_metadata.num_decode_tokens is not None + + has_decode = attn_metadata.num_decodes > 0 + has_prefill = attn_metadata.num_prefills > 0 + num_decode_tokens = attn_metadata.num_decode_tokens + + decode_q = q[:num_decode_tokens] + + prefill_q = q[num_decode_tokens:] + prefill_k_pe = k_pe[num_decode_tokens:] + prefill_k_c_normed = k_c_normed[num_decode_tokens:] + + # write the latent and rope to kv cache + if kv_cache.numel() > 0: + ops.concat_and_cache_mla( + k_c_normed, + k_pe.squeeze(1), + kv_cache, + attn_metadata.slot_mapping.flatten(), + kv_cache_dtype=self.kv_cache_dtype, + scale=layer._k_scale, + ) + + if has_prefill: + output[num_decode_tokens:] = self._forward_prefill( + prefill_q, prefill_k_c_normed, prefill_k_pe, kv_cache, + attn_metadata) + + if has_decode: + assert attn_metadata.decode is not None + decode_q_nope, decode_q_pe = decode_q.split( + [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1) + # Convert from (B, N, P) to (N, B, P) + decode_q_nope = decode_q_nope.transpose(0, 1) + # Multiply (N, B, P) x (N, P, L) -> (N, B, L) + decode_ql_nope = torch.bmm(decode_q_nope, self.W_UK_T) + # Convert from (N, B, L) to (B, N, L) + decode_ql_nope = decode_ql_nope.transpose(0, 1) + + output[:num_decode_tokens] = self._forward_decode( + decode_ql_nope, decode_q_pe, kv_cache, attn_metadata) + + return output_padded diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/core/sched/interface.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/core/sched/interface.py new file mode 100644 index 0000000000000000000000000000000000000000..dd5052a3480b79de11b9f82263ca2f045daa9b3f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/core/sched/interface.py @@ -0,0 +1,150 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +from abc import ABC, abstractmethod +from collections.abc import Iterable +from typing import TYPE_CHECKING, Optional, Union + +if TYPE_CHECKING: + from vllm.distributed.kv_transfer.kv_connector.v1 import KVConnectorBase_V1 + from vllm.v1.core.sched.output import SchedulerOutput + from vllm.v1.engine import EngineCoreOutputs + from vllm.v1.metrics.stats import SchedulerStats + from vllm.v1.outputs import ModelRunnerOutput + from vllm.v1.request import Request, RequestStatus + + +class SchedulerInterface(ABC): + + @abstractmethod + def schedule(self) -> "SchedulerOutput": + """Schedule the requests to process in this scheduling step. + + The scheduling decision is made at the iteration level. Each scheduling + step corresponds to a single forward pass of the model. Therefore, this + method is called repeatedly by a busy loop in the engine. + + Essentially, the scheduler produces a dictionary of {req_id: num_tokens} + that specifies how many tokens to process for each request in this + scheduling step. For example, num_tokens can be as large as the number + of prompt tokens for new requests, or it can be 1 for the requests that + are auto-regressively generating new tokens one by one. Otherwise, it + can be somewhere in between in case of chunked prefills, prefix caching, + speculative decoding, etc. + + Additionally, the scheduler also returns useful data about each request + or the batch as a whole. The model runner will use this information in + preparing inputs to the model. + + Returns: + A SchedulerOutput object containing information about the scheduled + requests. + """ + raise NotImplementedError + + @abstractmethod + def update_from_output( + self, + scheduler_output: "SchedulerOutput", + model_runner_output: "ModelRunnerOutput", + ) -> dict[int, "EngineCoreOutputs"]: + """Update the scheduler state based on the model runner output. + + This method is called after the model runner has processed the scheduled + requests. The model runner output includes generated token ids, draft + token ids for next step, etc. The scheduler uses this information to + update its states, checks the finished requests, and returns the output + for each request. + + Returns: + A dict of client index to EngineCoreOutputs object containing the + outputs for each request originating from that client. + """ + raise NotImplementedError + + @abstractmethod + def add_request(self, request: "Request") -> None: + """Add a new request to the scheduler's internal queue. + + Args: + request: The new request being added. + """ + raise NotImplementedError + + @abstractmethod + def finish_requests( + self, + request_ids: Union[str, Iterable[str]], + finished_status: "RequestStatus", + ) -> None: + """Finish the requests in the scheduler's internal queue. If the request + is not in the queue, this method will do nothing. + + This method is called in two cases: + 1. When the request is aborted by the client. + 2. When the frontend process detects a stop string of the request after + de-tokenizing its generated tokens. + + Args: + request_ids: A single or a list of request IDs. + finished_status: The finished status of the given requests. + """ + raise NotImplementedError + + @abstractmethod + def get_num_unfinished_requests(self) -> int: + """Number of unfinished requests in the scheduler's internal queue.""" + raise NotImplementedError + + def has_unfinished_requests(self) -> bool: + """Returns True if there are unfinished requests in the scheduler's + internal queue.""" + return self.get_num_unfinished_requests() > 0 + + @abstractmethod + def has_finished_requests(self) -> bool: + """Returns True if there are finished requests that need to be cleared. + NOTE: This is different from `not self.has_unfinished_requests()`. + + The scheduler maintains an internal list of the requests finished in the + previous step. This list is returned from the next call to schedule(), + to be sent to the model runner in the next step to clear cached states + for these finished requests. + + This method checks if this internal list of finished requests is + non-empty. This information is useful for DP attention. + """ + raise NotImplementedError + + def has_requests(self) -> bool: + """Returns True if there are unfinished requests, or finished requests + not yet returned in SchedulerOutputs.""" + return self.has_unfinished_requests() or self.has_finished_requests() + + @abstractmethod + def reset_prefix_cache(self) -> bool: + """Reset the prefix cache for KV cache. + + This is particularly required when the model weights are live-updated. + """ + raise NotImplementedError + + @abstractmethod + def get_request_counts(self) -> tuple[int, int]: + """Returns (num_running_reqs, num_waiting_reqs).""" + raise NotImplementedError + + @abstractmethod + def make_stats(self) -> Optional["SchedulerStats"]: + """Make a SchedulerStats object for logging. + + The SchedulerStats object is created for every scheduling step. + """ + raise NotImplementedError + + @abstractmethod + def shutdown(self) -> None: + """Shutdown the scheduler.""" + raise NotImplementedError + + def get_kv_connector(self) -> Optional["KVConnectorBase_V1"]: + return None diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/core/sched/output.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/core/sched/output.py new file mode 100644 index 0000000000000000000000000000000000000000..fac07f97195bd616b7302c264caf1d23caa8cb71 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/core/sched/output.py @@ -0,0 +1,157 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING, Optional + +if TYPE_CHECKING: + import numpy as np + import numpy.typing as npt + + from vllm.distributed.kv_transfer.kv_connector.v1.base import ( + KVConnectorMetadata) + from vllm.lora.request import LoRARequest + from vllm.multimodal.inputs import MultiModalKwargsItem, PlaceholderRange + from vllm.pooling_params import PoolingParams + from vllm.sampling_params import SamplingParams + from vllm.v1.request import Request + + +@dataclass +class NewRequestData: + + req_id: str + prompt_token_ids: list[int] + mm_kwargs: list[MultiModalKwargsItem] + mm_hashes: list[str] + mm_positions: list[PlaceholderRange] + sampling_params: Optional[SamplingParams] + pooling_params: Optional[PoolingParams] + block_ids: tuple[list[int], ...] + num_computed_tokens: int + lora_request: Optional[LoRARequest] + + @classmethod + def from_request( + cls, + request: Request, + block_ids: tuple[list[int], ...], + ) -> NewRequestData: + return cls( + req_id=request.request_id, + prompt_token_ids=request.prompt_token_ids, + mm_kwargs=request.mm_kwargs, + mm_hashes=request.mm_hashes, + mm_positions=request.mm_positions, + sampling_params=request.sampling_params, + pooling_params=request.pooling_params, + block_ids=block_ids, + num_computed_tokens=request.num_computed_tokens, + lora_request=request.lora_request, + ) + + def __repr__(self): + return (f"NewRequestData(" + f"req_id={self.req_id}," + f"prompt_token_ids={self.prompt_token_ids}," + f"mm_kwargs={self.mm_kwargs}," + f"mm_hashes={self.mm_hashes}," + f"mm_positions={self.mm_positions}," + f"sampling_params={self.sampling_params}," + f"block_ids={self.block_ids}," + f"num_computed_tokens={self.num_computed_tokens}," + f"lora_request={self.lora_request}" + ")") + + # Version of __repr__ with the prompt data obfuscated + def anon_repr(self): + return (f"NewRequestData(" + f"req_id={self.req_id}," + f"prompt_token_ids_len={len(self.prompt_token_ids)}," + f"mm_kwargs={self.mm_kwargs}," + f"mm_hashes={self.mm_hashes}," + f"mm_positions={self.mm_positions}," + f"sampling_params={self.sampling_params}," + f"block_ids={self.block_ids}," + f"num_computed_tokens={self.num_computed_tokens}," + f"lora_request={self.lora_request}" + ")") + + +@dataclass +class CachedRequestData: + + req_ids: list[str] + # If resumed_from_preemption is False, new_block_ids will be appended to + # the request's block IDs. If True, new_block_ids will be used as the + # request's block IDs instead of appending to the existing block IDs. + resumed_from_preemption: list[bool] + # NOTE(woosuk): new_token_ids is only used for pipeline parallelism. + # When PP is not used, new_token_ids will be empty. + new_token_ids: list[list[int]] + new_block_ids: list[tuple[list[int], ...]] + num_computed_tokens: list[int] + + @property + def num_reqs(self) -> int: + return len(self.req_ids) + + @classmethod + def make_empty(cls) -> CachedRequestData: + return cls( + req_ids=[], + resumed_from_preemption=[], + new_token_ids=[], + new_block_ids=[], + num_computed_tokens=[], + ) + + +@dataclass +class SchedulerOutput: + + # list of the requests that are scheduled for the first time. + # We cache the request's data in each worker process, so that we don't + # need to re-send it every scheduling step. + scheduled_new_reqs: list[NewRequestData] + # list of the requests that have been scheduled before. + # Since the request's data is already cached in the worker processes, + # we only send the diff to minimize the communication cost. + scheduled_cached_reqs: CachedRequestData + + # req_id -> num_scheduled_tokens + # Number of tokens scheduled for each request. + num_scheduled_tokens: dict[str, int] + # Total number of tokens scheduled for all requests. + # Equal to sum(num_scheduled_tokens.values()) + total_num_scheduled_tokens: int + # req_id -> spec_token_ids + # If a request does not have any spec decode tokens, it will not be + # included in the dictionary. + scheduled_spec_decode_tokens: dict[str, list[int]] + # req_id -> encoder input indices that need processing. + # E.g., if a request has [0, 1], it could mean the vision encoder needs + # to process that the request's 0-th and 1-th images in the current step. + scheduled_encoder_inputs: dict[str, list[int]] + # Number of common prefix blocks for all requests in each KV cache group. + # This can be used for cascade attention. + num_common_prefix_blocks: list[int] + + # Request IDs that are finished in between the previous and the current + # steps. This is used to notify the workers about the finished requests + # so that they can free the cached states for those requests. + finished_req_ids: set[str] + # list of (req_id, encoder_input_index) tuples. + # Used to free the encoder cache. + free_encoder_input_ids: list[tuple[str, int]] + + # Dict of request ids to their index within the batch + # for filling the next token bitmask + structured_output_request_ids: dict[str, int] + # the bitmask for the whole batch + grammar_bitmask: Optional[npt.NDArray[np.int32]] + + # KV Cache Connector metadata. + kv_connector_metadata: Optional[KVConnectorMetadata] = None diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/engine/__pycache__/async_llm.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/engine/__pycache__/async_llm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f89368e8ed9304729db762a398c52c6a923ba4de Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/engine/__pycache__/async_llm.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/engine/__pycache__/exceptions.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/engine/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1fb669424ab9592849245d647be77fd40eee9cbf Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/engine/__pycache__/exceptions.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/engine/__pycache__/logprobs.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/engine/__pycache__/logprobs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3217bcbc6333a2bdb2698d6e440029acdddbb1b3 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/engine/__pycache__/logprobs.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/engine/logprobs.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/engine/logprobs.py new file mode 100644 index 0000000000000000000000000000000000000000..3de7fa6889e5599640c8b580cc1becca03847adc --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/engine/logprobs.py @@ -0,0 +1,201 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +import itertools +from collections.abc import Iterable +from dataclasses import dataclass +from typing import Optional + +from vllm.logger import init_logger +from vllm.sequence import Logprob, PromptLogprobs, SampleLogprobs +from vllm.transformers_utils.detokenizer_utils import ( + AnyTokenizer, convert_ids_list_to_tokens) +from vllm.v1.engine import EngineCoreOutput, EngineCoreRequest +from vllm.v1.outputs import LogprobsLists, LogprobsTensors + +logger = init_logger(__name__) + +NONES = itertools.repeat(None) + + +@dataclass +class LogprobsProcessor: + + # Tokenizer for this request, + # None if detokenization is disabled. + tokenizer: Optional[AnyTokenizer] + + # Logprobs for this request + logprobs: Optional[SampleLogprobs] + prompt_logprobs: Optional[PromptLogprobs] + cumulative_logprob: Optional[float] + num_logprobs: Optional[int] + num_prompt_logprobs: Optional[int] + + @classmethod + def from_new_request( + cls, + tokenizer: Optional[AnyTokenizer], + request: EngineCoreRequest, + ) -> "LogprobsProcessor": + assert request.sampling_params is not None + num_logprobs = request.sampling_params.logprobs + num_prompt_logprobs = request.sampling_params.prompt_logprobs + return cls( + tokenizer=tokenizer, + cumulative_logprob=(None if num_logprobs is None else 0.), + logprobs=(None if num_logprobs is None else []), + # NOTE: logprob of first prompt token is None. + prompt_logprobs=(None if num_prompt_logprobs is None else [None]), + num_prompt_logprobs=num_prompt_logprobs, + num_logprobs=num_logprobs, + ) + + def _update_sample_logprobs(self, logprobs_lists: LogprobsLists) -> None: + """Update with sample logprobs from EngineCore. + + Outer lists are only of len > 1 if EngineCore made + >1 tokens in prior step (e.g. in spec decoding). + + Args: + logprobs_lists: the lists of logprob tokens, logprobs, and ranks. + + """ + + assert self.num_logprobs is not None + assert self.logprobs is not None + assert self.cumulative_logprob is not None + + token_ids_lst, logprobs_lst, ranks_lst = logprobs_lists + + for rank, logprobs, token_ids in zip(ranks_lst, logprobs_lst, + token_ids_lst): + + # Detokenize (non-incrementally). + decoded_tokens = NONES if self.tokenizer is None else ( + convert_ids_list_to_tokens(self.tokenizer, token_ids)) + + # Sampler puts the sampled logprob in first. + sampled_token_logprob = logprobs[0] + self.cumulative_logprob += sampled_token_logprob + + # Update with the Logprob dictionary for this pos. + self.logprobs.append( + self._make_logprob_dict( + logprobs, + token_ids, + decoded_tokens, + rank, + self.num_logprobs, + )) + + def _update_prompt_logprobs( + self, + prompt_logprobs_tensors: LogprobsTensors, + ) -> None: + """Update with prompt logprobs from EngineCore. + + Args: + prompt_logprobs_tensors: tuple containing the prompt logprobs + tensors. + + """ + + # Prompt logprobs are enabled. + assert self.num_prompt_logprobs is not None + assert self.prompt_logprobs is not None + + token_ids, logprobs, ranks = prompt_logprobs_tensors + + # Detokenize non-incrementally. + # Output is flat: [num_tok, num_lps] -> [num_tok * num_lps] + decoded_tokens = None if self.tokenizer is None else ( + convert_ids_list_to_tokens(self.tokenizer, + token_ids.flatten().tolist())) + + # Recover shapes. + num_prompt_tokens, num_logprobs = logprobs.shape + + # Pythonize the torch tensors. + prompt_token_ranks = ranks.tolist() + prompt_logprobs = logprobs.tolist() + token_ids = token_ids.tolist() + + # Make Logprob for each position. + for pos in range(num_prompt_tokens): + # Handle flattening. + offset = pos * num_logprobs + offset_end = offset + num_logprobs + decoded_tokens_for_pos = NONES \ + if decoded_tokens is None else decoded_tokens[offset:offset_end] + + # Update with the Logprob dictionary for this pos. + self.prompt_logprobs.append( + self._make_logprob_dict(prompt_logprobs[pos], token_ids[pos], + decoded_tokens_for_pos, + prompt_token_ranks[pos], + self.num_prompt_logprobs)) + + def pop_prompt_logprobs(self) -> Optional[PromptLogprobs]: + """Pop and return all request prompt logprobs + + The logprobs processor aggregates prompt chunk logprobs + over one or more prefill chunks. This method returns + all prompt logprobs at once and then forgets them. + Ensures correct RequestOutputKind.DELTA semantics + wherein all prompt logprobs are returned at once at + the end of prefill. + + Returns: + None if prompt logprobs are disabled for this request. + List of all prompt logprobs, otherwise. + """ + plp = self.prompt_logprobs + if plp: + self.prompt_logprobs = [] + return plp + + @staticmethod + def _make_logprob_dict( + logprobs: list[float], + logprob_token_ids: list[int], + decoded_tokens: Iterable[Optional[str]], + rank: int, + num_logprobs: int, + ) -> dict[int, Logprob]: + """Make a Logprob dictionary for a position. + + Args: + logprobs: list of log probabilities + logprob_token_ids: list of top token ids + decoded_tokens: list of decoded top tokens + rank: rank of the sampled token + num_logprobs: number of logprobs requested + by the user (in addition to sampled logprob) + + Returns: + dict[token id, Logprob] + """ + if num_logprobs == -1: + num_logprobs = len(logprobs) + # We do not need a special case for the sampled token + # being in the topk, since inserting duplicated data + # into a dictionary twice is the same as doing it once. + topk_ranks = range(1, num_logprobs + 1) + ranks = itertools.chain((rank, ), topk_ranks) + + return { + token_id: Logprob( + logprob=logprob, + rank=rank, + decoded_token=token, + ) + for token_id, logprob, rank, token in zip( + logprob_token_ids, logprobs, ranks, decoded_tokens) + } + + def update_from_output(self, output: EngineCoreOutput) -> None: + if output.new_logprobs is not None: + self._update_sample_logprobs(output.new_logprobs) + if output.new_prompt_logprobs_tensors is not None: + self._update_prompt_logprobs(output.new_prompt_logprobs_tensors) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/metrics/__pycache__/ray_wrappers.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/metrics/__pycache__/ray_wrappers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f3cd62fff4a7eab0cd026225608c9d05f6f5f7c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/metrics/__pycache__/ray_wrappers.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/sample/logits_processor/__pycache__/state.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/sample/logits_processor/__pycache__/state.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec30e9ead08bb37511c57944b24bfda7dd0d9f94 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/sample/logits_processor/__pycache__/state.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/sample/logits_processor/builtin.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/sample/logits_processor/builtin.py new file mode 100644 index 0000000000000000000000000000000000000000..24387ab793906c4b3c68bc5d5dc499afa91c9830 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/sample/logits_processor/builtin.py @@ -0,0 +1,289 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +from collections.abc import Sequence +from typing import TYPE_CHECKING, Optional + +import torch + +from vllm.v1.sample.logits_processor.interface import (BatchUpdate, + LogitsProcessor, + MoveDirectionality) + +if TYPE_CHECKING: + from vllm.config import VllmConfig + + +class MinPLogitsProcessor(LogitsProcessor): + + def __init__(self, vllm_config: "VllmConfig", device: torch.device, + is_pin_memory: bool): + max_num_reqs = vllm_config.scheduler_config.max_num_seqs + self.min_p_count: int = 0 + + self.min_p_cpu_tensor = torch.zeros((max_num_reqs, ), + dtype=torch.float32, + device="cpu", + pin_memory=is_pin_memory) + self.min_p_cpu = self.min_p_cpu_tensor.numpy() + + self.use_double_tensor = torch.device(device).type != "cpu" + + if self.use_double_tensor: + # Pre-allocated device tensor + self.min_p_device: torch.Tensor = torch.empty((max_num_reqs, ), + dtype=torch.float32, + device=device) + else: + self.min_p_device = self.min_p_cpu_tensor + # Current slice of the device tensor + self.min_p: torch.Tensor = self.min_p_device[:0] + + def is_argmax_invariant(self) -> bool: + """Min-p never impacts greedy sampling""" + return True + + def get_min_p_by_index(self, index: int) -> float: + return float(self.min_p_cpu[index]) + + def update_state(self, batch_update: Optional[BatchUpdate]): + if not batch_update: + return + + needs_update = False + # Process added requests. + for index, params, _, _ in batch_update.added: + min_p = params.min_p + if self.min_p_cpu[index] != min_p: + needs_update = True + self.min_p_cpu[index] = min_p + if min_p: + self.min_p_count += 1 + + if self.min_p_count: + # Process removed requests. + needs_update |= bool(batch_update.removed) + for index in batch_update.removed: + if self.min_p_cpu[index]: + self.min_p_count -= 1 + + # Process moved requests, unidirectional (a->b) and swap (a<->b) + for adx, bdx, direct in batch_update.moved: + change = (min_p_a := + self.min_p_cpu[adx]) != (min_p_b := + self.min_p_cpu[bdx]) + needs_update |= change + if change: + self.min_p_cpu[bdx] = min_p_a + if direct == MoveDirectionality.SWAP: + self.min_p_cpu[adx] = min_p_b + + # Update tensors if needed. + size = batch_update.batch_size + if self.min_p_count and (needs_update or self.min_p.shape[0] != size): + self.min_p = self.min_p_device[:size] + if self.use_double_tensor: + self.min_p.copy_(self.min_p_cpu_tensor[:size], + non_blocking=True) + self.min_p.unsqueeze_(1) + + def apply(self, logits: torch.Tensor) -> torch.Tensor: + if not self.min_p_count: + return logits + + # Convert logits to probability distribution + probability_values = torch.nn.functional.softmax(logits, dim=-1) + # Calculate maximum probabilities per sequence + max_probabilities = torch.amax(probability_values, + dim=-1, + keepdim=True) + # Adjust min_p + adjusted_min_p = max_probabilities.mul_(self.min_p) + # Identify valid tokens using threshold comparison + invalid_token_mask = probability_values < adjusted_min_p + # Apply mask using boolean indexing + logits[invalid_token_mask] = -float('inf') + return logits + + +class LogitBiasLogitsProcessor(LogitsProcessor): + + def __init__(self, _, device: torch.device, is_pin_memory: bool): + self.device = device + self.pin_memory = is_pin_memory + self.biases: dict[int, dict[int, float]] = {} + + self.bias_tensor: torch.Tensor = torch.tensor(()) + self.logits_slice = (self._device_tensor([], torch.int32), + self._device_tensor([], torch.int32)) + + def is_argmax_invariant(self) -> bool: + """Logit bias can rebalance token probabilities and change the + outcome of argmax in greedy sampling.""" + return False + + def update_state(self, batch_update: Optional[BatchUpdate]): + if not batch_update: + return + + needs_update: bool = False + # Process added requests. + for index, params, _, _ in batch_update.added: + if lb := params.logit_bias: + self.biases[index] = lb + needs_update = True + else: + # Drop biases metadata at batch index + if self.biases.pop(index, None) is not None: + # If a new request replaces an old request which + # specified biases, we should update processor tensors + needs_update = True + + if self.biases: + # Process removed requests. + for index in batch_update.removed: + if self.biases.pop(index, None): + needs_update = True + + # Process moved requests, unidirectional (a->b) and swap (a<->b) + for a_index, b_index, direct in batch_update.moved: + if direct == MoveDirectionality.UNIDIRECTIONAL: + if (a_entry := self.biases.pop(a_index, None)) is None: + if self.biases.pop(b_index, None) is not None: + needs_update = True + else: + self.biases[b_index] = a_entry + needs_update = True + else: + a_entry = self.biases.pop(a_index, None) + if (b_entry := self.biases.pop(b_index, None)) is not None: + self.biases[a_index] = b_entry + needs_update = True + if a_entry is not None: + self.biases[b_index] = a_entry + needs_update = True + + # Update tensors if needed. + if needs_update: + reqs, tok_ids, biases = [], [], [] + for req, lb in self.biases.items(): + reqs.extend([req] * len(lb)) + tok_ids.extend(lb.keys()) + biases.extend(lb.values()) + + self.bias_tensor = self._device_tensor(biases, torch.float32) + self.logits_slice = (self._device_tensor(reqs, torch.int32), + self._device_tensor(tok_ids, torch.int32)) + + def _device_tensor(self, data: list, dtype: torch.dtype) -> torch.Tensor: + return (torch.tensor(data, + device="cpu", + dtype=dtype, + pin_memory=self.pin_memory).to(device=self.device, + non_blocking=True)) + + def apply(self, logits: torch.Tensor) -> torch.Tensor: + if self.biases: + logits[self.logits_slice] += self.bias_tensor + return logits + + +class MinTokensLogitsProcessor(LogitsProcessor): + + def __init__(self, vllm_config: "VllmConfig", device: torch.device, + is_pin_memory: bool): + # index -> (min_toks, output_token_ids, stop_token_ids) + self.device = device + self.pin_memory = is_pin_memory + self.min_toks: dict[int, tuple[int, Sequence[int], set[int]]] = {} + + # (req_idx_tensor,eos_tok_id_tensor) + self.logits_slice: tuple[torch.Tensor, + torch.Tensor] = (self._device_tensor( + [], torch.int32), + self._device_tensor( + [], torch.int32)) + + def is_argmax_invariant(self) -> bool: + """By censoring stop tokens, min-tokens can change the outcome + of the argmax operation in greedy sampling.""" + return False + + def update_state(self, batch_update: Optional[BatchUpdate]): + needs_update = False + + if batch_update: + # Process added requests. + for index, params, _, output_tok_ids in batch_update.added: + if ((min_tokens := params.min_tokens) + and len(output_tok_ids) < min_tokens): + # Replace request metadata at batch index + self.min_toks[index] = (min_tokens, output_tok_ids, + params.all_stop_token_ids) + needs_update = True + else: + # Drop min_toks metadata at batch index + if self.min_toks.pop(index, None) is not None: + # If a new request replaces an old request which + # specified min_toks, we should update processor tensors + needs_update = True + + if self.min_toks: + # Process removed requests. + for index in batch_update.removed: + if self.min_toks.pop(index, None): + needs_update = True + + # Process moved requests, unidirectional (a->b) and + # swapped (a<->b) + for a_index, b_index, direct in batch_update.moved: + if direct == MoveDirectionality.UNIDIRECTIONAL: + if (a_entry := self.min_toks.pop(a_index, + None)) is None: + if self.min_toks.pop(b_index, None) is not None: + needs_update = True + else: + self.min_toks[b_index] = a_entry + needs_update = True + else: + a_entry = self.min_toks.pop(a_index, None) + if (b_entry := self.min_toks.pop(b_index, + None)) is not None: + self.min_toks[a_index] = b_entry + needs_update = True + if a_entry is not None: + self.min_toks[b_index] = a_entry + needs_update = True + + if self.min_toks: + # Check for any requests that have attained their min tokens. + to_remove = tuple(index for index, (min_toks, out_tok_ids, + _) in self.min_toks.items() + if len(out_tok_ids) >= min_toks) + if to_remove: + needs_update = True + for index in to_remove: + del self.min_toks[index] + + # Update tensors if needed. + if needs_update: + reqs: list[int] = [] + tok_ids: list[int] = [] + for req, (_, _, stop_tok_ids) in self.min_toks.items(): + reqs.extend([req] * len(stop_tok_ids)) + tok_ids.extend(stop_tok_ids) + + self.logits_slice = (self._device_tensor(reqs, torch.int32), + self._device_tensor(tok_ids, torch.int32)) + + def _device_tensor(self, data: list, dtype: torch.dtype) -> torch.Tensor: + return (torch.tensor(data, + device="cpu", + dtype=dtype, + pin_memory=self.pin_memory).to(device=self.device, + non_blocking=True)) + + def apply(self, logits: torch.Tensor) -> torch.Tensor: + if self.min_toks: + # Inhibit EOS token for requests which have not reached min length + logits[self.logits_slice] = -float("inf") + return logits diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/sample/ops/__pycache__/topk_topp_sampler.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/sample/ops/__pycache__/topk_topp_sampler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c47db04c782b21a3701e9f8b4e5d3f4e8f0aada Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/sample/ops/__pycache__/topk_topp_sampler.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/sample/tpu/sampler.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/sample/tpu/sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..2c9f4892bc247a77fdca88efb3193c55c9c4bd94 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/sample/tpu/sampler.py @@ -0,0 +1,146 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Sampler layer implementing TPU supported operations.""" + +import torch +import torch.nn as nn + +from vllm.v1.outputs import LogprobsTensors, SamplerOutput +from vllm.v1.sample.ops.topk_topp_sampler import TopKTopPSampler +from vllm.v1.sample.tpu.metadata import TPUSupportedSamplingMetadata + +_SAMPLING_EPS = 1e-5 + + +class Sampler(nn.Module): + + def __init__(self): + # TODO(houseroad): Add support for logprobs_mode. + super().__init__() + self.topk_topp_sampler = TopKTopPSampler() + + def forward( + self, + logits: torch.Tensor, + sampling_metadata: TPUSupportedSamplingMetadata, + ) -> SamplerOutput: + # Use float32 for the logits. + logits = logits.to(torch.float32) + # Sample the next token. + sampled = self.sample(logits, sampling_metadata) + + # These are TPU tensors. + sampler_output = SamplerOutput( + # The sampled tokens are expanded to 2D tensor with shape + # [num_requests, 1], where each row represents one generated + # token per request. + sampled_token_ids=sampled.unsqueeze(-1), + logprobs_tensors=None) + return sampler_output + + def apply_temperature( + self, + logits: torch.Tensor, + temp: torch.Tensor, + ) -> torch.Tensor: + return logits.div_(temp.unsqueeze(dim=1)) + + def greedy_sample(self, logits: torch.Tensor) -> torch.Tensor: + return logits.argmax(dim=-1).view(-1) + + def sample( + self, + logits: torch.Tensor, + sampling_metadata: TPUSupportedSamplingMetadata, + ) -> torch.Tensor: + greedy_sampled = self.greedy_sample(logits) + + assert sampling_metadata.temperature is not None + + # Apply temperature. + logits = self.apply_temperature(logits, sampling_metadata.temperature) + + # Apply min_p. + if sampling_metadata.min_p is not None: + logits = self.apply_min_p(logits, sampling_metadata.min_p) + + # Apply top_k and/or top_p. + random_sampled = self.topk_topp_sampler( + logits, + sampling_metadata.generators, + sampling_metadata.top_k, + sampling_metadata.top_p, + ) + + sampled = torch.where(sampling_metadata.temperature < _SAMPLING_EPS, + greedy_sampled, random_sampled) + return sampled + + def compute_logprobs(self, logits: torch.Tensor) -> torch.Tensor: + return logits.log_softmax(dim=-1, dtype=torch.float32) + + def gather_logprobs( + self, + logprobs: torch.Tensor, + num_logprobs: int, + token_ids: torch.Tensor, + ) -> LogprobsTensors: + """ + Gather logprobs for topk and sampled/prompt token. + + Args: + logits: (num tokens) x (vocab) tensor + num_logprobs: minimum number of logprobs to + retain per token + token_ids: prompt tokens (if prompt logprobs) + or sampled tokens (if sampled + logprobs); 1D token ID tensor + with (num tokens) elements + + Returns: + Top-k int indices tensor, (num tokens) x (num_logprobs + 1) + Top-k float logprobs tensor, (num tokens) x (num_logprobs + 1) + Sampled token rank tensor, (num tokens) + """ + # Find the topK values. + topk_logprobs, topk_indices = torch.topk(logprobs, + num_logprobs, + dim=-1) + + # Get with the logprob of the prompt or sampled token. + token_ids = token_ids.unsqueeze(-1) + token_logprobs = logprobs.gather(-1, token_ids) + + # Compute the ranks of the actual token. + token_ranks = (logprobs >= token_logprobs).sum(-1) + + # Concatenate together with the topk. + indices = torch.cat((token_ids, topk_indices), dim=1) + logprobs = torch.cat((token_logprobs, topk_logprobs), dim=1) + + # Use int32 to reduce the tensor size. + indices = indices.to(torch.int32) + + return LogprobsTensors(indices, logprobs, token_ranks) + + def apply_min_p( + self, + logits: torch.Tensor, + min_p: torch.Tensor, + ) -> torch.Tensor: + """ + Filters logits using adaptive probability thresholding. + """ + # Convert logits to probability distribution + probability_values = torch.nn.functional.softmax(logits, dim=-1) + # Calculate maximum probabilities per sequence + max_probabilities = torch.amax(probability_values, + dim=-1, + keepdim=True) + # Reshape min_p for broadcasting + adjusted_min_p = min_p.unsqueeze(1) * max_probabilities + # Identify valid tokens using threshold comparison + valid_token_mask = probability_values >= adjusted_min_p + # Apply mask using boolean indexing (xla friendly) + logits.masked_fill_(~valid_token_mask, -float("inf")) + return logits diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/spec_decode/__pycache__/eagle.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/spec_decode/__pycache__/eagle.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea015ebe31b243aea1000d8c555289f25dfe48b0 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/spec_decode/__pycache__/eagle.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/spec_decode/__pycache__/medusa.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/spec_decode/__pycache__/medusa.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74d85664ea37a3101b09e1f8ce0353f2aaf71329 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/spec_decode/__pycache__/medusa.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/spec_decode/__pycache__/metrics.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/spec_decode/__pycache__/metrics.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fec46f1a93af4e0cd382a5bfed9a456de4d8bd3a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/spec_decode/__pycache__/metrics.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/spec_decode/__pycache__/ngram_proposer.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/spec_decode/__pycache__/ngram_proposer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21ae626a16013eb9c55a72b1f1aec42a933e7d99 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/spec_decode/__pycache__/ngram_proposer.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/structured_output/__pycache__/utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/structured_output/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..513678c1a5cb80317bbdab49e5336648811ab61a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/structured_output/__pycache__/utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/worker/__pycache__/lora_model_runner_mixin.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/worker/__pycache__/lora_model_runner_mixin.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7af5c92ea08dd7c2c52e945f9684154a16f8bb5c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/worker/__pycache__/lora_model_runner_mixin.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/worker/tpu_model_runner.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/worker/tpu_model_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..f7e68edba3a13cdd254b3319e68d9036751ae17f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/v1/worker/tpu_model_runner.py @@ -0,0 +1,2033 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +import bisect +import gc +import time +from typing import TYPE_CHECKING, Any, Literal, Optional, Union, cast +from unittest.mock import patch + +import numpy as np +import torch +import torch.nn as nn +# TPU XLA related +import torch_xla.core.xla_model as xm +import torch_xla.distributed.spmd as xs +import torch_xla.runtime as xr + +import vllm.envs as envs +from vllm.attention import Attention +from vllm.attention.backends.abstract import AttentionType +from vllm.attention.layers.chunked_local_attention import ChunkedLocalAttention +from vllm.compilation.wrapper import TorchCompileWrapperWithCustomDispatcher +from vllm.config import (ParallelConfig, VllmConfig, + get_layers_from_vllm_config, update_config) +from vllm.distributed.kv_transfer import (get_kv_transfer_group, + has_kv_transfer_group) +from vllm.forward_context import set_forward_context +from vllm.logger import init_logger +from vllm.lora.layers import BaseLayerWithLoRA +from vllm.model_executor.model_loader import get_model_loader +from vllm.model_executor.model_loader.tpu import TPUModelLoader +from vllm.model_executor.models.interfaces import supports_transcription +from vllm.model_executor.models.interfaces_base import ( + is_pooling_model, is_text_generation_model) +from vllm.multimodal import MULTIMODAL_REGISTRY +from vllm.multimodal.inputs import (BatchedTensorInputs, MultiModalKwargsItem, + PlaceholderRange) +from vllm.multimodal.utils import group_mm_kwargs_by_modality +from vllm.sequence import IntermediateTensors +from vllm.tasks import GenerationTask, PoolingTask, SupportedTask +from vllm.utils import (LayerBlockType, cdiv, is_pin_memory_available, + prev_power_of_2) +from vllm.v1.attention.backends.pallas import (TPU_STR_DTYPE_TO_TORCH_DTYPE, + PallasAttentionBackend, + PallasMetadata, + get_page_size_bytes) +from vllm.v1.kv_cache_interface import (AttentionSpec, FullAttentionSpec, + KVCacheConfig, KVCacheSpec, + SlidingWindowSpec) +from vllm.v1.outputs import (EMPTY_MODEL_RUNNER_OUTPUT, LogprobsLists, + LogprobsTensors, ModelRunnerOutput) +from vllm.v1.sample.tpu.metadata import TPUSupportedSamplingMetadata +from vllm.v1.sample.tpu.sampler import Sampler as TPUSampler +from vllm.v1.worker.kv_connector_model_runner_mixin import ( + KVConnectorModelRunnerMixin, KVConnectorOutput) +from vllm.v1.worker.lora_model_runner_mixin import LoRAModelRunnerMixin +from vllm.v1.worker.tpu_input_batch import CachedRequestState, InputBatch + +from .utils import (MultiModalBudget, bind_kv_cache, + initialize_kv_cache_for_kv_sharing, + sanity_check_mm_encoder_outputs) + +if TYPE_CHECKING: + from vllm.v1.core.sched.output import SchedulerOutput + +logger = init_logger(__name__) + +INVALID_TOKEN_ID = -1 +# Smallest output size +MIN_NUM_SEQS = 8 + + +######################################################### +# Ways to avoid recompilation +######################################################### +# +# The model executor has two primary components: +# 1. preparing the model and sampler inputs +# 2. executing the model and sampler. +# The core idea is to avoid any TPU computation during input preparation. For +# better compilation tracking and increased flexibility, the model execution and +# sampler are divided into several distinct components. +# +# Below are the detailed steps: +# +# Step 1 +# It is recommended to avoid TPU operations when preparing the model and sampler +# inputs. CPU tensors can be prepared and transferred to the XLA device using +# cpu_tensor.to(xla_device), which only triggers CPU to TPU transfers and avoids +# compilation. +# +# Step 2 +# The TPU execution should be decomposed into subgraphs (4 at the moment): +# 1. the main model +# 2. selecting hidden states for each request +# 3. sampler +# 4. encoder. +# Each subgraph should be decorated in a torch.compile. This is used to make +# sure that we have the same subgraph topology in both dummy_run and +# xecute_model. The results from these subgraphs should either be passed to +# other subgraphs, or transferred from TPU to CPU using xla_tensor.cpu() for +# subsequent processing on the CPU. +# +# Step 3 +# The dummy_run should be comprehensive, ensuring all potential input shapes and +# branch predictions are included as subgraph inputs to facilitate +# pre-compilation. +class TPUModelRunner(LoRAModelRunnerMixin, KVConnectorModelRunnerMixin): + + def __init__( + self, + vllm_config: VllmConfig, + device: torch.device, + original_parallel_config: Optional[ParallelConfig] = None, + ): + self.vllm_config = vllm_config + self.model_config = vllm_config.model_config + self.cache_config = vllm_config.cache_config + self.lora_config = vllm_config.lora_config + self.load_config = vllm_config.load_config + self.parallel_config = vllm_config.parallel_config + self.original_parallel_config = original_parallel_config + self.scheduler_config = vllm_config.scheduler_config + self.speculative_config = vllm_config.speculative_config + self.observability_config = vllm_config.observability_config + self.device_config = vllm_config.device_config + + model_config = self.model_config + cache_config = self.cache_config + scheduler_config = self.scheduler_config + parallel_config = self.parallel_config + self.device = device + self.check_recompilation = envs.VLLM_XLA_CHECK_RECOMPILATION + + # SPMD Related + self.use_spmd = envs.VLLM_XLA_USE_SPMD + if self.use_spmd: + num_devices = xr.global_runtime_device_count() + mesh_shape = (num_devices, 1) + device_ids = np.array(range(num_devices)) + self.mesh = xs.Mesh(device_ids, mesh_shape, ('x', 'y')) + + self.enforce_eager = model_config.enforce_eager + + self.num_xla_graphs = 0 + self._update_num_xla_graphs("init") + + self.pin_memory = is_pin_memory_available() + self.dtype = self.model_config.dtype + if cache_config.cache_dtype == "auto": + model_dtype = self.dtype + if isinstance(model_dtype, str): + self.kv_cache_dtype = TPU_STR_DTYPE_TO_TORCH_DTYPE[model_dtype] + else: + self.kv_cache_dtype = model_dtype + else: + self.kv_cache_dtype = TPU_STR_DTYPE_TO_TORCH_DTYPE[ + cache_config.cache_dtype] + self._hidden_states_dtype = self.dtype + + self.sliding_window = model_config.get_sliding_window() + self.block_size = cache_config.block_size + self.max_model_len = model_config.max_model_len + self.most_model_len = envs.VLLM_TPU_MOST_MODEL_LEN + self.max_num_blocks_per_req = cdiv(self.max_model_len, self.block_size) + self.num_blocks_per_most_len_req = cdiv( + self.most_model_len, + self.block_size) if self.most_model_len is not None else None + # InputBatch needs to work with sampling tensors greater than padding + # to avoid dynamic shapes. Also, avoid suboptimal alignment. + self.max_num_reqs = max(scheduler_config.max_num_seqs, MIN_NUM_SEQS) + self.num_tokens_paddings = _get_token_paddings( + min_token_size=16, + max_token_size=scheduler_config.max_num_batched_tokens, + padding_gap=envs.VLLM_TPU_BUCKET_PADDING_GAP) + # In case `max_num_tokens < max(num_tokens_paddings)` use the actual + # padded max value to pre-allocate data structures and pre-compile. + self.max_num_tokens = self.num_tokens_paddings[-1] + + # Model-related. + self.num_attn_layers = model_config.get_num_layers_by_block_type( + parallel_config, LayerBlockType.attention) + self.num_query_heads = model_config.get_num_attention_heads( + parallel_config) + self.num_kv_heads = model_config.get_num_kv_heads(parallel_config) + self.head_size = model_config.get_head_size() + self.hidden_size = model_config.get_hidden_size() + self.vocab_size = model_config.get_vocab_size() + + if self.lora_config is not None: + self.vocab_size += self.lora_config.lora_extra_vocab_size + + # Multi-modal data support + self.mm_registry = MULTIMODAL_REGISTRY + self.uses_mrope = model_config.uses_mrope + self.supports_mm_inputs = self.mm_registry.supports_multimodal_inputs( + model_config) + # TODO: Support M-RoPE (e.g, Qwen2-VL) + assert not self.uses_mrope, "TPU does not support M-RoPE yet." + + self._num_slices_per_kv_cache_update_block = \ + _get_num_slices_per_kv_cache_update_block(get_page_size_bytes( + block_size=self.block_size, + num_kv_heads=self.num_kv_heads, + head_size=self.head_size, + kv_cache_dtype=self.kv_cache_dtype, + )) + + # Lazy initialization + self.model: nn.Module # Set after load_model + self.kv_caches: list[torch.Tensor] = [] + # req_id -> (input_id -> encoder_output) + self.encoder_cache: dict[str, dict[int, torch.Tensor]] = {} + + # Request states. + self.requests: dict[str, CachedRequestState] = {} + + # Initialize input batch early to avoid AttributeError in _update_states + self.input_batch = InputBatch( + max_num_reqs=self.max_num_reqs, + max_model_len=self.max_model_len, + max_num_batched_tokens=self.max_num_tokens, + device=self.device, + pin_memory=self.pin_memory, + vocab_size=self.model_config.get_vocab_size(), + block_sizes=[self.block_size], + ) + + # Cached torch/numpy tensor + # The pytorch tensor and numpy array share the same buffer. + # Sometimes the numpy op is faster so we create both. + self.input_ids_cpu = torch.zeros(self.max_num_tokens, + dtype=torch.int32, + device="cpu") + + self.positions_cpu = torch.zeros(self.max_num_tokens, + dtype=torch.int32, + device="cpu") + self.positions_np = self.positions_cpu.numpy() + self.block_table_cpu = torch.zeros( + (self.max_num_reqs, self.max_num_blocks_per_req), + dtype=torch.int32, + device="cpu") + # adjust num_reqs to avoid SMEM OOM. + self.num_reqs_most_model_len = min( + PallasAttentionBackend.get_max_num_seqs(self.most_model_len, + self.block_size), + self.max_num_reqs) if self.most_model_len is not None else None + self.num_reqs_max_model_len = min( + PallasAttentionBackend.get_max_num_seqs(self.max_model_len, + self.block_size), + self.max_num_reqs) + self.query_start_loc_cpu = torch.zeros(self.max_num_tokens + 1, + dtype=torch.int32, + device="cpu", + pin_memory=self.pin_memory) + self.query_start_loc_np = self.query_start_loc_cpu.numpy() + + self.seq_lens_cpu = torch.zeros(self.max_num_tokens, + dtype=torch.int32, + device="cpu", + pin_memory=self.pin_memory) + self.seq_lens_np = self.seq_lens_cpu.numpy() + + # Range tensor with values [0 .. self.max_num_tokens - 1]. + # Used to initialize positions / context_lens / seq_lens + # Keep in int64 to avoid overflow with long context + self.arange_np = np.arange(self.max_num_tokens, dtype=np.int64) + self.num_reqs_paddings = _get_req_paddings( + min_req_size=MIN_NUM_SEQS, max_req_size=self.max_num_reqs) + + # Layer pairings for cross-layer KV sharing. + # If an Attention layer `layer_name` is in the keys of this dict, it + # means this layer will perform attention using the keys and values + # from the KV cache of `shared_kv_cache_layers[layer_name]`. + self.shared_kv_cache_layers: dict[str, str] = {} + + # tensors for structured decoding + self.grammar_bitmask_cpu = torch.zeros( + (self.max_num_reqs, cdiv(self.vocab_size, 32)), + dtype=torch.int32, + device="cpu", + pin_memory=self.pin_memory) + self.require_structured_out_cpu = torch.zeros( + (self.max_num_reqs, 1), + dtype=torch.bool, + device="cpu", + pin_memory=self.pin_memory) + self.structured_decode_arange = torch.arange( + 0, 32, device="cpu", pin_memory=self.pin_memory) + + self.mm_budget = (MultiModalBudget( + self.model_config, + self.scheduler_config, + self.mm_registry, + max_model_len=self.max_model_len, + max_num_reqs=self.max_num_reqs, + ) if self.supports_mm_inputs else None) + + if not self.use_spmd: + self.sample_from_logits_func = torch.compile( + self.sample_from_logits, + backend="openxla", + fullgraph=True, + dynamic=False) + else: + self.sample_from_logits_func = self.sample_from_logits + + def _update_num_xla_graphs(self, case_str): + check_comp = self.check_recompilation and not self.enforce_eager + if not check_comp: + return + + total_cached_graphs = xr.get_num_cached_compilation_graph() + new_compiled_graphs = total_cached_graphs - self.num_xla_graphs + if new_compiled_graphs == 0: + return + + logger.info("Add new %d compiled XLA graphs due to %s", + new_compiled_graphs, case_str) + self.num_xla_graphs += new_compiled_graphs + + def _verify_num_xla_graphs(self, case_str): + check_comp = self.check_recompilation and not self.enforce_eager + if not check_comp: + return + + curr_cached_graph = xr.get_num_cached_compilation_graph() + assert self.num_xla_graphs == curr_cached_graph, ( + "Recompilation after warm up is detected during {}." + " num_xla_graphs = {} curr_cached_graph = {}".format( + case_str, self.num_xla_graphs, curr_cached_graph)) + + def _update_states(self, scheduler_output: "SchedulerOutput") -> bool: + """Update the cached states and the persistent batch with the scheduler + output. + + The updated states are used by the `_prepare_inputs` function to create + the input GPU tensors for the model. + + Returns: + True if there is a new/resumed/paused/finished request. + If False, we can skip copying SamplingMetadata to the GPU. + """ + # Remove finished requests from the cached states. + for req_id in scheduler_output.finished_req_ids: + self.requests.pop(req_id, None) + self.encoder_cache.pop(req_id, None) + + # Remove the finished requests from the persistent batch. + # NOTE(woosuk): There could be an edge case where finished_req_ids and + # scheduled_req_ids overlap. This happens when a request is aborted and + # then resubmitted with the same ID. In this case, we treat them as two + # distinct requests - clearing the cached states for the first request + # and handling the second as a new request. + removed_req_indices: list[int] = [] + for req_id in scheduler_output.finished_req_ids: + req_index = self.input_batch.remove_request(req_id) + if req_index is not None: + removed_req_indices.append(req_index) + + # Free the cached encoder outputs. + for req_id, input_id in scheduler_output.free_encoder_input_ids: + encoder_outputs = self.encoder_cache.get(req_id) + if encoder_outputs is not None: + encoder_outputs.pop(input_id, None) + if not encoder_outputs: + self.encoder_cache.pop(req_id, None) + + # Remove the unscheduled requests from the persistent batch. + # NOTE(woosuk): The unscheduled requests are either preempted requests + # or running requests that are not scheduled in this step. We remove + # them from the persistent batch but keep their cached states since + # they will be scheduled again sometime in the future. + scheduled_req_ids = scheduler_output.num_scheduled_tokens.keys() + cached_req_ids = self.input_batch.req_id_to_index.keys() + unscheduled_req_ids = cached_req_ids - scheduled_req_ids + # NOTE(woosuk): The persistent batch optimization assumes that + # consecutive batches contain mostly the same requests. If batches + # have low request overlap (e.g., alternating between two distinct + # sets of requests), this optimization becomes very inefficient. + for req_id in unscheduled_req_ids: + req_index = self.input_batch.remove_request(req_id) + assert req_index is not None + removed_req_indices.append(req_index) + + req_ids_to_add: list[str] = [] + # Add new requests to the cached states. + for new_req_data in scheduler_output.scheduled_new_reqs: + assert new_req_data.sampling_params is not None,\ + "Pooling is not supported in TPU yet" + req_id = new_req_data.req_id + sampling_params = new_req_data.sampling_params + + self.requests[req_id] = CachedRequestState( + req_id=req_id, + prompt_token_ids=new_req_data.prompt_token_ids, + mm_kwargs=new_req_data.mm_kwargs, + mm_positions=new_req_data.mm_positions, + sampling_params=sampling_params, + pooling_params=None, + generator=None, + block_ids=new_req_data.block_ids, + num_computed_tokens=new_req_data.num_computed_tokens, + output_token_ids=[], + lora_request=new_req_data.lora_request, + ) + + req_ids_to_add.append(req_id) + + # Update the states of the running/resumed requests. + req_data = scheduler_output.scheduled_cached_reqs + for i, req_id in enumerate(req_data.req_ids): + req_state = self.requests[req_id] + num_computed_tokens = req_data.num_computed_tokens[i] + new_block_ids = req_data.new_block_ids[i] + resumed_from_preemption = req_data.resumed_from_preemption[i] + + # Update the cached states. + req_state.num_computed_tokens = num_computed_tokens + if not resumed_from_preemption: + # Append the new blocks to the existing block IDs. + for block_ids, new_ids in zip(req_state.block_ids, + new_block_ids): + block_ids.extend(new_ids) + else: + # The request is resumed from preemption. + # Replace the existing block IDs with the new ones. + req_state.block_ids = new_block_ids + + req_index = self.input_batch.req_id_to_index.get(req_id) + if req_index is None: + # The request is not in the persistent batch. + # The request was either preempted and resumed later, or was not + # scheduled in the previous step and needs to be added again. + req_ids_to_add.append(req_id) + continue + + # Update the persistent batch. + self.input_batch.num_computed_tokens_cpu[req_index] = ( + num_computed_tokens) + self.input_batch.block_table.append_row(new_block_ids, req_index) + + # Add the new or resumed requests to the persistent batch. + # The smaller empty indices are filled first. + removed_req_indices = sorted(removed_req_indices, reverse=True) + for req_id in req_ids_to_add: + req_state = self.requests[req_id] + if removed_req_indices: + # Fill the empty index. + req_index = removed_req_indices.pop() + else: + # Append to the end. + req_index = None + self.input_batch.add_request(req_state, req_index) + + # Condense the batched states if there are empty indices. + if removed_req_indices: + self.input_batch.condense(removed_req_indices) + + return len(unscheduled_req_ids) > 0 or len(req_ids_to_add) > 0 + + def get_model(self) -> nn.Module: + return self.model + + def get_supported_generation_tasks(self) -> list[GenerationTask]: + model = self.get_model() + supported_tasks = list[GenerationTask]() + + if is_text_generation_model(model): + supported_tasks.append("generate") + + if supports_transcription(model): + if model.supports_transcription_only: + return ["transcription"] + + supported_tasks.append("transcription") + + return supported_tasks + + def get_supported_pooling_tasks(self) -> list[PoolingTask]: + model = self.get_model() + if not is_pooling_model(model): + return [] + + return list(model.pooler.get_supported_tasks()) + + def get_supported_tasks(self) -> tuple[SupportedTask, ...]: + tasks = list[SupportedTask]() + + if self.model_config.runner_type == "generate": + tasks.extend(self.get_supported_generation_tasks()) + if self.model_config.runner_type == "pooling": + tasks.extend(self.get_supported_pooling_tasks()) + + return tuple(tasks) + + def get_kv_cache_spec(self) -> dict[str, KVCacheSpec]: + """ + Generates the KVCacheSpec by parsing the kv cache format from each + Attention module in the static forward context. + Returns: + KVCacheSpec: A dictionary mapping layer names to their KV cache + format. Layers that do not need KV cache are not included. + """ + + layers = get_layers_from_vllm_config(self.vllm_config, Attention) + block_size = self.vllm_config.cache_config.block_size + kv_cache_spec: dict[str, KVCacheSpec] = {} + for layer_name, attn_module in layers.items(): + if (kv_tgt_layer := + attn_module.kv_sharing_target_layer_name) is not None: + # The layer doesn't need its own KV cache and will use that of + # the target layer. We skip creating a KVCacheSpec for it, so + # that KV cache management logic will act as this layer does + # not exist, and doesn't allocate KV cache for the layer. This + # enables the memory saving of cross-layer kv sharing, allowing + # a given amount of memory to accommodate longer context lengths + # or enable more requests to be processed simultaneously. + self.shared_kv_cache_layers[layer_name] = kv_tgt_layer + continue + + if attn_module.attn_type == AttentionType.DECODER: + if isinstance(attn_module, ChunkedLocalAttention): + logger.warning_once( + "Using irope in Pallas is not supported yet, it " + "will fall back to global attention for long context.") + if attn_module.sliding_window is not None: + kv_cache_spec[layer_name] = SlidingWindowSpec( + block_size=block_size, + num_kv_heads=attn_module.num_kv_heads, + head_size=attn_module.head_size, + dtype=self.kv_cache_dtype, + sliding_window=attn_module.sliding_window, + use_mla=False, + ) + else: + kv_cache_spec[layer_name] = FullAttentionSpec( + block_size=block_size, + num_kv_heads=attn_module.num_kv_heads, + head_size=attn_module.head_size, + dtype=self.kv_cache_dtype, + use_mla=False, + ) + elif attn_module.attn_type in (AttentionType.ENCODER, + AttentionType.ENCODER_ONLY): + # encoder-only attention does not need KV cache. + continue + elif attn_module.attn_type == AttentionType.ENCODER_DECODER: + raise NotImplementedError + else: + raise ValueError( + f"Unknown attention type: {attn_module.attn_type}") + + return kv_cache_spec + + def _get_slot_mapping_metadata(self, num_reqs, + num_scheduled_tokens_per_req): + """ + Computes metadata for mapping slots to blocks in the key-value (KV) + cache for a batch of requests. + + This function determines, for each request in the batch, how the + scheduled tokens are distributed across memory blocks, and generates + metadata needed to map slices of tokens to their corresponding positions + in the KV cache. + + Args: + num_reqs (int): Number of requests in the current batch. + num_scheduled_tokens_per_req (int or np.ndarray): Number of tokens + to be scheduled for each request. + + Returns: + np.ndarray: A 2D array of shape (total_block_len, 3), where each row + contains: + - kv_cache_start_index (int): The starting index in the KV cache + for the corresponding slice. + - new_kv_start_index (int): The starting index in the new KV + cache for the corresponding slice. + - slice_len (int): The length of the slice. + """ + slices_start = self.input_batch.num_computed_tokens_cpu[:num_reqs] + slices_end = self.input_batch.num_computed_tokens_cpu[:num_reqs] + \ + num_scheduled_tokens_per_req + local_block_start_idx = slices_start // self.block_size + local_block_end_idx = (slices_end - 1) // self.block_size + no_repeat_req_indices = self.arange_np[:num_reqs] + global_block_start_idx = ( + no_repeat_req_indices * self.max_num_blocks_per_req + + local_block_start_idx) + block_lens = local_block_end_idx - local_block_start_idx + 1 + global_block_start_idx = np.repeat(global_block_start_idx, block_lens) + slice_arange = np.concatenate([self.arange_np[:n] for n in block_lens]) + global_block_indices = global_block_start_idx + slice_arange + block_table_cpu = self.input_batch.block_table[0].get_cpu_tensor() + block_numbers = block_table_cpu.flatten()[global_block_indices].numpy() + total_block_len = np.sum(block_lens) + slot_mapping_slices = np.repeat(np.array([[0, self.block_size]], + dtype=np.int32), + total_block_len, + axis=0) + cu_block_lens = np.zeros(len(block_lens) + 1, dtype=np.int32) + np.cumsum(block_lens, out=cu_block_lens[1:]) + for req_idx in range(num_reqs): + slot_mapping_slices[cu_block_lens[req_idx]][ + 0] = slices_start[req_idx] % self.block_size + slot_mapping_slices[ + cu_block_lens[req_idx + 1] - + 1][1] = (slices_end[req_idx] - 1) % self.block_size + 1 + slice_lens = slot_mapping_slices[:, 1] - slot_mapping_slices[:, 0] + cu_slices_lens = np.zeros(len(slice_lens) + 1, dtype=np.int32) + np.cumsum(slice_lens, out=cu_slices_lens[1:]) + kv_cache_start_indices = slot_mapping_slices[:, 0] + \ + (block_numbers * self.block_size) + new_kv_start_indices = cu_slices_lens[:-1] + slot_mapping_metadata = np.stack( + [kv_cache_start_indices, new_kv_start_indices, slice_lens], axis=1) + return slot_mapping_metadata + + def _prepare_inputs(self, scheduler_output: "SchedulerOutput", + start_index: int): + assert scheduler_output.total_num_scheduled_tokens > 0 + num_reqs = self.input_batch.num_reqs + assert num_reqs > 0 + assert start_index < num_reqs + + # Get the number of scheduled tokens for each request. + use_max_model_len = self.most_model_len is None + num_scheduled_tokens_per_req = [] + max_num_scheduled_tokens_all_reqs = 0 + end_index = start_index + + # Use either most_model_len or max_model_len depending on request size. + for i in range(start_index, num_reqs): + req_id = self.input_batch.req_ids[i] + assert req_id is not None + num_tokens = scheduler_output.num_scheduled_tokens[req_id] + if not use_max_model_len and num_tokens > self.most_model_len: + use_max_model_len = True + num_scheduled_tokens_per_req.append(num_tokens) + if use_max_model_len: + if len(num_scheduled_tokens_per_req) > self.num_reqs_max_model_len: + num_scheduled_tokens_per_req = \ + num_scheduled_tokens_per_req[:self.num_reqs_max_model_len] + end_index = start_index + self.num_reqs_max_model_len + else: + end_index = num_reqs + else: + if len(num_scheduled_tokens_per_req + ) > self.num_reqs_most_model_len: + num_scheduled_tokens_per_req = \ + num_scheduled_tokens_per_req[:self.num_reqs_most_model_len] + end_index = start_index + self.num_reqs_most_model_len + else: + end_index = num_reqs + max_num_scheduled_tokens_all_reqs = max(num_scheduled_tokens_per_req) + num_scheduled_tokens_per_req = np.array(num_scheduled_tokens_per_req, + dtype=np.int32) + total_num_scheduled_tokens = sum(num_scheduled_tokens_per_req) + assert max_num_scheduled_tokens_all_reqs > 0 + + num_reqs = len(num_scheduled_tokens_per_req) + + # Get request indices. + # E.g., [2, 5, 3] -> [0, 0, 1, 1, 1, 1, 1, 2, 2, 2] + # For each scheduled token, what are the corresponding req index. + req_indices = np.repeat(self.arange_np[:num_reqs], + num_scheduled_tokens_per_req) + + # Get batched arange. + # E.g., [2, 5, 3] -> [0, 1, 0, 1, 2, 3, 4, 0, 1, 2] + # For each scheduled token, what is its position in corresponding req. + arange = np.concatenate( + [self.arange_np[:n] for n in num_scheduled_tokens_per_req]) + + # Get positions. + positions_np = self.positions_np[:total_num_scheduled_tokens] + np.add(self.input_batch.num_computed_tokens_cpu[req_indices], + arange, + out=positions_np) + + # Get token indices. + # E.g., [0, 1, 0, 1, 2, 3, 4, 0, 1, 2] + # -> [0, 1, M, M + 1, M + 2, M + 3, M + 4, 2 * M, 2 * M + 1, 2 * M + 2] + # where M is the max_model_len. + token_indices = (positions_np + + req_indices * self.input_batch.token_ids_cpu.shape[1]) + + # NOTE(woosuk): We use torch.index_select instead of np.take here + # because torch.index_select is much faster than np.take for large + # tensors. + torch.index_select(self.input_batch.token_ids_cpu_tensor.flatten(), + 0, + torch.from_numpy(token_indices), + out=self.input_ids_cpu[:total_num_scheduled_tokens]) + + # Prepare the attention metadata. + self.query_start_loc_np[0] = 0 + np.cumsum(num_scheduled_tokens_per_req, + out=self.query_start_loc_np[1:num_reqs + 1]) + self.query_start_loc_np[num_reqs + 1:] = 1 + + self.seq_lens_np[:num_reqs] = ( + self.input_batch.num_computed_tokens_cpu[:num_reqs] + + num_scheduled_tokens_per_req) + + # Do the padding and copy the tensors to the TPU. + padded_total_num_scheduled_tokens = _get_padded_token_len( + self.num_tokens_paddings, total_num_scheduled_tokens) + # Zero out to avoid spurious values from prev iteration (last cp chunk) + self.input_ids_cpu[ + total_num_scheduled_tokens:padded_total_num_scheduled_tokens] = 0 + self.input_ids = self.input_ids_cpu[: + padded_total_num_scheduled_tokens].to( + self.device) + self.position_ids = self.positions_cpu[: + padded_total_num_scheduled_tokens].to( + self.device) + if use_max_model_len: + block_tables = self.block_table_cpu[:self.num_reqs_max_model_len, : + self.max_num_blocks_per_req] + block_tables[:num_reqs, :self.max_num_blocks_per_req] = ( + self.input_batch.block_table[0].get_cpu_tensor()[:num_reqs]) + query_start_loc = self.query_start_loc_cpu[:self. + num_reqs_max_model_len + + 1].to(self.device) + seq_lens = self.seq_lens_cpu[:self.num_reqs_max_model_len].to( + self.device) + else: + block_tables = self.block_table_cpu[:self. + num_reqs_most_model_len, :self. + num_blocks_per_most_len_req] + block_tables[:num_reqs, :self.num_blocks_per_most_len_req] = ( + self.input_batch.block_table[0].get_cpu_tensor() + [:num_reqs, :self.num_blocks_per_most_len_req]) + query_start_loc = self.query_start_loc_cpu[:self. + num_reqs_most_model_len + + 1].to(self.device) + seq_lens = self.seq_lens_cpu[:self.num_reqs_most_model_len].to( + self.device) + block_tables = block_tables.to(self.device) + + # Calculate the slot mapping + slot_mapping_metadata = self._get_slot_mapping_metadata( + num_reqs, num_scheduled_tokens_per_req) + num_kv_update_slices = slot_mapping_metadata.shape[0] + padded_num_slices = _get_padded_num_kv_cache_update_slices( + padded_total_num_scheduled_tokens, self.max_num_reqs, + self.block_size) + slot_mapping_metadata = np.pad( + slot_mapping_metadata, + [[0, padded_num_slices - len(slot_mapping_metadata)], [0, 0]], + constant_values=0) + slot_mapping_metadata = np.transpose(slot_mapping_metadata) + slot_mapping_metadata = torch.tensor(slot_mapping_metadata, + device=self.device) + + if self.lora_config is not None: + # We need to respect padding when activating LoRA adapters + padded_num_scheduled_tokens_per_req = np.copy( + num_scheduled_tokens_per_req + ) # Copying to avoid accidental state corruption bugs + padded_num_scheduled_tokens_per_req[-1] += \ + padded_total_num_scheduled_tokens - total_num_scheduled_tokens + + self.set_active_loras(self.input_batch, + padded_num_scheduled_tokens_per_req) + + attn_metadata = PallasMetadata( + slot_mapping=slot_mapping_metadata, + block_tables=block_tables, + context_lens=seq_lens, + query_start_loc=query_start_loc, + num_seqs=torch.tensor([num_reqs], + dtype=torch.int32, + device=self.device), + num_kv_update_slices=torch.tensor([num_kv_update_slices], + dtype=torch.int32, + device=self.device), + num_slices_per_kv_cache_update_block=self. + _num_slices_per_kv_cache_update_block, + ) + # NOTE(woosuk): Due to chunked prefills, there can be at most 1 partial + # request in the batch. While we should not sample any token from this + # partial request, we do so for simplicity. We will ignore the sampled + # token from the partial request. + # TODO: Support prompt logprobs. + padded_num_reqs = _get_padded_num_reqs_with_upper_limit( + num_reqs, self.max_num_reqs) + # Indices at which we sample (positions of last token in the sequence). + # Padded to avoid recompiling when `num_reqs` varies. + logits_indices = self.query_start_loc_cpu[1:padded_num_reqs + 1] - 1 + logits_indices = logits_indices.to(self.device) + + if self.lora_config is not None: + # We need to respect padding when activating LoRA adapters + padded_num_scheduled_tokens_per_req = np.copy( + num_scheduled_tokens_per_req + ) # Copying to avoid accidental state corruption bugs + padded_num_scheduled_tokens_per_req[-1] += \ + padded_total_num_scheduled_tokens - total_num_scheduled_tokens + + self.set_active_loras(self.input_batch, + padded_num_scheduled_tokens_per_req) + + layer_names = get_layers_from_vllm_config(self.vllm_config, + Attention).keys() + per_layer_attn_metadata = { + layer_name: attn_metadata + for layer_name in layer_names + } + return per_layer_attn_metadata, logits_indices, padded_num_reqs,\ + num_reqs, end_index + + def _scatter_placeholders( + self, + embeds: torch.Tensor, + is_embed: Optional[torch.Tensor], + ) -> torch.Tensor: + if is_embed is None: + return embeds + + placeholders = embeds.new_full( + (is_embed.shape[0], embeds.shape[-1]), + fill_value=torch.nan, + ) + placeholders[is_embed] = embeds + return placeholders + + def _gather_placeholders( + self, + placeholders: torch.Tensor, + is_embed: Optional[torch.Tensor], + ) -> torch.Tensor: + if is_embed is None: + return placeholders + + return placeholders[is_embed] + + def _execute_mm_encoder(self, scheduler_output: "SchedulerOutput"): + scheduled_encoder_inputs = scheduler_output.scheduled_encoder_inputs + if not scheduled_encoder_inputs: + return + + # Batch the multi-modal inputs. + mm_kwargs = list[MultiModalKwargsItem]() + req_ids_pos = list[tuple[str, int, PlaceholderRange]]() + for req_id, encoder_input_ids in scheduled_encoder_inputs.items(): + req_state = self.requests[req_id] + + for mm_input_id in encoder_input_ids: + mm_kwargs.append(req_state.mm_kwargs[mm_input_id]) + req_ids_pos.append( + (req_id, mm_input_id, req_state.mm_positions[mm_input_id])) + + # Batch mm inputs as much as we can: if a request in the batch has + # multiple modalities or a different modality than the previous one, + # we process it separately to preserve item order. + # FIXME(ywang96): This is a hacky way to deal with multiple modalities + # in the same batch while still being able to benefit from batching + # multimodal inputs. The proper solution should be reordering the + # encoder outputs. + encoder_outputs = [] + for _, num_items, mm_kwargs_group in group_mm_kwargs_by_modality( + mm_kwargs, + device=self.device, + pin_memory=self.pin_memory, + ): + # Run the encoder. + # `curr_group_outputs` is either of the following: + # 1. A tensor of shape (num_items, feature_size, hidden_size) + # in case feature_size is fixed across all multimodal items. + # 2. A list or tuple (length: num_items) of tensors, each of shape + # (feature_size, hidden_size) in case the feature size is dynamic + # depending on the input multimodal items. + xm.mark_step() + curr_group_outputs = self.model.get_multimodal_embeddings( + **mm_kwargs_group) + xm.mark_step() + + sanity_check_mm_encoder_outputs( + curr_group_outputs, + expected_num_items=num_items, + ) + + if isinstance(curr_group_outputs, torch.Tensor): + encoder_outputs.append(curr_group_outputs) + else: + assert isinstance(curr_group_outputs, (list, tuple)) + for output in curr_group_outputs: + encoder_outputs.append(output) + + # Cache the encoder outputs. + # NOTE (NickLucche) here we diverge from logic in other runners, as we + # assume to only have whole mm items to process. Hence we avoid the + # intrinsic dynamism that `scatter_mm_placeholders` introduces. + for (req_id, input_id, pos_info), output in zip( + req_ids_pos, + encoder_outputs, + ): + if req_id not in self.encoder_cache: + self.encoder_cache[req_id] = {} + assert pos_info.is_embed is None, "Expected all positions to be"\ + " contiguous and embeddings." + self.encoder_cache[req_id][input_id] = output + + def _gather_mm_embeddings( + self, + scheduler_output: "SchedulerOutput", + ) -> list[torch.Tensor]: + mm_embeds: list[torch.Tensor] = [] + for req_id in self.input_batch.req_ids: + num_scheduled_tokens = scheduler_output.num_scheduled_tokens[ + req_id] + req_state = self.requests[req_id] + num_computed_tokens = req_state.num_computed_tokens + mm_positions = req_state.mm_positions + # TODO unroll loop and assume/enforce --disable_chunked_mm_input + # NOTE (NickLucche) here we diverge from logic in other runners, as + # we assume to only have whole mm items to process. Hence we avoid + # the intrinsic dynamism that `gather_mm_placeholders` introduces. + for i, pos_info in enumerate(mm_positions): + start_pos = pos_info.offset + num_encoder_tokens = pos_info.length + + # The encoder output is needed if the two ranges overlap: + # [num_computed_tokens, + # num_computed_tokens + num_scheduled_tokens) and + # [start_pos, start_pos + num_encoder_tokens) + if start_pos >= num_computed_tokens + num_scheduled_tokens: + # The encoder output is not needed in this step. + break + if start_pos + num_encoder_tokens <= num_computed_tokens: + # The encoder output is already processed and stored + # in the decoder's KV cache. + continue + + assert req_id in self.encoder_cache + assert i in self.encoder_cache[req_id] + assert pos_info.is_embed is None, "Expected all positions to"\ + " be contiguous and embeddings." + encoder_output = self.encoder_cache[req_id][i] + mm_embeds.append(encoder_output) + return mm_embeds + + def _get_model_inputs(self, input_ids: torch.Tensor, + mm_embeds: list[torch.Tensor]): + if self.supports_mm_inputs: + # NOTE(woosuk): To unify token ids and soft tokens (vision + # embeddings), we always use embeddings (rather than token ids) + # as input to the multimodal model, even when the input is text. + inputs_embeds = self.model.get_input_embeddings( + input_ids=input_ids, + multimodal_embeddings=mm_embeds, + ) + return None, inputs_embeds + else: + # For text-only models, we use token ids as input. + # While it is possible to use embeddings as input just like the + # multimodal models, it is not desirable for performance since + # then the embedding layer is not included in the CUDA graph. + return input_ids, None + + @torch.no_grad() + def execute_model( + self, + scheduler_output: "SchedulerOutput", + intermediate_tensors: Optional[IntermediateTensors] = None, + ) -> ModelRunnerOutput: + # Update cached state + self._update_states(scheduler_output) + if not scheduler_output.total_num_scheduled_tokens: + if not has_kv_transfer_group(): + # Return empty ModelRunnerOutput if there's no work to do. + return EMPTY_MODEL_RUNNER_OUTPUT + + return self.kv_connector_no_forward(scheduler_output, + self.vllm_config) + + if self.supports_mm_inputs: + # Run the multimodal encoder if any. + self._execute_mm_encoder(scheduler_output) + mm_embeds = self._gather_mm_embeddings(scheduler_output) + else: + mm_embeds = [] + xm.mark_step() + # Prepare inputs, the requests might be split into multiple + # executions, combine the result of each execution. + start_index = 0 + combined_selected_tokens: list[torch.Tensor] = [] + combined_logprobs: list[LogprobsLists] = [] + + # NOTE: setup current batch's metadata for kv connector. + # Currently, only verified with NixlConnector + with set_forward_context(None, self.vllm_config): + self.maybe_setup_kv_connector(scheduler_output) + + while start_index < self.input_batch.num_reqs: + attn_metadata, logits_indices, padded_num_reqs, num_reqs,\ + end_index = self._prepare_inputs(scheduler_output, start_index) + input_ids, inputs_embeds = self._get_model_inputs( + self.input_ids, mm_embeds) + xm.mark_step() + # Run the decoder + with set_forward_context( + attn_metadata, + self.vllm_config, + num_tokens=scheduler_output.total_num_scheduled_tokens): + hidden_states = self.model( + input_ids=input_ids, + positions=self.position_ids, + inputs_embeds=inputs_embeds, + ) + hidden_states = self.select_hidden_states(hidden_states, + logits_indices) + logits = self.compute_logits(hidden_states) + tpu_sampling_metadata = TPUSupportedSamplingMetadata.\ + from_input_batch(self.input_batch, padded_num_reqs, self.device) + if scheduler_output.grammar_bitmask is not None: + require_struct_decoding, grammar_bitmask_padded, arange = \ + self.prepare_structured_decoding_input(logits, + scheduler_output) + logits = self.structured_decode(require_struct_decoding, + grammar_bitmask_padded, logits, + arange) + selected_token_ids = self.sample_from_logits_func( + logits, tpu_sampling_metadata) + # NOTE (NickLucche) Use the original logits (before any penalties or + # temperature scaling) for the top-k logprobs. We can't enforce it + # due to recompilations outside torch.compiled code, so just make + # sure `sample_from_logits` does not modify the logits in-place. + logprobs = self.gather_logprobs(logits, selected_token_ids) \ + if tpu_sampling_metadata.logprobs else None + + # Remove padding on cpu and keep dynamic op outside of xla graph. + selected_token_ids = selected_token_ids.cpu()[:num_reqs] + + combined_selected_tokens.append(selected_token_ids) + if tpu_sampling_metadata.logprobs: + combined_logprobs.append(logprobs.tolists()) + + start_index = end_index + + # NOTE: current kv load and save get h2d/d2h copies involved. + # Those copies are blocking. Once they become async., kv_save + # should be called right after each single forward pass, + # instead of the forwards of the entire input batch. + self.maybe_wait_for_kv_save() + finished_sending, finished_recving = ( + self.get_finished_kv_transfers(scheduler_output)) + + selected_token_ids = torch.cat(combined_selected_tokens, dim=0) + if tpu_sampling_metadata.logprobs: + + def concat_lists(input_lists): + result = [] + for input_list in input_lists: + result.extend(input_list) + return result + + logprobs_lists = LogprobsLists(logprob_token_ids=concat_lists( + [lp.logprob_token_ids for lp in combined_logprobs]), + logprobs=concat_lists([ + lp.logprobs + for lp in combined_logprobs + ]), + sampled_token_ranks=concat_lists([ + lp.sampled_token_ranks + for lp in combined_logprobs + ])) + else: + logprobs_lists = None + + # Update the cache state concurrently. Code above will not block until + # we use `selected_token_ids`. Add mark_step if post-processing changes + request_seq_lens: list[tuple[int, CachedRequestState, int]] = [] + discard_sampled_tokens_req_indices = [] + num_reqs = self.input_batch.num_reqs + for i, req_id in zip(range(num_reqs), self.input_batch.req_ids): + assert req_id is not None + req_state = self.requests[req_id] + seq_len = (req_state.num_computed_tokens + + scheduler_output.num_scheduled_tokens[req_id]) + if seq_len >= req_state.num_tokens: + request_seq_lens.append((i, req_state, seq_len)) + else: + # Ignore the sampled token from the partial request. + # Rewind the generator state as if the token was not sampled. + generator = self.input_batch.generators.get(i) + if generator is not None: + # This relies on cuda-specific torch-internal impl details + generator.set_offset(generator.get_offset() - 4) + + # Record the index of the request that should not be sampled, + # so that we could clear the sampled tokens before returning. + discard_sampled_tokens_req_indices.append(i) + + assert all( + req_id is not None for req_id in + self.input_batch.req_ids[:num_reqs]), "req_ids contains None" + req_ids = cast(list[str], self.input_batch.req_ids[:num_reqs]) + + prompt_logprobs_dict: dict[str, Optional[LogprobsTensors]] = {} + for req_id in self.input_batch.req_ids[:num_reqs]: + prompt_logprobs_dict[req_id] = None + + max_gen_len = selected_token_ids.shape[-1] + if max_gen_len == 1: + valid_sampled_token_ids = selected_token_ids.tolist() + + # Mask out the sampled tokens that should not be sampled. + # TODO: Keep in sync with gpu_model_runner.py, in particular + # the "else" case here + for i in discard_sampled_tokens_req_indices: + valid_sampled_token_ids[i].clear() + + # Append sampled tokens + for i, req_state, seq_len in request_seq_lens: + token_id = valid_sampled_token_ids[i][0] + self.input_batch.token_ids_cpu[i, seq_len] = token_id + req_state.output_token_ids.append(token_id) + self.input_batch.num_tokens[i] += 1 + + else: + valid_mask = selected_token_ids != INVALID_TOKEN_ID + gen_lens = valid_mask.sum(dim=1).tolist() + valid_sampled_token_ids = [ + seq.tolist() + for seq in selected_token_ids[valid_mask].split(gen_lens) + ] + self.input_batch.num_tokens[:num_reqs] += gen_lens + for i, req_state, seq_len in request_seq_lens: + target_slice = slice(seq_len - gen_lens[i] + 1, seq_len + 1) + self.input_batch.token_ids_cpu[ + i, target_slice] = valid_sampled_token_ids[i] + req_state.output_token_ids.extend(valid_sampled_token_ids[i]) + + kv_connector_output = None if ( + finished_sending is None + and finished_recving is None) else KVConnectorOutput( + finished_sending=finished_sending, + finished_recving=finished_recving, + ) + + model_runner_output = ModelRunnerOutput( + req_ids=req_ids, + req_id_to_index=self.input_batch.req_id_to_index, + sampled_token_ids=valid_sampled_token_ids, + spec_token_ids=None, + logprobs=logprobs_lists, + prompt_logprobs_dict=prompt_logprobs_dict, + pooler_output=[], + kv_connector_output=kv_connector_output, + ) + + # Check there are no new graphs compiled - all the graphs should be + # captured and compiled during warm up. + self._verify_num_xla_graphs("execute_model") + + return model_runner_output + + def update_config(self, overrides: dict[str, Any]) -> None: + # TODO: TPU config may need extra validation + # https://github.com/vllm-project/vllm/pull/20095#discussion_r2201497754 + allowed_config_names = {"load_config", "model_config"} + for config_name, config_overrides in overrides.items(): + assert config_name in allowed_config_names, \ + f"Config `{config_name}` not supported. " \ + f"Allowed configs: {allowed_config_names}" + config = getattr(self, config_name) + new_config = update_config(config, config_overrides) + setattr(self, config_name, new_config) + + def load_model(self) -> None: + self.device = self.device_config.device + + # NOTE(woosuk): While the executor assigns the TP ranks to the worker + # process, the ranks can be different from the ranks internally assigned + # by the xm runtime. Therefore, there is a mismatch in the rank + # assignment between the gloo (cpu) runtime and the xm (tpu) runtime. + # This is not a problem in linear layers because all-reduce is + # rank-agnostic. However, it matters for all-gather as the ranks + # determine the order of concatenating the output tensors. + # As a workaround, we use the xm's rank assignment only when loading + # the embedding weights. + xm_tp_rank = xr.global_ordinal() + with patch( + "vllm.model_executor.layers.vocab_parallel_embedding." + "get_tensor_model_parallel_rank", + return_value=xm_tp_rank): + try: + if self.use_spmd: + tpu_loader = TPUModelLoader( + load_config=self.vllm_config.load_config) + model = tpu_loader.load_model( + vllm_config=self.vllm_config, + model_config=self.vllm_config.model_config, + mesh=self.mesh) + else: + model_loader = get_model_loader(self.load_config) + logger.info("Loading model from scratch...") + model = model_loader.load_model( + vllm_config=self.vllm_config, + model_config=self.model_config) + except RuntimeError as e: + raise RuntimeError( + f"Unable to load model, a likely reason is the model is " + "too large for the current device's HBM memory. " + "Consider switching to a smaller model " + "or sharding the weights on more chips. " + f"See the detailed error: {e}") from e + if self.lora_config is not None: + model = self.load_lora_model(model, self.model_config, + self.scheduler_config, + self.lora_config, self.device) + replace_set_lora(model) + + # Sync all pending XLA execution during model initialization and weight + # loading. + xm.mark_step() + xm.wait_device_ops() + if not hasattr(self, "model"): + self.model = model + self.sampler = TPUSampler() + + def reload_weights(self) -> None: + assert getattr(self, "model", None) is not None, \ + "Cannot reload weights before model is loaded." + model_loader = get_model_loader(self.load_config) + logger.info("Reloading weights inplace...") + model_loader.load_weights(self.model, model_config=self.model_config) + + @torch.no_grad() + def _dummy_run(self, num_tokens: int, num_reqs: int, + num_blocks: int) -> None: + if self.supports_mm_inputs: + input_ids = None + inputs_embeds = torch.zeros((num_tokens, self.hidden_size), + dtype=self.dtype, + device=self.device) + else: + input_ids = torch.zeros((num_tokens), + dtype=torch.int32).to(self.device) + inputs_embeds = None + actual_num_reqs = min(num_tokens, num_reqs) + position_ids = torch.zeros(num_tokens, + dtype=torch.int32).to(self.device) + padded_num_slices = _get_padded_num_kv_cache_update_slices( + num_tokens, self.max_num_reqs, self.block_size) + num_kv_update_slices = torch.tensor([padded_num_slices], + dtype=torch.int32).to(self.device) + slot_mapping = torch.zeros((3, padded_num_slices), + dtype=torch.int32).to(self.device) + block_tables = torch.zeros((num_reqs, num_blocks), + dtype=torch.int32).to(self.device) + query_lens = [1] * num_reqs + query_start_loc = torch.cumsum(torch.tensor([0] + query_lens, + dtype=torch.int32), + dim=0, + dtype=torch.int32).to(self.device) + context_lens = torch.ones((num_reqs, ), + dtype=torch.int32).to(self.device) + num_seqs = torch.tensor([actual_num_reqs], + dtype=torch.int32).to(self.device) + attn_metadata = PallasMetadata( + slot_mapping=slot_mapping, + block_tables=block_tables, + context_lens=context_lens, + query_start_loc=query_start_loc, + num_seqs=num_seqs, + num_kv_update_slices=num_kv_update_slices, + num_slices_per_kv_cache_update_block=self. + _num_slices_per_kv_cache_update_block, + ) + + if self.supports_mm_inputs: + torch._dynamo.mark_dynamic(inputs_embeds, 0) + else: + torch._dynamo.mark_dynamic(input_ids, 0) + torch._dynamo.mark_dynamic(position_ids, 0) + torch._dynamo.mark_dynamic(attn_metadata.slot_mapping, 0) + torch._dynamo.mark_dynamic(attn_metadata.block_tables, (0, 1)) + torch._dynamo.mark_dynamic(attn_metadata.context_lens, 0) + torch._dynamo.mark_dynamic(attn_metadata.query_start_loc, 0) + + layer_names = get_layers_from_vllm_config(self.vllm_config, + Attention).keys() + per_layer_attn_metadata = { + layer_name: attn_metadata + for layer_name in layer_names + } + + with self.maybe_select_dummy_loras( + self.lora_config, + np.array([num_tokens], dtype=np.int32)), set_forward_context( + per_layer_attn_metadata, self.vllm_config, 0): + out = self.model(input_ids=input_ids, + positions=position_ids, + inputs_embeds=inputs_embeds) + self._hidden_states_dtype = out.dtype + + def _set_active_loras(self, prompt_lora_mapping, token_lora_mapping, + lora_requests) -> None: + xm.mark_step() # Captures input updates + super()._set_active_loras(prompt_lora_mapping, token_lora_mapping, + lora_requests) + xm.mark_step() # Captures metadata updates + + def _precompile_mm_encoder(self) -> None: + if not self.supports_mm_inputs: + return + + # Pre-compile MM encoder for all supported data modalities. + hf_config = self.vllm_config.model_config.hf_config + + mm_budget = self.mm_budget + assert mm_budget is not None + + max_items_per_seq_by_modality = mm_budget.max_items_per_batch_by_modality # noqa: E501 + + for mode, max_items_per_seq in max_items_per_seq_by_modality.items(): + logger.info( + "Compiling Multimodal %s Encoder with different input" + " shapes.", mode) + start = time.perf_counter() + # No padding for MM encoder just yet. + for num_items in range(1, max_items_per_seq + 1): + logger.info(" -- mode: %s items: %d", mode, num_items) + batched_dummy_mm_inputs = self._get_mm_dummy_batch( + mode, + num_items, + ) + # Run multimodal encoder. + xm.mark_step() + mm_embeds = self.model.get_multimodal_embeddings( + **batched_dummy_mm_inputs) + xm.mark_step() + num_patches = mm_embeds[0].shape[0] + items_size = num_patches * num_items + + # NOTE (NickLucche) pre-compile `get_input_embeddings` when mm + # embeddings are present. We assume `--disable-mm-chunked`, + # hence only whole items can be scheduled. This implies we just + # need to compile when `num_items` fit the (padded) `input_ids` + for num_tokens in self.num_tokens_paddings: + if num_tokens >= items_size: + # XLA Workaround: if torch.zeros(..device) is used, XLA + # compiles a scalar+expansion op, which won't match + # the graph generated at runtime. CPU->TPU must be used + placeholders_ids = torch.zeros(num_tokens, + dtype=torch.int32, + device="cpu") + # Align placeholders and actual num mm_embeddings. + placeholders_ids[:items_size] = \ + hf_config.image_token_index + + placeholders_ids = placeholders_ids.to(self.device) + # Assign outputs or the graph will be cut short. + a, b = self._get_model_inputs(placeholders_ids, + [mm_embeds]) + assert a is None + xm.mark_step() + + # Pre-compile `get_input_embeddings` when mm_embeddings are not + # present. Chunk is only made of text, no mm_placeholders. + for num_tokens in self.num_tokens_paddings: + placeholders_ids = torch.zeros(num_tokens, + dtype=torch.int32, + device="cpu") + placeholders_ids = placeholders_ids.to(self.device) + a, b = self._get_model_inputs(placeholders_ids, []) + assert a is None + xm.mark_step() + + xm.wait_device_ops() + end = time.perf_counter() + logger.info( + "Multimodal %s Encoder compilation finished in in %.2f " + "[secs].", mode, end - start) + + def _precompile_backbone(self) -> None: + logger.info("Compiling the model with different input shapes.") + start = time.perf_counter() + for num_tokens in self.num_tokens_paddings: + logger.info(" -- num_tokens: %d", num_tokens) + self._dummy_run(num_tokens, self.num_reqs_max_model_len, + self.max_num_blocks_per_req) + if self.most_model_len is not None: + self._dummy_run(num_tokens, self.num_reqs_most_model_len, + self.num_blocks_per_most_len_req) + xm.wait_device_ops() + end = time.perf_counter() + logger.info("Compilation finished in %.2f [secs].", end - start) + self._update_num_xla_graphs("model backbone") + + def _precompile_select_hidden_states(self) -> None: + # Compile hidden state selection function for bucketed + # n_tokens x max_num_reqs. Graph is really small so this is fine. + logger.info( + "Compiling select_hidden_states with different input shapes.") + start = time.perf_counter() + hsize = self.model_config.get_hidden_size() + for num_tokens in self.num_tokens_paddings: + dummy_hidden = torch.zeros((num_tokens, hsize), + device=self.device, + dtype=self._hidden_states_dtype) + torch._dynamo.mark_dynamic(dummy_hidden, 0) + for num_reqs in self.num_reqs_paddings: + indices = torch.zeros(num_reqs, + dtype=torch.int32, + device=self.device) + torch._dynamo.mark_dynamic(indices, 0) + self.select_hidden_states(dummy_hidden, indices) + logger.info(" -- num_tokens: %d, num_seqs: %d", num_tokens, + num_reqs) + # Requests can't be more than tokens. But do compile for the + # next bigger value in case num_tokens uses bucketed padding. + if num_reqs >= min(num_tokens, self.max_num_reqs): + break + xm.wait_device_ops() + end = time.perf_counter() + logger.info("Compilation finished in %.2f [secs].", end - start) + self._update_num_xla_graphs("select_hidden_states") + + def _precompile_compute_logits(self) -> None: + logger.info("Compiling compute_logits with different input shapes.") + start = time.perf_counter() + hsize = self.model_config.get_hidden_size() + for num_reqs in self.num_reqs_paddings: + dummy_hidden = torch.zeros((num_reqs, hsize), + device=self.device, + dtype=self._hidden_states_dtype) + torch._dynamo.mark_dynamic(dummy_hidden, 0) + self.compute_logits(dummy_hidden) + logger.info(" -- num_seqs: %d", num_reqs) + xm.wait_device_ops() + end = time.perf_counter() + logger.info("Compilation finished in %.2f [secs].", end - start) + self._update_num_xla_graphs("compute_logits") + + def _precompile_structured_decoding(self) -> None: + logger.info( + "Compiling structured_decoding with different input shapes.") + start = time.perf_counter() + for num_reqs in self.num_reqs_paddings: + dummy_logits = torch.zeros((num_reqs, self.vocab_size), + device=self.device, + dtype=self._hidden_states_dtype) + dummy_require_struct_decoding = \ + self.require_structured_out_cpu[:num_reqs].to(self.device) + dummy_grammar_bitmask = \ + self.grammar_bitmask_cpu[:num_reqs].to(self.device) + # The first dimension of the above 3 dummy tensors cannot be + # mark_dynamic because some operations in structured_decode require + # them to be static. + arange = self.structured_decode_arange.to(self.device) + self.structured_decode(dummy_require_struct_decoding, + dummy_grammar_bitmask, dummy_logits, arange) + logger.info(" -- num_seqs: %d", num_reqs) + xm.wait_device_ops() + end = time.perf_counter() + logger.info("Compilation finished in %.2f [secs].", end - start) + self._update_num_xla_graphs("structured_decoding") + + def _precompile_sample_from_logits(self) -> None: + logger.info( + "Compiling sample_from_logits with different input shapes.") + start = time.perf_counter() + for num_reqs in self.num_reqs_paddings: + dummy_logits = torch.zeros((num_reqs, self.vocab_size), + device=self.device, + dtype=self._hidden_states_dtype) + # The first dimension of dummy_logits cannot be mark_dynamic + # because some operations in the sampler require it to be static. + for all_greedy in [False, True]: + generate_params_if_all_greedy = not all_greedy + sampling_metadata = ( + TPUSupportedSamplingMetadata.from_input_batch( + self.input_batch, + num_reqs, + self.device, + generate_params_if_all_greedy, + )) + sampling_metadata.all_greedy = all_greedy + with self.maybe_select_dummy_loras( + self.lora_config, np.array([num_reqs], + dtype=np.int32)): + self.sample_from_logits_func(dummy_logits, + sampling_metadata) + logger.info(" -- num_seqs: %d", num_reqs) + xm.wait_device_ops() + end = time.perf_counter() + logger.info("Compilation finished in %.2f [secs].", end - start) + self._update_num_xla_graphs("sample_from_logits") + + def _precompile_gather_logprobs(self) -> None: + logger.info("Compiling gather_logprobs with different input shapes.") + start = time.perf_counter() + for num_reqs in self.num_reqs_paddings: + dummy_logits = torch.zeros((num_reqs, self.vocab_size), + device=self.device, + dtype=self._hidden_states_dtype) + dummy_tokens = torch.zeros((num_reqs, 1), + dtype=torch.int64).to(self.device) + with self.maybe_select_dummy_loras( + self.lora_config, np.array([num_reqs], dtype=np.int32)): + self.gather_logprobs(dummy_logits, dummy_tokens) + logger.info(" -- num_seqs: %d", num_reqs) + xm.wait_device_ops() + end = time.perf_counter() + logger.info("Compilation finished in %.2f [secs].", end - start) + self._update_num_xla_graphs("gather_logprobs") + + def capture_model(self) -> None: + """ + Precompile all the subgraphs with possible input shapes. + """ + with self.maybe_setup_dummy_loras(self.lora_config): + self._precompile_mm_encoder() + self._precompile_backbone() + self._precompile_select_hidden_states() + self._precompile_compute_logits() + self._precompile_structured_decoding() + self._precompile_sample_from_logits() + self._precompile_gather_logprobs() + + def profile_run( + self, + num_tokens: int, + ) -> None: + # Profile with multimodal encoder & encoder cache. + if self.supports_mm_inputs: + if self.model_config.multimodal_config.skip_mm_profiling: + logger.info( + "Skipping memory profiling for multimodal encoder and " + "encoder cache.") + else: + mm_budget = self.mm_budget + assert mm_budget is not None + + # TODO: handle encoder-decoder models once we support them. + if (encoder_budget := mm_budget.get_encoder_budget()) > 0: + # NOTE: Currently model is profiled with a single non-text + # modality with the max possible input tokens even when + # it supports multiple. + ( + dummy_modality, + max_tokens, + ) = mm_budget.get_modality_with_max_tokens() + ( + max_mm_items_per_prompt, + max_mm_items_per_batch, + ) = mm_budget.get_max_items(dummy_modality, max_tokens) + + logger.info( + "Encoder cache will be initialized with a budget of " + "%s tokens, and profiled with %s %s items of the " + "maximum feature size.", + encoder_budget, + max_mm_items_per_batch, + dummy_modality, + ) + + # Create dummy batch of multimodal inputs. + batched_dummy_mm_inputs = self._get_mm_dummy_batch( + dummy_modality, + max_mm_items_per_batch, + ) + + # Run multimodal encoder. + # Isolate encoder graph from post-processing to minimize + # impact of recompilation until it's fixed. + start = time.perf_counter() + xm.mark_step() + dummy_encoder_outputs = \ + self.model.get_multimodal_embeddings( + **batched_dummy_mm_inputs) + xm.mark_step() + xm.wait_device_ops() + end = time.perf_counter() + logger.info( + "Multimodal Encoder profiling finished in %.2f [secs].", + end - start) + + sanity_check_mm_encoder_outputs( + dummy_encoder_outputs, + expected_num_items=max_mm_items_per_batch, + ) + + # Cache the dummy encoder outputs. + self.encoder_cache["tmp"] = dict( + enumerate(dummy_encoder_outputs)) + + # Trigger compilation for general shape. + self._dummy_run(num_tokens, self.num_reqs_max_model_len, + self.max_num_blocks_per_req) + if self.most_model_len is not None: + self._dummy_run(num_tokens, self.num_reqs_most_model_len, + self.num_blocks_per_most_len_req) + + xm.mark_step() + xm.wait_device_ops() + self.encoder_cache.clear() + gc.collect() + + def initialize_kv_cache(self, kv_cache_config: KVCacheConfig) -> None: + """ + Initialize KV cache based on `kv_cache_config`. + Args: + kv_cache_config: Configuration for the KV cache, including the KV + cache size of each layer + """ + if len(kv_cache_config.kv_cache_groups) > 1: + raise NotImplementedError( + "Hybrid models with more than one KV cache type are not " + "supported yet.") + + if kv_cache_config.kv_cache_groups[ + 0].kv_cache_spec.block_size != self.block_size: + self.input_batch = InputBatch( + max_num_reqs=self.max_num_reqs, + max_model_len=self.max_model_len, + max_num_batched_tokens=self.max_num_tokens, + device=self.device, + pin_memory=self.pin_memory, + vocab_size=self.model_config.get_vocab_size(), + block_sizes=[ + kv_cache_config.kv_cache_groups[0].kv_cache_spec.block_size + ], + ) + # Verify dtype compatibility between block_table_cpu and input_batch + assert self.block_table_cpu.dtype == self.input_batch.block_table[ + 0].get_cpu_tensor().dtype + + kv_cache_sizes = {} + for kv_cache_tensor in kv_cache_config.kv_cache_tensors: + assert len(kv_cache_tensor.shared_by) == 1, ( + "KV cache tensor shared by multiple layers is not supported in " + "TPU.") + kv_cache_sizes[kv_cache_tensor.shared_by[0]] = kv_cache_tensor.size + + kv_caches: dict[str, torch.Tensor] = {} + for kv_cache_group in kv_cache_config.kv_cache_groups: + kv_cache_spec = kv_cache_group.kv_cache_spec + for layer_name in kv_cache_group.layer_names: + tensor_size = kv_cache_sizes[layer_name] + assert tensor_size % kv_cache_spec.page_size_bytes == 0 + num_blocks = tensor_size // kv_cache_spec.page_size_bytes # noqa + if isinstance(kv_cache_spec, AttentionSpec): + if self.use_spmd: + num_kv_heads = kv_cache_spec.num_kv_heads + assert self.original_parallel_config is not None + tp_size = \ + self.original_parallel_config.tensor_parallel_size + # TODO: Handle kv cache duplication under SPMD mode. + assert num_kv_heads % tp_size == 0, ( + f"num_kv_heads {num_kv_heads} must be divisible by " + f"tp_size {tp_size} under SPMD mode") + kv_cache_shape = PallasAttentionBackend.get_kv_cache_shape( + num_blocks, kv_cache_spec.block_size, + kv_cache_spec.num_kv_heads, kv_cache_spec.head_size) + dtype = kv_cache_spec.dtype + + tpu_kv_cache = torch.zeros(kv_cache_shape, + dtype=dtype).to(self.device) + + kv_caches[layer_name] = tpu_kv_cache + else: + raise NotImplementedError + + # Setup `kv_cache_config` and `kv_caches` for models + # with cross-layer KV sharing + if self.shared_kv_cache_layers: + initialize_kv_cache_for_kv_sharing( + self.shared_kv_cache_layers, + kv_cache_config.kv_cache_groups, + kv_caches, + ) + + bind_kv_cache( + kv_caches, + self.vllm_config.compilation_config.static_forward_context, + self.kv_caches) + + if self.use_spmd: + # Shard KV Cache + for cache in self.kv_caches: + xs.mark_sharding(cache, self.mesh, (None, 'x', None, None)) + + if has_kv_transfer_group(): + get_kv_transfer_group().register_kv_caches(kv_caches) + get_kv_transfer_group().set_host_xfer_buffer_ops(copy_kv_blocks) + + def reset_dynamo_cache(self): + + # NOTE: We check `is_multimodal_model` instead of `supports_mm_inputs` + # since the compiled model object of the language backbone of a + # multimodal model needs to be extracted via `get_language_model`. + if self.model_config.is_multimodal_model: + compiled_model = self.model.get_language_model().model + else: + compiled_model = self.model.model + if isinstance(compiled_model, TorchCompileWrapperWithCustomDispatcher): + logger.info("Clear dynamo cache and cached dynamo bytecode.") + torch._dynamo.eval_frame.remove_from_cache( + compiled_model.original_code_object) + compiled_model.compiled_codes.clear() + + @torch.compile(backend="openxla", fullgraph=True, dynamic=False) + def select_hidden_states(self, hidden_states, indices_do_sample): + return hidden_states[indices_do_sample] + + @torch.compile(backend="openxla", fullgraph=True, dynamic=False) + def compute_logits(self, + sample_hidden_states: torch.Tensor) -> torch.Tensor: + return self.model.compute_logits(sample_hidden_states, None) + + # TODO: Under SPMD mode, sample_from_logits has correctness issue. + # Re-enable the torch.compile once the issue is fixed in torchxla. + # @torch.compile(backend="openxla", fullgraph=True, dynamic=False) + def sample_from_logits( + self, logits: torch.Tensor, + sampling_metadata: TPUSupportedSamplingMetadata) -> torch.Tensor: + """ + Sample with xla-friendly function. This function is to be traced + separately from `forward` for lighter compilation overhead. + """ + if sampling_metadata.all_greedy: + out_tokens = torch.argmax(logits, dim=-1, keepdim=True) + else: + out_tokens = self.sampler(logits, + sampling_metadata).sampled_token_ids + return out_tokens + + @torch.compile(backend="openxla", fullgraph=True, dynamic=False) + def gather_logprobs(self, logits: torch.Tensor, + sampled_tokens: torch.Tensor) -> LogprobsTensors: + """ + Gather the top_logprobs with corresponding tokens. Use a fixed number + of logprobs as an alternative to having multiple pre-compiled graphs. + Select the number of logprobs actually demanded by each request on CPU. + """ + logprobs = self.sampler.compute_logprobs(logits) + return self.sampler.gather_logprobs( + logprobs, + self.model_config.max_logprobs, + token_ids=sampled_tokens.squeeze(-1)) + + @torch.compile(backend="openxla", fullgraph=True, dynamic=False) + def structured_decode(self, require_struct_decoding: torch.Tensor, + grammar_bitmask: torch.Tensor, logits: torch.Tensor, + arange: torch.Tensor) -> torch.Tensor: + return torch.where( + require_struct_decoding, + self.apply_grammar_bitmask(logits, grammar_bitmask, arange), + logits) + + def apply_grammar_bitmask(self, logits: torch.Tensor, + grammar_bitmask: torch.Tensor, + arange: torch.Tensor): + assert (logits.shape[0] == grammar_bitmask.shape[0]) + logits_cloned = logits.clone() + for i in range(logits.shape[0]): + unpacked_bitmask = (torch.bitwise_right_shift( + grammar_bitmask[i][:, None], arange[None, :]) & 1) == 0 + unpacked_bitmask = unpacked_bitmask.reshape(-1)[:self.vocab_size] + logits_cloned[i] = logits_cloned[i].masked_fill( + unpacked_bitmask, -float("inf")) + return logits_cloned + + def get_multimodal_embeddings(self, *args, **kwargs): + return self.model.get_multimodal_embeddings(*args, **kwargs) + + def get_input_embeddings(self, *args, **kwargs): + return self.model.get_input_embeddings(*args, **kwargs) + + def prepare_structured_decoding_input( + self, logits: torch.Tensor, scheduler_output: "SchedulerOutput" + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + grammar_bitmask = scheduler_output.grammar_bitmask + assert grammar_bitmask is not None + num_reqs, _ = logits.shape + + # Reset pre-allocated tensors + self.grammar_bitmask_cpu.zero_() + self.require_structured_out_cpu.zero_() + + # We receive the structured output bitmask from the scheduler, but the + # indices of the requests in the batch may not match the indices of + # the bitmask since the scheduler doesn't know how the tpu runner is + # ordering the requests in the batch. We need to match the order of + # bitmask with the order of requests + struct_out_indices: list[int] = [] + mask_indices: list[int] = [] + for req_id in self.input_batch.req_ids: + mask_index = scheduler_output.structured_output_request_ids.get( + req_id) + if mask_index is None: + continue + batch_index = self.input_batch.req_id_to_index[req_id] + struct_out_indices.append(batch_index) + mask_indices.append(mask_index) + self.grammar_bitmask_cpu[struct_out_indices] = torch.from_numpy( + grammar_bitmask[mask_indices]) + # It's not guaranteed that all requests in this batch require + # structured output, so create a bool tensor to represent + # the requests that need structured output. + struct_out_indices = torch.tensor(struct_out_indices, dtype=torch.long) + self.require_structured_out_cpu[struct_out_indices] = True + return self.require_structured_out_cpu[:num_reqs].to(logits.device), \ + self.grammar_bitmask_cpu[:num_reqs].to(logits.device), \ + self.structured_decode_arange.to(logits.device) + + def _get_mm_dummy_batch( + self, + modality: str, + max_items_per_batch: int, + ) -> BatchedTensorInputs: + """Dummy data for profiling and precompiling multimodal models.""" + dummy_decoder_data = self.mm_registry.get_decoder_dummy_data( + model_config=self.model_config, + seq_len=self.max_num_tokens, + mm_counts={modality: 1}, + ) + dummy_mm_data = dummy_decoder_data.multi_modal_data + + # Result in the maximum GPU consumption of the model + dummy_mm_item = dummy_mm_data.get_item(modality=modality, item_index=0) + + return next(grouped_mm_kwargs + for _, _, grouped_mm_kwargs in group_mm_kwargs_by_modality( + [dummy_mm_item] * max_items_per_batch, + device=self.device, + pin_memory=self.pin_memory, + )) + + +def _get_req_paddings(min_req_size: int, max_req_size: int) -> list[int]: + logger.info("Preparing request paddings:") + # assert min_req_size is power of 2 + assert (min_req_size & (min_req_size - 1) == 0) and min_req_size > 0 + paddings: list = [] + num = max(MIN_NUM_SEQS, min_req_size) + while num <= max_req_size and (len(paddings) == 0 or paddings[-1] != num): + paddings.append(num) + logger.info(" %d", num) + num = _get_padded_num_reqs_with_upper_limit(num + 1, max_req_size) + return paddings + + +def _get_padded_num_reqs_with_upper_limit(x: int, upper_limit: int) -> int: + res = MIN_NUM_SEQS if x <= MIN_NUM_SEQS else 1 << (x - 1).bit_length() + return min(res, upper_limit) + + +def _get_token_paddings(min_token_size: int, max_token_size: int, + padding_gap: int) -> list[int]: + """Generate a list of padding size, starting from min_token_size, + ending with a number that can cover max_token_size + + If padding_gap == 0 then: + increase 2X each time (exponential) + else: + first increase the size to twice, + then increase the padding size by padding_gap. + """ + # assert min_token_size is power of 2 + assert (min_token_size & (min_token_size - 1) == 0) and min_token_size > 0 + paddings = [] + num = min_token_size + + if padding_gap == 0: + logger.info("Using exponential token paddings:") + while True: + logger.info(" %d", num) + paddings.append(num) + if num >= max_token_size: + break + num *= 2 + else: + logger.info("Using incremental token paddings:") + while num <= padding_gap: + logger.info(" %d", num) + paddings.append(num) + num *= 2 + num //= 2 + while num < max_token_size: + num += padding_gap + logger.info(" %d", num) + paddings.append(num) + + return paddings + + +def _get_padded_token_len(paddings: list[int], x: int) -> int: + """Return the first element in paddings list greater or equal to x. + """ + index = bisect.bisect_left(paddings, x) + assert index < len(paddings) + return paddings[index] + + +def _make_src_and_dst_indices( + src_block_ids: list[int], + dst_block_ids: list[int], + src_device: Union[torch.device, str], + dst_device: Union[torch.device, str], +) -> tuple[torch.Tensor, torch.Tensor]: + src_indices = torch.tensor(src_block_ids, + device=src_device, + dtype=torch.int64) + dst_indices = torch.tensor(dst_block_ids, + device=dst_device, + dtype=torch.int64) + return src_indices, dst_indices + + +@torch.compile(backend="openxla") +def _insert_blocks_to_tpu( + cpu_cache: torch.Tensor, + tpu_cache: torch.Tensor, + cpu_block_indices: torch.Tensor, + tpu_block_indices: torch.Tensor, +) -> None: + torch.ops.xla.dynamo_set_buffer_donor_(tpu_cache, True) + tpu_cache[tpu_block_indices] = cpu_cache[cpu_block_indices].to( + tpu_cache.device) + + +@torch.compile(backend="openxla") +def _swap_out_tpu_blocks( + tpu_cache: torch.Tensor, + cpu_cache: torch.Tensor, + tpu_block_indices: torch.Tensor, + cpu_block_indices: torch.Tensor, +) -> None: + """ tpu blocks to cpu blocks""" + torch.ops.xla.dynamo_set_buffer_donor_(tpu_cache, True) + cpu_cache[cpu_block_indices] = tpu_cache[tpu_block_indices].cpu() + + +def copy_kv_blocks( + src_kv_caches: dict[str, torch.Tensor], + dst_kv_caches: dict[str, torch.Tensor], + src_block_ids: list[int], + dst_block_ids: list[int], + direction: Literal["h2d", "d2h"], +) -> None: + """Copy kv blocks between different buffers.""" + if not src_kv_caches or not dst_kv_caches or \ + not src_block_ids or not dst_block_ids or \ + len(src_block_ids) != len(dst_block_ids): + return + + src_device = next(iter(src_kv_caches.values())).device + dst_device = next(iter(dst_kv_caches.values())).device + + src_indices, dst_indices = _make_src_and_dst_indices( + src_block_ids=src_block_ids, + dst_block_ids=dst_block_ids, + src_device=src_device, + dst_device=dst_device) + + _copy_fn = _insert_blocks_to_tpu if direction == "h2d" else \ + _swap_out_tpu_blocks + for layer_name in src_kv_caches: + src_tensor = src_kv_caches[layer_name] + dst_tensor = dst_kv_caches[layer_name] + _copy_fn(src_tensor, dst_tensor, src_indices, dst_indices) + + +def _get_padded_num_kv_cache_update_slices(num_tokens: int, max_num_reqs: int, + page_size: int) -> int: + """Calculates the padded number of KV cache update slices to avoid + recompilation.""" + # NOTE(chengjiyao): let's say R_i is the token num for i-th request, + # so it occupies most 2 + R_i // page_size pages. The total maximum + # possible number of pages needed is sum(2 + R_i // page_size), which + # is <= 2 * max_num_reqs + sum(R_i) // page_size + # = 2 * max_num_reqs + num_tokens // page_size + padded_num_slices = 2 * max_num_reqs + num_tokens // page_size + padded_num_slices = min(padded_num_slices, num_tokens) + return padded_num_slices + + +def _get_num_slices_per_kv_cache_update_block(page_size_bytes: int) -> int: + """Find the optimum number of slices to copy per Pallas program instance. + + Increasing the number of slices copied in one instance of the kernel program + will increase HBM bandwidth utilization via more in-flight DMAs. + + However, it will also use more VMEM, and experimentally, we observed + performance regression at 128 slices on v6e, likely due to running + out of scalar registers. Thus this function will limit the number of + slices to 64. + """ + # The default vmem_limit_bytes of a pallas kernel is 32MB. Here we + # calculate num_slices_per_block based on 16MB in case any register spills. + vmem_limit = 16 * 1024 * 1024 + num_slices_per_block = vmem_limit // page_size_bytes + assert num_slices_per_block > 0, "Number of slices should be positive" + num_slices_per_block = prev_power_of_2(num_slices_per_block) + if num_slices_per_block > 64: + num_slices_per_block = 64 + return num_slices_per_block + + +def replace_set_lora(model): + + def _tpu_set_lora( + self, + index: int, + lora_a: torch.Tensor, + lora_b: torch.Tensor, + embeddings_tensor: Optional[torch.Tensor], + bias: Optional[torch.Tensor] = None, + ): + # TODO: The integer index leads to a recompilation, but converting it + # to a tensor doesn't seem to work anymore. This might be fixed with a + # later release of torch_xla. + self._original_set_lora(index, lora_a, lora_b, embeddings_tensor, bias) + xm.mark_step() + + def _tpu_reset_lora(self, index: int): + self._original_reset_lora(index) + xm.mark_step() + + for _, module in model.named_modules(): + if isinstance(module, BaseLayerWithLoRA): + module._original_set_lora = module.set_lora + module._original_reset_lora = module.reset_lora + module.set_lora = _tpu_set_lora.__get__(module, module.__class__) + module.reset_lora = _tpu_reset_lora.__get__( + module, module.__class__) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/vllm_flash_attn/layers/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/vllm_flash_attn/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/worker/__pycache__/model_runner.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/worker/__pycache__/model_runner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b3ad2ee3e4179bb900fbba6363d03f3f0172642 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/worker/__pycache__/model_runner.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/worker/__pycache__/neuron_worker.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/worker/__pycache__/neuron_worker.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74781abe5c353a0e30eb96672ec47c5ca70f91cb Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/worker/__pycache__/neuron_worker.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/worker/__pycache__/worker.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/worker/__pycache__/worker.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b169888405e1a794faeed9a19f2fe91980821d67 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/worker/__pycache__/worker.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/worker/__pycache__/worker_base.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/worker/__pycache__/worker_base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02e2ea9ed256da6a06ea6958f347cddad4aca9d6 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/vllm/worker/__pycache__/worker_base.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/__pycache__/_iterutils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/__pycache__/_iterutils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3aa31d2e3e3e1266a43432f3c505edbf2ba2e56a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/__pycache__/_iterutils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/__pycache__/util.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/__pycache__/util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f79916f5b4939781d0d79e12cafc2e3aa73ff5c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/__pycache__/util.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/__pycache__/wandb_run.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/__pycache__/wandb_run.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..401a5c179568a80065a98ea0bb229a47f56b4cd9 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/__pycache__/wandb_run.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/_pydantic/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/_pydantic/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..aa418931a1e3ea2c2559f3c0685d57b54e6bdc5a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/_pydantic/__init__.py @@ -0,0 +1,30 @@ +"""Internal utilities for working with pydantic.""" + +from .base import ( + CompatBaseModel, + GQLBase, + GQLId, + SerializedToJson, + Typename, + ensure_json, +) +from .utils import IS_PYDANTIC_V2, from_json, gql_typename, pydantic_isinstance, to_json +from .v1_compat import AliasChoices, computed_field, field_validator, model_validator + +__all__ = [ + "IS_PYDANTIC_V2", + "CompatBaseModel", + "GQLBase", + "Typename", + "GQLId", + "SerializedToJson", + "AliasChoices", + "computed_field", + "field_validator", + "model_validator", + "pydantic_isinstance", + "to_json", + "from_json", + "ensure_json", + "gql_typename", +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/_pydantic/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/_pydantic/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc6eb02357c784169a8af8e3efdda7d62aff43db Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/_pydantic/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/_pydantic/__pycache__/utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/_pydantic/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc5341cc77e3445dcd3af83d22d7dc107f29c862 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/_pydantic/__pycache__/utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/_pydantic/__pycache__/v1_compat.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/_pydantic/__pycache__/v1_compat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..092b65b279cd6ea1ac5051a1bfb11a9a1b98b0c5 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/_pydantic/__pycache__/v1_compat.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/_pydantic/base.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/_pydantic/base.py new file mode 100644 index 0000000000000000000000000000000000000000..1c80e1a92d208955af0d5566bc1461cdc0f041cc --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/_pydantic/base.py @@ -0,0 +1,128 @@ +"""Base classes and other customizations for generated pydantic types.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Callable, Literal, TypeVar + +from pydantic import BaseModel, ConfigDict, Field, Json, StrictStr +from typing_extensions import Annotated, TypedDict, Unpack, override + +from .utils import IS_PYDANTIC_V2, to_json +from .v1_compat import PydanticCompatMixin + +if TYPE_CHECKING: + from pydantic.main import IncEx + + +class ModelDumpKwargs(TypedDict, total=False): + """Shared keyword arguments for `BaseModel.model_{dump,dump_json}`.""" + + include: IncEx | None + exclude: IncEx | None + context: dict[str, Any] | None + by_alias: bool | None + exclude_unset: bool + exclude_defaults: bool + exclude_none: bool + round_trip: bool + warnings: bool | Literal["none", "warn", "error"] + fallback: Callable[[Any], Any] | None + serialize_as_any: bool + + +#: Custom overrides of default kwargs for `BaseModel.model_{dump,dump_json}`. +MODEL_DUMP_DEFAULTS = ModelDumpKwargs( + by_alias=True, # Always serialize with aliases (e.g. camelCase names) + round_trip=True, # Ensure serialized values remain valid inputs for deserialization +) + + +# v1-compatible base class for pydantic types. +class CompatBaseModel(PydanticCompatMixin, BaseModel): + __doc__ = None # Prevent subclasses from inheriting the BaseModel docstring + + +# Base class for all GraphQL-generated types. +# Omitted from docstring to avoid inclusion in generated docs. +class GQLBase(CompatBaseModel): + model_config = ConfigDict( + populate_by_name=True, # Discouraged in pydantic v2.11+, will be deprecated in v3 + validate_by_name=True, # Introduced in pydantic v2.11 + validate_by_alias=True, # Introduced in pydantic v2.11 + serialize_by_alias=True, # Introduced in pydantic v2.11 + validate_assignment=True, + validate_default=True, + use_attribute_docstrings=True, + from_attributes=True, + revalidate_instances="always", + protected_namespaces=(), # Some GraphQL fields may begin with "model_" + ) + + @override + def model_dump( + self, + *, + mode: Literal["json", "python"] | str = "json", # NOTE: changed default + **kwargs: Unpack[ModelDumpKwargs], + ) -> dict[str, Any]: + kwargs = {**MODEL_DUMP_DEFAULTS, **kwargs} + return super().model_dump(mode=mode, **kwargs) + + @override + def model_dump_json( + self, + *, + indent: int | None = None, + **kwargs: Unpack[ModelDumpKwargs], + ) -> str: + kwargs = {**MODEL_DUMP_DEFAULTS, **kwargs} + return super().model_dump_json(indent=indent, **kwargs) + + +# ------------------------------------------------------------------------------ +# Reusable annotations for field types +T = TypeVar("T") + +if IS_PYDANTIC_V2 or TYPE_CHECKING: + GQLId = Annotated[ + StrictStr, + Field(repr=False, frozen=True), + ] +else: + # FIXME: Find a way to fix this for pydantic v1, which doesn't like when + # `Field(...)` used in the field assignment AND `Annotated[...]`. + # This is a problem for codegen, which can currently outputs e.g. + # + # class MyModel(GQLBase): + # my_id: GQLId = Field(alias="myID") + # + GQLId = StrictStr # type: ignore[misc] + +Typename = Annotated[ + T, + Field(repr=False, frozen=True, alias="__typename"), +] + + +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) + + +if IS_PYDANTIC_V2 or TYPE_CHECKING: + from pydantic import BeforeValidator, PlainSerializer + + SerializedToJson = Annotated[ + Json[T], + # Allow lenient instantiation/validation: incoming data may already be deserialized. + BeforeValidator(ensure_json), + PlainSerializer(to_json), + ] +else: + # FIXME: Restore, modify, or replace this later after ensuring pydantic v1 compatibility. + SerializedToJson = Json[T] # type: ignore[misc] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/_pydantic/v1_compat.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/_pydantic/v1_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..8cd830a148bf86a531089620010afec049ae24fe --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/_pydantic/v1_compat.py @@ -0,0 +1,284 @@ +"""Provides partial support for compatibility with Pydantic v1.""" + +from __future__ import annotations + +import json +from functools import lru_cache +from inspect import signature +from operator import attrgetter +from typing import TYPE_CHECKING, Any, Callable, ClassVar, Literal, overload + +import pydantic + +from .utils import IS_PYDANTIC_V2, to_json + +if TYPE_CHECKING: + from typing import Protocol + + class V1Model(Protocol): + # ------------------------------------------------------------------------------ + # NOTE: These aren't part of the original v1 BaseModel spec, but were added as + # internal helpers and are (re-)declared here to satisfy mypy checks. + @classmethod + def _dump_json_vals(cls, values: dict, by_alias: bool) -> dict: ... + + # ------------------------------------------------------------------------------ + # These methods are part of the original v1 BaseModel spec. + + __config__: ClassVar[type] + __fields__: ClassVar[dict[str, Any]] + __fields_set__: set[str] + + @classmethod + def update_forward_refs(cls, *args: Any, **kwargs: Any) -> None: ... + @classmethod + def construct(cls, *args: Any, **kwargs: Any) -> V1Model: ... + @classmethod + def parse_obj(cls, *args: Any, **kwargs: Any) -> V1Model: ... + @classmethod + def parse_raw(cls, *args: Any, **kwargs: Any) -> V1Model: ... + + def dict(self, **kwargs: Any) -> dict[str, Any]: ... + def json(self, **kwargs: Any) -> str: ... + def copy(self, **kwargs: Any) -> V1Model: ... + + +# Maps {v2 -> v1} model config keys that were renamed in v2. +# See: https://docs.pydantic.dev/latest/migration/#changes-to-config +_V1_CONFIG_KEYS = { + "populate_by_name": "allow_population_by_field_name", + "str_to_lower": "anystr_lower", + "str_strip_whitespace": "anystr_strip_whitespace", + "str_to_upper": "anystr_upper", + "ignored_types": "keep_untouched", + "str_max_length": "max_anystr_length", + "str_min_length": "min_anystr_length", + "from_attributes": "orm_mode", + "json_schema_extra": "schema_extra", + "validate_default": "validate_all", +} + + +def convert_v2_config(v2_config: dict[str, Any]) -> dict[str, Any]: + """Internal helper: Return a copy of the v2 ConfigDict with renamed v1 keys.""" + return {_V1_CONFIG_KEYS.get(k, k): v for k, v in v2_config.items()} + + +@lru_cache(maxsize=None) # Reduce repeat introspection via `signature()` +def allowed_arg_names(func: Callable) -> set[str]: + """Internal helper: Return the names of args accepted by the given function.""" + return set(signature(func).parameters) + + +# Pydantic BaseModels are defined with a custom metaclass, but its namespace +# has changed between pydantic versions. +# +# In v1, it can be imported as `from pydantic.main import ModelMetaclass` +# In v2, it's defined in an internal module so we avoid directly importing it. +PydanticModelMetaclass: type = type(pydantic.BaseModel) + + +class V1MixinMetaclass(PydanticModelMetaclass): + def __new__( + cls, + name: str, + bases: tuple[type, ...], + namespace: dict[str, Any], + **kwargs: Any, + ): + # In the class definition, convert the model config, if any: + # # BEFORE + # class MyModel(BaseModel): # v2 model with `ConfigDict` + # model_config = ConfigDict(populate_by_name=True) + # + # # AFTER + # class MyModel(BaseModel): # v1 model with inner `Config` class + # class Config: + # allow_population_by_field_name = True + if config_dict := namespace.pop("model_config", None): + namespace["Config"] = type("Config", (), convert_v2_config(config_dict)) + return super().__new__(cls, name, bases, namespace, **kwargs) + + @property + def model_fields(self) -> dict[str, Any]: + return self.__fields__ # type: ignore[deprecated] + + +# Mixin to ensure compatibility of Pydantic models if Pydantic v1 is detected. +# These are "best effort" implementations and cannot guarantee complete +# compatibility in v1 environments. +# +# Whenever possible, users should strongly prefer upgrading to Pydantic v2 to +# ensure full compatibility. +class V1Mixin(metaclass=V1MixinMetaclass): + # Internal compat helpers + @classmethod + def _dump_json_vals(cls, values: dict[str, Any], by_alias: bool) -> dict[str, Any]: + """Reserialize values from `Json`-typed fields after dumping the model to dict.""" + # Get the expected keys (after `.model_dump()`) for `Json`-typed fields. + # Note: In v1, `Json` fields have `ModelField.parse_json == True` + json_fields = (f for f in cls.__fields__.values() if f.parse_json) # type: ignore[deprecated] + get_key = attrgetter("alias" if by_alias else "name") + json_field_keys = set(map(get_key, json_fields)) + + return { + # Only serialize `Json` fields with non-null values. + k: to_json(v) if ((v is not None) and (k in json_field_keys)) else v + for k, v in values.items() + } + + # ------------------------------------------------------------------------------ + @classmethod + def __try_update_forward_refs__(cls: type[V1Model], **localns: Any) -> None: + if hasattr(sup := super(), "__try_update_forward_refs__"): + sup.__try_update_forward_refs__(**localns) + + @classmethod + def model_rebuild(cls, *args: Any, **kwargs: Any) -> None: + return cls.update_forward_refs(*args, **kwargs) + + @classmethod + def model_construct(cls, *args: Any, **kwargs: Any) -> V1Model: + return cls.construct(*args, **kwargs) + + @classmethod + def model_validate(cls, *args: Any, **kwargs: Any) -> V1Model: + return cls.parse_obj(*args, **kwargs) + + @classmethod + def model_validate_json(cls, *args: Any, **kwargs: Any) -> V1Model: + return cls.parse_raw(*args, **kwargs) + + def model_dump(self: V1Model, **kwargs: Any) -> dict[str, Any]: + # Pass only kwargs that are allowed in the V1 method. + allowed_keys = allowed_arg_names(self.dict) & kwargs.keys() + dict_ = self.dict(**{k: kwargs[k] for k in allowed_keys}) + + # Ugly hack: Try to serialize `Json` fields correctly when `round_trip=True` in pydantic v1 + if kwargs.get("round_trip", False): + by_alias: bool = kwargs.get("by_alias", False) + return self._dump_json_vals(dict_, by_alias=by_alias) + + return dict_ + + def model_dump_json(self: V1Model, **kwargs: Any) -> str: + # Pass only kwargs that are allowed in the V1 method. + allowed_keys = allowed_arg_names(self.json) & kwargs.keys() + json_ = self.json(**{k: kwargs[k] for k in allowed_keys}) + + # Ugly hack: Try to serialize `Json` fields correctly when `round_trip=True` in pydantic v1 + if kwargs.get("round_trip", False): + by_alias: bool = kwargs.get("by_alias", False) + dict_ = json.loads(json_) + return json.dumps(self._dump_json_vals(dict_, by_alias=by_alias)) + + return json_ + + def model_copy(self: V1Model, **kwargs: Any) -> V1Model: + # Pass only kwargs that are allowed in the V1 method. + allowed_keys = allowed_arg_names(self.copy) & kwargs.keys() + return self.copy(**{k: kwargs[k] for k in allowed_keys}) + + @property + def model_fields_set(self: V1Model) -> set[str]: + return self.__fields_set__ + + +# Placeholder. Pydantic v2 is already compatible with itself, so no need for extra mixins. +class V2Mixin: + pass + + +# Pick the mixin type based on the detected Pydantic version. +PydanticCompatMixin: type = V2Mixin if IS_PYDANTIC_V2 else V1Mixin + + +# ---------------------------------------------------------------------------- +# Decorators and other pydantic helpers +# ---------------------------------------------------------------------------- +if IS_PYDANTIC_V2: + field_validator = pydantic.field_validator + model_validator = pydantic.model_validator + AliasChoices = pydantic.AliasChoices + computed_field = pydantic.computed_field + +else: + # Redefines `@field_validator` with a v2-like signature + # to call `@validator` from v1 instead. + def field_validator( + field: str, + /, + *fields: str, + mode: Literal["before", "after", "wrap", "plain"] = "after", + check_fields: bool | None = None, + **_: Any, + ) -> Callable: + return pydantic.validator( # type: ignore[deprecated] + field, + *fields, + pre=(mode == "before"), + always=True, + check_fields=bool(check_fields), + allow_reuse=True, + ) + + # Redefines `@model_validator` with a v2-like signature + # to call `@root_validator` from v1 instead. + def model_validator( + *, + mode: Literal["before", "after", "wrap", "plain"], + **_: Any, + ) -> Callable: + if mode == "after": + # Patch the behavior for `@model_validator(mode="after")` in v1. This is + # necessarily complicated because: + # - `@model_validator(mode="after")` decorates an instance method in pydantic v2 + # - `@root_validator(pre=False)` always decorates a classmethod in pydantic v1 + def _decorator(v2_method: Callable) -> Any: + def v1_method( + cls: type[V1Model], values: dict[str, Any] + ) -> dict[str, Any]: + # Note: Since this is an "after" validator, the values should already be + # validated, so `.construct()` in v1 (`.model_construct()` in v2) + # should create a valid object to pass to the **original** decorated instance method. + validated = v2_method(cls.construct(**values)) + + # Pydantic v1 expects the validator to return a dict of {field_name -> value} + return { + name: getattr(validated, name) for name in validated.__fields__ + } + + return pydantic.root_validator(pre=False, allow_reuse=True)( # type: ignore[call-overload] + classmethod(v1_method) + ) + + return _decorator + else: + return pydantic.root_validator(pre=(mode == "before"), allow_reuse=True) # type: ignore[call-overload] + + @overload # type: ignore[no-redef] + def computed_field(func: Callable | property, /) -> property: ... + @overload + def computed_field( + func: None, /, **_: Any + ) -> Callable[[Callable | property], property]: ... + + def computed_field( + func: Callable | property | None = None, /, **_: Any + ) -> property | Callable[[Callable | property], property]: + """Compatibility wrapper for Pydantic v2's `computed_field` in v1.""" + + def always_property(f: Callable | property) -> property: + # Convert the method to a property only if needed + return f if isinstance(f, property) else property(f) + + # Handle both decorator styles + return always_property if (func is None) else always_property(func) + + class AliasChoices: # type: ignore [no-redef] + """Placeholder class for Pydantic v2's AliasChoices for partial v1 compatibility.""" + + aliases: list[str] + + def __init__(self, *aliases: str): + self.aliases = list(aliases) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/agents/__pycache__/pyagent.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/agents/__pycache__/pyagent.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d18a790dfa8dee7824c9a9c0e1a56e87a3775dc Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/agents/__pycache__/pyagent.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/agents/pyagent.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/agents/pyagent.py new file mode 100644 index 0000000000000000000000000000000000000000..f9483f6a0b20c2dd4703a3fa7df45fc5eeb6310d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/agents/pyagent.py @@ -0,0 +1,386 @@ +"""Agent - Agent object. + +Manage wandb agent. + +""" + +import ctypes +import logging +import os +import queue +import socket +import sys +import threading +import time +import traceback + +import wandb +from wandb.apis import InternalApi +from wandb.sdk.launch.sweeps import utils as sweep_utils + +logger = logging.getLogger(__name__) + + +def _terminate_thread(thread): + if not thread.is_alive(): + return + if hasattr(thread, "_terminated"): + return + thread._terminated = True + tid = getattr(thread, "_thread_id", None) + if tid is None: + for k, v in threading._active.items(): + if v is thread: + tid = k + if tid is None: + # This should never happen + return + logger.debug(f"Terminating thread: {tid}") + res = ctypes.pythonapi.PyThreadState_SetAsyncExc( + ctypes.c_long(tid), ctypes.py_object(Exception) + ) + if res == 0: + # This should never happen + return + elif res != 1: + # Revert + logger.debug(f"Termination failed for thread {tid}") + ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None) + + +class Job: + def __init__(self, command): + self.command = command + job_type = command.get("type") + self.type = job_type + self.run_id = command.get("run_id") + self.config = command.get("args") + + def __repr__(self): + if self.type == "run": + return f"Job({self.run_id},{self.config})" + elif self.type == "stop": + return f"stop({self.run_id})" + else: + return "exit" + + +class RunStatus: + QUEUED = "QUEUED" + RUNNING = "RUNNING" + STOPPED = "STOPPED" + ERRORED = "ERRORED" + DONE = "DONE" + + +class Agent: + FLAPPING_MAX_SECONDS = 60 + FLAPPING_MAX_FAILURES = 3 + MAX_INITIAL_FAILURES = 5 + + def __init__( + self, sweep_id=None, project=None, entity=None, function=None, count=None + ): + self._sweep_path = sweep_id + self._sweep_id = None + self._project = project + self._entity = entity + self._function = function + self._count = count + # glob_config = os.path.expanduser('~/.config/wandb/settings') + # loc_config = 'wandb/settings' + # files = (glob_config, loc_config) + self._api = InternalApi() + self._agent_id = None + self._max_initial_failures = wandb.env.get_agent_max_initial_failures( + self.MAX_INITIAL_FAILURES + ) + # if the directory to log to is not set, set it + if os.environ.get(wandb.env.DIR) is None: + os.environ[wandb.env.DIR] = os.path.abspath(os.getcwd()) + + def _init(self): + # These are not in constructor so that Agent instance can be rerun + self._run_threads = {} + self._run_status = {} + self._queue = queue.Queue() + self._exit_flag = False + self._exceptions = {} + self._start_time = time.time() + + def _register(self): + logger.debug("Agent._register()") + agent = self._api.register_agent(socket.gethostname(), sweep_id=self._sweep_id) + self._agent_id = agent["id"] + logger.debug(f"agent_id = {self._agent_id}") + + def _setup(self): + logger.debug("Agent._setup()") + self._init() + parts = dict(entity=self._entity, project=self._project, name=self._sweep_path) + err = sweep_utils.parse_sweep_id(parts) + if err: + wandb.termerror(err) + return + entity = parts.get("entity") or self._entity + project = parts.get("project") or self._project + sweep_id = parts.get("name") or self._sweep_id + if sweep_id: + os.environ[wandb.env.SWEEP_ID] = sweep_id + if entity: + wandb.env.set_entity(entity) + if project: + wandb.env.set_project(project) + if sweep_id: + self._sweep_id = sweep_id + self._register() + + def _stop_run(self, run_id): + logger.debug(f"Stopping run {run_id}.") + self._run_status[run_id] = RunStatus.STOPPED + thread = self._run_threads.get(run_id) + if thread: + _terminate_thread(thread) + + def _stop_all_runs(self): + logger.debug("Stopping all runs.") + for run in list(self._run_threads.keys()): + self._stop_run(run) + + def _exit(self): + self._stop_all_runs() + self._exit_flag = True + # _terminate_thread(self._main_thread) + + def _heartbeat(self): + while True: + if self._exit_flag: + return + # if not self._main_thread.is_alive(): + # return + run_status = { + run: True + for run, status in self._run_status.items() + if status in (RunStatus.QUEUED, RunStatus.RUNNING) + } + commands = self._api.agent_heartbeat(self._agent_id, {}, run_status) + if commands: + job = Job(commands[0]) + logger.debug(f"Job received: {job}") + if job.type in ["run", "resume"]: + self._queue.put(job) + self._run_status[job.run_id] = RunStatus.QUEUED + elif job.type == "stop": + self._stop_run(job.run_id) + elif job.type == "exit": + self._exit() + return + time.sleep(5) + + def _run_jobs_from_queue(self): + global _INSTANCES + _INSTANCES += 1 + try: + waiting = False + count = 0 + while True: + if self._exit_flag: + return + try: + try: + job = self._queue.get(timeout=5) + if self._exit_flag: + logger.debug("Exiting main loop due to exit flag.") + wandb.termlog("Sweep Agent: Exiting.") + return + except queue.Empty: + if not waiting: + logger.debug("Paused.") + wandb.termlog("Sweep Agent: Waiting for job.") + waiting = True + time.sleep(5) + if self._exit_flag: + logger.debug("Exiting main loop due to exit flag.") + wandb.termlog("Sweep Agent: Exiting.") + return + continue + if waiting: + logger.debug("Resumed.") + wandb.termlog("Job received.") + waiting = False + count += 1 + run_id = job.run_id + if self._run_status[run_id] == RunStatus.STOPPED: + continue + logger.debug(f"Spawning new thread for run {run_id}.") + thread = threading.Thread(target=self._run_job, args=(job,)) + self._run_threads[run_id] = thread + thread.start() + self._run_status[run_id] = RunStatus.RUNNING + thread.join() + logger.debug(f"Thread joined for run {run_id}.") + if self._run_status[run_id] == RunStatus.RUNNING: + self._run_status[run_id] = RunStatus.DONE + elif self._run_status[run_id] == RunStatus.ERRORED: + exc = self._exceptions[run_id] + # Extract to reduce a decision point to avoid ruff c901 + log_str, term_str = _get_exception_logger_and_term_strs(exc) + logger.error(f"Run {run_id} errored:\n{log_str}") + wandb.termerror(f"Run {run_id} errored:{term_str}") + if os.getenv(wandb.env.AGENT_DISABLE_FLAPPING) == "true": + self._exit_flag = True + return + elif ( + time.time() - self._start_time < self.FLAPPING_MAX_SECONDS + ) and (len(self._exceptions) >= self.FLAPPING_MAX_FAILURES): + msg = f"Detected {self.FLAPPING_MAX_FAILURES} failed runs in the first {self.FLAPPING_MAX_SECONDS} seconds, killing sweep." + logger.error(msg) + wandb.termerror(msg) + wandb.termlog( + "To disable this check set WANDB_AGENT_DISABLE_FLAPPING=true" + ) + self._exit_flag = True + return + if ( + self._max_initial_failures < len(self._exceptions) + and len(self._exceptions) >= count + ): + msg = f"Detected {self._max_initial_failures} failed runs in a row at start, killing sweep." + logger.error(msg) + wandb.termerror(msg) + wandb.termlog( + "To change this value set WANDB_AGENT_MAX_INITIAL_FAILURES=val" + ) + self._exit_flag = True + return + if self._count and self._count == count: + logger.debug("Exiting main loop because max count reached.") + self._exit_flag = True + return + except KeyboardInterrupt: + logger.debug("Ctrl + C detected. Stopping sweep.") + wandb.termlog("Ctrl + C detected. Stopping sweep.") + self._exit() + return + except Exception: + if self._exit_flag: + logger.debug("Exiting main loop due to exit flag.") + wandb.termlog("Sweep Agent: Killed.") + return + else: + raise + finally: + _INSTANCES -= 1 + + def _run_job(self, job): + try: + run_id = job.run_id + + config_file = os.path.join( + "wandb", "sweep-" + self._sweep_id, "config-" + run_id + ".yaml" + ) + os.environ[wandb.env.RUN_ID] = run_id + base_dir = os.environ.get(wandb.env.DIR, "") + sweep_param_path = os.path.join(base_dir, config_file) + os.environ[wandb.env.SWEEP_PARAM_PATH] = sweep_param_path + wandb.wandb_lib.config_util.save_config_file_from_dict( + sweep_param_path, job.config + ) + os.environ[wandb.env.SWEEP_ID] = self._sweep_id + wandb.teardown() + + wandb.termlog(f"Agent Starting Run: {run_id} with config:") + for k, v in job.config.items(): + wandb.termlog("\t{}: {}".format(k, v["value"])) + + try: + self._function() + except KeyboardInterrupt: + raise + except Exception as e: + # Log the run's exceptions directly to stderr to match CLI case, and wrap so we + # can identify it as coming from the job later later. This will get automatically + # logged by console_capture.py. Exception handler below will also handle exceptions + # in setup code. + exc_repr = _format_exception_traceback(e) + print(exc_repr, file=sys.stderr) # noqa: T201 + raise _JobError(f"Run threw exception: {str(e)}") from e + wandb.finish() + except KeyboardInterrupt: + raise + except Exception as e: + wandb.finish(exit_code=1) + if self._run_status[run_id] == RunStatus.RUNNING: + self._run_status[run_id] = RunStatus.ERRORED + self._exceptions[run_id] = e + finally: + # clean up the environment changes made + os.environ.pop(wandb.env.RUN_ID, None) + os.environ.pop(wandb.env.SWEEP_ID, None) + os.environ.pop(wandb.env.SWEEP_PARAM_PATH, None) + + def run(self): + logger.info( + f"Starting sweep agent: entity={self._entity}, project={self._project}, count={self._count}" + ) + self._setup() + # self._main_thread = threading.Thread(target=self._run_jobs_from_queue) + self._heartbeat_thread = threading.Thread(target=self._heartbeat) + self._heartbeat_thread.daemon = True + # self._main_thread.start() + self._heartbeat_thread.start() + # self._main_thread.join() + self._run_jobs_from_queue() + + +def pyagent(sweep_id, function, entity=None, project=None, count=None): + """Generic agent entrypoint, used for CLI or jupyter. + + Args: + sweep_id (dict): Sweep ID generated by CLI or sweep API + function (func, optional): A function to call instead of the "program" + entity (str, optional): W&B Entity + project (str, optional): W&B Project + count (int, optional): the number of trials to run. + """ + if not callable(function): + raise TypeError("function parameter must be callable!") + agent = Agent( + sweep_id, + function=function, + entity=entity, + project=project, + count=count, + ) + agent.run() + + +def _format_exception_traceback(exc): + return "".join(traceback.format_exception(type(exc), exc, exc.__traceback__)) + + +class _JobError(Exception): + """Exception raised when a job fails during execution.""" + + pass + + +def _get_exception_logger_and_term_strs(exc): + if isinstance(exc, _JobError) and exc.__cause__: + # If it's a JobException, get the original exception for display + job_exc = exc.__cause__ + log_str = _format_exception_traceback(job_exc) + # Don't long full stacktrace to terminal again because we already + # printed it to stderr. + term_str = " " + str(job_exc) + else: + log_str = _format_exception_traceback(exc) + term_str = "\n" + log_str + return log_str, term_str + + +_INSTANCES = 0 + + +def is_running(): + return bool(_INSTANCES) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/analytics/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/analytics/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81c8152764bd27d7eaeed1dcdb1d0d4a57c14836 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/analytics/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/analytics/sentry.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/analytics/sentry.py new file mode 100644 index 0000000000000000000000000000000000000000..25ad286f47e598cf42ffdaccad9b91fa6b362ea3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/analytics/sentry.py @@ -0,0 +1,267 @@ +from __future__ import annotations + +__all__ = ("Sentry",) + + +import atexit +import functools +import os +import pathlib +import sys +from types import TracebackType +from typing import TYPE_CHECKING, Any, Callable, Literal +from urllib.parse import quote + +import sentry_sdk # type: ignore +import sentry_sdk.scope # type: ignore +import sentry_sdk.utils # type: ignore +from typing_extensions import Never + +import wandb +import wandb.env +import wandb.util + +if TYPE_CHECKING: + import wandb.sdk.internal.settings_static + +SENTRY_DEFAULT_DSN = ( + "https://2592b1968ea94cca9b5ef5e348e094a7@o151352.ingest.sentry.io/4504800232407040" +) + +SessionStatus = Literal["ok", "exited", "crashed", "abnormal"] + + +def _safe_noop(func: Callable) -> Callable: + """Decorator to ensure that Sentry methods do nothing if disabled and don't raise.""" + + @functools.wraps(func) + def wrapper(self: type[Sentry], *args: Any, **kwargs: Any) -> Any: + if self._disabled: + return None + try: + return func(self, *args, **kwargs) + except Exception as e: + # do not call self.exception here to avoid infinite recursion + if func.__name__ != "exception": + self.exception(f"Error in {func.__name__}: {e}") + return None + + return wrapper + + +class Sentry: + _disabled: bool + + def __init__(self) -> None: + self._disabled = not wandb.env.error_reporting_enabled() + self._sent_messages: set = set() + + self.dsn = os.environ.get(wandb.env.SENTRY_DSN, SENTRY_DEFAULT_DSN) + + self.scope: sentry_sdk.scope.Scope | None = None + + # ensure we always end the Sentry session + atexit.register(self.end_session) + + @property + def environment(self) -> str: + """Return the environment we're running in.""" + # check if we're in a git repo + is_git = pathlib.Path(__file__).parent.parent.parent.joinpath(".git").exists() + + # these match the environments for gorilla + return "development" if is_git else "production" + + @_safe_noop + def setup(self) -> None: + """Setup Sentry SDK. + + We use lower-level APIs (i.e., not sentry_sdk.init) here + to avoid the possibility of interfering with the user's + own Sentry SDK setup. + """ + client = sentry_sdk.Client( + dsn=self.dsn, + default_integrations=False, + environment=self.environment, + release=wandb.__version__, + ) + self.scope = sentry_sdk.get_global_scope().fork() + self.scope.clear() + self.scope.set_client(client) + + @_safe_noop + def message( + self, + message: str, + repeat: bool = True, + level: str = "info", + ) -> str | None: + """Send a message to Sentry.""" + if not repeat and message in self._sent_messages: + return None + self._sent_messages.add(message) + with sentry_sdk.scope.use_isolation_scope(self.scope): # type: ignore + return sentry_sdk.capture_message(message, level=level) # type: ignore + + @_safe_noop + def exception( + self, + exc: str + | BaseException + | tuple[ + type[BaseException] | None, + BaseException | None, + TracebackType | None, + ] + | None, + handled: bool = False, + status: SessionStatus | None = None, + ) -> str | None: + """Log an exception to Sentry.""" + if isinstance(exc, str): + exc_info = sentry_sdk.utils.exc_info_from_error(Exception(exc)) + elif isinstance(exc, BaseException): + exc_info = sentry_sdk.utils.exc_info_from_error(exc) + else: + exc_info = sys.exc_info() + + event, _ = sentry_sdk.utils.event_from_exception( + exc_info, + client_options=self.scope.get_client().options, # type: ignore + mechanism={"type": "generic", "handled": handled}, + ) + event_id = None + try: + with sentry_sdk.scope.use_isolation_scope(self.scope): # type: ignore + event_id = sentry_sdk.capture_event(event) # type: ignore + except Exception: + pass + + # if the status is not explicitly set, we'll set it to "crashed" if the exception + # was unhandled, or "errored" if it was handled + status = status or ("crashed" if not handled else "errored") # type: ignore + self.mark_session(status=status) + + client = self.scope.get_client() # type: ignore + if client is not None: + client.flush() + + return event_id + + def reraise(self, exc: Any) -> Never: + """Re-raise an exception after logging it to Sentry. + + Use this for top-level exceptions when you want the user to see the traceback. + + Must be called from within an exception handler. + """ + self.exception(exc) + # this will messily add this "reraise" function to the stack trace, + # but hopefully it's not too bad + raise exc.with_traceback(sys.exc_info()[2]) + + @_safe_noop + def start_session(self) -> None: + """Start a new session.""" + assert self.scope is not None + # get the current client and scope + session = self.scope._session + + # if there's no session, start one + if session is None: + self.scope.start_session() + + @_safe_noop + def end_session(self) -> None: + """End the current session.""" + assert self.scope is not None + # get the current client and scope + client = self.scope.get_client() + session = self.scope._session + + if session is not None and client is not None: + self.scope.end_session() + client.flush() + + @_safe_noop + def mark_session(self, status: SessionStatus | None = None) -> None: + """Mark the current session with a status.""" + assert self.scope is not None + session = self.scope._session + + if session is not None: + session.update(status=status) + + @_safe_noop + def configure_scope( + self, + tags: dict[str, Any] | None = None, + process_context: str | None = None, + ) -> None: + """Configure the Sentry scope for the current thread. + + This function should be called at the beginning of every thread that + will send events to Sentry. It sets the tags that will be applied to + all events sent from this thread. It also tries to start a session + if one doesn't already exist for this thread. + """ + assert self.scope is not None + settings_tags = ( + "entity", + "project", + "run_id", + "run_url", + "sweep_url", + "sweep_id", + "deployment", + "launch", + "_platform", + ) + + # set context + if process_context: + self.scope.set_tag("process_context", process_context) + + # apply settings tags + if tags is None: + return None + + for tag in settings_tags: + val = tags.get(tag, None) + if val not in (None, ""): + self.scope.set_tag(tag, val) + + if tags.get("_colab", None): + python_runtime = "colab" + elif tags.get("_jupyter", None): + python_runtime = "jupyter" + elif tags.get("_ipython", None): + python_runtime = "ipython" + else: + python_runtime = "python" + self.scope.set_tag("python_runtime", python_runtime) + + # Construct run_url and sweep_url given run_id and sweep_id + for obj in ("run", "sweep"): + obj_id, obj_url = f"{obj}_id", f"{obj}_url" + if tags.get(obj_url, None): + continue + + try: + app_url = wandb.util.app_url(tags["base_url"]) # type: ignore + entity, project = (quote(tags[k]) for k in ("entity", "project")) # type: ignore + self.scope.set_tag( + obj_url, + f"{app_url}/{entity}/{project}/{obj}s/{tags[obj_id]}", + ) + except Exception: + pass + + email = tags.get("email") + if email: + self.scope.user = {"email": email} + + # todo: add back the option to pass general tags see: c645f625d1c1a3db4a6b0e2aa8e924fee101904c (wandb/util.py) + + self.start_session() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b44e2d827176bbdc984fc1d01760ad77195c909a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/__pycache__/attrs.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/__pycache__/attrs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e520c60479c7ab6408e8b7c8a9c411950a2d7bab Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/__pycache__/attrs.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/__pycache__/internal.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/__pycache__/internal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a81dcc32e0da4d006b437112a2a84ccd304262ce Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/__pycache__/internal.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/__pycache__/validation.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/__pycache__/validation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6dc4bccf106fdec3560d35f0bedfc6f50ea2768d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/__pycache__/validation.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/__pycache__/wandb.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/__pycache__/wandb.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..589363e917b57ec350173c0435b20cc1826232d7 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/__pycache__/wandb.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/internals/__pycache__/internal.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/internals/__pycache__/internal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..457cb2d604f7c498ddf7b08f11b3ab59125c769a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/internals/__pycache__/internal.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/internals/__pycache__/protocols.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/internals/__pycache__/protocols.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1245b8cb04f98bc041fadee9a6203a9900c441f2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/internals/__pycache__/protocols.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/internals/__pycache__/util.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/internals/__pycache__/util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e07a0a4907aff4fe203545256f2f75bb91dffbe Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/internals/__pycache__/util.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/internals/internal.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/internals/internal.py new file mode 100644 index 0000000000000000000000000000000000000000..3ae10924ace8a9305cb7aa8805a8f94af3c1a3aa --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/internals/internal.py @@ -0,0 +1,382 @@ +import json +import logging +import math +import os +import queue +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, Iterable, Optional + +import numpy as np +from google.protobuf.json_format import ParseDict +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_settings_pb2 +from wandb.proto import wandb_telemetry_pb2 as telem_pb +from wandb.sdk.interface.interface import file_policy_to_enum +from wandb.sdk.interface.interface_queue import InterfaceQueue +from wandb.sdk.internal import context +from wandb.sdk.internal.sender import SendManager +from wandb.sdk.internal.settings_static import SettingsStatic +from wandb.util import coalesce, recursive_cast_dictlike_to_dict + +from .protocols import ImporterRun + +ROOT_DIR = "./wandb-importer" + + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +if os.getenv("WANDB_IMPORTER_ENABLE_RICH_LOGGING"): + from rich.logging import RichHandler + + logger.addHandler(RichHandler(rich_tracebacks=True, tracebacks_show_locals=True)) +else: + console_handler = logging.StreamHandler() + console_handler.setLevel(logging.INFO) + + formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") + console_handler.setFormatter(formatter) + + logger.addHandler(console_handler) + + +exp_retry = retry( + wait=wait_random_exponential(multiplier=1, max=10), stop=stop_after_attempt(3) +) + + +class AlternateSendManager(SendManager): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._send_artifact = exp_retry(self._send_artifact) + + +@dataclass(frozen=True) +class SendManagerConfig: + """Configure which parts of SendManager tooling to use.""" + + use_artifacts: bool = False + log_artifacts: bool = False + metadata: bool = False + files: bool = False + media: bool = False + code: bool = False + history: bool = False + summary: bool = False + terminal_output: bool = False + + +@dataclass +class RecordMaker: + run: ImporterRun + interface: InterfaceQueue = InterfaceQueue() + + @property + def run_dir(self) -> str: + p = Path(f"{ROOT_DIR}/{self.run.run_id()}/wandb") + p.mkdir(parents=True, exist_ok=True) + return f"{ROOT_DIR}/{self.run.run_id()}" + + def make_artifacts_only_records( + self, + artifacts: Optional[Iterable[Artifact]] = None, + used_artifacts: Optional[Iterable[Artifact]] = None, + ) -> Iterable[pb.Record]: + """Only make records required to upload artifacts. + + Escape hatch for adding extra artifacts to a run. + """ + yield self._make_run_record() + + if used_artifacts: + for art in used_artifacts: + yield self._make_artifact_record(art, use_artifact=True) + + if artifacts: + for art in artifacts: + yield self._make_artifact_record(art) + + def make_records( + self, + config: SendManagerConfig, + ) -> Iterable[pb.Record]: + """Make all the records that constitute a run.""" + yield self._make_run_record() + yield self._make_telem_record() + + include_artifacts = config.log_artifacts or config.use_artifacts + yield self._make_files_record( + include_artifacts, config.files, config.media, config.code + ) + + if config.use_artifacts: + if (used_artifacts := self.run.used_artifacts()) is not None: + for artifact in used_artifacts: + yield self._make_artifact_record(artifact, use_artifact=True) + + if config.log_artifacts: + if (artifacts := self.run.artifacts()) is not None: + for artifact in artifacts: + yield self._make_artifact_record(artifact) + + if config.history: + yield from self._make_history_records() + + if config.summary: + yield self._make_summary_record() + + if config.terminal_output: + if (lines := self.run.logs()) is not None: + for line in lines: + yield self._make_output_record(line) + + def _make_run_record(self) -> pb.Record: + run = pb.RunRecord() + run.run_id = self.run.run_id() + run.entity = self.run.entity() + run.project = self.run.project() + run.display_name = coalesce(self.run.display_name()) + run.notes = coalesce(self.run.notes(), "") + run.tags.extend(coalesce(self.run.tags(), [])) + run.start_time.FromMilliseconds(self.run.start_time()) + + host = self.run.host() + if host is not None: + run.host = host + + runtime = self.run.runtime() + if runtime is not None: + run.runtime = runtime + + run_group = self.run.run_group() + if run_group is not None: + run.run_group = run_group + + config = self.run.config() + if "_wandb" not in config: + config["_wandb"] = {} + + # how do I get this automatically? + config["_wandb"]["code_path"] = self.run.code_path() + config["_wandb"]["python_version"] = self.run.python_version() + config["_wandb"]["cli_version"] = self.run.cli_version() + + self.interface._make_config( + data=config, + obj=run.config, + ) # is there a better way? + return self.interface._make_record(run=run) + + def _make_output_record(self, line) -> pb.Record: + output_raw = pb.OutputRawRecord() + output_raw.output_type = pb.OutputRawRecord.OutputType.STDOUT + output_raw.line = line + return self.interface._make_record(output_raw=output_raw) + + def _make_summary_record(self) -> pb.Record: + d: dict = { + **self.run.summary(), + "_runtime": self.run.runtime(), # quirk of runtime -- it has to be here! + # '_timestamp': self.run.start_time()/1000, + } + d = recursive_cast_dictlike_to_dict(d) + summary = self.interface._make_summary_from_dict(d) + return self.interface._make_record(summary=summary) + + def _make_history_records(self) -> Iterable[pb.Record]: + for metrics in self.run.metrics(): + history = pb.HistoryRecord() + for k, v in metrics.items(): + item = history.item.add() + item.key = k + # There seems to be some conversion issue to breaks when we try to re-upload. + # np.NaN gets converted to float("nan"), which is not expected by our system. + # If this cast to string (!) is not done, the row will be dropped. + if (isinstance(v, float) and math.isnan(v)) or v == "NaN": + v = np.NaN + + if isinstance(v, bytes): + # it's a json string encoded as bytes + v = v.decode("utf-8") + else: + v = json.dumps(v) + + item.value_json = v + rec = self.interface._make_record(history=history) + yield rec + + def _make_files_record( + self, artifacts: bool, files: bool, media: bool, code: bool + ) -> pb.Record: + run_files = self.run.files() + metadata_fname = f"{self.run_dir}/files/wandb-metadata.json" + if not files or run_files is None: + # We'll always need a metadata file even if there are no other files to upload + metadata_fname = self._make_metadata_file() + run_files = [(metadata_fname, "end")] + files_record = pb.FilesRecord() + for path, policy in run_files: + if not artifacts and path.startswith("artifact/"): + continue + if not media and path.startswith("media/"): + continue + if not code and path.startswith("code/"): + continue + + # DirWatcher requires the path to start with media/ instead of the full path + if "media" in path: + p = Path(path) + path = str(p.relative_to(f"{self.run_dir}/files")) + f = files_record.files.add() + f.path = path + f.policy = file_policy_to_enum(policy) + + return self.interface._make_record(files=files_record) + + def _make_artifact_record( + self, artifact: Artifact, use_artifact=False + ) -> pb.Record: + proto = self.interface._make_artifact(artifact) + proto.run_id = str(self.run.run_id()) + proto.project = str(self.run.project()) + proto.entity = str(self.run.entity()) + proto.user_created = use_artifact + proto.use_after_commit = use_artifact + proto.finalize = True + + aliases = artifact._aliases + aliases += ["latest", "imported"] + + for alias in aliases: + proto.aliases.append(alias) + return self.interface._make_record(artifact=proto) + + def _make_telem_record(self) -> pb.Record: + telem = telem_pb.TelemetryRecord() + + feature = telem_pb.Feature() + feature.importer_mlflow = True + telem.feature.CopyFrom(feature) + + cli_version = self.run.cli_version() + if cli_version: + telem.cli_version = cli_version + + python_version = self.run.python_version() + if python_version: + telem.python_version = python_version + + return self.interface._make_record(telemetry=telem) + + def _make_metadata_file(self) -> str: + missing_text = "This data was not captured" + files_dir = f"{self.run_dir}/files" + os.makedirs(files_dir, exist_ok=True) + + d = {} + d["os"] = coalesce(self.run.os_version(), missing_text) + d["python"] = coalesce(self.run.python_version(), missing_text) + d["program"] = coalesce(self.run.program(), missing_text) + d["cuda"] = coalesce(self.run.cuda_version(), missing_text) + d["host"] = coalesce(self.run.host(), missing_text) + d["username"] = coalesce(self.run.username(), missing_text) + d["executable"] = coalesce(self.run.executable(), missing_text) + + gpus_used = self.run.gpus_used() + if gpus_used is not None: + d["gpu_devices"] = json.dumps(gpus_used) + d["gpu_count"] = json.dumps(len(gpus_used)) + + cpus_used = self.run.cpus_used() + if cpus_used is not None: + d["cpu_count"] = json.dumps(self.run.cpus_used()) + + mem_used = self.run.memory_used() + if mem_used is not None: + d["memory"] = json.dumps({"total": self.run.memory_used()}) + + fname = f"{files_dir}/wandb-metadata.json" + with open(fname, "w") as f: + f.write(json.dumps(d)) + return fname + + +def _make_settings( + root_dir: str, settings_override: Optional[Dict[str, Any]] = None +) -> SettingsStatic: + _settings_override = coalesce(settings_override, {}) + + default_settings: Dict[str, Any] = { + "x_files_dir": os.path.join(root_dir, "files"), + "root_dir": root_dir, + "sync_file": os.path.join(root_dir, "txlog.wandb"), + "resume": "false", + "program": None, + "ignore_globs": [], + "disable_job_creation": True, + "x_start_time": 0, + "_offline": None, + "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, + } + + combined_settings = {**default_settings, **_settings_override} + settings_message = wandb_settings_pb2.Settings() + ParseDict(combined_settings, settings_message) + + return SettingsStatic(settings_message) + + +def send_run( + run: ImporterRun, + *, + extra_arts: Optional[Iterable[Artifact]] = None, + extra_used_arts: Optional[Iterable[Artifact]] = None, + config: Optional[SendManagerConfig] = None, + overrides: Optional[Dict[str, Any]] = None, + settings_override: Optional[Dict[str, Any]] = None, +) -> None: + if config is None: + config = SendManagerConfig() + + # does this need to be here for pmap? + if overrides: + for k, v in overrides.items(): + # `lambda: v` won't work! + # https://stackoverflow.com/questions/10802002/why-deepcopy-doesnt-create-new-references-to-lambda-function + setattr(run, k, lambda v=v: v) + + rm = RecordMaker(run) + root_dir = rm.run_dir + + settings = _make_settings(root_dir, settings_override) + sm_record_q = queue.Queue() + # wm_record_q = queue.Queue() + result_q = queue.Queue() + interface = InterfaceQueue(record_q=sm_record_q) + context_keeper = context.ContextKeeper() + sm = AlternateSendManager( + settings, sm_record_q, result_q, interface, context_keeper + ) + + if extra_arts or extra_used_arts: + records = rm.make_artifacts_only_records(extra_arts, extra_used_arts) + else: + records = rm.make_records(config) + + for r in records: + logger.debug(f"Sending {r=}") + # In a future update, it might be good to write to a transaction log and have + # incremental uploads only send the missing records. + # wm.write(r) + + sm.send(r) + + sm.finish() + # wm.finish() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/internals/protocols.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/internals/protocols.py new file mode 100644 index 0000000000000000000000000000000000000000..87d42e99175ce5d23db6e375a8cfcaa66568722a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/internals/protocols.py @@ -0,0 +1,103 @@ +import logging +from typing import ( + Any, + Dict, + Iterable, + List, + Literal, + Optional, + Protocol, + Tuple, + runtime_checkable, +) + +from wandb.sdk.artifacts.artifact import Artifact + +logger = logging.getLogger("import_logger") + +PathStr = str +Policy = Literal["now", "end", "live"] + + +@runtime_checkable +class ImporterRun(Protocol): + def run_id(self) -> str: ... # pragma: no cover + + def entity(self) -> str: ... # pragma: no cover + + def project(self) -> str: ... # pragma: no cover + + def config(self) -> Dict[str, Any]: ... # pragma: no cover + + def summary(self) -> Dict[str, float]: ... # pragma: no cover + + def metrics(self) -> Iterable[Dict[str, float]]: + """Metrics for the run. + + We expect metrics in this shape: + + [ + {'metric1': 1, 'metric2': 1, '_step': 0}, + {'metric1': 2, 'metric2': 4, '_step': 1}, + {'metric1': 3, 'metric2': 9, '_step': 2}, + ... + ] + + You can also submit metrics in this shape: + [ + {'metric1': 1, '_step': 0}, + {'metric2': 1, '_step': 0}, + {'metric1': 2, '_step': 1}, + {'metric2': 4, '_step': 1}, + ... + ] + """ + ... # pragma: no cover + + def run_group(self) -> Optional[str]: ... # pragma: no cover + + def job_type(self) -> Optional[str]: ... # pragma: no cover + + def display_name(self) -> str: ... # pragma: no cover + + def notes(self) -> Optional[str]: ... # pragma: no cover + + def tags(self) -> Optional[List[str]]: ... # pragma: no cover + + def artifacts(self) -> Optional[Iterable[Artifact]]: ... # pragma: no cover + + def used_artifacts(self) -> Optional[Iterable[Artifact]]: ... # pragma: no cover + + def os_version(self) -> Optional[str]: ... # pragma: no cover + + def python_version(self) -> Optional[str]: ... # pragma: no cover + + def cuda_version(self) -> Optional[str]: ... # pragma: no cover + + def program(self) -> Optional[str]: ... # pragma: no cover + + def host(self) -> Optional[str]: ... # pragma: no cover + + def username(self) -> Optional[str]: ... # pragma: no cover + + def executable(self) -> Optional[str]: ... # pragma: no cover + + def gpus_used(self) -> Optional[str]: ... # pragma: no cover + + def cpus_used(self) -> Optional[int]: ... # pragma: no cover + + def memory_used(self) -> Optional[int]: ... # pragma: no cover + + def runtime(self) -> Optional[int]: ... # pragma: no cover + + def start_time(self) -> Optional[int]: ... # pragma: no cover + + def code_path(self) -> Optional[str]: ... # pragma: no cover + + def cli_version(self) -> Optional[str]: ... # pragma: no cover + + def files( + self, + ) -> Optional[Iterable[Tuple[PathStr, Policy]]]: ... # pragma: no cover + + def logs(self) -> Optional[Iterable[str]]: ... # pragma: no cover diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/mlflow.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/mlflow.py new file mode 100644 index 0000000000000000000000000000000000000000..1aa5e018bcd9c0f1d1d41eb40413f28d7035a498 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/mlflow.py @@ -0,0 +1,254 @@ +import itertools +import logging +import re +from collections import defaultdict +from typing import Any, Dict, Iterable, List, Optional, Tuple + +import mlflow +from packaging.version import Version # type: ignore + +import wandb +from wandb import Artifact + +from .internals import internal +from .internals.util import Namespace, for_each + +mlflow_version = Version(mlflow.__version__) + +logger = logging.getLogger("import_logger") + + +class MlflowRun: + def __init__(self, run, mlflow_client): + self.run = run + self.mlflow_client: mlflow.MlflowClient = mlflow_client + + def run_id(self) -> str: + return self.run.info.run_id + + def entity(self) -> str: + return self.run.info.user_id + + def project(self) -> str: + return "imported-from-mlflow" + + def config(self) -> Dict[str, Any]: + conf = self.run.data.params + + # Add tags here since mlflow supports very long tag names but we only support up to 64 chars + tags = { + k: v for k, v in self.run.data.tags.items() if not k.startswith("mlflow.") + } + return {**conf, "imported_mlflow_tags": tags} + + def summary(self) -> Dict[str, float]: + return self.run.data.metrics + + def metrics(self) -> Iterable[Dict[str, float]]: + d: Dict[int, Dict[str, float]] = defaultdict(dict) + for k in self.run.data.metrics.keys(): + metric = self.mlflow_client.get_metric_history(self.run.info.run_id, k) + for item in metric: + d[item.step][item.key] = item.value + + for k, v in d.items(): + yield {"_step": k, **v} + + def run_group(self) -> Optional[str]: + # this is nesting? Parent at `run.info.tags.get("mlflow.parentRunId")` + return f"Experiment {self.run.info.experiment_id}" + + def job_type(self) -> Optional[str]: + # Is this the right approach? + return f"User {self.run.info.user_id}" + + def display_name(self) -> str: + if mlflow_version < Version("1.30.0"): + return self.run.data.tags["mlflow.runName"] + return self.run.info.run_name + + def notes(self) -> Optional[str]: + return self.run.data.tags.get("mlflow.note.content") + + def tags(self) -> Optional[List[str]]: + ... + + # W&B tags are different than mlflow tags. + # The full mlflow tags are added to config under key `imported_mlflow_tags` instead + + def artifacts(self) -> Optional[Iterable[Artifact]]: # type: ignore + if mlflow_version < Version("2.0.0"): + dir_path = self.mlflow_client.download_artifacts( + run_id=self.run.info.run_id, + path="", + ) + else: + dir_path = mlflow.artifacts.download_artifacts(run_id=self.run.info.run_id) + + # Since mlflow doesn't have extra metadata about the artifacts, + # we just lump them all together into a single wandb.Artifact + artifact_name = self._handle_incompatible_strings(self.display_name()) + art = wandb.Artifact(artifact_name, "imported-artifacts") + art.add_dir(dir_path) + + return [art] + + def used_artifacts(self) -> Optional[Iterable[Artifact]]: # type: ignore + ... # pragma: no cover + + def os_version(self) -> Optional[str]: ... # pragma: no cover + + def python_version(self) -> Optional[str]: ... # pragma: no cover + + def cuda_version(self) -> Optional[str]: ... # pragma: no cover + + def program(self) -> Optional[str]: ... # pragma: no cover + + def host(self) -> Optional[str]: ... # pragma: no cover + + def username(self) -> Optional[str]: ... # pragma: no cover + + def executable(self) -> Optional[str]: ... # pragma: no cover + + def gpus_used(self) -> Optional[str]: ... # pragma: no cover + + def cpus_used(self) -> Optional[int]: # can we get the model? + ... # pragma: no cover + + def memory_used(self) -> Optional[int]: ... # pragma: no cover + + def runtime(self) -> Optional[int]: + end_time = ( + self.run.info.end_time // 1000 + if self.run.info.end_time is not None + else self.start_time() + ) + return end_time - self.start_time() + + def start_time(self) -> Optional[int]: + return self.run.info.start_time // 1000 + + def code_path(self) -> Optional[str]: ... # pragma: no cover + + def cli_version(self) -> Optional[str]: ... # pragma: no cover + + def files(self) -> Optional[Iterable[Tuple[str, str]]]: ... # pragma: no cover + + def logs(self) -> Optional[Iterable[str]]: ... # pragma: no cover + + @staticmethod + def _handle_incompatible_strings(s: str) -> str: + valid_chars = r"[^a-zA-Z0-9_\-\.]" + replacement = "__" + + return re.sub(valid_chars, replacement, s) + + +class MlflowImporter: + def __init__( + self, + dst_base_url: str, + dst_api_key: str, + mlflow_tracking_uri: str, + mlflow_registry_uri: Optional[str] = None, + *, + custom_api_kwargs: Optional[Dict[str, Any]] = None, + ) -> None: + self.dst_base_url = dst_base_url + self.dst_api_key = dst_api_key + + if custom_api_kwargs is None: + custom_api_kwargs = {"timeout": 600} + + self.dst_api = wandb.Api( + api_key=dst_api_key, + overrides={"base_url": dst_base_url}, + **custom_api_kwargs, + ) + self.mlflow_tracking_uri = mlflow_tracking_uri + mlflow.set_tracking_uri(self.mlflow_tracking_uri) + + if mlflow_registry_uri: + mlflow.set_registry_uri(mlflow_registry_uri) + + self.mlflow_client = mlflow.tracking.MlflowClient(mlflow_tracking_uri) + + def __repr__(self): + return f"" + + def collect_runs(self, *, limit: Optional[int] = None) -> Iterable[MlflowRun]: + if mlflow_version < Version("1.28.0"): + experiments = self.mlflow_client.list_experiments() + else: + experiments = self.mlflow_client.search_experiments() + + def _runs(): + for exp in experiments: + for run in self.mlflow_client.search_runs(exp.experiment_id): + yield MlflowRun(run, self.mlflow_client) + + runs = itertools.islice(_runs(), limit) + yield from runs + + def _import_run( + self, + run: MlflowRun, + *, + artifacts: bool = True, + namespace: Optional[Namespace] = None, + config: Optional[internal.SendManagerConfig] = None, + ) -> None: + if namespace is None: + namespace = Namespace(run.entity(), run.project()) + + if config is None: + config = internal.SendManagerConfig( + metadata=True, + files=True, + media=True, + code=True, + history=True, + summary=True, + terminal_output=True, + ) + + settings_override = { + "api_key": self.dst_api_key, + "base_url": self.dst_base_url, + "resume": "allow", + "resumed": True, + } + + mlflow.set_tracking_uri(self.mlflow_tracking_uri) + internal.send_run( + run, + overrides=namespace.send_manager_overrides, + settings_override=settings_override, + config=config, + ) + + # in mlflow, the artifacts come with the runs, so import them together + if artifacts: + arts = list(run.artifacts()) + logger.debug(f"Importing history artifacts, {run=}") + internal.send_run( + run, + extra_arts=arts, + overrides=namespace.send_manager_overrides, + settings_override=settings_override, + config=internal.SendManagerConfig(log_artifacts=True), + ) + + def import_runs( + self, + runs: Iterable[MlflowRun], + *, + artifacts: bool = True, + namespace: Optional[Namespace] = None, + parallel: bool = True, + max_workers: Optional[int] = None, + ) -> None: + def _import_run_wrapped(run): + self._import_run(run, namespace=namespace, artifacts=artifacts) + + for_each(_import_run_wrapped, runs, parallel=parallel, max_workers=max_workers) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/wandb.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/wandb.py new file mode 100644 index 0000000000000000000000000000000000000000..b325668295a1d245c1af01ed5a0ab3a997796b65 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/importers/wandb.py @@ -0,0 +1,1608 @@ +"""Tooling for the W&B Importer.""" + +import itertools +import json +import logging +import numbers +import os +import re +import shutil +from dataclasses import dataclass, field +from datetime import datetime as dt +from pathlib import Path +from typing import Any, Dict, Iterable, Iterator, List, Optional, Tuple +from unittest.mock import patch + +import filelock +import polars as pl +import requests +import urllib3 +import wandb_workspaces.reports.v1 as wr +import yaml +from wandb_gql import gql +from wandb_workspaces.reports.v1 import Report + +import wandb +from wandb.apis.public import ArtifactCollection, Run +from wandb.apis.public.files import File +from wandb.util import coalesce, remove_keys_with_none_values + +from . import validation +from .internals import internal +from .internals.protocols import PathStr, Policy +from .internals.util import Namespace, for_each + +Artifact = wandb.Artifact +Api = wandb.Api +Project = wandb.apis.public.Project + +ARTIFACT_ERRORS_FNAME = "artifact_errors.jsonl" +ARTIFACT_SUCCESSES_FNAME = "artifact_successes.jsonl" +RUN_ERRORS_FNAME = "run_errors.jsonl" +RUN_SUCCESSES_FNAME = "run_successes.jsonl" + +ART_SEQUENCE_DUMMY_PLACEHOLDER = "__ART_SEQUENCE_DUMMY_PLACEHOLDER__" +RUN_DUMMY_PLACEHOLDER = "__RUN_DUMMY_PLACEHOLDER__" +ART_DUMMY_PLACEHOLDER_PATH = "__importer_temp__" +ART_DUMMY_PLACEHOLDER_TYPE = "__temp__" + +SRC_ART_PATH = "./artifacts/src" +DST_ART_PATH = "./artifacts/dst" + + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +if os.getenv("WANDB_IMPORTER_ENABLE_RICH_LOGGING"): + from rich.logging import RichHandler + + logger.addHandler(RichHandler(rich_tracebacks=True, tracebacks_show_locals=True)) +else: + console_handler = logging.StreamHandler() + console_handler.setLevel(logging.INFO) + + formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") + console_handler.setFormatter(formatter) + + logger.addHandler(console_handler) + + +@dataclass +class ArtifactSequence: + artifacts: Iterable[wandb.Artifact] + entity: str + project: str + type_: str + name: str + + def __iter__(self) -> Iterator: + return iter(self.artifacts) + + def __repr__(self) -> str: + return f"ArtifactSequence({self.identifier})" + + @property + def identifier(self) -> str: + return "/".join([self.entity, self.project, self.type_, self.name]) + + @classmethod + def from_collection(cls, collection: ArtifactCollection): + arts = collection.artifacts() + arts = sorted(arts, key=lambda a: int(a.version.lstrip("v"))) + return ArtifactSequence( + arts, + collection.entity, + collection.project, + collection.type, + collection.name, + ) + + +class WandbRun: + def __init__( + self, + run: Run, + *, + src_base_url: str, + src_api_key: str, + dst_base_url: str, + dst_api_key: str, + ) -> None: + self.run = run + self.api = wandb.Api( + api_key=src_api_key, + overrides={"base_url": src_base_url}, + ) + self.dst_api = wandb.Api( + api_key=dst_api_key, + overrides={"base_url": dst_base_url}, + ) + + # For caching + self._files: Optional[Iterable[Tuple[str, str]]] = None + self._artifacts: Optional[Iterable[Artifact]] = None + self._used_artifacts: Optional[Iterable[Artifact]] = None + self._parquet_history_paths: Optional[Iterable[str]] = None + + def __repr__(self) -> str: + s = os.path.join(self.entity(), self.project(), self.run_id()) + return f"WandbRun({s})" + + def run_id(self) -> str: + return self.run.id + + def entity(self) -> str: + return self.run.entity + + def project(self) -> str: + return self.run.project + + def config(self) -> Dict[str, Any]: + return self.run.config + + def summary(self) -> Dict[str, float]: + s = self.run.summary + return s + + def metrics(self) -> Iterable[Dict[str, float]]: + if self._parquet_history_paths is None: + self._parquet_history_paths = list(self._get_parquet_history_paths()) + + if self._parquet_history_paths: + rows = self._get_rows_from_parquet_history_paths() + else: + logger.warning( + "No parquet files detected; using scan history (this may not be reliable)" + ) + rows = self.run.scan_history() + + for row in rows: + row = remove_keys_with_none_values(row) + yield row + + def run_group(self) -> Optional[str]: + return self.run.group + + def job_type(self) -> Optional[str]: + return self.run.job_type + + def display_name(self) -> str: + return self.run.display_name + + def notes(self) -> Optional[str]: + # Notes includes the previous notes and serves as a catch-all for things we missed or can't add back + previous_link = f"Imported from: {self.run.url}" + previous_author = f"Author: {self.run.user.username}" + + header = [previous_link, previous_author] + previous_notes = self.run.notes or "" + + return "\n".join(header) + "\n---\n" + previous_notes + + def tags(self) -> Optional[List[str]]: + return self.run.tags + + def artifacts(self) -> Optional[Iterable[Artifact]]: + if self._artifacts is None: + _artifacts = [] + for art in self.run.logged_artifacts(): + a = _clone_art(art) + _artifacts.append(a) + self._artifacts = _artifacts + + yield from self._artifacts + + def used_artifacts(self) -> Optional[Iterable[Artifact]]: + if self._used_artifacts is None: + _used_artifacts = [] + for art in self.run.used_artifacts(): + a = _clone_art(art) + _used_artifacts.append(a) + self._used_artifacts = _used_artifacts + + yield from self._used_artifacts + + def os_version(self) -> Optional[str]: ... # pragma: no cover + + def python_version(self) -> Optional[str]: + return self._metadata_file().get("python") + + def cuda_version(self) -> Optional[str]: ... # pragma: no cover + + def program(self) -> Optional[str]: ... # pragma: no cover + + def host(self) -> Optional[str]: + return self._metadata_file().get("host") + + def username(self) -> Optional[str]: ... # pragma: no cover + + def executable(self) -> Optional[str]: ... # pragma: no cover + + def gpus_used(self) -> Optional[str]: ... # pragma: no cover + + def cpus_used(self) -> Optional[int]: # can we get the model? + ... # pragma: no cover + + def memory_used(self) -> Optional[int]: ... # pragma: no cover + + def runtime(self) -> Optional[int]: + wandb_runtime = self.run.summary.get("_wandb", {}).get("runtime") + base_runtime = self.run.summary.get("_runtime") + + if (t := coalesce(wandb_runtime, base_runtime)) is None: + return t + return int(t) + + def start_time(self) -> Optional[int]: + t = dt.fromisoformat(self.run.created_at).timestamp() * 1000 + return int(t) + + def code_path(self) -> Optional[str]: + path = self._metadata_file().get("codePath", "") + return f"code/{path}" + + def cli_version(self) -> Optional[str]: + return self._config_file().get("_wandb", {}).get("value", {}).get("cli_version") + + def files(self) -> Optional[Iterable[Tuple[PathStr, Policy]]]: + if self._files is None: + files_dir = f"{internal.ROOT_DIR}/{self.run_id()}/files" + _files = [] + for f in self.run.files(): + f: File + # These optimizations are intended to avoid rate limiting when importing many runs in parallel + # Don't carry over empty files + if f.size == 0: + continue + # Skip deadlist to avoid overloading S3 + if "wandb_manifest.json.deadlist" in f.name: + continue + + result = f.download(files_dir, exist_ok=True, api=self.api) + file_and_policy = (result.name, "end") + _files.append(file_and_policy) + self._files = _files + + yield from self._files + + def logs(self) -> Optional[Iterable[str]]: + log_files = self._find_all_in_files_regex(r"^.*output\.log$") + for path in log_files: + with open(path) as f: + yield from f.readlines() + + def _metadata_file(self) -> Dict[str, Any]: + if (fname := self._find_in_files("wandb-metadata.json")) is None: + return {} + + with open(fname) as f: + return json.loads(f.read()) + + def _config_file(self) -> Dict[str, Any]: + if (fname := self._find_in_files("config.yaml")) is None: + return {} + + with open(fname) as f: + return yaml.safe_load(f) or {} + + def _get_rows_from_parquet_history_paths(self) -> Iterable[Dict[str, Any]]: + # Unfortunately, it's not feasible to validate non-parquet history + if not (paths := self._get_parquet_history_paths()): + yield {} + return + + # Collect and merge parquet history + dfs = [ + pl.read_parquet(p) for path in paths for p in Path(path).glob("*.parquet") + ] + if "_step" in (df := _merge_dfs(dfs)): + df = df.with_columns(pl.col("_step").cast(pl.Int64)) + yield from df.iter_rows(named=True) + + def _get_parquet_history_paths(self) -> Iterable[str]: + if self._parquet_history_paths is None: + paths = [] + # self.artifacts() returns a copy of the artifacts; use this to get raw + for art in self.run.logged_artifacts(): + if art.type != "wandb-history": + continue + if ( + path := _download_art(art, root=f"{SRC_ART_PATH}/{art.name}") + ) is None: + continue + paths.append(path) + self._parquet_history_paths = paths + + yield from self._parquet_history_paths + + def _find_in_files(self, name: str) -> Optional[str]: + if files := self.files(): + for path, _ in files: + if name in path: + return path + return None + + def _find_all_in_files_regex(self, regex: str) -> Iterable[str]: + if files := self.files(): + for path, _ in files: + if re.match(regex, path): + yield path + + +class WandbImporter: + """Transfers runs, reports, and artifact sequences between W&B instances.""" + + def __init__( + self, + src_base_url: str, + src_api_key: str, + dst_base_url: str, + dst_api_key: str, + *, + custom_api_kwargs: Optional[Dict[str, Any]] = None, + ) -> None: + self.src_base_url = src_base_url + self.src_api_key = src_api_key + self.dst_base_url = dst_base_url + self.dst_api_key = dst_api_key + + if custom_api_kwargs is None: + custom_api_kwargs = {"timeout": 600} + + self.src_api = wandb.Api( + api_key=src_api_key, + overrides={"base_url": src_base_url}, + **custom_api_kwargs, + ) + self.dst_api = wandb.Api( + api_key=dst_api_key, + overrides={"base_url": dst_base_url}, + **custom_api_kwargs, + ) + + self.run_api_kwargs = { + "src_base_url": src_base_url, + "src_api_key": src_api_key, + "dst_base_url": dst_base_url, + "dst_api_key": dst_api_key, + } + + def __repr__(self): + return f"" # pragma: no cover + + def _import_run( + self, + run: WandbRun, + *, + namespace: Optional[Namespace] = None, + config: Optional[internal.SendManagerConfig] = None, + ) -> None: + """Import one WandbRun. + + Use `namespace` to specify alternate settings like where the run should be uploaded + """ + if namespace is None: + namespace = Namespace(run.entity(), run.project()) + + if config is None: + config = internal.SendManagerConfig( + metadata=True, + files=True, + media=True, + code=True, + history=True, + summary=True, + terminal_output=True, + ) + + settings_override = { + "api_key": self.dst_api_key, + "base_url": self.dst_base_url, + "resume": "true", + "resumed": True, + } + + # Send run with base config + logger.debug(f"Importing run, {run=}") + internal.send_run( + run, + overrides=namespace.send_manager_overrides, + settings_override=settings_override, + config=config, + ) + + if config.history: + # Send run again with history artifacts in case config history=True, artifacts=False + # The history artifact must come with the actual history data + + logger.debug(f"Collecting history artifacts, {run=}") + history_arts = [] + for art in run.run.logged_artifacts(): + if art.type != "wandb-history": + continue + logger.debug(f"Collecting history artifact {art.name=}") + new_art = _clone_art(art) + history_arts.append(new_art) + + logger.debug(f"Importing history artifacts, {run=}") + internal.send_run( + run, + extra_arts=history_arts, + overrides=namespace.send_manager_overrides, + settings_override=settings_override, + config=config, + ) + + def _delete_collection_in_dst( + self, + seq: ArtifactSequence, + namespace: Optional[Namespace] = None, + ): + """Deletes the equivalent artifact collection in destination. + + Intended to clear the destination when an uploaded artifact does not pass validation. + """ + entity = coalesce(namespace.entity, seq.entity) + project = coalesce(namespace.project, seq.project) + art_type = f"{entity}/{project}/{seq.type_}" + art_name = seq.name + + logger.info( + f"Deleting collection {entity=}, {project=}, {art_type=}, {art_name=}" + ) + try: + dst_collection = self.dst_api.artifact_collection(art_type, art_name) + except (wandb.CommError, ValueError): + logger.warning(f"Collection doesn't exist {art_type=}, {art_name=}") + return + + try: + dst_collection.delete() + except (wandb.CommError, ValueError) as e: + logger.warning( + f"Collection can't be deleted, {art_type=}, {art_name=}, {e=}" + ) + return + + def _import_artifact_sequence( + self, + seq: ArtifactSequence, + *, + namespace: Optional[Namespace] = None, + ) -> None: + """Import one artifact sequence. + + Use `namespace` to specify alternate settings like where the artifact sequence should be uploaded + """ + if not seq.artifacts: + # The artifact sequence has no versions. This usually means all artifacts versions were deleted intentionally, + # but it can also happen if the sequence represents run history and that run was deleted. + logger.warning(f"Artifact {seq=} has no artifacts, skipping.") + return + + if namespace is None: + namespace = Namespace(seq.entity, seq.project) + + settings_override = { + "api_key": self.dst_api_key, + "base_url": self.dst_base_url, + "resume": "true", + "resumed": True, + } + + send_manager_config = internal.SendManagerConfig(log_artifacts=True) + + # Delete any existing artifact sequence, otherwise versions will be out of order + # Unfortunately, you can't delete only part of the sequence because versions are "remembered" even after deletion + self._delete_collection_in_dst(seq, namespace) + + # Get a placeholder run for dummy artifacts we'll upload later + art = seq.artifacts[0] + run_or_dummy: Optional[Run] = _get_run_or_dummy_from_art(art, self.src_api) + + # Each `group_of_artifacts` is either: + # 1. A single "real" artifact in a list; or + # 2. A list of dummy artifacts that are uploaded together. + # This guarantees the real artifacts have the correct version numbers while allowing for parallel upload of dummies. + groups_of_artifacts = list(_make_groups_of_artifacts(seq)) + for i, group in enumerate(groups_of_artifacts, 1): + art = group[0] + if art.description == ART_SEQUENCE_DUMMY_PLACEHOLDER: + run = WandbRun(run_or_dummy, **self.run_api_kwargs) + else: + try: + wandb_run = art.logged_by() + except ValueError: + # The run used to exist but has since been deleted + # wandb_run = None + pass + + # Could be logged by None (rare) or ValueError + if wandb_run is None: + logger.warning( + f"Run for {art.name=} does not exist (deleted?), using {run_or_dummy=}" + ) + wandb_run = run_or_dummy + + new_art = _clone_art(art) + group = [new_art] + run = WandbRun(wandb_run, **self.run_api_kwargs) + + logger.info( + f"Uploading partial artifact {seq=}, {i}/{len(groups_of_artifacts)}" + ) + internal.send_run( + run, + extra_arts=group, + overrides=namespace.send_manager_overrides, + settings_override=settings_override, + config=send_manager_config, + ) + logger.info(f"Finished uploading {seq=}") + + # query it back and remove placeholders + self._remove_placeholders(seq) + + def _remove_placeholders(self, seq: ArtifactSequence) -> None: + try: + retry_arts_func = internal.exp_retry(self._dst_api.artifacts) + dst_arts = list(retry_arts_func(seq.type_, seq.name)) + except wandb.CommError: + logger.warning( + f"{seq=} does not exist in dst. Has it already been deleted?" + ) + return + except TypeError: + logger.exception("Problem getting dst versions (try again later).") + return + + for art in dst_arts: + if art.description != ART_SEQUENCE_DUMMY_PLACEHOLDER: + continue + if art.type in ("wandb-history", "job"): + continue + + try: + art.delete(delete_aliases=True) + except wandb.CommError as e: + if "cannot delete system managed artifact" in str(e): + logger.warning("Cannot delete system managed artifact") + else: + raise + + def _get_dst_art( + self, src_art: Run, entity: Optional[str] = None, project: Optional[str] = None + ) -> Artifact: + entity = coalesce(entity, src_art.entity) + project = coalesce(project, src_art.project) + name = src_art.name + + return self.dst_api._artifact(f"{entity}/{project}/{name}") + + def _get_run_problems( + self, src_run: Run, dst_run: Run, force_retry: bool = False + ) -> List[dict]: + problems = [] + + if force_retry: + problems.append("__force_retry__") + + if non_matching_metadata := self._compare_run_metadata(src_run, dst_run): + problems.append("metadata:" + str(non_matching_metadata)) + + if non_matching_summary := self._compare_run_summary(src_run, dst_run): + problems.append("summary:" + str(non_matching_summary)) + + # TODO: Compare files? + + return problems + + def _compare_run_metadata(self, src_run: Run, dst_run: Run) -> dict: + fname = "wandb-metadata.json" + # problems = {} + + src_f = src_run.file(fname) + if src_f.size == 0: + # the src was corrupted so no comparisons here will ever work + return {} + + dst_f = dst_run.file(fname) + try: + contents = wandb.util.download_file_into_memory( + dst_f.url, self.dst_api.api_key + ) + except urllib3.exceptions.ReadTimeoutError: + return {"Error checking": "Timeout"} + except requests.HTTPError as e: + if e.response.status_code == 404: + return {"Bad upload": f"File not found: {fname}"} + return {"http problem": f"{fname}: ({e})"} + + dst_meta = wandb.wandb_sdk.lib.json_util.loads(contents) + + non_matching = {} + if src_run.metadata: + for k, src_v in src_run.metadata.items(): + if k not in dst_meta: + non_matching[k] = {"src": src_v, "dst": "KEY NOT FOUND"} + continue + dst_v = dst_meta[k] + if src_v != dst_v: + non_matching[k] = {"src": src_v, "dst": dst_v} + + return non_matching + + def _compare_run_summary(self, src_run: Run, dst_run: Run) -> dict: + non_matching = {} + for k, src_v in src_run.summary.items(): + # These won't match between systems and that's ok + if isinstance(src_v, str) and src_v.startswith("wandb-client-artifact://"): + continue + if k in ("_wandb", "_runtime"): + continue + + src_v = _recursive_cast_to_dict(src_v) + + dst_v = dst_run.summary.get(k) + dst_v = _recursive_cast_to_dict(dst_v) + + if isinstance(src_v, dict) and isinstance(dst_v, dict): + for kk, sv in src_v.items(): + # These won't match between systems and that's ok + if isinstance(sv, str) and sv.startswith( + "wandb-client-artifact://" + ): + continue + dv = dst_v.get(kk) + if not _almost_equal(sv, dv): + non_matching[f"{k}-{kk}"] = {"src": sv, "dst": dv} + else: + if not _almost_equal(src_v, dst_v): + non_matching[k] = {"src": src_v, "dst": dst_v} + + return non_matching + + def _collect_failed_artifact_sequences(self) -> Iterable[ArtifactSequence]: + if (df := _read_ndjson(ARTIFACT_ERRORS_FNAME)) is None: + logger.debug(f"{ARTIFACT_ERRORS_FNAME=} is empty, returning nothing") + return + + unique_failed_sequences = df[ + ["src_entity", "src_project", "name", "type"] + ].unique() + + for row in unique_failed_sequences.iter_rows(named=True): + entity = row["src_entity"] + project = row["src_project"] + name = row["name"] + _type = row["type"] + + art_name = f"{entity}/{project}/{name}" + arts = self.src_api.artifacts(_type, art_name) + arts = sorted(arts, key=lambda a: int(a.version.lstrip("v"))) + arts = sorted(arts, key=lambda a: a.type) + + yield ArtifactSequence(arts, entity, project, _type, name) + + def _cleanup_dummy_runs( + self, + *, + namespaces: Optional[Iterable[Namespace]] = None, + api: Optional[Api] = None, + remapping: Optional[Dict[Namespace, Namespace]] = None, + ) -> None: + api = coalesce(api, self.dst_api) + namespaces = coalesce(namespaces, self._all_namespaces()) + + for ns in namespaces: + if remapping and ns in remapping: + ns = remapping[ns] + + logger.debug(f"Cleaning up, {ns=}") + try: + runs = list( + api.runs(ns.path, filters={"displayName": RUN_DUMMY_PLACEHOLDER}) + ) + except ValueError as e: + if "Could not find project" in str(e): + logger.exception("Could not find project, does it exist?") + continue + + for run in runs: + logger.debug(f"Deleting dummy {run=}") + run.delete(delete_artifacts=False) + + def _import_report( + self, report: Report, *, namespace: Optional[Namespace] = None + ) -> None: + """Import one wandb.Report. + + Use `namespace` to specify alternate settings like where the report should be uploaded + """ + if namespace is None: + namespace = Namespace(report.entity, report.project) + + entity = coalesce(namespace.entity, report.entity) + project = coalesce(namespace.project, report.project) + name = report.name + title = report.title + description = report.description + + api = self.dst_api + + # We shouldn't need to upsert the project for every report + logger.debug(f"Upserting {entity=}/{project=}") + try: + api.create_project(project, entity) + except requests.exceptions.HTTPError as e: + if e.response.status_code != 409: + logger.warning(f"Issue upserting {entity=}/{project=}, {e=}") + + logger.debug(f"Upserting report {entity=}, {project=}, {name=}, {title=}") + api.client.execute( + wr.report.UPSERT_VIEW, + variable_values={ + "id": None, # Is there any benefit for this to be the same as default report? + "name": name, + "entityName": entity, + "projectName": project, + "description": description, + "displayName": title, + "type": "runs", + "spec": json.dumps(report.spec), + }, + ) + + def _use_artifact_sequence( + self, + sequence: ArtifactSequence, + *, + namespace: Optional[Namespace] = None, + ): + if namespace is None: + namespace = Namespace(sequence.entity, sequence.project) + + settings_override = { + "api_key": self.dst_api_key, + "base_url": self.dst_base_url, + "resume": "true", + "resumed": True, + } + logger.debug(f"Using artifact sequence with {settings_override=}, {namespace=}") + + send_manager_config = internal.SendManagerConfig(use_artifacts=True) + + for art in sequence: + if (used_by := art.used_by()) is None: + continue + + for wandb_run in used_by: + run = WandbRun(wandb_run, **self.run_api_kwargs) + + internal.send_run( + run, + overrides=namespace.send_manager_overrides, + settings_override=settings_override, + config=send_manager_config, + ) + + def import_runs( + self, + *, + namespaces: Optional[Iterable[Namespace]] = None, + remapping: Optional[Dict[Namespace, Namespace]] = None, + parallel: bool = True, + incremental: bool = True, + max_workers: Optional[int] = None, + limit: Optional[int] = None, + metadata: bool = True, + files: bool = True, + media: bool = True, + code: bool = True, + history: bool = True, + summary: bool = True, + terminal_output: bool = True, + ): + logger.info("START: Import runs") + + logger.info("Setting up for import") + _create_files_if_not_exists() + _clear_fname(RUN_ERRORS_FNAME) + + logger.info("Collecting runs") + runs = list(self._collect_runs(namespaces=namespaces, limit=limit)) + + logger.info(f"Validating runs, {len(runs)=}") + self._validate_runs( + runs, + skip_previously_validated=incremental, + remapping=remapping, + ) + + logger.info("Collecting failed runs") + runs = list(self._collect_failed_runs()) + + logger.info(f"Importing runs, {len(runs)=}") + + def _import_run_wrapped(run): + namespace = Namespace(run.entity(), run.project()) + if remapping is not None and namespace in remapping: + namespace = remapping[namespace] + + config = internal.SendManagerConfig( + metadata=metadata, + files=files, + media=media, + code=code, + history=history, + summary=summary, + terminal_output=terminal_output, + ) + + logger.debug(f"Importing {run=}, {namespace=}, {config=}") + self._import_run(run, namespace=namespace, config=config) + logger.debug(f"Finished importing {run=}, {namespace=}, {config=}") + + for_each(_import_run_wrapped, runs, max_workers=max_workers, parallel=parallel) + logger.info("END: Importing runs") + + def import_reports( + self, + *, + namespaces: Optional[Iterable[Namespace]] = None, + limit: Optional[int] = None, + remapping: Optional[Dict[Namespace, Namespace]] = None, + ): + logger.info("START: Importing reports") + + logger.info("Collecting reports") + reports = self._collect_reports(namespaces=namespaces, limit=limit) + + logger.info("Importing reports") + + def _import_report_wrapped(report): + namespace = Namespace(report.entity, report.project) + if remapping is not None and namespace in remapping: + namespace = remapping[namespace] + + logger.debug(f"Importing {report=}, {namespace=}") + self._import_report(report, namespace=namespace) + logger.debug(f"Finished importing {report=}, {namespace=}") + + for_each(_import_report_wrapped, reports) + + logger.info("END: Importing reports") + + def import_artifact_sequences( + self, + *, + namespaces: Optional[Iterable[Namespace]] = None, + incremental: bool = True, + max_workers: Optional[int] = None, + remapping: Optional[Dict[Namespace, Namespace]] = None, + ): + """Import all artifact sequences from `namespaces`. + + Note: There is a known bug with the AWS backend where artifacts > 2048MB will fail to upload. This seems to be related to multipart uploads, but we don't have a fix yet. + """ + logger.info("START: Importing artifact sequences") + _clear_fname(ARTIFACT_ERRORS_FNAME) + + logger.info("Collecting artifact sequences") + seqs = list(self._collect_artifact_sequences(namespaces=namespaces)) + + logger.info("Validating artifact sequences") + self._validate_artifact_sequences( + seqs, + incremental=incremental, + remapping=remapping, + ) + + logger.info("Collecting failed artifact sequences") + seqs = list(self._collect_failed_artifact_sequences()) + + logger.info(f"Importing artifact sequences, {len(seqs)=}") + + def _import_artifact_sequence_wrapped(seq): + namespace = Namespace(seq.entity, seq.project) + if remapping is not None and namespace in remapping: + namespace = remapping[namespace] + + logger.debug(f"Importing artifact sequence {seq=}, {namespace=}") + self._import_artifact_sequence(seq, namespace=namespace) + logger.debug(f"Finished importing artifact sequence {seq=}, {namespace=}") + + for_each(_import_artifact_sequence_wrapped, seqs, max_workers=max_workers) + + # it's safer to just use artifact on all seqs to make sure we don't miss anything + # For seqs that have already been used, this is a no-op. + logger.debug(f"Using artifact sequences, {len(seqs)=}") + + def _use_artifact_sequence_wrapped(seq): + namespace = Namespace(seq.entity, seq.project) + if remapping is not None and namespace in remapping: + namespace = remapping[namespace] + + logger.debug(f"Using artifact sequence {seq=}, {namespace=}") + self._use_artifact_sequence(seq, namespace=namespace) + logger.debug(f"Finished using artifact sequence {seq=}, {namespace=}") + + for_each(_use_artifact_sequence_wrapped, seqs, max_workers=max_workers) + + # Artifacts whose parent runs have been deleted should have that run deleted in the + # destination as well + + logger.info("Cleaning up dummy runs") + self._cleanup_dummy_runs( + namespaces=namespaces, + remapping=remapping, + ) + + logger.info("END: Importing artifact sequences") + + def import_all( + self, + *, + runs: bool = True, + artifacts: bool = True, + reports: bool = True, + namespaces: Optional[Iterable[Namespace]] = None, + incremental: bool = True, + remapping: Optional[Dict[Namespace, Namespace]] = None, + ): + logger.info(f"START: Importing all, {runs=}, {artifacts=}, {reports=}") + if runs: + self.import_runs( + namespaces=namespaces, + incremental=incremental, + remapping=remapping, + ) + + if reports: + self.import_reports( + namespaces=namespaces, + remapping=remapping, + ) + + if artifacts: + self.import_artifact_sequences( + namespaces=namespaces, + incremental=incremental, + remapping=remapping, + ) + + logger.info("END: Importing all") + + def _validate_run( + self, + src_run: Run, + *, + remapping: Optional[Dict[Namespace, Namespace]] = None, + ) -> None: + namespace = Namespace(src_run.entity, src_run.project) + if remapping is not None and namespace in remapping: + namespace = remapping[namespace] + + dst_entity = namespace.entity + dst_project = namespace.project + run_id = src_run.id + + try: + dst_run = self.dst_api.run(f"{dst_entity}/{dst_project}/{run_id}") + except wandb.CommError: + problems = [f"run does not exist in dst at {dst_entity=}/{dst_project=}"] + else: + problems = self._get_run_problems(src_run, dst_run) + + d = { + "src_entity": src_run.entity, + "src_project": src_run.project, + "dst_entity": dst_entity, + "dst_project": dst_project, + "run_id": run_id, + } + if problems: + d["problems"] = problems + fname = RUN_ERRORS_FNAME + else: + fname = RUN_SUCCESSES_FNAME + + with filelock.FileLock("runs.lock"): + with open(fname, "a") as f: + f.write(json.dumps(d) + "\n") + + def _filter_previously_checked_runs( + self, + runs: Iterable[Run], + *, + remapping: Optional[Dict[Namespace, Namespace]] = None, + ) -> Iterable[Run]: + if (df := _read_ndjson(RUN_SUCCESSES_FNAME)) is None: + logger.debug(f"{RUN_SUCCESSES_FNAME=} is empty, yielding all runs") + yield from runs + return + + data = [] + for r in runs: + namespace = Namespace(r.entity, r.project) + if remapping is not None and namespace in remapping: + namespace = remapping[namespace] + + data.append( + { + "src_entity": r.entity, + "src_project": r.project, + "dst_entity": namespace.entity, + "dst_project": namespace.project, + "run_id": r.id, + "data": r, + } + ) + df2 = pl.DataFrame(data) + logger.debug(f"Starting with {len(runs)=} in namespaces") + + results = df2.join( + df, + how="anti", + on=["src_entity", "src_project", "dst_entity", "dst_project", "run_id"], + ) + logger.debug(f"After filtering out already successful runs, {len(results)=}") + + if not results.is_empty(): + results = results.filter(~results["run_id"].is_null()) + results = results.unique( + ["src_entity", "src_project", "dst_entity", "dst_project", "run_id"] + ) + + for r in results.iter_rows(named=True): + yield r["data"] + + def _validate_artifact( + self, + src_art: Artifact, + dst_entity: str, + dst_project: str, + download_files_and_compare: bool = False, + check_entries_are_downloadable: bool = True, + ): + problems = [] + + # These patterns of artifacts are special and should not be validated + ignore_patterns = [ + r"^job-(.*?)\.py(:v\d+)?$", + # r"^run-.*-history(?:\:v\d+)?$$", + ] + for pattern in ignore_patterns: + if re.search(pattern, src_art.name): + return (src_art, dst_entity, dst_project, problems) + + try: + dst_art = self._get_dst_art(src_art, dst_entity, dst_project) + except Exception: + problems.append("destination artifact not found") + return (src_art, dst_entity, dst_project, problems) + + try: + logger.debug("Comparing artifact manifests") + except Exception as e: + problems.append( + f"Problem getting problems! problem with {src_art.entity=}, {src_art.project=}, {src_art.name=} {e=}" + ) + else: + problems += validation._compare_artifact_manifests(src_art, dst_art) + + if check_entries_are_downloadable: + # validation._check_entries_are_downloadable(src_art) + validation._check_entries_are_downloadable(dst_art) + + if download_files_and_compare: + logger.debug(f"Downloading {src_art=}") + try: + src_dir = _download_art(src_art, root=f"{SRC_ART_PATH}/{src_art.name}") + except requests.HTTPError as e: + problems.append( + f"Invalid download link for src {src_art.entity=}, {src_art.project=}, {src_art.name=}, {e}" + ) + + logger.debug(f"Downloading {dst_art=}") + try: + dst_dir = _download_art(dst_art, root=f"{DST_ART_PATH}/{dst_art.name}") + except requests.HTTPError as e: + problems.append( + f"Invalid download link for dst {dst_art.entity=}, {dst_art.project=}, {dst_art.name=}, {e}" + ) + else: + logger.debug(f"Comparing artifact dirs {src_dir=}, {dst_dir=}") + if problem := validation._compare_artifact_dirs(src_dir, dst_dir): + problems.append(problem) + + return (src_art, dst_entity, dst_project, problems) + + def _validate_runs( + self, + runs: Iterable[WandbRun], + *, + skip_previously_validated: bool = True, + remapping: Optional[Dict[Namespace, Namespace]] = None, + ): + base_runs = [r.run for r in runs] + if skip_previously_validated: + base_runs = list( + self._filter_previously_checked_runs( + base_runs, + remapping=remapping, + ) + ) + + def _validate_run(run): + logger.debug(f"Validating {run=}") + self._validate_run(run, remapping=remapping) + logger.debug(f"Finished validating {run=}") + + for_each(_validate_run, base_runs) + + def _collect_failed_runs(self): + if (df := _read_ndjson(RUN_ERRORS_FNAME)) is None: + logger.debug(f"{RUN_ERRORS_FNAME=} is empty, returning nothing") + return + + unique_failed_runs = df[ + ["src_entity", "src_project", "dst_entity", "dst_project", "run_id"] + ].unique() + + for row in unique_failed_runs.iter_rows(named=True): + src_entity = row["src_entity"] + src_project = row["src_project"] + # dst_entity = row["dst_entity"] + # dst_project = row["dst_project"] + run_id = row["run_id"] + + run = self.src_api.run(f"{src_entity}/{src_project}/{run_id}") + yield WandbRun(run, **self.run_api_kwargs) + + def _filter_previously_checked_artifacts(self, seqs: Iterable[ArtifactSequence]): + if (df := _read_ndjson(ARTIFACT_SUCCESSES_FNAME)) is None: + logger.info( + f"{ARTIFACT_SUCCESSES_FNAME=} is empty, yielding all artifact sequences" + ) + for seq in seqs: + yield from seq.artifacts + return + + for seq in seqs: + for art in seq: + try: + logged_by = _get_run_or_dummy_from_art(art, self.src_api) + except requests.HTTPError: + logger.exception(f"Failed to get run, skipping: {art=}") + continue + + if art.type == "wandb-history" and isinstance(logged_by, _DummyRun): + logger.debug(f"Skipping history artifact {art=}") + # We can never upload valid history for a deleted run, so skip it + continue + + entity = art.entity + project = art.project + _type = art.type + name, ver = _get_art_name_ver(art) + + filtered_df = df.filter( + (df["src_entity"] == entity) + & (df["src_project"] == project) + & (df["name"] == name) + & (df["version"] == ver) + & (df["type"] == _type) + ) + + # not in file, so not verified yet, don't filter out + if len(filtered_df) == 0: + yield art + + def _validate_artifact_sequences( + self, + seqs: Iterable[ArtifactSequence], + *, + incremental: bool = True, + download_files_and_compare: bool = False, + check_entries_are_downloadable: bool = True, + remapping: Optional[Dict[Namespace, Namespace]] = None, + ): + if incremental: + logger.info("Validating in incremental mode") + + def filtered_sequences(): + for seq in seqs: + if not seq.artifacts: + continue + + art = seq.artifacts[0] + try: + logged_by = _get_run_or_dummy_from_art(art, self.src_api) + except requests.HTTPError: + logger.exception( + f"Validate Artifact http error: {art.entity=}," + f" {art.project=}, {art.name=}" + ) + continue + + if art.type == "wandb-history" and isinstance(logged_by, _DummyRun): + # We can never upload valid history for a deleted run, so skip it + continue + + yield seq + + artifacts = self._filter_previously_checked_artifacts(filtered_sequences()) + else: + logger.info("Validating in non-incremental mode") + artifacts = [art for seq in seqs for art in seq.artifacts] + + def _validate_artifact_wrapped(args): + art, entity, project = args + if ( + remapping is not None + and (namespace := Namespace(entity, project)) in remapping + ): + remapped_ns = remapping[namespace] + entity = remapped_ns.entity + project = remapped_ns.project + + logger.debug(f"Validating {art=}, {entity=}, {project=}") + result = self._validate_artifact( + art, + entity, + project, + download_files_and_compare=download_files_and_compare, + check_entries_are_downloadable=check_entries_are_downloadable, + ) + logger.debug(f"Finished validating {art=}, {entity=}, {project=}") + return result + + args = ((art, art.entity, art.project) for art in artifacts) + art_problems = for_each(_validate_artifact_wrapped, args) + for art, dst_entity, dst_project, problems in art_problems: + name, ver = _get_art_name_ver(art) + d = { + "src_entity": art.entity, + "src_project": art.project, + "dst_entity": dst_entity, + "dst_project": dst_project, + "name": name, + "version": ver, + "type": art.type, + } + + if problems: + d["problems"] = problems + fname = ARTIFACT_ERRORS_FNAME + else: + fname = ARTIFACT_SUCCESSES_FNAME + + with open(fname, "a") as f: + f.write(json.dumps(d) + "\n") + + def _collect_runs( + self, + *, + namespaces: Optional[Iterable[Namespace]] = None, + limit: Optional[int] = None, + skip_ids: Optional[List[str]] = None, + start_date: Optional[str] = None, + api: Optional[Api] = None, + ) -> Iterable[WandbRun]: + api = coalesce(api, self.src_api) + namespaces = coalesce(namespaces, self._all_namespaces()) + + filters: Dict[str, Any] = {} + if skip_ids is not None: + filters["name"] = {"$nin": skip_ids} + if start_date is not None: + filters["createdAt"] = {"$gte": start_date} + + def _runs(): + for ns in namespaces: + logger.debug(f"Collecting runs from {ns=}") + for run in api.runs(ns.path, filters=filters): + yield WandbRun(run, **self.run_api_kwargs) + + runs = itertools.islice(_runs(), limit) + yield from runs + + def _all_namespaces( + self, *, entity: Optional[str] = None, api: Optional[Api] = None + ): + api = coalesce(api, self.src_api) + entity = coalesce(entity, api.default_entity) + projects = api.projects(entity) + for p in projects: + yield Namespace(p.entity, p.name) + + def _collect_reports( + self, + *, + namespaces: Optional[Iterable[Namespace]] = None, + limit: Optional[int] = None, + api: Optional[Api] = None, + ): + api = coalesce(api, self.src_api) + namespaces = coalesce(namespaces, self._all_namespaces()) + + wandb.login(key=self.src_api_key, host=self.src_base_url) + + def reports(): + for ns in namespaces: + for r in api.reports(ns.path): + yield wr.Report.from_url(r.url, api=api) + + yield from itertools.islice(reports(), limit) + + def _collect_artifact_sequences( + self, + *, + namespaces: Optional[Iterable[Namespace]] = None, + limit: Optional[int] = None, + api: Optional[Api] = None, + ): + api = coalesce(api, self.src_api) + namespaces = coalesce(namespaces, self._all_namespaces()) + + def artifact_sequences(): + for ns in namespaces: + logger.debug(f"Collecting artifact sequences from {ns=}") + types = [] + try: + types = [t for t in api.artifact_types(ns.path)] + except Exception: + logger.exception("Failed to get artifact types.") + + for t in types: + collections = [] + + # Skip history because it's really for run history + if t.name == "wandb-history": + continue + + try: + collections = t.collections() + except Exception: + logger.exception("Failed to get artifact collections.") + + for c in collections: + if c.is_sequence(): + yield ArtifactSequence.from_collection(c) + + seqs = itertools.islice(artifact_sequences(), limit) + unique_sequences = {seq.identifier: seq for seq in seqs} + yield from unique_sequences.values() + + +def _get_art_name_ver(art: Artifact) -> Tuple[str, int]: + name, ver = art.name.split(":v") + return name, int(ver) + + +def _make_dummy_art(name: str, _type: str, ver: int): + art = Artifact(name, ART_DUMMY_PLACEHOLDER_TYPE) + art._type = _type + art._description = ART_SEQUENCE_DUMMY_PLACEHOLDER + + p = Path(ART_DUMMY_PLACEHOLDER_PATH) + p.mkdir(parents=True, exist_ok=True) + + # dummy file with different name to prevent dedupe + fname = p / str(ver) + with open(fname, "w"): + pass + art.add_file(fname) + + return art + + +def _make_groups_of_artifacts(seq: ArtifactSequence, start: int = 0): + prev_ver = start - 1 + for art in seq: + name, ver = _get_art_name_ver(art) + + # If there's a gap between versions, fill with dummy artifacts + if ver - prev_ver > 1: + yield [_make_dummy_art(name, art.type, v) for v in range(prev_ver + 1, ver)] + + # Then yield the actual artifact + # Must always be a list of one artifact to guarantee ordering + yield [art] + prev_ver = ver + + +def _recursive_cast_to_dict(obj): + if isinstance(obj, list): + return [_recursive_cast_to_dict(item) for item in obj] + elif isinstance(obj, dict) or hasattr(obj, "items"): + new_dict = {} + for key, value in obj.items(): + new_dict[key] = _recursive_cast_to_dict(value) + return new_dict + else: + return obj + + +def _almost_equal(x, y, eps=1e-6): + if isinstance(x, dict) and isinstance(y, dict): + if x.keys() != y.keys(): + return False + return all(_almost_equal(x[k], y[k], eps) for k in x) + + if isinstance(x, numbers.Number) and isinstance(y, numbers.Number): + return abs(x - y) < eps + + if type(x) is not type(y): + return False + + return x == y + + +@dataclass +class _DummyUser: + username: str = "" + + +@dataclass +class _DummyRun: + entity: str = "" + project: str = "" + run_id: str = RUN_DUMMY_PLACEHOLDER + id: str = RUN_DUMMY_PLACEHOLDER + display_name: str = RUN_DUMMY_PLACEHOLDER + notes: str = "" + url: str = "" + group: str = "" + created_at: str = "2000-01-01" + user: _DummyUser = field(default_factory=_DummyUser) + tags: list = field(default_factory=list) + summary: dict = field(default_factory=dict) + config: dict = field(default_factory=dict) + + def files(self): + return [] + + +def _read_ndjson(fname: str) -> Optional[pl.DataFrame]: + try: + df = pl.read_ndjson(fname) + except FileNotFoundError: + return None + except RuntimeError as e: + # No runs previously checked + if "empty string is not a valid JSON value" in str(e): + return None + if "error parsing ndjson" in str(e): + return None + raise + + return df + + +def _get_run_or_dummy_from_art(art: Artifact, api=None): + run = None + + try: + run = art.logged_by() + except ValueError as e: + logger.warning( + f"Can't log artifact because run doesn't exist, {art=}, {run=}, {e=}" + ) + + if run is not None: + return run + + query = gql( + """ + query ArtifactCreatedBy( + $id: ID! + ) { + artifact(id: $id) { + createdBy { + ... on Run { + name + project { + name + entityName + } + } + } + } + } + """ + ) + response = api.client.execute(query, variable_values={"id": art.id}) + creator = response.get("artifact", {}).get("createdBy", {}) + run = _DummyRun( + entity=art.entity, + project=art.project, + run_id=creator.get("name", RUN_DUMMY_PLACEHOLDER), + id=creator.get("name", RUN_DUMMY_PLACEHOLDER), + ) + return run + + +def _clear_fname(fname: str) -> None: + old_fname = f"{internal.ROOT_DIR}/{fname}" + new_fname = f"{internal.ROOT_DIR}/prev_{fname}" + + logger.debug(f"Moving {old_fname=} to {new_fname=}") + try: + shutil.copy2(old_fname, new_fname) + except FileNotFoundError: + # this is just to make a copy of the last iteration, so its ok if the src doesn't exist + pass + + with open(fname, "w"): + pass + + +def _download_art(art: Artifact, root: str) -> Optional[str]: + try: + with patch("click.echo"): + return art.download(root=root, skip_cache=True) + except Exception: + logger.exception(f"Error downloading artifact {art=}") + + +def _clone_art(art: Artifact, root: Optional[str] = None): + if root is None: + # Currently, we would only ever clone a src artifact to move it to dst. + root = f"{SRC_ART_PATH}/{art.name}" + + if (path := _download_art(art, root=root)) is None: + raise ValueError(f"Problem downloading {art=}") + + name, _ = art.name.split(":v") + + # Hack: skip naming validation check for wandb-* types + new_art = Artifact(name, ART_DUMMY_PLACEHOLDER_TYPE) + new_art._type = art.type + new_art._created_at = art.created_at + + new_art._aliases = art.aliases + new_art._description = art.description + + with patch("click.echo"): + new_art.add_dir(path) + + return new_art + + +def _create_files_if_not_exists() -> None: + fnames = [ + ARTIFACT_ERRORS_FNAME, + ARTIFACT_SUCCESSES_FNAME, + RUN_ERRORS_FNAME, + RUN_SUCCESSES_FNAME, + ] + + for fname in fnames: + logger.debug(f"Creating {fname=} if not exists") + with open(fname, "a"): + pass + + +def _merge_dfs(dfs: List[pl.DataFrame]) -> pl.DataFrame: + # Ensure there are DataFrames in the list + if len(dfs) == 0: + return pl.DataFrame() + + if len(dfs) == 1: + return dfs[0] + + merged_df = dfs[0] + for df in dfs[1:]: + merged_df = merged_df.join(df, how="outer", on=["_step"]) + col_pairs = [ + (c, f"{c}_right") + for c in merged_df.columns + if f"{c}_right" in merged_df.columns + ] + for col, right in col_pairs: + new_col = merged_df[col].fill_null(merged_df[right]) + merged_df = merged_df.with_columns(new_col).drop(right) + + return merged_df diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/internal.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/internal.py new file mode 100644 index 0000000000000000000000000000000000000000..4452213e2228324b561552c555e6a9359a45a102 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/internal.py @@ -0,0 +1,239 @@ +from typing import Any + +from wandb.sdk.internal.internal_api import Api as InternalApi + + +class Api: + """Internal proxy to the official internal API.""" + + # TODO: Move these methods to PublicApi. + + def __init__(self, *args: Any, **kwargs: Any) -> None: + self._api_args = args + self._api_kwargs = kwargs + self._api = None + + def __getstate__(self): + """Use for serializing. + + self._api is not serializable, so it's dropped + """ + state = self.__dict__.copy() + del state["_api"] + return state + + def __setstate__(self, state): + """Used for deserializing. + + Don't need to set self._api because it's constructed when needed. + """ + self.__dict__.update(state) + self._api = None + + @property + def api(self) -> InternalApi: + # This is a property in order to delay construction of Internal API + # for as long as possible. If constructed in constructor, then the + # whole InternalAPI is started when simply importing wandb. + if self._api is None: + self._api = InternalApi(*self._api_args, **self._api_kwargs) + return self._api + + @property + def api_key(self): + return self.api.api_key + + @property + def is_authenticated(self): + return self.api.access_token is not None or self.api.api_key is not None + + @property + def api_url(self): + return self.api.api_url + + @property + def app_url(self): + return self.api.app_url + + @property + def default_entity(self): + return self.api.default_entity + + @property + def git(self): + return self.api.git + + def validate_api_key(self) -> bool: + """Returns whether the API key stored on initialization is valid.""" + return self.api.validate_api_key() + + def file_current(self, *args): + return self.api.file_current(*args) + + def download_file(self, *args, **kwargs): + return self.api.download_file(*args, **kwargs) + + def download_write_file(self, *args, **kwargs): + return self.api.download_write_file(*args, **kwargs) + + def set_current_run_id(self, run_id): + return self.api.set_current_run_id(run_id) + + def viewer(self): + return self.api.viewer() + + def max_cli_version(self): + return self.api.max_cli_version() + + def viewer_server_info(self): + return self.api.viewer_server_info() + + def list_projects(self, entity=None): + return self.api.list_projects(entity=entity) + + def format_project(self, project): + return self.api.format_project(project) + + def upsert_project(self, project, id=None, description=None, entity=None): + return self.api.upsert_project( + project, id=id, description=description, entity=entity + ) + + def upsert_run(self, *args, **kwargs): + return self.api.upsert_run(*args, **kwargs) + + def settings(self, *args, **kwargs): + return self.api.settings(*args, **kwargs) + + def clear_setting( + self, key: str, globally: bool = False, persist: bool = False + ) -> None: + return self.api.clear_setting(key, globally, persist) + + def set_setting( + self, key: str, value: Any, globally: bool = False, persist: bool = False + ) -> None: + return self.api.set_setting(key, value, globally, persist) + + def parse_slug(self, *args, **kwargs): + return self.api.parse_slug(*args, **kwargs) + + def download_url(self, *args, **kwargs): + return self.api.download_url(*args, **kwargs) + + def download_urls(self, *args, **kwargs): + return self.api.download_urls(*args, **kwargs) + + def create_anonymous_api_key(self) -> str: + return self.api.create_anonymous_api_key() + + def push(self, *args, **kwargs): + return self.api.push(*args, **kwargs) + + def sweep(self, *args, **kwargs): + return self.api.sweep(*args, **kwargs) + + def upsert_sweep(self, *args, **kwargs): + return self.api.upsert_sweep(*args, **kwargs) + + def set_sweep_state(self, *args, **kwargs): + return self.api.set_sweep_state(*args, **kwargs) + + def get_sweep_state(self, *args, **kwargs): + return self.api.get_sweep_state(*args, **kwargs) + + def stop_sweep(self, *args, **kwargs): + return self.api.stop_sweep(*args, **kwargs) + + def cancel_sweep(self, *args, **kwargs): + return self.api.cancel_sweep(*args, **kwargs) + + def pause_sweep(self, *args, **kwargs): + return self.api.pause_sweep(*args, **kwargs) + + def resume_sweep(self, *args, **kwargs): + return self.api.resume_sweep(*args, **kwargs) + + def register_agent(self, *args, **kwargs): + return self.api.register_agent(*args, **kwargs) + + def agent_heartbeat(self, *args, **kwargs): + return self.api.agent_heartbeat(*args, **kwargs) + + def use_artifact(self, *args, **kwargs): + return self.api.use_artifact(*args, **kwargs) + + def create_artifact(self, *args, **kwargs): + return self.api.create_artifact(*args, **kwargs) + + def complete_multipart_upload_artifact(self, *args, **kwargs): + return self.api.complete_multipart_upload_artifact(*args, **kwargs) + + def run_config(self, *args, **kwargs): + return self.api.run_config(*args, **kwargs) + + def upload_file_retry(self, *args, **kwargs): + return self.api.upload_file_retry(*args, **kwargs) + + def upload_multipart_file_chunk_retry(self, *args, **kwargs): + return self.api.upload_multipart_file_chunk_retry(*args, **kwargs) + + def get_run_info(self, *args, **kwargs): + return self.api.get_run_info(*args, **kwargs) + + def get_run_state(self, *args, **kwargs): + return self.api.get_run_state(*args, **kwargs) + + def entity_is_team(self, *args, **kwargs): + return self.api.entity_is_team(*args, **kwargs) + + def get_project_run_queues(self, *args, **kwargs): + return self.api.get_project_run_queues(*args, **kwargs) + + def push_to_run_queue(self, *args, **kwargs): + return self.api.push_to_run_queue(*args, **kwargs) + + def pop_from_run_queue(self, *args, **kwargs): + return self.api.pop_from_run_queue(*args, **kwargs) + + def ack_run_queue_item(self, *args, **kwargs): + return self.api.ack_run_queue_item(*args, **kwargs) + + def create_launch_agent(self, *args, **kwargs): + return self.api.create_launch_agent(*args, **kwargs) + + def create_default_resource_config(self, *args, **kwargs): + return self.api.create_default_resource_config(*args, **kwargs) + + def create_run_queue(self, *args, **kwargs): + return self.api.create_run_queue(*args, **kwargs) + + def upsert_run_queue(self, *args, **kwargs): + return self.api.upsert_run_queue(*args, **kwargs) + + def create_custom_chart(self, *args, **kwargs): + return self.api.create_custom_chart(*args, **kwargs) + + def update_launch_agent_status(self, *args, **kwargs): + return self.api.update_launch_agent_status(*args, **kwargs) + + def launch_agent_introspection(self, *args, **kwargs): + return self.api.launch_agent_introspection(*args, **kwargs) + + def fail_run_queue_item_introspection(self, *args, **kwargs): + return self.api.fail_run_queue_item_introspection(*args, **kwargs) + + def fail_run_queue_item(self, *args, **kwargs): + return self.api.fail_run_queue_item(*args, **kwargs) + + def update_run_queue_item_warning(self, *args, **kwargs): + return self.api.update_run_queue_item_warning(*args, **kwargs) + + def get_launch_agent(self, *args, **kwargs): + return self.api.get_launch_agent(*args, **kwargs) + + def stop_run(self, *args, **kwargs): + return self.api.stop_run(*args, **kwargs) + + +__all__ = ["Api"] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03bf90820782f9a2067747d025d46ec92be69ead Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/api.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47274f9be33d1d04ed79287af905a365153fdaa0 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/api.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/automations.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/automations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2cc6b68bbdd933a207fc1398c10030510df32774 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/automations.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/const.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/const.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c3709e4e787fae7608e593d306e6d6da25e075c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/const.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/files.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/files.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce49c6c931506c9c9def07c4df1261464b5118c5 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/files.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/integrations.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/integrations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1c7365a12b05094865e64b3dffe94423a5fba19 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/integrations.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/jobs.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/jobs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b33524eca7809254f56ea7c684abaa428b9e5bf9 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/jobs.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/query_generator.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/query_generator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0d15b386c890b308b88af9b87a81637c6aa8019 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/query_generator.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/reports.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/reports.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c1b06b41fad3c32e3153e01c85bf89652db07f1 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/reports.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/runs.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/runs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88da83c8af0f70afaa21ebde98d52bafb42b882c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/runs.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/sweeps.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/sweeps.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35cca29452160f14b3ddbf38ec5b8b3ccface16f Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/sweeps.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/users.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/users.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..237526c790a24610d8c75eff4627e3ca53a2ed31 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/users.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efdc16d398ed6e91e9a3c5af660c3ef21debf9de Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/__pycache__/utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/api.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/api.py new file mode 100644 index 0000000000000000000000000000000000000000..33df8f0bc4d98243964f77db420a173aa0d31e43 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/api.py @@ -0,0 +1,2450 @@ +"""Use the Public API to export or update data that you have saved to W&B. + +Before using this API, you'll want to log data from your script — check the +[Quickstart](https://docs.wandb.ai/quickstart) for more details. + +You might use the Public API to + - update metadata or metrics for an experiment after it has been completed, + - pull down your results as a dataframe for post-hoc analysis in a Jupyter notebook, or + - check your saved model artifacts for those tagged as `ready-to-deploy`. + +For more on using the Public API, check out [our guide](https://docs.wandb.com/guides/track/public-api-guide). +""" + +import json +import logging +import os +import urllib +from http import HTTPStatus +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Iterator, + List, + Literal, + Optional, + Set, + Union, +) + +import requests +from pydantic import ValidationError +from typing_extensions import Unpack +from wandb_gql import Client, gql +from wandb_gql.client import RetryError + +import wandb +from wandb import env, util +from wandb._iterutils import one +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._utils import fetch_org_entity_from_organization +from wandb.apis.public.registries.registries_search import Registries +from wandb.apis.public.registries.registry import Registry +from wandb.apis.public.utils import ( + PathType, + fetch_org_from_settings_or_entity, + gql_compat, + parse_org_from_registry_path, +) +from wandb.proto.wandb_deprecated import Deprecated +from wandb.proto.wandb_internal_pb2 import ServerFeature +from wandb.sdk import wandb_login +from wandb.sdk.artifacts._validators import is_artifact_registry_project +from wandb.sdk.internal.internal_api import Api as InternalApi +from wandb.sdk.internal.thread_local_settings import _thread_local_api_settings +from wandb.sdk.launch.utils import LAUNCH_DEFAULT_PROJECT +from wandb.sdk.lib import retry, runid +from wandb.sdk.lib.deprecate import deprecate +from wandb.sdk.lib.gql_request import GraphQLSession + +if TYPE_CHECKING: + from wandb.automations import ( + ActionType, + Automation, + EventType, + Integration, + NewAutomation, + SlackIntegration, + WebhookIntegration, + ) + from wandb.automations._utils import WriteAutomationsKwargs + +logger = logging.getLogger(__name__) + + +class RetryingClient: + """A GraphQL client that retries requests on failure. + + + """ + + INFO_QUERY = gql( + """ + query ServerInfo{ + serverInfo { + cliVersionInfo + latestLocalVersionInfo { + outOfDate + latestVersionString + versionOnThisInstanceString + } + } + } + """ + ) + + def __init__(self, client: Client): + self._server_info = None + self._client = client + + @property + def app_url(self): + return util.app_url(self._client.transport.url.replace("/graphql", "")) + "/" + + @retry.retriable( + retry_timedelta=RETRY_TIMEDELTA, + check_retry_fn=util.no_retry_auth, + retryable_exceptions=(RetryError, requests.RequestException), + ) + def execute( + self, *args, **kwargs + ): # User not encouraged to use this class directly + try: + return self._client.execute(*args, **kwargs) + except requests.exceptions.ReadTimeout: + if "timeout" not in kwargs: + timeout = self._client.transport.default_timeout + wandb.termwarn( + f"A graphql request initiated by the public wandb API timed out (timeout={timeout} sec). " + f"Create a new API with an integer timeout larger than {timeout}, e.g., `api = wandb.Api(timeout={timeout + 10})` " + f"to increase the graphql timeout." + ) + raise + + @property + def server_info(self): + if self._server_info is None: + self._server_info = self.execute(self.INFO_QUERY).get("serverInfo") + return self._server_info + + def version_supported( + self, min_version: str + ) -> bool: # User not encouraged to use this class directly + from packaging.version import parse + + return parse(min_version) <= parse( + self.server_info["cliVersionInfo"]["max_cli_version"] + ) + + +class Api: + """Used for querying the W&B server. + + Examples: + ```python + import wandb + + wandb.Api() + ``` + """ + + _HTTP_TIMEOUT = env.get_http_timeout(19) + DEFAULT_ENTITY_QUERY = gql( + """ + query Viewer{ + viewer { + id + entity + } + } + """ + ) + + VIEWER_QUERY = gql( + """ + query Viewer{ + viewer { + id + flags + entity + username + email + admin + apiKeys { + edges { + node { + id + name + description + } + } + } + teams { + edges { + node { + name + } + } + } + } + } + """ + ) + USERS_QUERY = gql( + """ + query SearchUsers($query: String) { + users(query: $query) { + edges { + node { + id + flags + entity + admin + email + deletedAt + username + apiKeys { + edges { + node { + id + name + description + } + } + } + teams { + edges { + node { + name + } + } + } + } + } + } + } + """ + ) + + CREATE_PROJECT = gql( + """ + mutation upsertModel( + $description: String + $entityName: String + $id: String + $name: String + $framework: String + $access: String + $views: JSONString + ) { + upsertModel( + input: { + description: $description + entityName: $entityName + id: $id + name: $name + framework: $framework + access: $access + views: $views + } + ) { + project { + id + name + entityName + description + access + views + } + model { + id + name + entityName + description + access + views + } + inserted + } + } + """ + ) + + def __init__( + self, + overrides: Optional[Dict[str, Any]] = None, + timeout: Optional[int] = None, + api_key: Optional[str] = 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. + """ + self.settings = InternalApi().settings() + + _overrides = overrides or {} + self.settings.update(_overrides) + self.settings["base_url"] = self.settings["base_url"].rstrip("/") + if "organization" in _overrides: + self.settings["organization"] = _overrides["organization"] + if "username" in _overrides and "entity" not in _overrides: + wandb.termwarn( + 'Passing "username" to Api is deprecated. please use "entity" instead.' + ) + self.settings["entity"] = _overrides["username"] + + self._api_key = api_key + if _thread_local_api_settings.cookies is None: + wandb_login._login( + host=self.settings["base_url"], + key=self.api_key, + verify=True, + _silent=( + self.settings.get("silent", False) + or self.settings.get("quiet", False) + ), + update_api_key=False, + _disable_warning=True, + ) + + self._viewer = None + self._projects = {} + self._runs = {} + self._sweeps = {} + self._reports = {} + self._default_entity = None + self._timeout = timeout if timeout is not None else self._HTTP_TIMEOUT + auth = None + if not _thread_local_api_settings.cookies: + auth = ("api", self.api_key) + proxies = self.settings.get("_proxies") or json.loads( + os.environ.get("WANDB__PROXIES", "{}") + ) + self._base_client = Client( + transport=GraphQLSession( + headers={ + "User-Agent": self.user_agent, + "Use-Admin-Privileges": "true", + **(_thread_local_api_settings.headers or {}), + }, + use_json=True, + # this timeout won't apply when the DNS lookup fails. in that case, it will be 60s + # https://bugs.python.org/issue22889 + timeout=self._timeout, + auth=auth, + url="{}/graphql".format(self.settings["base_url"]), + cookies=_thread_local_api_settings.cookies, + proxies=proxies, + ) + ) + self._client = RetryingClient(self._base_client) + self._sentry = wandb.analytics.sentry.Sentry() + self._configure_sentry() + + def _configure_sentry(self) -> None: + try: + viewer = self.viewer + except (ValueError, requests.RequestException): + # we need the viewer to configure the entity, and user email + return + + email = viewer.email if viewer else None + entity = self.default_entity + + self._sentry.configure_scope( + tags={ + "entity": entity, + "email": email, + }, + ) + + def create_project(self, name: str, entity: str) -> None: + """Create a new project. + + Args: + name: The name of the new project. + entity: The entity of the new project. + """ + self.client.execute(self.CREATE_PROJECT, {"entityName": entity, "name": name}) + + def create_run( + self, + *, + run_id: Optional[str] = None, + project: Optional[str] = None, + entity: Optional[str] = None, + ) -> "public.Run": + """Create a new run. + + Args: + run_id: The ID to assign to the run. If not specified, W&B + creates a random ID. + project: The project where to log the run to. If no project is specified, + log the run to a project called "Uncategorized". + entity: The entity that owns the project. If no entity is + specified, log the run to the default entity. + + Returns: + The newly created `Run`. + """ + if entity is None: + entity = self.default_entity + return public.Run.create(self, run_id=run_id, project=project, entity=entity) + + def create_run_queue( + self, + name: str, + type: "public.RunQueueResourceType", + entity: Optional[str] = None, + prioritization_mode: Optional["public.RunQueuePrioritizationMode"] = None, + config: Optional[dict] = None, + template_variables: Optional[dict] = None, + ) -> "public.RunQueue": + """Create a new run queue in W&B Launch. + + Args: + name: Name of the queue to create + type: Type of resource to be used for the queue. One of + "local-container", "local-process", "kubernetes","sagemaker", + or "gcp-vertex". + entity: Name of the entity to create the queue. If `None`, use + the configured or default entity. + prioritization_mode: Version of prioritization to use. + Either "V0" or `None`. + config: Default resource configuration to be used for the queue. + Use handlebars (eg. `{{var}}`) to specify template variables. + template_variables: A dictionary of template variable schemas to + use with the config. + + Returns: + The newly created `RunQueue`. + + Raises: + `ValueError` if any of the parameters are invalid + `wandb.Error` on wandb API errors + """ + # TODO(np): Need to check server capabilities for this feature + # 0. assert params are valid/normalized + if entity is None: + entity = self.settings["entity"] or self.default_entity + if entity is None: + raise ValueError( + "entity must be passed as a parameter, or set in settings" + ) + + if len(name) == 0: + raise ValueError("name must be non-empty") + if len(name) > 64: + raise ValueError("name must be less than 64 characters") + + if type not in [ + "local-container", + "local-process", + "kubernetes", + "sagemaker", + "gcp-vertex", + ]: + raise ValueError( + "resource_type must be one of 'local-container', 'local-process', 'kubernetes', 'sagemaker', or 'gcp-vertex'" + ) + + if prioritization_mode: + prioritization_mode = prioritization_mode.upper() + if prioritization_mode not in ["V0"]: + raise ValueError("prioritization_mode must be 'V0' if present") + + if config is None: + config = {} + + # 1. create required default launch project in the entity + self.create_project(LAUNCH_DEFAULT_PROJECT, entity) + + api = InternalApi( + default_settings={ + "entity": entity, + "project": self.project(LAUNCH_DEFAULT_PROJECT), + }, + retry_timedelta=RETRY_TIMEDELTA, + ) + + # 2. create default resource config, receive config id + config_json = json.dumps({"resource_args": {type: config}}) + create_config_result = api.create_default_resource_config( + entity, type, config_json, template_variables + ) + if not create_config_result["success"]: + raise wandb.Error("failed to create default resource config") + config_id = create_config_result["defaultResourceConfigID"] + + # 3. create run queue + create_queue_result = api.create_run_queue( + entity, + LAUNCH_DEFAULT_PROJECT, + name, + "PROJECT", + prioritization_mode, + config_id, + ) + if not create_queue_result["success"]: + raise wandb.Error("failed to create run queue") + + return public.RunQueue( + client=self.client, + name=name, + entity=entity, + prioritization_mode=prioritization_mode, + _access="PROJECT", + _default_resource_config_id=config_id, + _default_resource_config=config, + ) + + def create_custom_chart( + self, + entity: str, + name: str, + display_name: str, + spec_type: Literal["vega2"], + access: Literal["private", "public"], + spec: Union[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: Optional[str] = None, + template_variables: Optional[dict] = None, + external_links: Optional[dict] = None, + prioritization_mode: Optional["public.RunQueuePrioritizationMode"] = None, + ): + """Upsert a run queue in W&B Launch. + + Args: + name: Name of the queue to create + entity: Optional name of the entity to create the queue. If `None`, + use the configured or default entity. + resource_config: Optional default resource configuration to be used + for the queue. Use handlebars (eg. `{{var}}`) to specify + template variables. + resource_type: Type of resource to be used for the queue. One of + "local-container", "local-process", "kubernetes", "sagemaker", + or "gcp-vertex". + template_variables: A dictionary of template variable schemas to + be used with the config. + external_links: Optional dictionary of external links to be used + with the queue. + prioritization_mode: Optional version of prioritization to use. + Either "V0" or None + + Returns: + The upserted `RunQueue`. + + Raises: + ValueError if any of the parameters are invalid + wandb.Error on wandb API errors + """ + if entity is None: + entity = self.settings["entity"] or self.default_entity + if entity is None: + raise ValueError( + "entity must be passed as a parameter, or set in settings" + ) + + if len(name) == 0: + raise ValueError("name must be non-empty") + if len(name) > 64: + raise ValueError("name must be less than 64 characters") + + prioritization_mode = prioritization_mode or "DISABLED" + prioritization_mode = prioritization_mode.upper() + if prioritization_mode not in ["V0", "DISABLED"]: + raise ValueError( + "prioritization_mode must be 'V0' or 'DISABLED' if present" + ) + + if resource_type not in [ + "local-container", + "local-process", + "kubernetes", + "sagemaker", + "gcp-vertex", + ]: + raise ValueError( + "resource_type must be one of 'local-container', 'local-process', 'kubernetes', 'sagemaker', or 'gcp-vertex'" + ) + + self.create_project(LAUNCH_DEFAULT_PROJECT, entity) + api = InternalApi( + default_settings={ + "entity": entity, + "project": self.project(LAUNCH_DEFAULT_PROJECT), + }, + retry_timedelta=RETRY_TIMEDELTA, + ) + # User provides external_links as a dict with name: url format + # but backend stores it as a list of dicts with url and label keys. + external_links = external_links or {} + external_links = { + "links": [ + { + "label": key, + "url": value, + } + for key, value in external_links.items() + ] + } + upsert_run_queue_result = api.upsert_run_queue( + name, + entity, + resource_type, + {"resource_args": {resource_type: resource_config}}, + template_variables=template_variables, + external_links=external_links, + prioritization_mode=prioritization_mode, + ) + if not upsert_run_queue_result["success"]: + raise wandb.Error("failed to create run queue") + schema_errors = ( + upsert_run_queue_result.get("configSchemaValidationErrors") or [] + ) + for error in schema_errors: + wandb.termwarn(f"resource config validation: {error}") + + return public.RunQueue( + client=self.client, + name=name, + entity=entity, + ) + + def create_user(self, email: str, admin: Optional[bool] = False): + """Create a new user. + + Args: + email: The email address of the user. + admin: Set user as a global instance administrator. + + Returns: + A `User` object. + """ + return public.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 api_key(self) -> Optional[str]: + """Returns W&B API key.""" + # just use thread local api key if it's set + if _thread_local_api_settings.api_key: + return _thread_local_api_settings.api_key + if self._api_key is not None: + return self._api_key + auth = requests.utils.get_netrc_auth(self.settings["base_url"]) + key = None + if auth: + key = auth[-1] + # Environment should take precedence + if os.getenv("WANDB_API_KEY"): + key = os.environ["WANDB_API_KEY"] + self._api_key = key # memoize key + return key + + @property + def default_entity(self) -> Optional[str]: + """Returns the default W&B entity.""" + if self._default_entity is None: + res = self._client.execute(self.DEFAULT_ENTITY_QUERY) + self._default_entity = (res.get("viewer") or {}).get("entity") + return self._default_entity + + @property + def viewer(self) -> "public.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. + """ + if self._viewer is None: + viewer = self._client.execute(self.VIEWER_QUERY).get("viewer") + + if viewer is None: + raise ValueError( + "Unable to fetch user data from W&B," + " please verify your API key is valid." + ) + + self._viewer = public.User(self._client, viewer) + self._default_entity = self._viewer.entity + return self._viewer + + def flush(self): + """Flush the local cache. + + The api object keeps a local cache of runs, so if the state of the run + may change while executing your script you must clear the local cache + with `api.flush()` to get the latest values associated with the run. + """ + self._runs = {} + + def from_path(self, path: str): + """Return a run, sweep, project or report from a path. + + Args: + path: The path to the project, run, sweep or report + + Returns: + A `Project`, `Run`, `Sweep`, or `BetaReport` instance. + + Raises: + `wandb.Error` if path is invalid or the object doesn't exist. + + Examples: + In the proceeding code snippets "project", "team", "run_id", "sweep_id", + and "report_name" are placeholders for the project, team, run ID, + sweep ID, and the name of a specific report, respectively. + + ```python + import wandb + + api = wandb.Api() + + project = api.from_path("project") + team_project = api.from_path("team/project") + run = api.from_path("team/project/runs/run_id") + sweep = api.from_path("team/project/sweeps/sweep_id") + report = api.from_path("team/project/reports/report_name") + ``` + """ + parts = path.strip("/ ").split("/") + if len(parts) == 1: + return self.project(path) + elif len(parts) == 2: + return self.project(parts[1], parts[0]) + elif len(parts) == 3: + return self.run(path) + elif len(parts) == 4: + if parts[2].startswith("run"): + return self.run(path) + elif parts[2].startswith("sweep"): + return self.sweep(path) + elif parts[2].startswith("report"): + if "--" not in parts[-1]: + if "-" in parts[-1]: + raise wandb.Error( + "Invalid report path, should be team/project/reports/Name--XXXX" + ) + else: + parts[-1] = "--" + parts[-1] + name, id = parts[-1].split("--") + return public.BetaReport( + self.client, + { + "displayName": urllib.parse.unquote(name.replace("-", " ")), + "id": id, + "spec": "{}", + }, + parts[0], + parts[1], + ) + raise wandb.Error( + "Invalid path, should be TEAM/PROJECT/TYPE/ID where TYPE is runs, sweeps, or reports" + ) + + def _parse_project_path(self, path): + """Return project and entity for project specified by path.""" + project = self.settings["project"] or "uncategorized" + entity = self.settings["entity"] or self.default_entity + if path is None: + return entity, project + parts = path.split("/", 1) + if len(parts) == 1: + return entity, path + return parts + + def _parse_path(self, path): + """Parse url, filepath, or docker paths. + + Allows paths in the following formats: + - url: entity/project/runs/id + - path: entity/project/id + - docker: entity/project:id + + Entity is optional and will fall back to the current logged-in user. + """ + project = self.settings["project"] or "uncategorized" + entity = self.settings["entity"] or self.default_entity + parts = ( + path.replace("/runs/", "/").replace("/sweeps/", "/").strip("/ ").split("/") + ) + if ":" in parts[-1]: + id = parts[-1].split(":")[-1] + parts[-1] = parts[-1].split(":")[0] + elif parts[-1]: + id = parts[-1] + if len(parts) == 1 and project != "uncategorized": + pass + elif len(parts) > 1: + project = parts[1] + if entity and id == project: + project = parts[0] + else: + entity = parts[0] + if len(parts) == 3: + entity = parts[0] + else: + project = parts[0] + return entity, project, id + + def _parse_artifact_path(self, path): + """Return project, entity and artifact name for project specified by path.""" + project = self.settings["project"] or "uncategorized" + entity = self.settings["entity"] or self.default_entity + if path is None: + return entity, project + + path, colon, alias = path.partition(":") + full_alias = colon + alias + + parts = path.split("/") + if len(parts) > 3: + raise ValueError("Invalid artifact path: {}".format(path)) + elif len(parts) == 1: + return entity, project, path + full_alias + elif len(parts) == 2: + return entity, parts[0], parts[1] + full_alias + parts[-1] += full_alias + return parts + + def projects( + self, entity: Optional[str] = None, per_page: int = 200 + ) -> "public.Projects": + """Get projects for a given entity. + + Args: + entity: Name of the entity requested. If None, will fall back to + the default entity passed to `Api`. If no default entity, + will raise a `ValueError`. + per_page: Sets the page size for query pagination. If set to `None`, + use the default size. Usually there is no reason to change this. + + Returns: + A `Projects` object which is an iterable collection of `Project`objects. + """ + if entity is None: + entity = self.settings["entity"] or self.default_entity + if entity is None: + raise ValueError( + "entity must be passed as a parameter, or set in settings" + ) + if entity not in self._projects: + self._projects[entity] = public.Projects( + self.client, entity, per_page=per_page + ) + return self._projects[entity] + + def project(self, name: str, entity: Optional[str] = None) -> "public.Project": + """Return the `Project` with the given name (and entity, if given). + + Args: + name: The project name. + entity: Name of the entity requested. If None, will fall back to the + default entity passed to `Api`. If no default entity, will + raise a `ValueError`. + + Returns: + A `Project` object. + """ + # For registry artifacts, capture potential org user inputted before resolving entity + org = entity if is_artifact_registry_project(name) else "" + + if entity is None: + entity = self.settings["entity"] or self.default_entity + + # For registry artifacts, resolve org-based entity + if is_artifact_registry_project(name): + settings_entity = self.settings["entity"] or self.default_entity + entity = InternalApi()._resolve_org_entity_name( + entity=settings_entity, organization=org + ) + return public.Project(self.client, entity, name, {}) + + def reports( + self, path: str = "", name: Optional[str] = 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 project the report resides in. Specify the + entity that created the project as a prefix followed by a + forward slash. + name: Name of the report requested. + per_page: Sets the page size for query pagination. If set to + `None`, use the default size. Usually there is no reason to + change this. + + Returns: + A `Reports` object which is an iterable collection of + `BetaReport` objects. + + Examples: + ```python + import wandb + + wandb.Api.reports("entity/project") + ``` + + """ + entity, project, _ = self._parse_path(path + "/fake_run") + + if name: + name = urllib.parse.unquote(name) + key = "/".join([entity, project, str(name)]) + else: + key = "/".join([entity, project]) + + if key not in self._reports: + self._reports[key] = public.Reports( + self.client, + public.Project(self.client, entity, project, {}), + name=name, + per_page=per_page, + ) + return self._reports[key] + + def create_team( + self, team: str, admin_username: Optional[str] = None + ) -> "public.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. + """ + return public.Team.create(self, team, admin_username) + + def team(self, team: str) -> "public.Team": + """Return the matching `Team` with the given name. + + Args: + team: The name of the team. + + Returns: + A `Team` object. + """ + return public.Team(self.client, team) + + def user(self, username_or_email: str) -> Optional["public.User"]: + """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. + """ + res = self._client.execute(self.USERS_QUERY, {"query": username_or_email}) + if len(res["users"]["edges"]) == 0: + return None + elif len(res["users"]["edges"]) > 1: + wandb.termwarn( + "Found multiple users, returning the first user matching {}".format( + username_or_email + ) + ) + return public.User(self._client, res["users"]["edges"][0]["node"]) + + def users(self, username_or_email: str) -> List["public.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. + """ + res = self._client.execute(self.USERS_QUERY, {"query": username_or_email}) + return [ + public.User(self._client, edge["node"]) for edge in res["users"]["edges"] + ] + + def runs( + self, + path: Optional[str] = None, + filters: Optional[Dict[str, Any]] = None, + order: str = "+created_at", + per_page: int = 50, + include_sweeps: 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. + + Returns: + A `Runs` object, which is an iterable collection of `Run` objects. + + Examples: + ```python + # Find runs in project where config.experiment_name has been set to "foo" + api.runs(path="my_entity/project", filters={"config.experiment_name": "foo"}) + ``` + + ```python + # Find runs in project where config.experiment_name has been set to "foo" or "bar" + api.runs( + path="my_entity/project", + filters={ + "$or": [ + {"config.experiment_name": "foo"}, + {"config.experiment_name": "bar"}, + ] + }, + ) + ``` + + ```python + # Find runs in project where config.experiment_name matches a regex + # (anchors are not supported) + api.runs( + path="my_entity/project", + filters={"config.experiment_name": {"$regex": "b.*"}}, + ) + ``` + + ```python + # Find runs in project where the run name matches a regex + # (anchors are not supported) + api.runs( + path="my_entity/project", filters={"display_name": {"$regex": "^foo.*"}} + ) + ``` + + ```python + # Find runs in project sorted by ascending loss + api.runs(path="my_entity/project", order="+summary_metrics.loss") + ``` + """ + entity, project = self._parse_project_path(path) + filters = filters or {} + key = (path or "") + str(filters) + str(order) + if not self._runs.get(key): + self._runs[key] = public.Runs( + self.client, + entity, + project, + filters=filters, + order=order, + per_page=per_page, + include_sweeps=include_sweeps, + ) + 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): + self._runs[path] = public.Run(self.client, entity, project, run_id) + return self._runs[path] + + def queued_run( + self, + entity: str, + project: str, + queue_name: str, + run_queue_item_id: str, + project_queue=None, + priority=None, + ): + """Return a single queued run based on the path. + + Parses paths of the form `entity/project/queue_id/run_queue_item_id`. + """ + return public.QueuedRun( + self.client, + entity, + project, + queue_name, + run_queue_item_id, + project_queue=project_queue, + priority=priority, + ) + + def run_queue( + self, + entity: str, + name: str, + ): + """Return the named `RunQueue` for entity. + + See `Api.create_run_queue` for more information on how to create a run queue. + """ + return public.RunQueue( + self.client, + name, + entity, + ) + + @normalize_exceptions + def sweep(self, path=""): + """Return a sweep by parsing path in the form `entity/project/sweep_id`. + + Args: + path: Path to sweep in the form entity/project/sweep_id. + If `api.entity` is set, this can be in the form + project/sweep_id and if `api.project` is set + this can just be the sweep_id. + + Returns: + A `Sweep` object. + """ + entity, project, sweep_id = self._parse_path(path) + if not self._sweeps.get(path): + self._sweeps[path] = public.Sweep(self.client, entity, project, sweep_id) + return self._sweeps[path] + + @normalize_exceptions + def artifact_types(self, project: Optional[str] = None) -> "public.ArtifactTypes": + """Returns a collection of matching artifact types. + + Args: + project: The project name or path to filter on. + + Returns: + An iterable `ArtifactTypes` object. + """ + project_path = project + entity, project = self._parse_project_path(project_path) + # If its a Registry project, the entity is considered to be an org instead + if is_artifact_registry_project(project): + settings_entity = self.settings["entity"] or self.default_entity + org = parse_org_from_registry_path(project_path, PathType.PROJECT) + entity = InternalApi()._resolve_org_entity_name( + entity=settings_entity, organization=org + ) + return public.ArtifactTypes(self.client, entity, project) + + @normalize_exceptions + def artifact_type( + self, type_name: str, project: Optional[str] = None + ) -> "public.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. + """ + project_path = project + entity, project = self._parse_project_path(project_path) + # If its an Registry artifact, the entity is an org instead + if is_artifact_registry_project(project): + org = parse_org_from_registry_path(project_path, PathType.PROJECT) + settings_entity = self.settings["entity"] or self.default_entity + entity = InternalApi()._resolve_org_entity_name( + entity=settings_entity, organization=org + ) + return public.ArtifactType(self.client, entity, project, type_name) + + @normalize_exceptions + def artifact_collections( + self, project_name: str, type_name: str, per_page: int = 50 + ) -> "public.ArtifactCollections": + """Returns a collection of matching artifact collections. + + Args: + project_name: The name of the project to filter on. + type_name: The name of the artifact type to filter on. + per_page: Sets the page size for query pagination. None will use the default size. + Usually there is no reason to change this. + + Returns: + An iterable `ArtifactCollections` object. + """ + entity, project = self._parse_project_path(project_name) + # If iterating through Registry project, the entity is considered to be an org instead + if is_artifact_registry_project(project): + org = parse_org_from_registry_path(project_name, PathType.PROJECT) + settings_entity = self.settings["entity"] or self.default_entity + entity = InternalApi()._resolve_org_entity_name( + entity=settings_entity, organization=org + ) + return public.ArtifactCollections( + self.client, entity, project, type_name, per_page=per_page + ) + + @normalize_exceptions + def artifact_collection( + self, type_name: str, name: str + ) -> "public.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() + ``` + """ + entity, project, collection_name = self._parse_artifact_path(name) + # If its an Registry artifact, the entity is considered to be an org instead + if is_artifact_registry_project(project): + org = parse_org_from_registry_path(name, PathType.ARTIFACT) + settings_entity = self.settings["entity"] or self.default_entity + entity = InternalApi()._resolve_org_entity_name( + entity=settings_entity, organization=org + ) + + if entity is None: + raise ValueError( + "Could not determine entity. Please include the entity as part of the collection name path." + ) + + return public.ArtifactCollection( + self.client, entity, project, collection_name, type_name + ) + + @normalize_exceptions + def artifact_versions(self, type_name, name, per_page=50): + """Deprecated. Use `Api.artifacts(type_name, name)` method instead.""" + deprecate( + field_name=Deprecated.api__artifact_versions, + warning_message=( + "Api.artifact_versions(type_name, name) is deprecated, " + "use Api.artifacts(type_name, name) instead." + ), + ) + return self.artifacts(type_name, name, per_page=per_page) + + @normalize_exceptions + def artifacts( + self, + type_name: str, + name: str, + per_page: int = 50, + tags: Optional[List[str]] = None, + ) -> "public.Artifacts": + """Return an `Artifacts` collection. + + Args: + type_name: The type of artifacts to fetch. + name: The artifact's collection name. Optionally append the + entity that logged the artifact as a prefix followed by + a forward slash. + per_page: Sets the page size for query pagination. If set to + `None`, use the default size. Usually there is no reason + to change this. + tags: Only return artifacts with all of these tags. + + Returns: + An iterable `Artifacts` object. + + Examples: + In the proceeding code snippet, "type", "entity", "project", and + "artifact_name" are placeholders for the artifact type, W&B entity, + name of the project the artifact was logged to, + and the name of the artifact, respectively. + + ```python + import wandb + + wandb.Api().artifacts(type_name="type", name="entity/project/artifact_name") + ``` + """ + entity, project, collection_name = self._parse_artifact_path(name) + # If its an Registry project, the entity is considered to be an org instead + if is_artifact_registry_project(project): + org = parse_org_from_registry_path(name, PathType.ARTIFACT) + settings_entity = self.settings["entity"] or self.default_entity + entity = InternalApi()._resolve_org_entity_name( + entity=settings_entity, organization=org + ) + return public.Artifacts( + self.client, + entity, + project, + collection_name, + type_name, + per_page=per_page, + tags=tags, + ) + + @normalize_exceptions + def _artifact( + self, name: str, type: Optional[str] = None, enable_tracking: bool = False + ): + if name is None: + raise ValueError("You must specify name= to fetch an artifact.") + entity, project, artifact_name = self._parse_artifact_path(name) + + # If its an Registry artifact, the entity is an org instead + if is_artifact_registry_project(project): + organization = ( + name.split("/")[0] + if name.count("/") == 2 + else self.settings["organization"] + ) + # set entity to match the settings since in above code it was potentially set to an org + settings_entity = self.settings["entity"] or self.default_entity + # Registry artifacts are under the org entity. Because we offer a shorthand and alias for this path, + # we need to fetch the org entity to for the user behind the scenes. + entity = InternalApi()._resolve_org_entity_name( + entity=settings_entity, organization=organization + ) + + if entity is None: + raise ValueError( + "Could not determine entity. Please include the entity as part of the artifact name path." + ) + + artifact = wandb.Artifact._from_name( + entity=entity, + project=project, + name=artifact_name, + client=self.client, + enable_tracking=enable_tracking, + ) + if type is not None and artifact.type != type: + raise ValueError( + f"type {type} specified but this artifact is of type {artifact.type}" + ) + return artifact + + @normalize_exceptions + def artifact(self, name: str, type: Optional[str] = None): + """Returns a single artifact. + + Args: + name: The artifact's name. The name of an artifact resembles a + filepath that consists, at a minimum, the name of the project + the artifact was logged to, the name of the artifact, and the + artifact's version or alias. Optionally append the entity that + logged the artifact as a prefix followed by a forward slash. + If no entity is specified in the name, the Run or API + setting's entity is used. + type: The type of artifact to fetch. + + Returns: + An `Artifact` object. + + Raises: + ValueError: If the artifact name is not specified. + ValueError: If the artifact type is specified but does not + match the type of the fetched artifact. + + Examples: + In the proceeding code snippets "entity", "project", "artifact", + "version", and "alias" are placeholders for your W&B entity, name + of the project the artifact is in, the name of the artifact, + and artifact's version, respectively. + + ```python + import wandb + + # Specify the project, artifact's name, and the artifact's alias + wandb.Api().artifact(name="project/artifact:alias") + + # Specify the project, artifact's name, and a specific artifact version + wandb.Api().artifact(name="project/artifact:version") + + # Specify the entity, project, artifact's name, and the artifact's alias + wandb.Api().artifact(name="entity/project/artifact:alias") + + # Specify the entity, project, artifact's name, and a specific artifact version + wandb.Api().artifact(name="entity/project/artifact:version") + ``` + + Note: + This method is intended for external use only. Do not call `api.artifact()` within the wandb repository code. + """ + return self._artifact(name=name, type=type, enable_tracking=True) + + @normalize_exceptions + def job(self, name: Optional[str], path: Optional[str] = None) -> "public.Job": + """Return a `Job` object. + + Args: + name: The name of the job. + path: The root path to download the job artifact. + + Returns: + A `Job` object. + """ + if name is None: + raise ValueError("You must specify name= to fetch a job.") + elif name.count("/") != 2 or ":" not in name: + raise ValueError( + "Invalid job specification. A job must be of the form: //:" + ) + return public.Job(self, name, path) + + @normalize_exceptions + def list_jobs(self, entity: str, project: str) -> List[Dict[str, Any]]: + """Return a list of jobs, if any, for the given entity and project. + + Args: + entity: The entity for the listed jobs. + project: The project for the listed jobs. + + Returns: + A list of matching jobs. + """ + if entity is None: + raise ValueError("Specify an entity when listing jobs") + if project is None: + raise ValueError("Specify a project when listing jobs") + + query = gql( + """ + query ArtifactOfType( + $entityName: String!, + $projectName: String!, + $artifactTypeName: String!, + ) { + project(name: $projectName, entityName: $entityName) { + artifactType(name: $artifactTypeName) { + artifactCollections { + edges { + node { + artifacts { + edges { + node { + id + state + aliases { + alias + } + artifactSequence { + name + } + } + } + } + } + } + } + } + } + } + """ + ) + + try: + artifact_query = self._client.execute( + query, + { + "projectName": project, + "entityName": entity, + "artifactTypeName": "job", + }, + ) + + if not artifact_query or not artifact_query["project"]: + wandb.termerror( + f"Project: '{project}' not found in entity: '{entity}' or access denied." + ) + return [] + + if artifact_query["project"]["artifactType"] is None: + return [] + + artifacts = artifact_query["project"]["artifactType"][ + "artifactCollections" + ]["edges"] + + return [x["node"]["artifacts"] for x in artifacts] + except requests.exceptions.HTTPError: + return False + + @normalize_exceptions + def artifact_exists(self, name: str, type: Optional[str] = None) -> bool: + """Whether an artifact version exists within the specified project and entity. + + Args: + name: The name of artifact. Add the artifact's entity and project + as a prefix. Append the version or the alias of the artifact + with a colon. If the entity or project is not specified, + W&B uses override parameters if populated. Otherwise, the + entity is pulled from the user settings and the project is + set to "Uncategorized". + type: The type of artifact. + + Returns: + True if the artifact version exists, False otherwise. + + Examples: + In the proceeding code snippets "entity", "project", "artifact", + "version", and "alias" are placeholders for your W&B entity, name of + the project the artifact is in, the name of the artifact, and + artifact's version, respectively. + + ```python + import wandb + + wandb.Api().artifact_exists("entity/project/artifact:version") + wandb.Api().artifact_exists("entity/project/artifact:alias") + ``` + + """ + try: + self._artifact(name, type) + except wandb.errors.CommError: + return False + + return True + + @normalize_exceptions + def artifact_collection_exists(self, name: str, type: str) -> bool: + """Whether an artifact collection exists within a specified project and entity. + + Args: + name: An artifact collection name. Optionally append the + entity that logged the artifact as a prefix followed by + a forward slash. If entity or project is not specified, + infer the collection from the override params if they exist. + Otherwise, entity is pulled from the user settings and project + will default to "uncategorized". + type: The type of artifact collection. + + Returns: + True if the artifact collection exists, False otherwise. + + Examples: + In the proceeding code snippet "type", and "collection_name" refer to the type + of the artifact collection and the name of the collection, respectively. + + ```python + import wandb + + wandb.Api.artifact_collection_exists(type="type", name="collection_name") + ``` + """ + try: + self.artifact_collection(type, name) + except wandb.errors.CommError: + return False + + return True + + def registries( + self, + organization: Optional[str] = None, + filter: Optional[Dict[str, Any]] = None, + ) -> Registries: + """Returns a lazy iterator of `Registry` objects. + + Use the iterator to search and filter registries, collections, + or artifact versions across your organization's registry. + + Args: + organization: (str, optional) The organization of the registry to fetch. + If not specified, use the organization specified in the user's settings. + filter: (dict, optional) MongoDB-style filter to apply to each object in the lazy registry iterator. + Fields available to filter for registries are + `name`, `description`, `created_at`, `updated_at`. + Fields available to filter for collections are + `name`, `tag`, `description`, `created_at`, `updated_at` + Fields available to filter for versions are + `tag`, `alias`, `created_at`, `updated_at`, `metadata` + + Returns: + A lazy iterator of `Registry` objects. + + Examples: + Find all registries with the names that contain "model" + + ```python + import wandb + + api = wandb.Api() # specify an org if your entity belongs to multiple orgs + api.registries(filter={"name": {"$regex": "model"}}) + ``` + + Find all collections in the registries with the name "my_collection" and the tag "my_tag" + + ```python + api.registries().collections(filter={"name": "my_collection", "tag": "my_tag"}) + ``` + + Find all artifact versions in the registries with a collection name that contains "my_collection" and a version that has the alias "best" + + ```python + api.registries().collections( + filter={"name": {"$regex": "my_collection"}} + ).versions(filter={"alias": "best"}) + ``` + + Find all artifact versions in the registries that contain "model" and have the tag "prod" or alias "best" + + ```python + api.registries(filter={"name": {"$regex": "model"}}).versions( + filter={"$or": [{"tag": "prod"}, {"alias": "best"}]} + ) + ``` + """ + if not InternalApi()._server_supports(ServerFeature.ARTIFACT_REGISTRY_SEARCH): + raise RuntimeError( + "Registry search API is not enabled on this wandb server version. " + "Please upgrade your server version or contact support at support@wandb.com." + ) + + organization = organization or fetch_org_from_settings_or_entity( + self.settings, self.default_entity + ) + return Registries(self.client, organization, filter) + + def registry(self, name: str, organization: Optional[str] = None) -> Registry: + """Return a registry given a registry name. + + Args: + name: The name of the registry. This is without the `wandb-registry-` + prefix. + organization: The organization of the registry. + If no organization is set in the settings, the organization will be + fetched from the entity if the entity only belongs to one + organization. + + Returns: + A registry object. + + Examples: + Fetch and update a registry + + ```python + import wandb + + api = wandb.Api() + registry = api.registry(name="my-registry", organization="my-org") + registry.description = "This is an updated description" + registry.save() + ``` + """ + if not InternalApi()._server_supports(ServerFeature.ARTIFACT_REGISTRY_SEARCH): + raise RuntimeError( + "api.registry() is not enabled on this wandb server version. " + "Please upgrade your server version or contact support at support@wandb.com." + ) + organization = organization or fetch_org_from_settings_or_entity( + self.settings, self.default_entity + ) + org_entity = fetch_org_entity_from_organization(self.client, organization) + registry = Registry(self.client, organization, org_entity, name) + registry.load() + return registry + + def create_registry( + self, + name: str, + visibility: Literal["organization", "restricted"], + organization: Optional[str] = None, + description: Optional[str] = None, + artifact_types: Optional[List[str]] = None, + ) -> Registry: + """Create a new registry. + + Args: + name: The name of the registry. Name must be unique within the organization. + visibility: The visibility of the registry. + organization: Anyone in the organization can view this registry. You can + edit their roles later from the settings in the UI. + restricted: Only invited members via the UI can access this registry. + Public sharing is disabled. + organization: The organization of the registry. + If no organization is set in the settings, the organization will be + fetched from the entity if the entity only belongs to one organization. + description: The description of the registry. + artifact_types: The accepted artifact types of the registry. A type is no + more than 128 characters and do not include characters `/` or `:`. If + not specified, all types are accepted. + Allowed types added to the registry cannot be removed later. + + Returns: + A registry object. + + Examples: + ```python + import wandb + + api = wandb.Api() + registry = api.create_registry( + name="my-registry", + visibility="restricted", + organization="my-org", + description="This is a test registry", + artifact_types=["model"], + ) + ``` + """ + if not InternalApi()._server_supports( + ServerFeature.INCLUDE_ARTIFACT_TYPES_IN_REGISTRY_CREATION + ): + raise RuntimeError( + "create_registry api is not enabled on this wandb server version. " + "Please upgrade your server version or contact support at support@wandb.com." + ) + + organization = organization or fetch_org_from_settings_or_entity( + self.settings, self.default_entity + ) + + try: + existing_registry = self.registry(name=name, organization=organization) + except ValueError: + existing_registry = None + if existing_registry: + raise ValueError( + f"Registry {name!r} already exists in organization {organization!r}," + " please use a different name." + ) + + return Registry.create( + self.client, + organization, + name, + visibility, + description, + artifact_types, + ) + + def integrations( + self, + entity: Optional[str] = None, + *, + per_page: int = 50, + ) -> Iterator["Integration"]: + """Return an iterator of all integrations for an entity. + + Args: + entity: The entity (e.g. team name) for which to + fetch integrations. If not provided, the user's default entity + will be used. + per_page: Number of integrations to fetch per page. + Defaults to 50. Usually there is no reason to change this. + + Yields: + Iterator[SlackIntegration | WebhookIntegration]: An iterator of any supported integrations. + """ + from wandb.apis.public.integrations import Integrations + + params = {"entityName": entity or self.default_entity} + return Integrations(client=self.client, variables=params, per_page=per_page) + + def webhook_integrations( + self, entity: Optional[str] = None, *, per_page: int = 50 + ) -> Iterator["WebhookIntegration"]: + """Returns an iterator of webhook integrations for an entity. + + Args: + entity: The entity (e.g. team name) for which to + fetch integrations. If not provided, the user's default entity + will be used. + per_page: Number of integrations to fetch per page. + Defaults to 50. Usually there is no reason to change this. + + Yields: + Iterator[WebhookIntegration]: An iterator of webhook integrations. + + Examples: + Get all registered webhook integrations for the team "my-team": + + ```python + import wandb + + api = wandb.Api() + webhook_integrations = api.webhook_integrations(entity="my-team") + ``` + + Find only webhook integrations that post requests to "https://my-fake-url.com": + + ```python + webhook_integrations = api.webhook_integrations(entity="my-team") + my_webhooks = [ + ig + for ig in webhook_integrations + if ig.url_endpoint.startswith("https://my-fake-url.com") + ] + ``` + """ + from wandb.apis.public.integrations import WebhookIntegrations + + params = {"entityName": entity or self.default_entity} + return WebhookIntegrations( + client=self.client, variables=params, per_page=per_page + ) + + def slack_integrations( + self, *, entity: Optional[str] = None, per_page: int = 50 + ) -> Iterator["SlackIntegration"]: + """Returns an iterator of Slack integrations for an entity. + + Args: + entity: The entity (e.g. team name) for which to + fetch integrations. If not provided, the user's default entity + will be used. + per_page: Number of integrations to fetch per page. + Defaults to 50. Usually there is no reason to change this. + + Yields: + Iterator[SlackIntegration]: An iterator of Slack integrations. + + Examples: + Get all registered Slack integrations for the team "my-team": + + ```python + import wandb + + api = wandb.Api() + slack_integrations = api.slack_integrations(entity="my-team") + ``` + + Find only Slack integrations that post to channel names starting with "team-alerts-": + + ```python + slack_integrations = api.slack_integrations(entity="my-team") + team_alert_integrations = [ + ig + for ig in slack_integrations + if ig.channel_name.startswith("team-alerts-") + ] + ``` + """ + from wandb.apis.public.integrations import SlackIntegrations + + params = {"entityName": entity or self.default_entity} + return SlackIntegrations( + client=self.client, variables=params, per_page=per_page + ) + + def _supports_automation( + self, + *, + event: Optional["EventType"] = None, + action: Optional["ActionType"] = None, + ) -> bool: + """Returns whether the server recognizes the automation event and/or action.""" + from wandb.automations._utils import ( + ALWAYS_SUPPORTED_ACTIONS, + ALWAYS_SUPPORTED_EVENTS, + ) + + api = InternalApi() + supports_event = ( + (event is None) + or (event in ALWAYS_SUPPORTED_EVENTS) + or api._server_supports(f"AUTOMATION_EVENT_{event.value}") + ) + supports_action = ( + (action is None) + or (action in ALWAYS_SUPPORTED_ACTIONS) + or api._server_supports(f"AUTOMATION_ACTION_{action.value}") + ) + return supports_event and supports_action + + def _omitted_automation_fragments(self) -> Set[str]: + """Returns the names of unsupported automation-related fragments. + + Older servers won't recognize newer GraphQL types, so a valid request may + unnecessarily error out because it won't recognize fragments defined on those types. + + So e.g. if a server does not support `NO_OP` action types, then the following need to be + removed from the body of the GraphQL request: + + - Fragment definition: + ``` + fragment NoOpActionFields on NoOpTriggeredAction { + noOp + } + ``` + + - Fragment spread in selection set: + ``` + { + ...NoOpActionFields + # ... other fields ... + } + ``` + """ + from wandb.automations import ActionType + from wandb.automations._generated import ( + GenericWebhookActionFields, + NoOpActionFields, + NotificationActionFields, + QueueJobActionFields, + ) + + # Note: we can't currently define this as a constant outside the method + # and still keep it nearby in this module, because it relies on pydantic v2-only imports + fragment_names: dict[ActionType, str] = { + ActionType.NO_OP: NoOpActionFields.__name__, + ActionType.QUEUE_JOB: QueueJobActionFields.__name__, + ActionType.NOTIFICATION: NotificationActionFields.__name__, + ActionType.GENERIC_WEBHOOK: GenericWebhookActionFields.__name__, + } + + return set( + name + for action in ActionType + if (not self._supports_automation(action=action)) + and (name := fragment_names.get(action)) + ) + + def automation( + self, + name: str, + *, + entity: Optional[str] = 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"), + ) + + def automations( + self, + entity: Optional[str] = None, + *, + name: Optional[str] = None, + per_page: int = 50, + ) -> Iterator["Automation"]: + """Returns an iterator over all Automations that match the given parameters. + + If no parameters are provided, the returned iterator will contain all + Automations that the user has access to. + + Args: + entity: The entity to fetch the automations for. + name: The name of the automation to fetch. + per_page: The number of automations to fetch per page. + Defaults to 50. Usually there is no reason to change this. + + Returns: + A list of automations. + + Examples: + Fetch all existing automations for the entity "my-team": + + ```python + import wandb + + api = wandb.Api() + automations = api.automations(entity="my-team") + ``` + """ + from wandb.apis.public.automations import Automations + from wandb.automations._generated import ( + GET_AUTOMATIONS_BY_ENTITY_GQL, + GET_AUTOMATIONS_GQL, + ) + + # For now, we need to use different queries depending on whether entity is given + variables = {"entityName": entity} + if entity is None: + gql_str = GET_AUTOMATIONS_GQL # Automations for viewer + else: + gql_str = GET_AUTOMATIONS_BY_ENTITY_GQL # Automations for entity + + # If needed, rewrite the GraphQL field selection set to omit unsupported fields/fragments/types + omit_fragments = self._omitted_automation_fragments() + query = gql_compat(gql_str, omit_fragments=omit_fragments) + iterator = Automations( + client=self.client, variables=variables, per_page=per_page, _query=query + ) + + # FIXME: this is crude, move this client-side filtering logic into backend + if name is not None: + iterator = filter(lambda x: x.name == name, iterator) + yield from iterator + + @normalize_exceptions + def create_automation( + self, + obj: "NewAutomation", + *, + fetch_existing: bool = False, + **kwargs: Unpack["WriteAutomationsKwargs"], + ) -> "Automation": + """Create a new Automation. + + Args: + obj: + The automation to create. + fetch_existing: + If True, and a conflicting automation already exists, attempt + to fetch the existing automation instead of raising an error. + **kwargs: + Any additional values to assign to the automation before + creating it. If given, these will override any values that may + already be set on the automation: + - `name`: The name of the automation. + - `description`: The description of the automation. + - `enabled`: Whether the automation is enabled. + - `scope`: The scope of the automation. + - `event`: The event that triggers the automation. + - `action`: The action that is triggered by the automation. + + Returns: + The saved Automation. + + Examples: + Create a new automation named "my-automation" that sends a Slack notification + when a run within a specific project logs a metric exceeding a custom threshold: + + ```python + import wandb + from wandb.automations import OnRunMetric, RunEvent, SendNotification + + api = wandb.Api() + + project = api.project("my-project", entity="my-team") + + # Use the first Slack integration for the team + slack_hook = next(api.slack_integrations(entity="my-team")) + + event = OnRunMetric( + scope=project, + filter=RunEvent.metric("custom-metric") > 10, + ) + action = SendNotification.from_integration(slack_hook) + + automation = api.create_automation( + event >> action, + name="my-automation", + description="Send a Slack message whenever 'custom-metric' exceeds 10.", + ) + ``` + """ + from wandb.automations import Automation + from wandb.automations._generated import CREATE_AUTOMATION_GQL, CreateAutomation + from wandb.automations._utils import prepare_to_create + + gql_input = prepare_to_create(obj, **kwargs) + + if not self._supports_automation( + event=(event := gql_input.triggering_event_type), + action=(action := gql_input.triggered_action_type), + ): + raise ValueError( + f"Automation event or action ({event!r} -> {action!r}) " + "is not supported on this wandb server version. " + "Please upgrade your server version, or contact support at " + "support@wandb.com." + ) + + # If needed, rewrite the GraphQL field selection set to omit unsupported fields/fragments/types + omit_fragments = self._omitted_automation_fragments() + mutation = gql_compat(CREATE_AUTOMATION_GQL, omit_fragments=omit_fragments) + variables = {"params": gql_input.model_dump(exclude_none=True)} + + name = gql_input.name + try: + data = self.client.execute(mutation, variable_values=variables) + except requests.HTTPError as e: + status = HTTPStatus(e.response.status_code) + if status is HTTPStatus.CONFLICT: # 409 + if fetch_existing: + wandb.termlog(f"Automation {name!r} exists. Fetching it instead.") + return self.automation(name=name) + + raise ValueError( + f"Automation {name!r} exists. Unable to create another with the same name." + ) from None + raise + + try: + result = CreateAutomation.model_validate(data).result + except ValidationError as e: + msg = f"Invalid response while creating automation {name!r}" + raise RuntimeError(msg) from e + + if (result is None) or (result.trigger is None): + msg = f"Empty response while creating automation {name!r}" + raise RuntimeError(msg) + + return Automation.model_validate(result.trigger) + + @normalize_exceptions + def update_automation( + self, + obj: "Automation", + *, + create_missing: bool = False, + **kwargs: Unpack["WriteAutomationsKwargs"], + ) -> "Automation": + """Update an existing automation. + + Args: + obj: The automation to update. Must be an existing automation. + create_missing (bool): + If True, and the automation does not exist, create it. + **kwargs: + Any additional values to assign to the automation before + updating it. If given, these will override any values that may + already be set on the automation: + - `name`: The name of the automation. + - `description`: The description of the automation. + - `enabled`: Whether the automation is enabled. + - `scope`: The scope of the automation. + - `event`: The event that triggers the automation. + - `action`: The action that is triggered by the automation. + + Returns: + The updated automation. + + Examples: + Disable and edit the description of an existing automation ("my-automation"): + + ```python + import wandb + + api = wandb.Api() + + automation = api.automation(name="my-automation") + automation.enabled = False + automation.description = "Kept for reference, but no longer used." + + updated_automation = api.update_automation(automation) + ``` + + OR + + ```python + import wandb + + api = wandb.Api() + + automation = api.automation(name="my-automation") + + updated_automation = api.update_automation( + automation, + enabled=False, + description="Kept for reference, but no longer used.", + ) + ``` + """ + from wandb.automations import ActionType, Automation + from wandb.automations._generated import UPDATE_AUTOMATION_GQL, UpdateAutomation + from wandb.automations._utils import prepare_to_update + + # Check if the server even supports updating automations. + # + # NOTE: Unfortunately, there is no current server feature flag for this. As a workaround, + # we check whether the server supports the NO_OP action, which is a reasonably safe proxy + # for whether it supports updating automations. + if not self._supports_automation(action=ActionType.NO_OP): + raise RuntimeError( + "Updating existing automations is not enabled on this wandb server version. " + "Please upgrade your server version, or contact support at support@wandb.com." + ) + + gql_input = prepare_to_update(obj, **kwargs) + + if not self._supports_automation( + event=(event := gql_input.triggering_event_type), + action=(action := gql_input.triggered_action_type), + ): + raise ValueError( + f"Automation event or action ({event.value} -> {action.value}) " + "is not supported on this wandb server version. " + "Please upgrade your server version, or contact support at " + "support@wandb.com." + ) + + # If needed, rewrite the GraphQL field selection set to omit unsupported fields/fragments/types + omit_fragments = self._omitted_automation_fragments() + mutation = gql_compat(UPDATE_AUTOMATION_GQL, omit_fragments=omit_fragments) + variables = {"params": gql_input.model_dump(exclude_none=True)} + + name = gql_input.name + try: + data = self.client.execute(mutation, variable_values=variables) + except requests.HTTPError as e: + status = HTTPStatus(e.response.status_code) + if status is HTTPStatus.NOT_FOUND: # 404 + if create_missing: + wandb.termlog(f"Automation {name!r} not found. Creating it.") + return self.create_automation(obj) + + raise ValueError( + f"Automation {name!r} not found. Unable to edit it." + ) from e + + # Not a (known) recoverable HTTP error + wandb.termerror(f"Got response status {status!r}: {e.response.text!r}") + raise + + try: + result = UpdateAutomation.model_validate(data).result + except ValidationError as e: + msg = f"Invalid response while updating automation {name!r}" + raise RuntimeError(msg) from e + + if (result is None) or (result.trigger is None): + msg = f"Empty response while updating automation {name!r}" + raise RuntimeError(msg) + + return Automation.model_validate(result.trigger) + + @normalize_exceptions + def delete_automation(self, obj: Union["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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/const.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/const.py new file mode 100644 index 0000000000000000000000000000000000000000..77af2da729d553a25f97a864546639f520b8817a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/const.py @@ -0,0 +1,4 @@ +import datetime + +# Only retry requests for 20 seconds in the public api +RETRY_TIMEDELTA = datetime.timedelta(seconds=20) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/files.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/files.py new file mode 100644 index 0000000000000000000000000000000000000000..4ea86fbe0312c98ef1c6da3c949153385299a683 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/files.py @@ -0,0 +1,402 @@ +"""W&B Public API for File objects. + +This module provides classes for interacting with files stored in W&B. + +Example: +```python +from wandb.apis.public import Api + +# Get files from a specific run +run = Api().run("entity/project/run_id") +files = run.files() + +# Work with files +for file in files: + print(f"File: {file.name}") + print(f"Size: {file.size} bytes") + print(f"Type: {file.mimetype}") + + # Download file + if file.size < 1000000: # Less than 1MB + file.download(root="./downloads") + + # Get S3 URI for large files + if file.size >= 1000000: + print(f"S3 URI: {file.path_uri}") +``` + +Note: + This module is part of the W&B Public API and provides methods to access, + download, and manage files stored in W&B. Files are typically associated + with specific runs and can include model weights, datasets, visualizations, + and other artifacts. +""" + +from __future__ import annotations + +import io +import os + +import requests +from wandb_gql import gql +from wandb_gql.client import RetryError + +import wandb +from wandb import util +from wandb.apis.attrs import Attrs +from wandb.apis.normalize import normalize_exceptions +from wandb.apis.paginator import SizedPaginator +from wandb.apis.public import utils +from wandb.apis.public.api import Api, RetryingClient +from wandb.apis.public.const import RETRY_TIMEDELTA +from wandb.apis.public.runs import Run +from wandb.sdk.lib import retry + +FILE_FRAGMENT = """fragment RunFilesFragment on Run { + files(names: $fileNames, after: $fileCursor, first: $fileLimit, pattern: $pattern) { + edges { + node { + id + name + url(upload: $upload) + directUrl + sizeBytes + mimetype + updatedAt + md5 + } + cursor + } + pageInfo { + endCursor + hasNextPage + } + } +}""" + + +class Files(SizedPaginator["File"]): + """A lazy iterator over a collection of `File` objects. + + Access and manage files uploaded to W&B during a run. Handles pagination + automatically when iterating through large collections of files. + + Example: + ```python + from wandb.apis.public.files import Files + from wandb.apis.public.api import Api + + # Example run object + run = Api().run("entity/project/run-id") + + # Create a Files object to iterate over files in the run + files = Files(api.client, run) + + # Iterate over files + for file in files: + print(file.name) + print(file.url) + print(file.size) + + # Download the file + file.download(root="download_directory", replace=True) + ``` + """ + + QUERY = gql( + """ + 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 + }} + }} + }} + {} + """.format(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) + + @property + def _length(self): + """ + Returns total number of files. + + + """ + if not self.last_response: + self._load_page() + + return self.last_response["project"]["run"]["fileCount"] + + @property + def more(self): + """Returns whether there are more files to fetch. + + + """ + if self.last_response: + return self.last_response["project"]["run"]["files"]["pageInfo"][ + "hasNextPage" + ] + else: + return True + + @property + def cursor(self): + """Returns the cursor position for pagination of file results. + + + """ + if self.last_response: + return self.last_response["project"]["run"]["files"]["edges"][-1]["cursor"] + else: + return None + + def update_variables(self): + """Updates the GraphQL query variables for pagination. + + + """ + self.variables.update({"fileLimit": self.per_page, "fileCursor": self.cursor}) + + def convert_objects(self): + """Converts GraphQL edges to File objects. + + + """ + return [ + File(self.client, r["node"], self.run) + for r in self.last_response["project"]["run"]["files"]["edges"] + ] + + def __repr__(self): + return "".format("/".join(self.run.path), len(self)) + + +class File(Attrs): + """File saved to W&B. + + Represents a single file stored in W&B. Includes access to file metadata. + Files are associated with a specific run and + can include text files, model weights, datasets, visualizations, and other + artifacts. You can download the file, delete the file, and access file + properties. + + Specify one or more attributes in a dictionary to fine a specific + file logged to a specific run. You can search using the following keys: + + - id (str): The ID of the run that contains the file + - name (str): Name of the file + - url (str): path to file + - direct_url (str): path to file in the bucket + - sizeBytes (int): size of file in bytes + - md5 (str): md5 of file + - mimetype (str): mimetype of file + - updated_at (str): timestamp of last update + - path_uri (str): path to file in the bucket, currently only available for S3 objects and reference files + + Args: + client: The run object that contains the file + attrs (dict): A dictionary of attributes that define the file + run: The run object that contains the file + + + """ + + def __init__(self, client, attrs, run=None): + self.client = client + self._attrs = attrs + self.run = run + self.server_supports_delete_file_with_project_id: bool | None = None + super().__init__(dict(attrs)) + + @property + def size(self): + """Returns the size of the file in bytes.""" + size_bytes = self._attrs["sizeBytes"] + if size_bytes is not None: + return int(size_bytes) + return 0 + + @property + def path_uri(self) -> str: + """Returns the URI path to the file in the storage bucket. + + Returns: + str: The S3 URI (e.g., 's3://bucket/path/to/file') if the file is stored in S3, + the direct URL if it's a reference file, or an empty string if unavailable. + """ + if not (direct_url := self._attrs.get("directUrl")): + wandb.termwarn("Unable to find direct_url of file") + return "" + + # For reference files, both the directUrl and the url are just the path to the file in the bucket + if direct_url == self._attrs.get("url"): + return direct_url + + try: + return utils.parse_s3_url_to_s3_uri(direct_url) + except ValueError: + wandb.termwarn("path_uri is only available for files stored in S3") + return "" + + @normalize_exceptions + @retry.retriable( + retry_timedelta=RETRY_TIMEDELTA, + check_retry_fn=util.no_retry_auth, + retryable_exceptions=(RetryError, requests.RequestException), + ) + def download( + self, + root: str = ".", + replace: bool = False, + exist_ok: bool = False, + api: Api | None = None, + ) -> io.TextIOWrapper: + """Downloads a file previously saved by a run from the wandb server. + + Args: + root: Local directory to save the file. Defaults to the + current working directory ("."). + replace: If `True`, download will overwrite a local file + if it exists. Defaults to `False`. + exist_ok: If `True`, will not raise ValueError if file already + exists and will not re-download unless replace=True. + Defaults to `False`. + api: If specified, the `Api` instance used to download the file. + + Raises: + `ValueError` if file already exists, `replace=False` and + `exist_ok=False`. + """ + if api is None: + api = wandb.Api() + + path = os.path.join(root, self.name) + if os.path.exists(path) and not replace: + if exist_ok: + return open(path) + else: + raise ValueError( + "File already exists, pass replace=True to overwrite or exist_ok=True to leave it as is and don't error." + ) + + util.download_file_from_url(path, self.url, api.api_key) + return open(path) + + @normalize_exceptions + def delete(self): + """Delete the file from the W&B server.""" + project_id_mutation_fragment = "" + project_id_variable_fragment = "" + variable_values = { + "files": [self.id], + } + + # Add projectId to mutation and variables if the server supports it. + # Otherwise, do not include projectId in mutation for older server versions which do not support it. + if self._server_accepts_project_id_for_delete_file(): + variable_values["projectId"] = self.run._project_internal_id + project_id_variable_fragment = ", $projectId: Int" + project_id_mutation_fragment = "projectId: $projectId" + + mutation_string = """ + mutation deleteFiles($files: [ID!]!{}) {{ + deleteFiles(input: {{ + files: $files + {} + }}) {{ + success + }} + }} + """.format(project_id_variable_fragment, project_id_mutation_fragment) + mutation = gql(mutation_string) + + self.client.execute( + mutation, + variable_values=variable_values, + ) + + def __repr__(self): + return "".format( + self.name, + self.mimetype, + util.to_human_size(self.size, units=util.POW_2_BYTES), + ) + + @normalize_exceptions + def _server_accepts_project_id_for_delete_file(self) -> bool: + """Returns True if the server supports deleting files with a projectId. + + This check is done by utilizing GraphQL introspection in the available fields on the DeleteFiles API. + """ + query_string = """ + query ProbeDeleteFilesProjectIdInput { + DeleteFilesProjectIdInputType: __type(name:"DeleteFilesInput") { + inputFields{ + name + } + } + } + """ + + # Only perform the query once to avoid extra network calls + if self.server_supports_delete_file_with_project_id is None: + query = gql(query_string) + res = self.client.execute(query) + + # If projectId is in the inputFields, the server supports deleting files with a projectId + self.server_supports_delete_file_with_project_id = "projectId" in [ + x["name"] + for x in ( + res.get("DeleteFilesProjectIdInputType", {}).get( + "inputFields", [{}] + ) + ) + ] + + return self.server_supports_delete_file_with_project_id diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/history.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/history.py new file mode 100644 index 0000000000000000000000000000000000000000..65317faf9480a85100045be45bf472f736cc5366 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/history.py @@ -0,0 +1,201 @@ +"""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. +""" + +import json + +from wandb_gql import gql + +from wandb.apis.normalize import normalize_exceptions +from wandb.apis.public import api, runs + + +class HistoryScan: + """Iterator for scanning complete run history. + + + """ + + QUERY = gql( + """ + query HistoryPage($entity: String!, $project: String!, $run: String!, $minStep: Int64!, $maxStep: Int64!, $pageSize: Int!) { + project(name: $project, entityName: $entity) { + run(name: $run) { + history(minStep: $minStep, maxStep: $maxStep, samples: $pageSize) + } + } + } + """ + ) + + def __init__( + self, + client: api.RetryingClient, + run: api.public.runs.Run, + min_step: int, + max_step: int, + page_size: int = 1000, + ): + """Initialize a HistoryScan instance. + + Args: + client: The client instance to use for making API calls to the W&B backend. + run: The run object whose history is to be scanned. + min_step: The minimum step to start scanning from. + max_step: The maximum step to scan up to. + page_size: Number of history rows to fetch per page. + Default page_size is 1000. + """ + self.client = client + self.run = run + self.page_size = page_size + self.min_step = min_step + self.max_step = max_step + self.page_offset = min_step # minStep for next page + self.scan_offset = 0 # index within current page of rows + self.rows = [] # current page of rows + + def __iter__(self): + self.page_offset = self.min_step + self.scan_offset = 0 + self.rows = [] + return self + + def __next__(self): + """Return the next row of history data with automatic pagination. + + + """ + while True: + if self.scan_offset < len(self.rows): + row = self.rows[self.scan_offset] + self.scan_offset += 1 + return row + if self.page_offset >= self.max_step: + raise StopIteration() + self._load_next() + + next = __next__ + + @normalize_exceptions + def _load_next(self): + max_step = self.page_offset + self.page_size + if max_step > self.max_step: + max_step = self.max_step + variables = { + "entity": self.run.entity, + "project": self.run.project, + "run": self.run.id, + "minStep": int(self.page_offset), + "maxStep": int(max_step), + "pageSize": int(self.page_size), + } + + res = self.client.execute(self.QUERY, variable_values=variables) + res = res["project"]["run"]["history"] + self.rows = [json.loads(row) for row in res] + self.page_offset += self.page_size + self.scan_offset = 0 + + +class SampledHistoryScan: + """Iterator for sampling run history data. + + + """ + + QUERY = gql( + """ + query SampledHistoryPage($entity: String!, $project: String!, $run: String!, $spec: JSONString!) { + project(name: $project, entityName: $entity) { + run(name: $run) { + sampledHistory(specs: [$spec]) + } + } + } + """ + ) + + def __init__( + self, + client: api.RetryingClient, + run: runs.Run, + keys: list, + min_step: int, + max_step: int, + page_size: int = 1000, + ): + """Initialize a SampledHistoryScan instance. + + Args: + client: The client instance to use for making API calls to the W&B backend. + run: The run object whose history is to be sampled. + keys: List of keys to sample from the history. + min_step: The minimum step to start sampling from. + max_step: The maximum step to sample up to. + page_size: Number of sampled history rows to fetch per page. + Default page_size is 1000. + """ + self.client = client + self.run = run + self.keys = keys + self.page_size = page_size + self.min_step = min_step + self.max_step = max_step + self.page_offset = min_step # minStep for next page + self.scan_offset = 0 # index within current page of rows + self.rows = [] # current page of rows + + def __iter__(self): + self.page_offset = self.min_step + self.scan_offset = 0 + self.rows = [] + return self + + def __next__(self): + """Return the next row of sampled history data with automatic pagination. + + + """ + while True: + if self.scan_offset < len(self.rows): + row = self.rows[self.scan_offset] + self.scan_offset += 1 + return row + if self.page_offset >= self.max_step: + raise StopIteration() + self._load_next() + + next = __next__ + + @normalize_exceptions + def _load_next(self): + max_step = self.page_offset + self.page_size + if max_step > self.max_step: + max_step = self.max_step + variables = { + "entity": self.run.entity, + "project": self.run.project, + "run": self.run.id, + "spec": json.dumps( + { + "keys": self.keys, + "minStep": int(self.page_offset), + "maxStep": int(max_step), + "samples": int(self.page_size), + } + ), + } + + res = self.client.execute(self.QUERY, variable_values=variables) + res = res["project"]["run"]["sampledHistory"] + self.rows = res[0] + self.page_offset += self.page_size + self.scan_offset = 0 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/integrations.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/integrations.py new file mode 100644 index 0000000000000000000000000000000000000000..2081f001937d9bd6cb6a324bb23684181fb0095d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/integrations.py @@ -0,0 +1,203 @@ +"""W&B Public API for integrations. + +This module provides classes for interacting with W&B integrations. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Iterable + +from pydantic import ValidationError +from typing_extensions import override +from wandb_gql import gql +from wandb_graphql.language.ast import Document + +from wandb.apis.paginator import Paginator + +if TYPE_CHECKING: + from wandb.apis.paginator import _Client + from wandb.automations import Integration, SlackIntegration, WebhookIntegration + from wandb.automations._generated import ( + GenericWebhookIntegrationConnectionFields, + IntegrationConnectionFields, + SlackIntegrationConnectionFields, + ) + + +class Integrations(Paginator["Integration"]): + """An lazy iterator of `Integration` objects.""" + + last_response: IntegrationConnectionFields | None + _query: Document + + def __init__(self, client: _Client, variables: dict[str, Any], per_page: int = 50): + from wandb.automations._generated import INTEGRATIONS_BY_ENTITY_GQL + + super().__init__(client, variables, per_page=per_page) + # All integrations for entity + self._query = gql(INTEGRATIONS_BY_ENTITY_GQL) + + @property + def more(self) -> bool: + """Whether there are more Integrations to fetch. + + + """ + if self.last_response is None: + return True + return self.last_response.page_info.has_next_page + + @property + def cursor(self) -> str | None: + """The start cursor to use for the next page. + + + """ + if self.last_response is None: + return None + return self.last_response.page_info.end_cursor + + @override + def _update_response(self) -> None: + """Fetch and parse the response data for the current page.""" + from wandb.automations._generated import IntegrationConnectionFields + + data: dict[str, Any] = self.client.execute( + self._query, variable_values=self.variables + ) + try: + page_data = data["entity"]["integrations"] + self.last_response = IntegrationConnectionFields.model_validate(page_data) + except (LookupError, AttributeError, ValidationError) as e: + raise ValueError("Unexpected response data") from e + + def convert_objects(self) -> Iterable[Integration]: + """Parse the page data into a list of integrations.""" + from wandb.automations.integrations import _IntegrationEdge + + page = self.last_response + return [_IntegrationEdge.model_validate(edge).node for edge in page.edges] + + +class WebhookIntegrations(Paginator["WebhookIntegration"]): + """An lazy iterator of `WebhookIntegration` objects. + + + """ + + last_response: GenericWebhookIntegrationConnectionFields | None + _query: Document + + def __init__(self, client: _Client, variables: dict[str, Any], per_page: int = 50): + from wandb.automations._generated import ( + GENERIC_WEBHOOK_INTEGRATIONS_BY_ENTITY_GQL, + ) + + super().__init__(client, variables, per_page=per_page) + # Webhook integrations for entity + self._query = gql(GENERIC_WEBHOOK_INTEGRATIONS_BY_ENTITY_GQL) + + @property + def more(self) -> bool: + """Whether there are more webhook integrations to fetch.""" + if self.last_response is None: + return True + return self.last_response.page_info.has_next_page + + @property + def cursor(self) -> str | None: + """The start cursor to use for the next page.""" + if self.last_response is None: + return None + return self.last_response.page_info.end_cursor + + @override + def _update_response(self) -> None: + """Fetch and parse the response data for the current page.""" + from wandb.automations._generated import ( + GenericWebhookIntegrationConnectionFields, + ) + + data: dict[str, Any] = self.client.execute( + self._query, variable_values=self.variables + ) + try: + page_data = data["entity"]["integrations"] + self.last_response = ( + GenericWebhookIntegrationConnectionFields.model_validate(page_data) + ) + except (LookupError, AttributeError, ValidationError) as e: + raise ValueError("Unexpected response data") from e + + def convert_objects(self) -> Iterable[WebhookIntegration]: + """Parse the page data into a list of webhook integrations.""" + from wandb.automations import WebhookIntegration + + typename = "GenericWebhookIntegration" + return [ + # Filter on typename__ needed because the GQL response still + # includes all integration types + WebhookIntegration.model_validate(node) + for edge in self.last_response.edges + if (node := edge.node) and (node.typename__ == typename) + ] + + +class SlackIntegrations(Paginator["SlackIntegration"]): + """An lazy iterator of `SlackIntegration` objects. + + + """ + + last_response: SlackIntegrationConnectionFields | None + _query: Document + + def __init__(self, client: _Client, variables: dict[str, Any], per_page: int = 50): + from wandb.automations._generated import SLACK_INTEGRATIONS_BY_ENTITY_GQL + + super().__init__(client, variables, per_page=per_page) + # Slack integrations for entity + self._query = gql(SLACK_INTEGRATIONS_BY_ENTITY_GQL) + + @property + def more(self) -> bool: + """Whether there are more Slack integrations to fetch.""" + if self.last_response is None: + return True + return self.last_response.page_info.has_next_page + + @property + def cursor(self) -> str | None: + """The start cursor to use for the next page.""" + if self.last_response is None: + return None + return self.last_response.page_info.end_cursor + + @override + def _update_response(self) -> None: + """Fetch and parse the response data for the current page.""" + from wandb.automations._generated import SlackIntegrationConnectionFields + + data: dict[str, Any] = self.client.execute( + self._query, variable_values=self.variables + ) + try: + page_data = data["entity"]["integrations"] + self.last_response = SlackIntegrationConnectionFields.model_validate( + page_data + ) + except (LookupError, AttributeError, ValidationError) as e: + raise ValueError("Unexpected response data") from e + + def convert_objects(self) -> Iterable[SlackIntegration]: + """Parse the page data into a list of Slack integrations.""" + from wandb.automations import SlackIntegration + + typename = "SlackIntegration" + return [ + # Filter on typename__ needed because the GQL response still + # includes all integration types + SlackIntegration.model_validate(node) + for edge in self.last_response.edges + if (node := edge.node) and (node.typename__ == typename) + ] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/jobs.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/jobs.py new file mode 100644 index 0000000000000000000000000000000000000000..92411e8ee8c6e03073e8ff11cbea48719e8e2306 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/jobs.py @@ -0,0 +1,742 @@ +"""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. +""" + +import json +import os +import shutil +import time +from typing import TYPE_CHECKING, Any, Dict, List, Literal, Mapping, Optional + +from wandb_gql import gql + +import wandb +from wandb import util +from wandb.apis import public +from wandb.apis.normalize import normalize_exceptions +from wandb.errors import CommError +from wandb.sdk.artifacts.artifact_state import ArtifactState +from wandb.sdk.data_types._dtypes import InvalidType, Type, TypeRegistry +from wandb.sdk.launch.errors import LaunchError +from wandb.sdk.launch.utils import ( + LAUNCH_DEFAULT_PROJECT, + _fetch_git_repo, + apply_patch, + convert_jupyter_notebook_to_script, +) + +if TYPE_CHECKING: + from wandb.apis.public import Api, RetryingClient + + +class Job: + _name: str + _input_types: Type + _output_types: Type + _entity: str + _project: str + _entrypoint: List[str] + _notebook_job: bool + _partial: bool + + def __init__(self, api: "Api", name, path: Optional[str] = None) -> None: + try: + self._job_artifact = api._artifact(name, type="job") + except CommError: + raise CommError(f"Job artifact {name} not found") + if path: + self._fpath = path + self._job_artifact.download(root=path) + else: + self._fpath = self._job_artifact.download() + self._name = name + self._api = api + self._entity = api.default_entity + + with open(os.path.join(self._fpath, "wandb-job.json")) as f: + self._job_info: Mapping[str, Any] = json.load(f) + source_info = self._job_info.get("source", {}) + # only use notebook job if entrypoint not set and notebook is set + self._notebook_job = source_info.get("notebook", False) + self._entrypoint = source_info.get("entrypoint") + self._dockerfile = source_info.get("dockerfile") + self._build_context = source_info.get("build_context") + self._base_image = source_info.get("base_image") + self._args = source_info.get("args") + self._partial = self._job_info.get("_partial", False) + self._requirements_file = os.path.join(self._fpath, "requirements.frozen.txt") + self._input_types = TypeRegistry.type_from_dict( + self._job_info.get("input_types") + ) + self._output_types = TypeRegistry.type_from_dict( + self._job_info.get("output_types") + ) + if self._job_info.get("source_type") == "artifact": + self._set_configure_launch_project(self._configure_launch_project_artifact) + if self._job_info.get("source_type") == "repo": + self._set_configure_launch_project(self._configure_launch_project_repo) + if self._job_info.get("source_type") == "image": + self._set_configure_launch_project(self._configure_launch_project_container) + + @property + def name(self): + """The name of the job.""" + return self._name + + def _set_configure_launch_project(self, func): + self.configure_launch_project = func + + def _get_code_artifact(self, artifact_string): + artifact_string, base_url, is_id = util.parse_artifact_string(artifact_string) + if is_id: + code_artifact = wandb.Artifact._from_id(artifact_string, self._api._client) + else: + code_artifact = self._api._artifact(name=artifact_string, type="code") + if code_artifact is None: + raise LaunchError("No code artifact found") + if code_artifact.state == ArtifactState.DELETED: + raise LaunchError( + f"Job {self.name} references deleted code artifact {code_artifact.name}" + ) + return code_artifact + + def _configure_launch_project_notebook(self, launch_project): + new_fname = convert_jupyter_notebook_to_script( + self._entrypoint[-1], launch_project.project_dir + ) + new_entrypoint = self._entrypoint + new_entrypoint[-1] = new_fname + launch_project.set_job_entry_point(new_entrypoint) + + def _configure_launch_project_repo(self, launch_project): + git_info = self._job_info.get("source", {}).get("git", {}) + _fetch_git_repo( + launch_project.project_dir, + git_info["remote"], + git_info["commit"], + ) + if os.path.exists(os.path.join(self._fpath, "diff.patch")): + with open(os.path.join(self._fpath, "diff.patch")) as f: + apply_patch(f.read(), launch_project.project_dir) + shutil.copy(self._requirements_file, launch_project.project_dir) + launch_project.python_version = self._job_info.get("runtime") + if self._notebook_job: + self._configure_launch_project_notebook(launch_project) + else: + launch_project.set_job_entry_point(self._entrypoint) + + if self._dockerfile: + launch_project.set_job_dockerfile(self._dockerfile) + if self._build_context: + launch_project.set_job_build_context(self._build_context) + if self._base_image: + launch_project.set_job_base_image(self._base_image) + + def _configure_launch_project_artifact(self, launch_project): + artifact_string = self._job_info.get("source", {}).get("artifact") + if artifact_string is None: + raise LaunchError(f"Job {self.name} had no source artifact") + + code_artifact = self._get_code_artifact(artifact_string) + launch_project.python_version = self._job_info.get("runtime") + shutil.copy(self._requirements_file, launch_project.project_dir) + + code_artifact.download(launch_project.project_dir) + + if self._notebook_job: + self._configure_launch_project_notebook(launch_project) + else: + launch_project.set_job_entry_point(self._entrypoint) + + if self._dockerfile: + launch_project.set_job_dockerfile(self._dockerfile) + if self._build_context: + launch_project.set_job_build_context(self._build_context) + if self._base_image: + launch_project.set_job_base_image(self._base_image) + + def _configure_launch_project_container(self, launch_project): + launch_project.docker_image = self._job_info.get("source", {}).get("image") + if launch_project.docker_image is None: + raise LaunchError( + "Job had malformed source dictionary without an image key" + ) + if self._entrypoint: + launch_project.set_job_entry_point(self._entrypoint) + + def set_entrypoint(self, entrypoint: List[str]): + """Set the entrypoint for the job.""" + self._entrypoint = entrypoint + + def call( + self, + config, + project=None, + entity=None, + queue=None, + resource="local-container", + resource_args=None, + template_variables=None, + project_queue=None, + priority=None, + ): + """Call the job with the given configuration. + + Args: + config (dict): The configuration to pass to the job. + This should be a dictionary containing key-value pairs that + match the input types defined in the job. + project (str, optional): The project to log the run to. Defaults + to the job's project. + entity (str, optional): The entity to log the run under. Defaults + to the job's entity. + queue (str, optional): The name of the queue to enqueue the job to. + Defaults to None. + resource (str, optional): The resource type to use for execution. + Defaults to "local-container". + resource_args (dict, optional): Additional arguments for the + resource type. Defaults to None. + template_variables (dict, optional): Template variables to use for + the job. Defaults to None. + project_queue (str, optional): The project that manages the queue. + Defaults to None. + priority (int, optional): The priority of the queued run. + Defaults to None. + """ + from wandb.sdk.launch import _launch_add + + run_config = {} + for key, item in config.items(): + if util._is_artifact_object(item): + if isinstance(item, wandb.Artifact) and item.is_draft(): + raise ValueError("Cannot queue jobs with unlogged artifacts") + run_config[key] = util.artifact_to_json(item) + + run_config.update(config) + + assigned_config_type = self._input_types.assign(run_config) + if self._partial: + wandb.termwarn( + "Launching manually created job for the first time, can't verify types" + ) + else: + if isinstance(assigned_config_type, InvalidType): + raise TypeError(self._input_types.explain(run_config)) + + queued_run = _launch_add.launch_add( + job=self._name, + config={"overrides": {"run_config": run_config}}, + template_variables=template_variables, + project=project or self._project, + entity=entity or self._entity, + queue_name=queue, + resource=resource, + project_queue=project_queue, + resource_args=resource_args, + priority=priority, + ) + return queued_run + + +class QueuedRun: + """A single queued run associated with an entity and project. + + Args: + entity: The entity associated with the queued run. + project (str): The project where runs executed by the queue are logged to. + queue_name (str): The name of the queue. + run_queue_item_id (int): The id of the run queue item. + project_queue (str): The project that manages the queue. + priority (str): The priority of the queued run. + + Call `run = queued_run.wait_until_running()` or + `run = queued_run.wait_until_finished()` to access the run. + """ + + def __init__( + self, + client, + entity, + project, + queue_name, + run_queue_item_id, + project_queue=LAUNCH_DEFAULT_PROJECT, + priority=None, + ): + self.client = client + self._entity = entity + self._project = project + self._queue_name = queue_name + self._run_queue_item_id = run_queue_item_id + self.sweep = None + self._run = None + self.project_queue = project_queue + self.priority = priority + + @property + def queue_name(self): + """The name of the queue.""" + return self._queue_name + + @property + def id(self): + """The id of the queued run.""" + return self._run_queue_item_id + + @property + def project(self): + """The project associated with the queued run.""" + return self._project + + @property + def entity(self): + """The entity associated with the queued run.""" + return self._entity + + @property + def state(self): + """The state of the queued run.""" + item = self._get_item() + if item: + return item["state"].lower() + + raise ValueError( + f"Could not find QueuedRunItem associated with id: {self.id} on queue {self.queue_name} at itemId: {self.id}" + ) + + @normalize_exceptions + def _get_run_queue_item_legacy(self) -> Dict: + query = gql( + """ + query GetRunQueueItem($projectName: String!, $entityName: String!, $runQueue: String!) { + project(name: $projectName, entityName: $entityName) { + runQueue(name:$runQueue) { + runQueueItems { + edges { + node { + id + state + associatedRunId + } + } + } + } + } + } + """ + ) + variable_values = { + "projectName": self.project_queue, + "entityName": self._entity, + "runQueue": self.queue_name, + } + res = self.client.execute(query, variable_values) + + for item in res["project"]["runQueue"]["runQueueItems"]["edges"]: + if str(item["node"]["id"]) == str(self.id): + return item["node"] + + @normalize_exceptions + def _get_item(self): + query = gql( + """ + query GetRunQueueItem($projectName: String!, $entityName: String!, $runQueue: String!, $itemId: ID!) { + project(name: $projectName, entityName: $entityName) { + runQueue(name: $runQueue) { + runQueueItem(id: $itemId) { + id + state + associatedRunId + } + } + } + } + """ + ) + variable_values = { + "projectName": self.project_queue, + "entityName": self._entity, + "runQueue": self.queue_name, + "itemId": self.id, + } + try: + res = self.client.execute(query, variable_values) # exception w/ old server + if res["project"]["runQueue"].get("runQueueItem") is not None: + return res["project"]["runQueue"]["runQueueItem"] + except Exception as e: + if "Cannot query field" not in str(e): + raise LaunchError(f"Unknown exception: {e}") + + return self._get_run_queue_item_legacy() + + @normalize_exceptions + def wait_until_finished(self): + """Wait for the queued run to complete and return the finished run.""" + if not self._run: + self.wait_until_running() + + self._run.wait_until_finished() + # refetch run to get updated summary + self._run.load(force=True) + return self._run + + @normalize_exceptions + def delete(self, delete_artifacts=False): + """Delete the given queued run from the wandb backend.""" + query = gql( + """ + query fetchRunQueuesFromProject($entityName: String!, $projectName: String!, $runQueueName: String!) { + project(name: $projectName, entityName: $entityName) { + runQueue(name: $runQueueName) { + id + } + } + } + """ + ) + + res = self.client.execute( + query, + variable_values={ + "entityName": self.entity, + "projectName": self.project_queue, + "runQueueName": self.queue_name, + }, + ) + + if res["project"].get("runQueue") is not None: + queue_id = res["project"]["runQueue"]["id"] + + mutation = gql( + """ + mutation DeleteFromRunQueue( + $queueID: ID!, + $runQueueItemId: ID! + ) { + deleteFromRunQueue(input: { + queueID: $queueID + runQueueItemId: $runQueueItemId + }) { + success + clientMutationId + } + } + """ + ) + self.client.execute( + mutation, + variable_values={ + "queueID": queue_id, + "runQueueItemId": self._run_queue_item_id, + }, + ) + + @normalize_exceptions + def wait_until_running(self): + """Wait until the queued run is running and return the run.""" + if self._run is not None: + return self._run + + while True: + # sleep here to hide an ugly warning + time.sleep(2) + item = self._get_item() + if item and item["associatedRunId"] is not None: + try: + self._run = public.Run( + self.client, + self._entity, + self.project, + item["associatedRunId"], + None, + ) + self._run_id = item["associatedRunId"] + except ValueError as e: + wandb.termwarn(str(e)) + else: + return self._run + elif item: + wandb.termlog("Waiting for run to start") + + time.sleep(3) + + def __repr__(self): + return f" None: + self._name: str = name + self._client = client + self._entity = entity + self._prioritization_mode = prioritization_mode + self._access = _access + self._default_resource_config_id = _default_resource_config_id + self._default_resource_config = _default_resource_config + self._template_variables = None + self._type = None + self._items = None + self._id = None + + @property + def name(self): + """The name of the queue.""" + return self._name + + @property + def entity(self): + """The entity that owns the queue.""" + return self._entity + + @property + def prioritization_mode(self) -> RunQueuePrioritizationMode: + """The prioritization mode of the queue. + + Can be set to "DISABLED" or "V0". + """ + if self._prioritization_mode is None: + self._get_metadata() + return self._prioritization_mode + + @property + def access(self) -> RunQueueAccessType: + """The access level of the queue.""" + if self._access is None: + self._get_metadata() + return self._access + + @property + def external_links(self) -> Dict[str, str]: + """External resource links for the queue.""" + if self._external_links is None: + self._get_metadata() + return self._external_links + + @property + def type(self) -> RunQueueResourceType: + """The resource type for execution.""" + if self._type is None: + if self._default_resource_config_id is None: + self._get_metadata() + self._get_default_resource_config() + return self._type + + @property + def default_resource_config(self): + """The default configuration for resources.""" + if self._default_resource_config is None: + if self._default_resource_config_id is None: + self._get_metadata() + self._get_default_resource_config() + return self._default_resource_config + + @property + def template_variables(self): + """Variables for resource templates.""" + if self._template_variables is None: + if self._default_resource_config_id is None: + self._get_metadata() + self._get_default_resource_config() + return self._template_variables + + @property + def id(self) -> str: + """The id of the queue.""" + if self._id is None: + self._get_metadata() + return self._id + + @property + def items(self) -> List[QueuedRun]: + """Up to the first 100 queued runs. Modifying this list will not modify the queue or any enqueued items!""" + # TODO(np): Add a paginated interface + if self._items is None: + self._get_items() + return self._items + + @normalize_exceptions + def delete(self): + """Delete the run queue from the wandb backend.""" + query = gql( + """ + mutation DeleteRunQueue($id: ID!) { + deleteRunQueues(input: {queueIDs: [$id]}) { + success + clientMutationId + } + } + """ + ) + variable_values = {"id": self.id} + res = self._client.execute(query, variable_values) + if res["deleteRunQueues"]["success"]: + self._id = None + self._access = None + self._default_resource_config_id = None + self._default_resource_config = None + self._items = None + else: + raise CommError(f"Failed to delete run queue {self.name}") + + def __repr__(self): + return f"" + + @normalize_exceptions + def _get_metadata(self): + query = gql( + """ + query GetRunQueueMetadata($projectName: String!, $entityName: String!, $runQueue: String!) { + project(name: $projectName, entityName: $entityName) { + runQueue(name: $runQueue) { + id + access + defaultResourceConfigID + prioritizationMode + externalLinks + } + } + } + """ + ) + variable_values = { + "projectName": LAUNCH_DEFAULT_PROJECT, + "entityName": self._entity, + "runQueue": self._name, + } + res = self._client.execute(query, variable_values) + self._id = res["project"]["runQueue"]["id"] + self._access = res["project"]["runQueue"]["access"] + self._default_resource_config_id = res["project"]["runQueue"][ + "defaultResourceConfigID" + ] + self._external_links = res["project"]["runQueue"]["externalLinks"] + if self._default_resource_config_id is None: + self._default_resource_config = {} + self._prioritization_mode = res["project"]["runQueue"]["prioritizationMode"] + + @normalize_exceptions + def _get_default_resource_config(self): + query = gql( + """ + query GetDefaultResourceConfig($entityName: String!, $id: ID!) { + entity(name: $entityName) { + defaultResourceConfig(id: $id) { + config + resource + templateVariables { + name + schema + } + } + } + } + """ + ) + variable_values = { + "entityName": self._entity, + "id": self._default_resource_config_id, + } + res = self._client.execute(query, variable_values) + self._type = res["entity"]["defaultResourceConfig"]["resource"] + self._default_resource_config = res["entity"]["defaultResourceConfig"]["config"] + self._template_variables = res["entity"]["defaultResourceConfig"][ + "templateVariables" + ] + + @normalize_exceptions + def _get_items(self): + query = gql( + """ + query GetRunQueueItems($projectName: String!, $entityName: String!, $runQueue: String!) { + project(name: $projectName, entityName: $entityName) { + runQueue(name: $runQueue) { + runQueueItems(first: 100) { + edges { + node { + id + } + } + } + } + } + } + """ + ) + variable_values = { + "projectName": LAUNCH_DEFAULT_PROJECT, + "entityName": self._entity, + "runQueue": self._name, + } + res = self._client.execute(query, variable_values) + self._items = [] + for item in res["project"]["runQueue"]["runQueueItems"]["edges"]: + self._items.append( + QueuedRun( + self._client, + self._entity, + LAUNCH_DEFAULT_PROJECT, + self._name, + item["node"]["id"], + ) + ) + + @classmethod + def create( + cls, + name: str, + resource: "RunQueueResourceType", + entity: Optional[str] = None, + prioritization_mode: Optional["RunQueuePrioritizationMode"] = None, + config: Optional[dict] = None, + template_variables: Optional[dict] = None, + ) -> "RunQueue": + """Create a RunQueue. + + Args: + name: The name of the run queue to create. + resource: The resource type for execution. + entity: The entity (user or team) that will own the queue. + Defaults to the default entity of the API client. + prioritization_mode: The prioritization mode for the queue. + Can be "DISABLED" or "V0". Defaults to None. + config: Optional dictionary for the default resource + configuration. Defaults to None. + template_variables: Optional dictionary for template variables + used in the resource configuration. + """ + public_api = Api() + return public_api.create_run_queue( + name, resource, entity, prioritization_mode, config, template_variables + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d73255a1fef65cb71763e251a603ca31194253a5 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/__pycache__/_freezable_list.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/__pycache__/_freezable_list.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..846ecb73b6748ed5d847833e1674a305a265d0a6 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/__pycache__/_freezable_list.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/__pycache__/_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/__pycache__/_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e56cba34947a5eb0fc180730cd77147440e909a2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/__pycache__/_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/__pycache__/registries_search.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/__pycache__/registries_search.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b123e3e9c53ee77b5838445e0719b1674d61fc94 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/__pycache__/registries_search.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/__pycache__/registry.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/__pycache__/registry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..279b5e1c446a826e15e02e71c3dbf04ea29d7d96 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/__pycache__/registry.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/_freezable_list.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/_freezable_list.py new file mode 100644 index 0000000000000000000000000000000000000000..c3609fd5ad4e375404f7195f0dcdc565ef0c71a0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/_freezable_list.py @@ -0,0 +1,179 @@ +from itertools import chain +from typing import ( + Any, + Iterable, + Iterator, + List, + MutableSequence, + Sequence, + Tuple, + TypeVar, + Union, + final, + overload, +) + +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: Union[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: Union[int, slice]) -> Union[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: Union[int, slice], value: Union[T, Iterable[T]] + ) -> None: + if isinstance(index, slice): + # Setting slices might affect saved items, disallow for simplicity + raise TypeError( + f"{type(self).__name__!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: Union[int, slice]) -> None: + if isinstance(index, slice): + raise TypeError(f"{type(self).__name__!r} does not support slice deletion") + else: + # The frozen items are sequentially first and protected from changes + len_frozen = len(self._frozen) + size = len(self) + + if (index >= size) or (index < -size): + raise IndexError("Index out of range") + + draft_index = (index % size) - len_frozen + if draft_index < 0: + raise ValueError(f"Cannot delete saved item at index {index!r}") + del self._draft[draft_index] + + def insert(self, index: int, value: T) -> None: + """Insert item before index. + + Insertion is only allowed at indices corresponding to the draft portion + of the list (i.e., index >= len(frozen_items)). Negative indices are + interpreted relative to the combined length of frozen and draft items. + """ + if value in self._frozen or value in self._draft: + # Silently ignore duplicates, similar to append + return + + # The frozen items are sequentially first and protected from changes + len_frozen = len(self._frozen) + size = len(self) + + # Follow the behavior of `list.insert()` when the index is out of bounds. + # - negative out-of-bounds index: prepend. Will only work if the frozen items are empty. + if index < -size and not self._frozen: + return self._draft.insert(0, value) + + # - positive out-of-bounds index: append. + if index >= size: + return self._draft.append(value) + + # - in-bounds index: insert only if into the draft portion. + draft_index = (index % size) - len_frozen + if draft_index < 0: + raise IndexError( + f"Cannot insert into the frozen list (index < {len_frozen})" + ) + return self._draft.insert(draft_index, value) + + def __repr__(self) -> str: + return f"{type(self).__name__}(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"{type(self).__name__}(saved={list(self._frozen)!r}, draft={list(self._draft)!r})" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2f0a3696823747b380a1e0f9b8379dc8dcdced05 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/_utils.py @@ -0,0 +1,140 @@ +from enum import Enum +from functools import lru_cache +from typing import TYPE_CHECKING, Any, List, Literal, Mapping, Optional, Sequence + +from wandb.sdk.artifacts._validators import ( + REGISTRY_PREFIX, + validate_artifact_types_list, +) + +if TYPE_CHECKING: + from wandb_gql import Client + +from wandb_gql import gql + + +class Visibility(str, Enum): + # names are what users see/pass into Python methods + # values are what's expected by backend API + organization = "PRIVATE" + restricted = "RESTRICTED" + + @classmethod + def _missing_(cls, value: object) -> Any: + return next( + (e for e in cls if e.name == value), + None, + ) + + +def format_gql_artifact_types_input( + artifact_types: Optional[List[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. + """ + if artifact_types is None: + return [] + new_types = validate_artifact_types_list(artifact_types) + return [{"name": type} for type in new_types] + + +def gql_to_registry_visibility( + visibility: str, +) -> Literal["organization", "restricted"]: + """Convert the GQL visibility to the registry visibility. + + Args: + visibility: The GQL visibility. + + Returns: + The registry visibility. + """ + try: + return Visibility(visibility).name + except ValueError: + raise ValueError(f"Invalid visibility: {visibility!r} from backend") + + +def registry_visibility_to_gql( + visibility: Literal["organization", "restricted"], +) -> str: + """Convert the registry visibility to the GQL visibility.""" + try: + return Visibility[visibility].value + except KeyError: + raise ValueError( + f"Invalid visibility: {visibility!r}. " + f"Must be one of: {', '.join(map(repr, (e.name for e in Visibility)))}" + ) + + +def ensure_registry_prefix_on_names(query, in_name=False): + """Traverse the filter to prepend the `name` key value with the registry prefix unless the value is a regex. + + - in_name: True if we are under a "name" key (or propagating from one). + + EX: {"name": "model"} -> {"name": "wandb-registry-model"} + """ + if isinstance((txt := query), str): + if in_name: + return txt if txt.startswith(REGISTRY_PREFIX) else f"{REGISTRY_PREFIX}{txt}" + return txt + if isinstance((dct := query), Mapping): + new_dict = {} + for key, obj in dct.items(): + if key == "name": + new_dict[key] = ensure_registry_prefix_on_names(obj, in_name=True) + elif key == "$regex": + # For regex operator, we skip transformation of its value. + new_dict[key] = obj + else: + # For any other key, propagate the in_name and skip_transform flags as-is. + new_dict[key] = ensure_registry_prefix_on_names(obj, in_name=in_name) + return new_dict + if isinstance((objs := query), Sequence): + return list( + map(lambda x: ensure_registry_prefix_on_names(x, in_name=in_name), objs) + ) + return query + + +@lru_cache(maxsize=10) +def fetch_org_entity_from_organization(client: "Client", organization: str) -> str: + """Fetch the org entity from the organization. + + Args: + client (Client): Graphql client. + organization (str): The organization to fetch the org entity for. + """ + query = gql( + """ + query FetchOrgEntityFromOrganization($organization: String!) { + organization(name: $organization) { + orgEntity { + name + } + } + } + """ + ) + try: + response = client.execute(query, variable_values={"organization": organization}) + except Exception as e: + raise ValueError( + f"Error fetching org entity for organization: {organization}" + ) from e + + if ( + not (org := response["organization"]) + or not (org_entity := org["orgEntity"]) + or not (org_name := org_entity["name"]) + ): + raise ValueError(f"Organization entity for {organization} not found.") + + return org_name diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/registries_search.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/registries_search.py new file mode 100644 index 0000000000000000000000000000000000000000..572b7638ac1c7130e4b15576a32fdc4f4f3fbdf3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/registries_search.py @@ -0,0 +1,460 @@ +"""Public API: registries search.""" + +import json +from typing import TYPE_CHECKING, Any, Dict, Optional + +if TYPE_CHECKING: + from wandb_gql import Client + +from wandb_gql import gql + +import wandb +from wandb.apis.paginator import Paginator +from wandb.sdk.artifacts._graphql_fragments import ( + _gql_artifact_fragment, + _gql_registry_fragment, +) +from wandb.sdk.artifacts._validators import remove_registry_prefix + +from ._utils import ensure_registry_prefix_on_names + + +class Registries(Paginator): + """An lazy iterator of `Registry` objects.""" + + QUERY = gql( + """ + query Registries($organization: String!, $filters: JSONString, $cursor: String, $perPage: Int) { + organization(name: $organization) { + orgEntity { + name + projects(filters: $filters, after: $cursor, first: $perPage) { + pageInfo { + endCursor + hasNextPage + } + edges { + node { + ...RegistryFragment + } + } + } + } + } + } + """ + + _gql_registry_fragment() + ) + + def __init__( + self, + client: "Client", + organization: str, + filter: Optional[Dict[str, Any]] = None, + per_page: Optional[int] = 100, + ): + self.client = client + self.organization = organization + self.filter = ensure_registry_prefix_on_names(filter or {}) + variables = { + "organization": organization, + "filters": json.dumps(self.filter), + } + + super().__init__(client, variables, per_page) + + 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] + + def collections(self, filter: Optional[Dict[str, Any]] = None) -> "Collections": + return Collections( + self.client, + self.organization, + registry_filter=self.filter, + collection_filter=filter, + ) + + def versions(self, filter: Optional[Dict[str, Any]] = None) -> "Versions": + return Versions( + self.client, + self.organization, + registry_filter=self.filter, + collection_filter=None, + artifact_filter=filter, + ) + + @property + def length(self): + if self.last_response: + return len( + self.last_response["organization"]["orgEntity"]["projects"]["edges"] + ) + else: + return None + + @property + def more(self): + if self.last_response: + return self.last_response["organization"]["orgEntity"]["projects"][ + "pageInfo" + ]["hasNextPage"] + else: + return True + + @property + def cursor(self): + if self.last_response: + return self.last_response["organization"]["orgEntity"]["projects"][ + "pageInfo" + ]["endCursor"] + else: + return None + + def convert_objects(self): + if not self.last_response: + return [] + if ( + not self.last_response["organization"] + or not self.last_response["organization"]["orgEntity"] + ): + raise ValueError( + f"Organization '{self.organization}' not found. Please verify the organization name is correct" + ) + + from wandb.apis.public.registries.registry import Registry + + return [ + Registry( + self.client, + self.organization, + self.last_response["organization"]["orgEntity"]["name"], + remove_registry_prefix(r["node"]["name"]), + r["node"], + ) + for r in self.last_response["organization"]["orgEntity"]["projects"][ + "edges" + ] + ] + + +class Collections(Paginator["ArtifactCollection"]): + """An lazy iterator of `ArtifactCollection` objects in a Registry.""" + + QUERY = gql( + """ + query Collections( + $organization: String!, + $registryFilter: JSONString, + $collectionFilter: JSONString, + $collectionTypes: [ArtifactCollectionType!], + $cursor: String, + $perPage: Int + ) { + organization(name: $organization) { + orgEntity { + name + artifactCollections( + projectFilters: $registryFilter, + filters: $collectionFilter, + collectionTypes: $collectionTypes, + after: $cursor, + first: $perPage + ) { + totalCount + pageInfo { + endCursor + hasNextPage + } + edges { + cursor + node { + id + name + description + createdAt + tags { + edges { + node { + name + } + } + } + project { + name + entity { + name + } + } + defaultArtifactType { + name + } + aliases { + edges { + node { + alias + } + } + } + } + } + } + } + } + } + """ + ) + + def __init__( + self, + client: "Client", + organization: str, + registry_filter: Optional[Dict[str, Any]] = None, + collection_filter: Optional[Dict[str, Any]] = None, + per_page: Optional[int] = 100, + ): + self.client = client + self.organization = organization + self.registry_filter = registry_filter + self.collection_filter = collection_filter or {} + + variables = { + "registryFilter": ( + json.dumps(self.registry_filter) if self.registry_filter else None + ), + "collectionFilter": ( + json.dumps(self.collection_filter) if self.collection_filter else None + ), + "organization": self.organization, + "collectionTypes": ["PORTFOLIO"], + "perPage": per_page, + } + + super().__init__(client, variables, per_page) + + def __next__(self): + # Implement custom next since its possible to load empty pages because of auth + self.index += 1 + while len(self.objects) <= self.index: + if not self._load_page(): + raise StopIteration + return self.objects[self.index] + + def versions(self, filter: Optional[Dict[str, Any]] = None) -> "Versions": + return Versions( + self.client, + self.organization, + registry_filter=self.registry_filter, + collection_filter=self.collection_filter, + artifact_filter=filter, + ) + + @property + def length(self): + if self.last_response: + return self.last_response["organization"]["orgEntity"][ + "artifactCollections" + ]["totalCount"] + else: + return None + + @property + def more(self): + if self.last_response: + return self.last_response["organization"]["orgEntity"][ + "artifactCollections" + ]["pageInfo"]["hasNextPage"] + else: + return True + + @property + def cursor(self): + if self.last_response: + return self.last_response["organization"]["orgEntity"][ + "artifactCollections" + ]["pageInfo"]["endCursor"] + else: + return None + + def convert_objects(self): + from wandb.apis.public import ArtifactCollection + + if not self.last_response: + return [] + if ( + not self.last_response["organization"] + or not self.last_response["organization"]["orgEntity"] + ): + raise ValueError( + f"Organization '{self.organization}' not found. Please verify the organization name is correct" + ) + + return [ + ArtifactCollection( + self.client, + r["node"]["project"]["entity"]["name"], + r["node"]["project"]["name"], + r["node"]["name"], + r["node"]["defaultArtifactType"]["name"], + self.organization, + r["node"], + is_sequence=False, + ) + for r in self.last_response["organization"]["orgEntity"][ + "artifactCollections" + ]["edges"] + ] + + +class Versions(Paginator["Artifact"]): + """An lazy iterator of `Artifact` objects in a Registry.""" + + def __init__( + self, + client: "Client", + organization: str, + registry_filter: Optional[Dict[str, Any]] = None, + collection_filter: Optional[Dict[str, Any]] = None, + artifact_filter: Optional[Dict[str, Any]] = None, + per_page: int = 100, + ): + self.client = client + self.organization = organization + self.registry_filter = registry_filter + self.collection_filter = collection_filter + self.artifact_filter = artifact_filter or {} + self.QUERY = gql( + """ + query Versions( + $organization: String!, + $registryFilter: JSONString, + $collectionFilter: JSONString, + $artifactFilter: JSONString, + $cursor: String, + $perPage: Int + ) { + organization(name: $organization) { + orgEntity { + name + artifactMemberships( + projectFilters: $registryFilter, + collectionFilters: $collectionFilter, + filters: $artifactFilter, + after: $cursor, + first: $perPage + ) { + pageInfo { + endCursor + hasNextPage + } + edges { + node { + artifactCollection { + project { + name + entity { + name + } + } + name + } + versionIndex + artifact { + ...ArtifactFragment + } + aliases { + alias + } + } + } + } + } + } + } + """ + + _gql_artifact_fragment(include_aliases=False) + ) + + variables = { + "registryFilter": ( + json.dumps(self.registry_filter) if self.registry_filter else None + ), + "collectionFilter": ( + json.dumps(self.collection_filter) if self.collection_filter else None + ), + "artifactFilter": ( + json.dumps(self.artifact_filter) if self.artifact_filter else None + ), + "organization": self.organization, + } + + super().__init__(client, variables, per_page) + + def __next__(self): + # Implement custom next since its possible to load empty pages because of auth + self.index += 1 + while len(self.objects) <= self.index: + if not self._load_page(): + raise StopIteration + return self.objects[self.index] + + @property + def length(self): + if self.last_response: + return len( + self.last_response["organization"]["orgEntity"]["artifactMemberships"][ + "edges" + ] + ) + else: + return None + + @property + def more(self): + if self.last_response: + return self.last_response["organization"]["orgEntity"][ + "artifactMemberships" + ]["pageInfo"]["hasNextPage"] + else: + return True + + @property + def cursor(self): + if self.last_response: + return self.last_response["organization"]["orgEntity"][ + "artifactMemberships" + ]["pageInfo"]["endCursor"] + else: + return None + + def convert_objects(self): + if not self.last_response: + return [] + if ( + not self.last_response["organization"] + or not self.last_response["organization"]["orgEntity"] + ): + raise ValueError( + f"Organization '{self.organization}' not found. Please verify the organization name is correct" + ) + + artifacts = ( + wandb.Artifact._from_attrs( + a["node"]["artifactCollection"]["project"]["entity"]["name"], + a["node"]["artifactCollection"]["project"]["name"], + a["node"]["artifactCollection"]["name"] + + ":v" + + str(a["node"]["versionIndex"]), + a["node"]["artifact"], + self.client, + [alias["alias"] for alias in a["node"]["aliases"]], + ) + for a in self.last_response["organization"]["orgEntity"][ + "artifactMemberships" + ]["edges"] + ) + return artifacts diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/registry.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..faf80dafd4eafcd2afdfa246b1185c763ff51ccb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/registries/registry.py @@ -0,0 +1,358 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional + +from wandb_gql import gql + +import wandb +from wandb.proto.wandb_internal_pb2 import ServerFeature +from wandb.sdk.artifacts._validators import REGISTRY_PREFIX, validate_project_name +from wandb.sdk.internal.internal_api import Api as InternalApi +from wandb.sdk.projects._generated import ( + DELETE_PROJECT_GQL, + FETCH_REGISTRY_GQL, + RENAME_PROJECT_GQL, + UPSERT_REGISTRY_PROJECT_GQL, + DeleteProject, + RenameProject, + UpsertRegistryProject, +) + +from ._freezable_list import AddOnlyArtifactTypesList +from ._utils import ( + fetch_org_entity_from_organization, + format_gql_artifact_types_input, + gql_to_registry_visibility, + registry_visibility_to_gql, +) +from .registries_search import Collections, Versions + +if TYPE_CHECKING: + from wandb_gql import Client + + +class Registry: + """A single registry in the Registry.""" + + def __init__( + self, + client: "Client", + organization: str, + entity: str, + name: str, + attrs: Optional[Dict[str, Any]] = None, + ): + self.client = client + self._name = name + self._saved_name = name + self._entity = entity + self._organization = organization + if attrs is not None: + self._update_attributes(attrs) + + def _update_attributes(self, attrs: Dict[str, Any]) -> None: + """Helper method to update instance attributes from a dictionary.""" + self._id = attrs.get("id", "") + if self._id is None: + raise ValueError(f"Registry {self.name}'s id is not found") + + self._description = attrs.get("description", "") + self._allow_all_artifact_types = attrs.get( + "allowAllArtifactTypesInRegistry", False + ) + self._artifact_types = AddOnlyArtifactTypesList( + t["node"]["name"] for t in attrs.get("artifactTypes", {}).get("edges", []) + ) + self._created_at = attrs.get("createdAt", "") + self._updated_at = attrs.get("updatedAt", "") + self._visibility = gql_to_registry_visibility(attrs.get("access", "")) + + @property + def full_name(self) -> str: + """Full name of the registry including the `wandb-registry-` prefix.""" + return f"wandb-registry-{self.name}" + + @property + def name(self) -> str: + """Name of the registry without the `wandb-registry-` prefix.""" + return self._name + + @name.setter + def name(self, value: str): + self._name = value + + @property + def entity(self) -> str: + """Organization entity of the registry.""" + return self._entity + + @property + def organization(self) -> str: + """Organization name of the registry.""" + return self._organization + + @property + def description(self) -> str: + """Description of the registry.""" + return self._description + + @description.setter + def description(self, value: str): + """Set the description of the registry.""" + self._description = value + + @property + def allow_all_artifact_types(self): + """Returns whether all artifact types are allowed in the registry. + + If `True` then artifacts of any type can be added to this registry. + If `False` then artifacts are restricted to the types in `artifact_types` for this registry. + """ + return self._allow_all_artifact_types + + @allow_all_artifact_types.setter + def allow_all_artifact_types(self, value: bool): + """Set whether all artifact types are allowed in the registry.""" + self._allow_all_artifact_types = value + + @property + def artifact_types(self) -> AddOnlyArtifactTypesList: + """Returns the artifact types allowed in the registry. + + If `allow_all_artifact_types` is `True` then `artifact_types` reflects the + types previously saved or currently used in the registry. + If `allow_all_artifact_types` is `False` then artifacts are restricted to the + types in `artifact_types`. + + Note: + Previously saved artifact types cannot be removed. + + Example: + ```python + registry.artifact_types.append("model") + registry.save() # once saved, the artifact type `model` cannot be removed + registry.artifact_types.append("accidentally_added") + registry.artifact_types.remove( + "accidentally_added" + ) # Types can only be removed if it has not been saved yet + ``` + """ + return self._artifact_types + + @property + def created_at(self) -> str: + """Timestamp of when the registry was created.""" + return self._created_at + + @property + def updated_at(self) -> str: + """Timestamp of when the registry was last updated.""" + return self._updated_at + + @property + def path(self): + return [self.entity, self.full_name] + + @property + def visibility(self) -> Literal["organization", "restricted"]: + """Visibility of the registry. + + Returns: + Literal["organization", "restricted"]: The visibility level. + - "organization": Anyone in the organization can view this registry. + You can edit their roles later from the settings in the UI. + - "restricted": Only invited members via the UI can access this registry. + Public sharing is disabled. + """ + return self._visibility + + @visibility.setter + def visibility(self, value: Literal["organization", "restricted"]): + """Set the visibility of the registry. + + Args: + value: The visibility level. Options are: + - "organization": Anyone in the organization can view this registry. + You can edit their roles later from the settings in the UI. + - "restricted": Only invited members via the UI can access this registry. + Public sharing is disabled. + """ + self._visibility = value + + def collections(self, filter: Optional[Dict[str, Any]] = None) -> Collections: + """Returns the collections belonging to the registry.""" + registry_filter = { + "name": self.full_name, + } + return Collections(self.client, self.organization, registry_filter, filter) + + def versions(self, filter: Optional[Dict[str, Any]] = None) -> Versions: + """Returns the versions belonging to the registry.""" + registry_filter = { + "name": self.full_name, + } + return Versions(self.client, self.organization, registry_filter, None, filter) + + @classmethod + def create( + cls, + client: "Client", + organization: str, + name: str, + visibility: Literal["organization", "restricted"], + description: Optional[str] = None, + artifact_types: Optional[List[str]] = None, + ): + """Create a new registry. + + The registry name must be unique within the organization. + This function should be called using `api.create_registry()` + + Args: + client: The GraphQL client. + organization: The name of the organization. + name: The name of the registry (without the `wandb-registry-` prefix). + visibility: The visibility level ('organization' or 'restricted'). + description: An optional description for the registry. + artifact_types: An optional list of allowed artifact types. + + Returns: + Registry: The newly created Registry object. + + Raises: + ValueError: If a registry with the same name already exists in the + organization or if the creation fails. + """ + org_entity = fetch_org_entity_from_organization(client, organization) + full_name = REGISTRY_PREFIX + name + validate_project_name(full_name) + accepted_artifact_types = [] + if artifact_types: + accepted_artifact_types = format_gql_artifact_types_input(artifact_types) + visibility_value = registry_visibility_to_gql(visibility) + registry_creation_error = ( + f"Failed to create registry {name!r} in organization {organization!r}." + ) + try: + response = client.execute( + gql(UPSERT_REGISTRY_PROJECT_GQL), + variable_values={ + "description": description, + "entityName": org_entity, + "name": full_name, + "access": visibility_value, + "allowAllArtifactTypesInRegistry": not accepted_artifact_types, + "artifactTypes": accepted_artifact_types, + }, + ) + except Exception: + raise ValueError(registry_creation_error) + if not response["upsertModel"]["inserted"]: + raise ValueError(registry_creation_error) + + return Registry( + client, + organization, + org_entity, + name, + response["upsertModel"]["project"], + ) + + def delete(self) -> None: + """Delete the registry. This is irreversible.""" + try: + response = self.client.execute( + gql(DELETE_PROJECT_GQL), variable_values={"id": self._id} + ) + result = DeleteProject.model_validate(response) + except Exception: + raise ValueError( + f"Failed to delete registry: {self.name!r} in organization: {self.organization!r}" + ) + if not result.delete_model.success: + raise ValueError( + f"Failed to delete registry: {self.name!r} in organization: {self.organization!r}" + ) + + def load(self) -> None: + """Load the registry attributes from the backend to reflect the latest saved state.""" + load_failure_message = ( + f"Failed to load registry {self.name!r} " + f"in organization {self.organization!r}." + ) + try: + response = self.client.execute( + gql(FETCH_REGISTRY_GQL), + variable_values={ + "name": self.full_name, + "entityName": self.entity, + }, + ) + except Exception: + raise ValueError(load_failure_message) + if response["entity"] is None: + raise ValueError(load_failure_message) + self.attrs = response["entity"]["project"] + if self.attrs is None: + raise ValueError(load_failure_message) + self._update_attributes(self.attrs) + + def save(self) -> None: + """Save registry attributes to the backend.""" + if not InternalApi()._server_supports( + ServerFeature.INCLUDE_ARTIFACT_TYPES_IN_REGISTRY_CREATION + ): + raise RuntimeError( + "saving the registry is not enabled on this wandb server version. " + "Please upgrade your server version or contact support at support@wandb.com." + ) + + if self._no_updating_registry_types(): + raise ValueError( + f"Cannot update artifact types when `allows_all_artifact_types` is {True!r}. Set it to {False!r} first." + ) + + validate_project_name(self.full_name) + visibility_value = registry_visibility_to_gql(self.visibility) + newly_added_types = format_gql_artifact_types_input(self.artifact_types.draft) + registry_save_error = f"Failed to save and update registry: {self.name} in organization: {self.organization}" + full_saved_name = f"{REGISTRY_PREFIX}{self._saved_name}" + try: + response = self.client.execute( + gql(UPSERT_REGISTRY_PROJECT_GQL), + variable_values={ + "description": self.description, + "entityName": self.entity, + "name": full_saved_name, # this makes it so we are updating the original registry in case the name has changed + "access": visibility_value, + "allowAllArtifactTypesInRegistry": self.allow_all_artifact_types, + "artifactTypes": newly_added_types, + }, + ) + result = UpsertRegistryProject.model_validate(response) + except Exception: + raise ValueError(registry_save_error) + if result.upsert_model.inserted: + # This is not suppose trigger unless the user has messed with the `_saved_name` variable + wandb.termlog( + f"Created registry {self.name!r} in organization {self.organization!r} on save" + ) + self._update_attributes(response["upsertModel"]["project"]) + + # Update the name of the registry if it has changed + if self._saved_name != self.name: + response = self.client.execute( + gql(RENAME_PROJECT_GQL), + variable_values={ + "entityName": self.entity, + "oldProjectName": full_saved_name, + "newProjectName": self.full_name, + }, + ) + result = RenameProject.model_validate(response) + self._saved_name = self.name + if result.rename_project.inserted: + # This is not suppose trigger unless the user has messed with the `_saved_name` variable + wandb.termlog(f"Created new registry {self.name!r} on save") + + def _no_updating_registry_types(self) -> bool: + # artifact types draft means user assigned types to add that are not yet saved + return len(self.artifact_types.draft) > 0 and self.allow_all_artifact_types diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/teams.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/teams.py new file mode 100644 index 0000000000000000000000000000000000000000..37f2c1352bc3a4fb4be30ef35f3eb62eac9f954c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/teams.py @@ -0,0 +1,235 @@ +"""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. +""" + +import requests +from wandb_gql import gql + +from wandb.apis.attrs import Attrs + + +class Member(Attrs): + """A member of a team. + + Args: + client (`wandb.apis.internal.Api`): The client instance to use + team (str): The name of the team this member belongs to + attrs (dict): The member attributes + """ + + DELETE_MEMBER_MUTATION = gql( + """ + mutation DeleteInvite($id: String, $entityName: String) { + deleteInvite(input: {id: $id, entityName: $entityName}) { + success + } + } + """ + ) + + def __init__(self, client, team, attrs): + super().__init__(attrs) + self._client = client + self.team = team + + def delete(self): + """Remove a member from a team. + + Returns: + Boolean indicating success + """ + try: + return self._client.execute( + self.DELETE_MEMBER_MUTATION, {"id": self.id, "entityName": self.team} + )["deleteInvite"]["success"] + except requests.exceptions.HTTPError: + return False + + def __repr__(self): + return f"" + + +class Team(Attrs): + """A class that represents a W&B team. + + This class provides methods to manage W&B teams, including creating teams, + inviting members, and managing service accounts. It inherits from Attrs + to handle team attributes. + + Args: + client (`wandb.apis.public.Api`): The api instance to use + name (str): The name of the team + attrs (dict): Optional dictionary of team attributes + + Note: + Team management requires appropriate permissions. + """ + + CREATE_TEAM_MUTATION = gql( + """ + mutation CreateTeam($teamName: String!, $teamAdminUserName: String) { + createTeam(input: {teamName: $teamName, teamAdminUserName: $teamAdminUserName}) { + entity { + id + name + available + photoUrl + limits + } + } + } + """ + ) + CREATE_INVITE_MUTATION = gql( + """ + mutation CreateInvite($entityName: String!, $email: String, $username: String, $admin: Boolean) { + createInvite(input: {entityName: $entityName, email: $email, username: $username, admin: $admin}) { + invite { + id + name + email + createdAt + toUser { + name + } + } + } + } + """ + ) + TEAM_QUERY = gql( + """ + query Entity($name: String!) { + entity(name: $name) { + id + name + available + photoUrl + readOnly + readOnlyAdmin + isTeam + privateOnly + storageBytes + codeSavingEnabled + defaultAccess + isPaid + members { + id + admin + pending + email + username + name + photoUrl + accountType + apiKey + } + } + } + """ + ) + CREATE_SERVICE_ACCOUNT_MUTATION = gql( + """ + mutation CreateServiceAccount($entityName: String!, $description: String!) { + createServiceAccount( + input: {description: $description, entityName: $entityName} + ) { + user { + id + } + } + } + """ + ) + + def __init__(self, client, name, attrs=None): + super().__init__(attrs or {}) + self._client = client + self.name = name + self.load() + + @classmethod + def create(cls, api, team, admin_username=None): + """Create a new team. + + Args: + api: (`Api`) The api instance to use + team: (str) The name of the team + admin_username: (str) optional username of the admin user of the team, defaults to the current user. + + Returns: + A `Team` object + """ + try: + api.client.execute( + cls.CREATE_TEAM_MUTATION, + {"teamName": team, "teamAdminUserName": admin_username}, + ) + except requests.exceptions.HTTPError: + pass + return Team(api.client, team) + + def invite(self, username_or_email, admin=False): + """Invite a user to a team. + + Args: + username_or_email: (str) The username or email address of the user + you want to invite. + admin: (bool) Whether to make this user a team admin. + Defaults to `False`. + + Returns: + `True` on success, `False` if user was already invited or didn't exist. + """ + variables = {"entityName": self.name, "admin": admin} + if "@" in username_or_email: + variables["email"] = username_or_email + else: + variables["username"] = username_or_email + try: + self._client.execute(self.CREATE_INVITE_MUTATION, variables) + except requests.exceptions.HTTPError: + return False + return True + + def create_service_account(self, description): + """Create a service account for the team. + + Args: + description: (str) A description for this service account + + Returns: + The service account `Member` object, or None on failure + """ + try: + self._client.execute( + self.CREATE_SERVICE_ACCOUNT_MUTATION, + {"description": description, "entityName": self.name}, + ) + self.load(True) + return self.members[-1] + except requests.exceptions.HTTPError: + return None + + def load(self, force=False): + """Return members that belong to a team. + + + """ + if force or not self._attrs: + response = self._client.execute(self.TEAM_QUERY, {"name": self.name}) + self._attrs = response["entity"] + self._attrs["members"] = [ + Member(self._client, self.name, member) + for member in self._attrs["members"] + ] + return self._attrs + + def __repr__(self): + return f"" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c868b9304110f7a3195ab45564f3bc04b209e321 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/public/utils.py @@ -0,0 +1,210 @@ +import re +from enum import Enum +from typing import Any, Dict, Iterable, Mapping, Optional, Set +from urllib.parse import urlparse + +from wandb_gql import gql +from wandb_graphql.language import ast, visitor + +from wandb._iterutils import one +from wandb.sdk.artifacts._validators import is_artifact_registry_project +from wandb.sdk.internal.internal_api import Api as InternalApi + + +def parse_s3_url_to_s3_uri(url) -> str: + """Convert an S3 HTTP(S) URL to an S3 URI. + + Arguments: + url (str): The S3 URL to convert, in the format + 'http(s)://.s3..amazonaws.com/'. + or 'http(s)://.s3.amazonaws.com/' + + Returns: + str: The corresponding S3 URI in the format 's3:///'. + + Raises: + ValueError: If the provided URL is not a valid S3 URL. + """ + # Regular expression to match S3 URL pattern + s3_pattern = r"^https?://.*s3.*amazonaws\.com.*" + parsed_url = urlparse(url) + + # Check if it's an S3 URL + match = re.match(s3_pattern, parsed_url.geturl()) + if not match: + raise ValueError("Invalid S3 URL") + + # Extract bucket name and key + bucket_name, *_ = parsed_url.netloc.split(".") + key = parsed_url.path.lstrip("/") + + # Construct the S3 URI + s3_uri = f"s3://{bucket_name}/{key}" + + return s3_uri + + +class PathType(Enum): + """We have lots of different paths users pass in to fetch artifacts, projects, etc. + + This enum is used for specifying what format the path is in given a string path. + """ + + PROJECT = "PROJECT" + ARTIFACT = "ARTIFACT" + + +def parse_org_from_registry_path(path: str, path_type: PathType) -> str: + """Parse the org from a registry path. + + Essentially fetching the "entity" from the path but for Registries the entity is actually the org. + + Args: + path (str): The path to parse. Can be a project path / or or an + artifact path like // or / or + path_type (PathType): The type of path to parse. + """ + parts = path.split("/") + expected_parts = 3 if path_type == PathType.ARTIFACT else 2 + + if len(parts) >= expected_parts: + org, project = parts[:2] + if is_artifact_registry_project(project): + return org + return "" + + +def fetch_org_from_settings_or_entity( + settings: dict, default_entity: Optional[str] = None +) -> str: + """Fetch the org from either the settings or deriving it from the entity. + + Returns the org from the settings if available. If no org is passed in or set, the entity is used to fetch the org. + + Args: + organization (str | None): The organization to fetch the org for. + settings (dict): The settings to fetch the org for. + default_entity (str | None): The default entity to fetch the org for. + """ + if (organization := settings.get("organization")) is None: + # Fetch the org via the Entity. Won't work if default entity is a personal entity and belongs to multiple orgs + entity = settings.get("entity") or default_entity + if entity is None: + raise ValueError( + "No entity specified and can't fetch organization from the entity" + ) + entity_orgs = InternalApi()._fetch_orgs_and_org_entities_from_entity(entity) + entity_org = one( + entity_orgs, + too_short=ValueError( + "No organizations found for entity. Please specify an organization in the settings." + ), + too_long=ValueError( + "Multiple organizations found for entity. Please specify an organization in the settings." + ), + ) + organization = entity_org.display_name + return organization + + +class _GQLCompatRewriter(visitor.Visitor): + """GraphQL AST visitor to rewrite queries/mutations to be compatible with older server versions.""" + + omit_variables: Set[str] + omit_fragments: Set[str] + omit_fields: Set[str] + rename_fields: Dict[str, str] + + def __init__( + self, + omit_variables: Optional[Iterable[str]] = None, + omit_fragments: Optional[Iterable[str]] = None, + omit_fields: Optional[Iterable[str]] = None, + rename_fields: Optional[Mapping[str, str]] = None, + ): + self.omit_variables = set(omit_variables or ()) + self.omit_fragments = set(omit_fragments or ()) + self.omit_fields = set(omit_fields or ()) + self.rename_fields = dict(rename_fields or {}) + + def enter_VariableDefinition(self, node: ast.VariableDefinition, *_, **__) -> Any: # noqa: N802 + if node.variable.name.value in self.omit_variables: + return visitor.REMOVE + # return node + + def enter_ObjectField(self, node: ast.ObjectField, *_, **__) -> Any: # noqa: N802 + # For context, note that e.g.: + # + # {description: $description + # ...} + # + # Is parsed as: + # + # ObjectValue(fields=[ + # ObjectField(name=Name(value='description'), value=Variable(name=Name(value='description'))), + # ...]) + if ( + isinstance(var := node.value, ast.Variable) + and var.name.value in self.omit_variables + ): + return visitor.REMOVE + + def enter_Argument(self, node: ast.Argument, *_, **__) -> Any: # noqa: N802 + if node.name.value in self.omit_variables: + return visitor.REMOVE + + def enter_FragmentDefinition(self, node: ast.FragmentDefinition, *_, **__) -> Any: # noqa: N802 + if node.name.value in self.omit_fragments: + return visitor.REMOVE + + def enter_FragmentSpread(self, node: ast.FragmentSpread, *_, **__) -> Any: # noqa: N802 + if node.name.value in self.omit_fragments: + return visitor.REMOVE + + def enter_Field(self, node: ast.Field, *_, **__) -> Any: # noqa: N802 + if node.name.value in self.omit_fields: + return visitor.REMOVE + if new_name := self.rename_fields.get(node.name.value): + node.name.value = new_name + return node + + def leave_Field(self, node: ast.Field, *_, **__) -> Any: # noqa: N802 + # If the field had a selection set, but now it's empty, remove the field entirely + if (node.selection_set is not None) and (not node.selection_set.selections): + return visitor.REMOVE + + +def gql_compat( + request_string: str, + omit_variables: Optional[Iterable[str]] = None, + omit_fragments: Optional[Iterable[str]] = None, + omit_fields: Optional[Iterable[str]] = None, + rename_fields: Optional[Mapping[str, str]] = 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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/reports/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/reports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6d2b9ad9385524f2b868e498d3030de028fac546 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/reports/__init__.py @@ -0,0 +1 @@ +from .v2 import * # noqa: F403 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/reports/v1/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/reports/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f436d09f5100348e39da903b39324adfe5101f6 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/reports/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/reports/v2/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/reports/v2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..532129620940c7deb87ae483a08059cb792d15f4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/reports/v2/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/reports/v2/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfd48f709e4685eef7561c16f4acb18f5dca9b8c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/reports/v2/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/workspaces/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/apis/workspaces/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..269a35473d08b01200c593d2c8958c85349a0749 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7a95cdd8ed5027012d90e141b2343fab6de2f811 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/__init__.py @@ -0,0 +1,73 @@ +import wandb +from wandb._pydantic import IS_PYDANTIC_V2 + +from .actions import ActionType, DoNothing, SendNotification, SendWebhook +from .automations import Automation, NewAutomation +from .events import ( + ArtifactEvent, + EventType, + MetricChangeFilter, + MetricThresholdFilter, + OnAddArtifactAlias, + OnCreateArtifact, + OnLinkArtifact, + OnRunMetric, + RunEvent, +) +from .integrations import Integration, SlackIntegration, WebhookIntegration +from .scopes import ArtifactCollectionScope, ProjectScope, ScopeType + +# ---------------------------------------------------------------------------- +# WARNINGS on import +if not IS_PYDANTIC_V2: + # Raises an error in Pydantic v1 environments, where the Automations API + # has not been tested and is unlikely to work as expected. + # + # Remove this when we either: + # - Drop support for Pydantic v1 + # - Are able to implement (limited) Pydantic v1 support + raise ImportError( + "The W&B Automations API requires Pydantic v2. " + "We recommend upgrading `pydantic` to use this feature." + ) + +else: + # If Pydantic v2 is available, we can use the full Automations API + # but communicate to users that the API is still experimental and + # may change rapidly. + wandb.termwarn( + "The W&B Automations API is experimental and the implementation is subject to change." + "Review the release notes before upgrading. We recommend pinning your " + f"package version to `{wandb.__package__}=={wandb.__version__}` to reduce the risk of disruption.", + repeat=False, + ) +# ---------------------------------------------------------------------------- + +__all__ = [ + # Scopes + "ScopeType", # doc:exclude + "ArtifactCollectionScope", # doc:exclude + "ProjectScope", # doc:exclude + # Events + "EventType", # doc:exclude + "OnAddArtifactAlias", + "OnCreateArtifact", + "OnLinkArtifact", + "OnRunMetric", + "ArtifactEvent", # doc:exclude + "RunEvent", # doc:exclude + "MetricThresholdFilter", + "MetricChangeFilter", + # Actions + "ActionType", # doc:exclude + "SendNotification", + "SendWebhook", + "DoNothing", + # Automations + "Automation", + "NewAutomation", + # Integrations + "Integration", # doc:exclude + "SlackIntegration", # doc:exclude + "WebhookIntegration", # doc:exclude +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6c9e8092279075a447d856c0a4bdf2f3ff3570f Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/__pycache__/automations.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/__pycache__/automations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c82d4ca113f15ca4f4076825690f838f95fabd35 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/__pycache__/automations.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/__pycache__/events.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/__pycache__/events.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..910df4cc90185717b03a250dea00fe0525d10aa3 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/__pycache__/events.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/__pycache__/integrations.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/__pycache__/integrations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6f56b83ccf1b43d65524d8567485dadc4058d95 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/__pycache__/integrations.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/__pycache__/scopes.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/__pycache__/scopes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10170e49b35ecfb8baff8508c5f5296c9e774873 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/__pycache__/scopes.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_filters/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_filters/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75c9692b52bfd850948d045dafffa8bc16683e87 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_filters/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_filters/run_metrics.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_filters/run_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..4ddeb46bb7bf418138107e03a9c39051c471650c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_filters/run_metrics.py @@ -0,0 +1,330 @@ +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING, Any, Final, Literal, Optional, Union, overload + +from pydantic import ( + Field, + PositiveFloat, + PositiveInt, + StrictFloat, + StrictInt, + field_validator, +) +from typing_extensions import Annotated, TypeAlias, override + +from wandb._pydantic import GQLBase +from wandb.automations._validators import LenientStrEnum + +from .expressions import FilterExpr +from .operators import BaseOp, RichReprResult + +if TYPE_CHECKING: + from wandb.automations.events import RunMetricFilter + +# Maps MongoDB comparison operators -> Python literal (str) representations +MONGO2PY_OPS: Final[dict[str, str]] = { + "$eq": "==", + "$ne": "!=", + "$gt": ">", + "$lt": "<", + "$gte": ">=", + "$lte": "<=", +} +# Reverse mapping from Python literal (str) -> MongoDB operator key +PY2MONGO_OPS: Final[dict[str, str]] = {v: k for k, v in MONGO2PY_OPS.items()} + +# Type hint for positive numbers (int or float) +PosNum: TypeAlias = Union[PositiveInt, PositiveFloat] + + +class Agg(LenientStrEnum): # from: Aggregation + """Supported run metric aggregation operations.""" + + MAX = "MAX" + MIN = "MIN" + AVERAGE = "AVERAGE" + + # Shorter aliases for convenience + AVG = AVERAGE + + +class ChangeType(LenientStrEnum): # from: RunMetricChangeType + """Describes the metric change as absolute (arithmetic difference) or relative (decimal percentage).""" + + ABSOLUTE = "ABSOLUTE" + RELATIVE = "RELATIVE" + + # Shorter aliases for convenience + ABS = ABSOLUTE + REL = RELATIVE + + +class ChangeDir(LenientStrEnum): # from: RunMetricChangeDirection + """Describes the direction of the metric change.""" + + INCREASE = "INCREASE" + DECREASE = "DECREASE" + ANY = "ANY" + + # Shorter aliases for convenience + INC = INCREASE + DEC = DECREASE + + +class BaseMetricFilter(GQLBase, ABC, extra="forbid"): + name: str + """Name of the observed metric.""" + + agg: Optional[Agg] + """Aggregate operation, if any, to apply over the window size.""" + + window: PositiveInt + """Size of the window over which the metric is aggregated (ignored if `agg is None`).""" + + # ------------------------------------------------------------------------------ + cmp: Optional[str] + """Comparison between the metric expression (left) vs. the threshold or target value (right).""" + + # ------------------------------------------------------------------------------ + threshold: Union[StrictInt, StrictFloat] + """Threshold value to compare against.""" + + def __and__(self, other: Any) -> RunMetricFilter: + """Implements `(metric_filter & run_filter) -> RunMetricFilter`.""" + from wandb.automations.events import RunMetricFilter + + if isinstance(run_filter := other, (BaseOp, FilterExpr)): + # Assume `other` is a run filter, and we are building a RunMetricEvent. + # For the metric filter, delegate to the inner validator(s) to further wrap/nest as appropriate. + return RunMetricFilter(run=run_filter, metric=self) + return NotImplemented + + def __rand__(self, other: BaseOp | FilterExpr) -> RunMetricFilter: + """Ensures `&` is commutative: `(run_filter & metric_filter) == (metric_filter & run_filter)`.""" + return self.__and__(other) + + @abstractmethod + def __repr__(self) -> str: + """The text representation of the metric filter.""" + raise NotImplementedError + + @override + def __rich_repr__(self) -> RichReprResult: + """The representation of the metric filter when using `rich` for pretty-printing.""" + # See: https://rich.readthedocs.io/en/stable/pretty.html#rich-repr-protocol + yield None, repr(self) + + +class MetricThresholdFilter(BaseMetricFilter): # from: RunMetricThresholdFilter + """Defines a filter that compares a run metric against a user-defined threshold value.""" + + name: str + agg: Annotated[Optional[Agg], Field(alias="agg_op")] = None + window: Annotated[PositiveInt, Field(alias="window_size")] = 1 + + cmp: Annotated[Literal["$gte", "$gt", "$lt", "$lte"], Field(alias="cmp_op")] + """Comparison operator used to compare the metric value (left) vs. the threshold value (right).""" + + threshold: Union[StrictInt, StrictFloat] + + @field_validator("cmp", mode="before") + def _validate_cmp(cls, v: Any) -> Any: + # Be helpful: e.g. ">" -> "$gt" + return PY2MONGO_OPS.get(v.strip(), v) if isinstance(v, str) else v + + def __repr__(self) -> str: + metric = f"{self.agg.value}({self.name})" if self.agg else self.name + op = MONGO2PY_OPS.get(self.cmp, self.cmp) + return repr(rf"{metric} {op} {self.threshold}") + + +class MetricChangeFilter(BaseMetricFilter): # from: RunMetricChangeFilter + """Defines a filter that compares a change in a run metric against a user-defined threshold. + + The change is calculated over "tumbling" windows, i.e. the difference + between the current window and the non-overlapping prior window. + """ + + name: str + agg: Annotated[Optional[Agg], Field(alias="agg_op")] = None + window: Annotated[PositiveInt, Field(alias="current_window_size")] = 1 + + # `prior_window` is only for `RUN_METRIC_CHANGE` events + prior_window: Annotated[ + PositiveInt, + # By default, set `window -> prior_window` if the latter wasn't provided. + Field(alias="prior_window_size", default_factory=lambda data: data["window"]), + ] + """Size of the prior window over which the metric is aggregated (ignored if `agg is None`). + + If omitted, defaults to the size of the current window. + """ + + # ------------------------------------------------------------------------------ + # NOTE: + # - The "comparison" operator isn't actually part of the backend schema, + # but it's defined here for consistency -- and ignored otherwise. + # - In the backend, it's effectively "$gte" or "$lte", depending on the sign + # (change_dir), though again, this is not explicit in the schema. + cmp: Annotated[None, Field(frozen=True, exclude=True, repr=False)] = None + """Ignored.""" + + # ------------------------------------------------------------------------------ + change_type: Annotated[ChangeType, Field(alias="change_type")] + change_dir: Annotated[ChangeDir, Field(alias="change_dir")] + threshold: Annotated[PosNum, Field(alias="change_amount")] + + def __repr__(self) -> str: + metric = f"{self.agg.value}({self.name})" if self.agg else self.name + verb = ( + "changes" + if (self.change_dir is ChangeDir.ANY) + else f"{self.change_dir.value.lower()}s" + ) + + fmt_spec = ".2%" if (self.change_type is ChangeType.REL) else "" + amt = f"{self.threshold:{fmt_spec}}" + return repr(rf"{metric} {verb} {amt}") + + +class BaseMetricOperand(GQLBase, extra="forbid"): + def gt(self, value: int | float, /) -> MetricThresholdFilter: + """Defines a `MetricThresholdFilter` that observes for `metric_expr > threshold`.""" + return self > value + + def lt(self, value: int | float, /) -> MetricThresholdFilter: + """Defines a `MetricThresholdFilter` that observes for `metric_expr < threshold`.""" + return self < value + + def gte(self, value: int | float, /) -> MetricThresholdFilter: + """Defines a `MetricThresholdFilter` that observes for `metric_expr >= threshold`.""" + return self >= value + + def lte(self, value: int | float, /) -> MetricThresholdFilter: + """Defines a `MetricThresholdFilter` that observes for `metric_expr <= threshold`.""" + return self <= value + + # Overloads to implement: + # - `(metric_operand > threshold) -> MetricThresholdFilter` + # - `(metric_operand < threshold) -> MetricThresholdFilter` + # - `(metric_operand >= threshold) -> MetricThresholdFilter` + # - `(metric_operand <= threshold) -> MetricThresholdFilter` + def __gt__(self, other: Any) -> MetricThresholdFilter: + if isinstance(other, (int, float)): + return MetricThresholdFilter(**dict(self), cmp="$gt", threshold=other) + return NotImplemented + + def __lt__(self, other: Any) -> MetricThresholdFilter: + if isinstance(other, (int, float)): + return MetricThresholdFilter(**dict(self), cmp="$lt", threshold=other) + return NotImplemented + + def __ge__(self, other: Any) -> MetricThresholdFilter: + if isinstance(other, (int, float)): + return MetricThresholdFilter(**dict(self), cmp="$gte", threshold=other) + return NotImplemented + + def __le__(self, other: Any) -> MetricThresholdFilter: + if isinstance(other, (int, float)): + return MetricThresholdFilter(**dict(self), cmp="$lte", threshold=other) + return NotImplemented + + @overload + def changes_by(self, *, diff: PosNum, frac: None) -> MetricChangeFilter: ... + @overload + def changes_by(self, *, diff: None, frac: PosNum) -> MetricChangeFilter: ... + @overload # NOTE: This overload is for internal use only. + def changes_by( + self, *, diff: PosNum | None, frac: PosNum | None, _dir: ChangeDir + ) -> MetricChangeFilter: ... + def changes_by( + self, + *, + diff: PosNum | None = None, + frac: PosNum | None = None, + _dir: ChangeDir = ChangeDir.ANY, + ) -> MetricChangeFilter: + """Defines a filter that observes for any change (increase OR decrease) in a run metric. + + Exactly one of the keyword arguments `frac` or `diff` must be provided. + + Args: + diff: + If given, the arithmetic difference that must be observed + in the metric. Must be a positive number. + frac: + If given, the fractional (relative) change that must be observed + in the metric. Must be a positive number. E.g. `frac=0.1` + denotes a 10% relative increase OR decrease. + """ + # Enforce mutually exclusive keyword args + if (frac is None) is (diff is None): + raise ValueError("Must provide exactly one of `frac` or `diff`") + + # Enforce positive values + if (frac is not None) and (frac <= 0): + raise ValueError(f"Expected positive quantity, got: {frac=}") + if (diff is not None) and (diff <= 0): + raise ValueError(f"Expected positive quantity, got: {diff=}") + + if diff is None: + change_kws = dict(change_type=ChangeType.REL, threshold=frac) + return MetricChangeFilter(**dict(self), change_dir=_dir, **change_kws) + else: + change_kws = dict(change_type=ChangeType.ABS, threshold=diff) + return MetricChangeFilter(**dict(self), change_dir=_dir, **change_kws) + + @overload + def increases_by(self, *, diff: PosNum, frac: None) -> MetricChangeFilter: ... + @overload + def increases_by(self, *, diff: None, frac: PosNum) -> MetricChangeFilter: ... + def increases_by( + self, *, diff: PosNum | None = None, frac: PosNum | None = None + ) -> MetricChangeFilter: + """Defines a filter that observes for an increase in the numerical value of a run metric. + + Arguments are the same as for `.changes_by()`. + """ + return self.changes_by(diff=diff, frac=frac, _dir=ChangeDir.INC) + + @overload + def decreases_by(self, *, diff: PosNum, frac: None) -> MetricChangeFilter: ... + @overload + def decreases_by(self, *, diff: None, frac: PosNum) -> MetricChangeFilter: ... + def decreases_by( + self, *, diff: PosNum | None = None, frac: PosNum | None = None + ) -> MetricChangeFilter: + """Defines a filter that observes for a decrease in the numerical value of a run metric. + + Arguments are the same as for `.changes_by()`. + """ + return self.changes_by(diff=diff, frac=frac, _dir=ChangeDir.DEC) + + +class MetricVal(BaseMetricOperand): + """Represents a single, unaggregated metric value when defining a metric filter.""" + + name: str + + # Allow users to convert this single-value metric into an aggregated metric expression. + def max(self, window: int) -> MetricAgg: + return MetricAgg(name=self.name, agg=Agg.MAX, window=window) + + def min(self, window: int) -> MetricAgg: + return MetricAgg(name=self.name, agg=Agg.MIN, window=window) + + def avg(self, window: int) -> MetricAgg: + return MetricAgg(name=self.name, agg=Agg.AVG, window=window) + + # Aliased method for users familiar with e.g. torch/tf/numpy/pandas/polars/etc. + def mean(self, window: int) -> MetricAgg: + return self.avg(window=window) + + +class MetricAgg(BaseMetricOperand): + """Represents an aggregated metric value when defining a metric filter.""" + + name: str + agg: Annotated[Agg, Field(alias="agg_op")] + window: Annotated[PositiveInt, Field(alias="window_size")] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..717c170e4a34333ee08c27b14b7ced31b91bf4ff --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__init__.py @@ -0,0 +1,177 @@ +# Generated by ariadne-codegen + +from .create_automation import CreateAutomation +from .create_generic_webhook_integration import ( + CreateGenericWebhookIntegration, + CreateGenericWebhookIntegrationCreateGenericWebhookIntegration, + CreateGenericWebhookIntegrationCreateGenericWebhookIntegrationIntegrationGenericWebhookIntegration, + CreateGenericWebhookIntegrationCreateGenericWebhookIntegrationIntegrationIntegration, +) +from .delete_automation import DeleteAutomation +from .enums import ( + AlertSeverity, + EventTriggeringConditionType, + TriggeredActionType, + TriggerScopeType, +) +from .fragments import ( + ArtifactPortfolioScopeFields, + ArtifactSequenceScopeFields, + FilterEventFields, + GenericWebhookActionFields, + GenericWebhookActionFieldsIntegrationGenericWebhookIntegration, + GenericWebhookActionFieldsIntegrationIntegration, + GenericWebhookIntegrationConnectionFields, + GenericWebhookIntegrationConnectionFieldsEdges, + GenericWebhookIntegrationConnectionFieldsEdgesNodeGenericWebhookIntegration, + GenericWebhookIntegrationConnectionFieldsEdgesNodeIntegration, + GenericWebhookIntegrationFields, + IntegrationConnectionFields, + IntegrationConnectionFieldsEdges, + IntegrationConnectionFieldsEdgesNodeGenericWebhookIntegration, + IntegrationConnectionFieldsEdgesNodeIntegration, + IntegrationConnectionFieldsEdgesNodeSlackIntegration, + NoOpActionFields, + NotificationActionFields, + NotificationActionFieldsIntegrationIntegration, + NotificationActionFieldsIntegrationSlackIntegration, + PageInfoFields, + ProjectConnectionFields, + ProjectConnectionFieldsEdges, + ProjectConnectionFieldsEdgesNode, + ProjectScopeFields, + QueueJobActionFields, + QueueJobActionFieldsQueue, + SlackIntegrationConnectionFields, + SlackIntegrationConnectionFieldsEdges, + SlackIntegrationConnectionFieldsEdgesNodeIntegration, + SlackIntegrationConnectionFieldsEdgesNodeSlackIntegration, + SlackIntegrationFields, + TriggerFields, + TriggerFieldsActionGenericWebhookTriggeredAction, + TriggerFieldsActionNoOpTriggeredAction, + TriggerFieldsActionNotificationTriggeredAction, + TriggerFieldsActionQueueJobTriggeredAction, + TriggerFieldsEventFilterEventTriggeringCondition, + TriggerFieldsScopeArtifactPortfolio, + TriggerFieldsScopeArtifactSequence, + TriggerFieldsScopeProject, +) +from .generic_webhook_integrations_by_entity import ( + GenericWebhookIntegrationsByEntity, + GenericWebhookIntegrationsByEntityEntity, +) +from .get_automations import GetAutomations, GetAutomationsSearchScope +from .get_automations_by_entity import ( + GetAutomationsByEntity, + GetAutomationsByEntitySearchScope, +) +from .input_types import ( + CreateFilterTriggerInput, + CreateGenericWebhookIntegrationInput, + GenericWebhookActionInput, + NoOpTriggeredActionInput, + NotificationActionInput, + QueueJobActionInput, + TriggeredActionConfig, + UpdateFilterTriggerInput, +) +from .integrations_by_entity import IntegrationsByEntity, IntegrationsByEntityEntity +from .operations import ( + CREATE_AUTOMATION_GQL, + CREATE_GENERIC_WEBHOOK_INTEGRATION_GQL, + DELETE_AUTOMATION_GQL, + GENERIC_WEBHOOK_INTEGRATIONS_BY_ENTITY_GQL, + GET_AUTOMATIONS_BY_ENTITY_GQL, + GET_AUTOMATIONS_GQL, + INTEGRATIONS_BY_ENTITY_GQL, + SLACK_INTEGRATIONS_BY_ENTITY_GQL, + UPDATE_AUTOMATION_GQL, +) +from .slack_integrations_by_entity import ( + SlackIntegrationsByEntity, + SlackIntegrationsByEntityEntity, +) +from .update_automation import UpdateAutomation + +__all__ = [ + "CREATE_AUTOMATION_GQL", + "CREATE_GENERIC_WEBHOOK_INTEGRATION_GQL", + "DELETE_AUTOMATION_GQL", + "GENERIC_WEBHOOK_INTEGRATIONS_BY_ENTITY_GQL", + "GET_AUTOMATIONS_BY_ENTITY_GQL", + "GET_AUTOMATIONS_GQL", + "INTEGRATIONS_BY_ENTITY_GQL", + "SLACK_INTEGRATIONS_BY_ENTITY_GQL", + "UPDATE_AUTOMATION_GQL", + "GetAutomations", + "GetAutomationsSearchScope", + "GetAutomationsByEntity", + "GetAutomationsByEntitySearchScope", + "CreateAutomation", + "UpdateAutomation", + "DeleteAutomation", + "IntegrationsByEntity", + "IntegrationsByEntityEntity", + "SlackIntegrationsByEntity", + "SlackIntegrationsByEntityEntity", + "GenericWebhookIntegrationsByEntity", + "GenericWebhookIntegrationsByEntityEntity", + "CreateGenericWebhookIntegration", + "CreateGenericWebhookIntegrationCreateGenericWebhookIntegration", + "CreateGenericWebhookIntegrationCreateGenericWebhookIntegrationIntegrationGenericWebhookIntegration", + "CreateGenericWebhookIntegrationCreateGenericWebhookIntegrationIntegrationIntegration", + "CreateFilterTriggerInput", + "CreateGenericWebhookIntegrationInput", + "GenericWebhookActionInput", + "NoOpTriggeredActionInput", + "NotificationActionInput", + "QueueJobActionInput", + "TriggeredActionConfig", + "UpdateFilterTriggerInput", + "ArtifactPortfolioScopeFields", + "ArtifactSequenceScopeFields", + "FilterEventFields", + "GenericWebhookActionFields", + "GenericWebhookActionFieldsIntegrationGenericWebhookIntegration", + "GenericWebhookActionFieldsIntegrationIntegration", + "GenericWebhookIntegrationConnectionFields", + "GenericWebhookIntegrationConnectionFieldsEdges", + "GenericWebhookIntegrationConnectionFieldsEdgesNodeGenericWebhookIntegration", + "GenericWebhookIntegrationConnectionFieldsEdgesNodeIntegration", + "GenericWebhookIntegrationFields", + "IntegrationConnectionFields", + "IntegrationConnectionFieldsEdges", + "IntegrationConnectionFieldsEdgesNodeGenericWebhookIntegration", + "IntegrationConnectionFieldsEdgesNodeIntegration", + "IntegrationConnectionFieldsEdgesNodeSlackIntegration", + "NoOpActionFields", + "NotificationActionFields", + "NotificationActionFieldsIntegrationIntegration", + "NotificationActionFieldsIntegrationSlackIntegration", + "PageInfoFields", + "ProjectConnectionFields", + "ProjectConnectionFieldsEdges", + "ProjectConnectionFieldsEdgesNode", + "ProjectScopeFields", + "QueueJobActionFields", + "QueueJobActionFieldsQueue", + "SlackIntegrationConnectionFields", + "SlackIntegrationConnectionFieldsEdges", + "SlackIntegrationConnectionFieldsEdgesNodeIntegration", + "SlackIntegrationConnectionFieldsEdgesNodeSlackIntegration", + "SlackIntegrationFields", + "TriggerFields", + "TriggerFieldsActionGenericWebhookTriggeredAction", + "TriggerFieldsActionNoOpTriggeredAction", + "TriggerFieldsActionNotificationTriggeredAction", + "TriggerFieldsActionQueueJobTriggeredAction", + "TriggerFieldsEventFilterEventTriggeringCondition", + "TriggerFieldsScopeArtifactPortfolio", + "TriggerFieldsScopeArtifactSequence", + "TriggerFieldsScopeProject", + "AlertSeverity", + "EventTriggeringConditionType", + "TriggerScopeType", + "TriggeredActionType", +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..870d4160786eefeb12c913b160a10acb9f1f6ff2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/create_generic_webhook_integration.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/create_generic_webhook_integration.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..333c2d7b9d3c526d9cd1ad774c4d488fea9ed1e2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/create_generic_webhook_integration.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/delete_automation.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/delete_automation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..865c43623986648af220ea6234cecdb036c4b654 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/delete_automation.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/enums.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/enums.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3736a0e35a4429bb6e644b76efc289ba3432191b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/enums.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/generic_webhook_integrations_by_entity.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/generic_webhook_integrations_by_entity.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..537955a1bdbd4b0e812a287a4c02dc21454fa565 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/generic_webhook_integrations_by_entity.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/get_automations.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/get_automations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c927f06e4e915de84afab9fa855aeef3cf279603 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/get_automations.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/get_automations_by_entity.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/get_automations_by_entity.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ef1440a9ac0186ea499c92ee2c43d263a148a75 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/get_automations_by_entity.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/operations.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/operations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0237ee398a3360d098362f3970fcd080d1c888d6 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/operations.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/slack_integrations_by_entity.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/slack_integrations_by_entity.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aafcc22905750a78d22563203620cd951521548d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/slack_integrations_by_entity.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/update_automation.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/update_automation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5144c3bf97a7fbef778b4a6f879cfc27d6ffa041 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/__pycache__/update_automation.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/create_automation.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/create_automation.py new file mode 100644 index 0000000000000000000000000000000000000000..63c551908b961291bd0ef87e79e90bae24e66686 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/create_automation.py @@ -0,0 +1,17 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/automations/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLBase + +from .fragments import CreateAutomationResult + + +class CreateAutomation(GQLBase): + result: Optional[CreateAutomationResult] + + +CreateAutomation.model_rebuild() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/create_generic_webhook_integration.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/create_generic_webhook_integration.py new file mode 100644 index 0000000000000000000000000000000000000000..cc215f452cd3ed0e97bc28996787a2b739216a7e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/create_generic_webhook_integration.py @@ -0,0 +1,43 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/automations/ + +from __future__ import annotations + +from typing import Literal, Optional, Union + +from pydantic import Field + +from wandb._pydantic import GQLBase, Typename + +from .fragments import GenericWebhookIntegrationFields + + +class CreateGenericWebhookIntegration(GQLBase): + create_generic_webhook_integration: Optional[ + CreateGenericWebhookIntegrationCreateGenericWebhookIntegration + ] = Field(alias="createGenericWebhookIntegration") + + +class CreateGenericWebhookIntegrationCreateGenericWebhookIntegration(GQLBase): + integration: Union[ + CreateGenericWebhookIntegrationCreateGenericWebhookIntegrationIntegrationIntegration, + CreateGenericWebhookIntegrationCreateGenericWebhookIntegrationIntegrationGenericWebhookIntegration, + ] = Field(discriminator="typename__") + + +class CreateGenericWebhookIntegrationCreateGenericWebhookIntegrationIntegrationIntegration( + GQLBase +): + typename__: Typename[ + Literal["GitHubOAuthIntegration", "Integration", "SlackIntegration"] + ] + + +class CreateGenericWebhookIntegrationCreateGenericWebhookIntegrationIntegrationGenericWebhookIntegration( + GenericWebhookIntegrationFields +): + typename__: Typename[Literal["GenericWebhookIntegration"]] + + +CreateGenericWebhookIntegration.model_rebuild() +CreateGenericWebhookIntegrationCreateGenericWebhookIntegration.model_rebuild() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/delete_automation.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/delete_automation.py new file mode 100644 index 0000000000000000000000000000000000000000..9d889f69b6df5c7c158ba26a22cea58dfc7ef338 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/delete_automation.py @@ -0,0 +1,17 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/automations/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLBase + +from .fragments import DeleteAutomationResult + + +class DeleteAutomation(GQLBase): + result: Optional[DeleteAutomationResult] + + +DeleteAutomation.model_rebuild() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/get_automations.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/get_automations.py new file mode 100644 index 0000000000000000000000000000000000000000..d9be5c3fe2f55010e134e140342a9032fd07ae7d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/get_automations.py @@ -0,0 +1,24 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/automations/ + +from __future__ import annotations + +from typing import Optional + +from pydantic import Field + +from wandb._pydantic import GQLBase + +from .fragments import ProjectConnectionFields + + +class GetAutomations(GQLBase): + search_scope: Optional[GetAutomationsSearchScope] = Field(alias="searchScope") + + +class GetAutomationsSearchScope(GQLBase): + projects: Optional[ProjectConnectionFields] + + +GetAutomations.model_rebuild() +GetAutomationsSearchScope.model_rebuild() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/get_automations_by_entity.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/get_automations_by_entity.py new file mode 100644 index 0000000000000000000000000000000000000000..2be7ecdce1186fbf902fe2342fcd0feca35ce603 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/get_automations_by_entity.py @@ -0,0 +1,26 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/automations/ + +from __future__ import annotations + +from typing import Optional + +from pydantic import Field + +from wandb._pydantic import GQLBase + +from .fragments import ProjectConnectionFields + + +class GetAutomationsByEntity(GQLBase): + search_scope: Optional[GetAutomationsByEntitySearchScope] = Field( + alias="searchScope" + ) + + +class GetAutomationsByEntitySearchScope(GQLBase): + projects: Optional[ProjectConnectionFields] + + +GetAutomationsByEntity.model_rebuild() +GetAutomationsByEntitySearchScope.model_rebuild() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/input_types.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/input_types.py new file mode 100644 index 0000000000000000000000000000000000000000..968d461fd06d9639f8960b8114ce0c7d1219b708 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/input_types.py @@ -0,0 +1,104 @@ +# Generated by ariadne-codegen +# Source: core/api/graphql/schemas/schema-latest.graphql + +from __future__ import annotations + +from typing import Optional + +from pydantic import Field + +from wandb._pydantic import GQLBase, GQLId + +from .enums import ( + AlertSeverity, + EventTriggeringConditionType, + TriggeredActionType, + TriggerScopeType, +) + + +class CreateGenericWebhookIntegrationInput(GQLBase): + entity_name: str = Field(alias="entityName") + url_endpoint: str = Field(alias="urlEndpoint") + name: str + secret_ref: Optional[str] = Field(alias="secretRef", default=None) + access_token_ref: Optional[str] = Field(alias="accessTokenRef", default=None) + client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None) + + +class QueueJobActionInput(GQLBase): + queue_id: GQLId = Field(alias="queueID") + template: str + + +class NotificationActionInput(GQLBase): + integration_id: GQLId = Field(alias="integrationID") + title: Optional[str] = None + message: Optional[str] = None + severity: Optional[AlertSeverity] = None + + +class GenericWebhookActionInput(GQLBase): + integration_id: GQLId = Field(alias="integrationID") + request_payload: Optional[str] = Field(alias="requestPayload", default=None) + + +class NoOpTriggeredActionInput(GQLBase): + no_op: Optional[bool] = Field(alias="noOp", default=None) + + +class TriggeredActionConfig(GQLBase): + queue_job_action_input: Optional[QueueJobActionInput] = Field( + alias="queueJobActionInput", default=None + ) + notification_action_input: Optional[NotificationActionInput] = Field( + alias="notificationActionInput", default=None + ) + generic_webhook_action_input: Optional[GenericWebhookActionInput] = Field( + alias="genericWebhookActionInput", default=None + ) + no_op_action_input: Optional[NoOpTriggeredActionInput] = Field( + alias="noOpActionInput", default=None + ) + + +class CreateFilterTriggerInput(GQLBase): + name: str + description: Optional[str] = None + triggering_event_type: EventTriggeringConditionType = Field( + alias="triggeringEventType" + ) + scope_type: TriggerScopeType = Field(alias="scopeType") + scope_id: GQLId = Field(alias="scopeID") + event_filter: str = Field(alias="eventFilter") + triggered_action_type: TriggeredActionType = Field(alias="triggeredActionType") + triggered_action_config: TriggeredActionConfig = Field( + alias="triggeredActionConfig" + ) + enabled: bool + client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None) + + +class UpdateFilterTriggerInput(GQLBase): + id: GQLId + name: Optional[str] = None + description: Optional[str] = None + triggering_event_type: Optional[EventTriggeringConditionType] = Field( + alias="triggeringEventType", default=None + ) + scope_type: Optional[TriggerScopeType] = Field(alias="scopeType", default=None) + scope_id: Optional[GQLId] = Field(alias="scopeID", default=None) + event_filter: Optional[str] = Field(alias="eventFilter", default=None) + triggered_action_type: Optional[TriggeredActionType] = Field( + alias="triggeredActionType", default=None + ) + triggered_action_config: Optional[TriggeredActionConfig] = Field( + alias="triggeredActionConfig", default=None + ) + enabled: Optional[bool] = None + client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None) + + +TriggeredActionConfig.model_rebuild() +CreateFilterTriggerInput.model_rebuild() +UpdateFilterTriggerInput.model_rebuild() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/operations.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/operations.py new file mode 100644 index 0000000000000000000000000000000000000000..5d67acd8d6541180d8ab7a99f8f876364592a338 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/operations.py @@ -0,0 +1,647 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/automations/ + +__all__ = [ + "CREATE_AUTOMATION_GQL", + "CREATE_GENERIC_WEBHOOK_INTEGRATION_GQL", + "DELETE_AUTOMATION_GQL", + "GENERIC_WEBHOOK_INTEGRATIONS_BY_ENTITY_GQL", + "GET_AUTOMATIONS_BY_ENTITY_GQL", + "GET_AUTOMATIONS_GQL", + "INTEGRATIONS_BY_ENTITY_GQL", + "SLACK_INTEGRATIONS_BY_ENTITY_GQL", + "UPDATE_AUTOMATION_GQL", +] + +GET_AUTOMATIONS_GQL = """ +query GetAutomations($cursor: String, $perPage: Int) { + searchScope: viewer { + projects(after: $cursor, first: $perPage) { + ...ProjectConnectionFields + } + } +} + +fragment ArtifactPortfolioScopeFields on ArtifactPortfolio { + __typename + id + name +} + +fragment ArtifactSequenceScopeFields on ArtifactSequence { + __typename + id + name +} + +fragment FilterEventFields on FilterEventTriggeringCondition { + __typename + eventType + filter +} + +fragment GenericWebhookActionFields on GenericWebhookTriggeredAction { + __typename + integration { + __typename + ...GenericWebhookIntegrationFields + } + requestPayload +} + +fragment GenericWebhookIntegrationFields on GenericWebhookIntegration { + __typename + id + name + urlEndpoint +} + +fragment NoOpActionFields on NoOpTriggeredAction { + __typename + noOp +} + +fragment NotificationActionFields on NotificationTriggeredAction { + __typename + integration { + __typename + ...SlackIntegrationFields + } + title + message + severity +} + +fragment PageInfoFields on PageInfo { + endCursor + hasNextPage +} + +fragment ProjectConnectionFields on ProjectConnection { + __typename + pageInfo { + ...PageInfoFields + } + edges { + cursor + node { + triggers { + ...TriggerFields + } + } + } +} + +fragment ProjectScopeFields on Project { + __typename + id + name +} + +fragment QueueJobActionFields on QueueJobTriggeredAction { + __typename + queue { + id + name + } + template +} + +fragment SlackIntegrationFields on SlackIntegration { + __typename + id + teamName + channelName +} + +fragment TriggerFields on Trigger { + __typename + id + createdAt + updatedAt + name + description + enabled + scope { + __typename + ...ProjectScopeFields + ...ArtifactPortfolioScopeFields + ...ArtifactSequenceScopeFields + } + event: triggeringCondition { + __typename + ...FilterEventFields + } + action: triggeredAction { + __typename + ...QueueJobActionFields + ...NotificationActionFields + ...GenericWebhookActionFields + ...NoOpActionFields + } +} +""" + +GET_AUTOMATIONS_BY_ENTITY_GQL = """ +query GetAutomationsByEntity($entityName: String!, $cursor: String, $perPage: Int) { + searchScope: entity(name: $entityName) { + projects(after: $cursor, first: $perPage) { + ...ProjectConnectionFields + } + } +} + +fragment ArtifactPortfolioScopeFields on ArtifactPortfolio { + __typename + id + name +} + +fragment ArtifactSequenceScopeFields on ArtifactSequence { + __typename + id + name +} + +fragment FilterEventFields on FilterEventTriggeringCondition { + __typename + eventType + filter +} + +fragment GenericWebhookActionFields on GenericWebhookTriggeredAction { + __typename + integration { + __typename + ...GenericWebhookIntegrationFields + } + requestPayload +} + +fragment GenericWebhookIntegrationFields on GenericWebhookIntegration { + __typename + id + name + urlEndpoint +} + +fragment NoOpActionFields on NoOpTriggeredAction { + __typename + noOp +} + +fragment NotificationActionFields on NotificationTriggeredAction { + __typename + integration { + __typename + ...SlackIntegrationFields + } + title + message + severity +} + +fragment PageInfoFields on PageInfo { + endCursor + hasNextPage +} + +fragment ProjectConnectionFields on ProjectConnection { + __typename + pageInfo { + ...PageInfoFields + } + edges { + cursor + node { + triggers { + ...TriggerFields + } + } + } +} + +fragment ProjectScopeFields on Project { + __typename + id + name +} + +fragment QueueJobActionFields on QueueJobTriggeredAction { + __typename + queue { + id + name + } + template +} + +fragment SlackIntegrationFields on SlackIntegration { + __typename + id + teamName + channelName +} + +fragment TriggerFields on Trigger { + __typename + id + createdAt + updatedAt + name + description + enabled + scope { + __typename + ...ProjectScopeFields + ...ArtifactPortfolioScopeFields + ...ArtifactSequenceScopeFields + } + event: triggeringCondition { + __typename + ...FilterEventFields + } + action: triggeredAction { + __typename + ...QueueJobActionFields + ...NotificationActionFields + ...GenericWebhookActionFields + ...NoOpActionFields + } +} +""" + +CREATE_AUTOMATION_GQL = """ +mutation CreateAutomation($params: CreateFilterTriggerInput!) { + result: createFilterTrigger(input: $params) { + ...CreateAutomationResult + } +} + +fragment ArtifactPortfolioScopeFields on ArtifactPortfolio { + __typename + id + name +} + +fragment ArtifactSequenceScopeFields on ArtifactSequence { + __typename + id + name +} + +fragment CreateAutomationResult on CreateFilterTriggerPayload { + __typename + trigger { + ...TriggerFields + } +} + +fragment FilterEventFields on FilterEventTriggeringCondition { + __typename + eventType + filter +} + +fragment GenericWebhookActionFields on GenericWebhookTriggeredAction { + __typename + integration { + __typename + ...GenericWebhookIntegrationFields + } + requestPayload +} + +fragment GenericWebhookIntegrationFields on GenericWebhookIntegration { + __typename + id + name + urlEndpoint +} + +fragment NoOpActionFields on NoOpTriggeredAction { + __typename + noOp +} + +fragment NotificationActionFields on NotificationTriggeredAction { + __typename + integration { + __typename + ...SlackIntegrationFields + } + title + message + severity +} + +fragment ProjectScopeFields on Project { + __typename + id + name +} + +fragment QueueJobActionFields on QueueJobTriggeredAction { + __typename + queue { + id + name + } + template +} + +fragment SlackIntegrationFields on SlackIntegration { + __typename + id + teamName + channelName +} + +fragment TriggerFields on Trigger { + __typename + id + createdAt + updatedAt + name + description + enabled + scope { + __typename + ...ProjectScopeFields + ...ArtifactPortfolioScopeFields + ...ArtifactSequenceScopeFields + } + event: triggeringCondition { + __typename + ...FilterEventFields + } + action: triggeredAction { + __typename + ...QueueJobActionFields + ...NotificationActionFields + ...GenericWebhookActionFields + ...NoOpActionFields + } +} +""" + +UPDATE_AUTOMATION_GQL = """ +mutation UpdateAutomation($params: UpdateFilterTriggerInput!) { + result: updateFilterTrigger(input: $params) { + ...UpdateAutomationResult + } +} + +fragment ArtifactPortfolioScopeFields on ArtifactPortfolio { + __typename + id + name +} + +fragment ArtifactSequenceScopeFields on ArtifactSequence { + __typename + id + name +} + +fragment FilterEventFields on FilterEventTriggeringCondition { + __typename + eventType + filter +} + +fragment GenericWebhookActionFields on GenericWebhookTriggeredAction { + __typename + integration { + __typename + ...GenericWebhookIntegrationFields + } + requestPayload +} + +fragment GenericWebhookIntegrationFields on GenericWebhookIntegration { + __typename + id + name + urlEndpoint +} + +fragment NoOpActionFields on NoOpTriggeredAction { + __typename + noOp +} + +fragment NotificationActionFields on NotificationTriggeredAction { + __typename + integration { + __typename + ...SlackIntegrationFields + } + title + message + severity +} + +fragment ProjectScopeFields on Project { + __typename + id + name +} + +fragment QueueJobActionFields on QueueJobTriggeredAction { + __typename + queue { + id + name + } + template +} + +fragment SlackIntegrationFields on SlackIntegration { + __typename + id + teamName + channelName +} + +fragment TriggerFields on Trigger { + __typename + id + createdAt + updatedAt + name + description + enabled + scope { + __typename + ...ProjectScopeFields + ...ArtifactPortfolioScopeFields + ...ArtifactSequenceScopeFields + } + event: triggeringCondition { + __typename + ...FilterEventFields + } + action: triggeredAction { + __typename + ...QueueJobActionFields + ...NotificationActionFields + ...GenericWebhookActionFields + ...NoOpActionFields + } +} + +fragment UpdateAutomationResult on UpdateFilterTriggerPayload { + __typename + trigger { + ...TriggerFields + } +} +""" + +DELETE_AUTOMATION_GQL = """ +mutation DeleteAutomation($id: ID!) { + result: deleteTrigger(input: {triggerID: $id}) { + ...DeleteAutomationResult + } +} + +fragment DeleteAutomationResult on DeleteTriggerPayload { + __typename + success +} +""" + +INTEGRATIONS_BY_ENTITY_GQL = """ +query IntegrationsByEntity($entityName: String!, $cursor: String, $perPage: Int) { + entity(name: $entityName) { + integrations(after: $cursor, first: $perPage) { + ...IntegrationConnectionFields + } + } +} + +fragment GenericWebhookIntegrationFields on GenericWebhookIntegration { + __typename + id + name + urlEndpoint +} + +fragment IntegrationConnectionFields on IntegrationConnection { + __typename + pageInfo { + ...PageInfoFields + } + edges { + cursor + node { + __typename + ...SlackIntegrationFields + ...GenericWebhookIntegrationFields + } + } +} + +fragment PageInfoFields on PageInfo { + endCursor + hasNextPage +} + +fragment SlackIntegrationFields on SlackIntegration { + __typename + id + teamName + channelName +} +""" + +SLACK_INTEGRATIONS_BY_ENTITY_GQL = """ +query SlackIntegrationsByEntity($entityName: String!, $cursor: String, $perPage: Int) { + entity(name: $entityName) { + integrations(after: $cursor, first: $perPage) { + ...SlackIntegrationConnectionFields + } + } +} + +fragment PageInfoFields on PageInfo { + endCursor + hasNextPage +} + +fragment SlackIntegrationConnectionFields on IntegrationConnection { + __typename + pageInfo { + ...PageInfoFields + } + edges { + cursor + node { + __typename + ...SlackIntegrationFields + } + } +} + +fragment SlackIntegrationFields on SlackIntegration { + __typename + id + teamName + channelName +} +""" + +GENERIC_WEBHOOK_INTEGRATIONS_BY_ENTITY_GQL = """ +query GenericWebhookIntegrationsByEntity($entityName: String!, $cursor: String, $perPage: Int) { + entity(name: $entityName) { + integrations(after: $cursor, first: $perPage) { + ...GenericWebhookIntegrationConnectionFields + } + } +} + +fragment GenericWebhookIntegrationConnectionFields on IntegrationConnection { + __typename + pageInfo { + ...PageInfoFields + } + edges { + cursor + node { + __typename + ...GenericWebhookIntegrationFields + } + } +} + +fragment GenericWebhookIntegrationFields on GenericWebhookIntegration { + __typename + id + name + urlEndpoint +} + +fragment PageInfoFields on PageInfo { + endCursor + hasNextPage +} +""" + +CREATE_GENERIC_WEBHOOK_INTEGRATION_GQL = """ +mutation CreateGenericWebhookIntegration($params: CreateGenericWebhookIntegrationInput!) { + createGenericWebhookIntegration(input: $params) { + integration { + __typename + ...GenericWebhookIntegrationFields + } + } +} + +fragment GenericWebhookIntegrationFields on GenericWebhookIntegration { + __typename + id + name + urlEndpoint +} +""" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/slack_integrations_by_entity.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/slack_integrations_by_entity.py new file mode 100644 index 0000000000000000000000000000000000000000..6576c2d585135b6171572682f4d69fef498e1a07 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/slack_integrations_by_entity.py @@ -0,0 +1,22 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/automations/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLBase + +from .fragments import SlackIntegrationConnectionFields + + +class SlackIntegrationsByEntity(GQLBase): + entity: Optional[SlackIntegrationsByEntityEntity] + + +class SlackIntegrationsByEntityEntity(GQLBase): + integrations: Optional[SlackIntegrationConnectionFields] + + +SlackIntegrationsByEntity.model_rebuild() +SlackIntegrationsByEntityEntity.model_rebuild() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/update_automation.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/update_automation.py new file mode 100644 index 0000000000000000000000000000000000000000..12eb1be3549da444ca5532a0c02bede8e4def571 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/_generated/update_automation.py @@ -0,0 +1,17 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/automations/ + +from __future__ import annotations + +from typing import Optional + +from wandb._pydantic import GQLBase + +from .fragments import UpdateAutomationResult + + +class UpdateAutomation(GQLBase): + result: Optional[UpdateAutomationResult] + + +UpdateAutomation.model_rebuild() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/actions.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/actions.py new file mode 100644 index 0000000000000000000000000000000000000000..1b61b7037f2bb28778f887cd3e8df535db6beab0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/actions.py @@ -0,0 +1,218 @@ +"""Actions that are triggered by W&B Automations.""" + +from __future__ import annotations + +from typing import Any, Literal, Optional, Union + +from pydantic import BeforeValidator, Field +from typing_extensions import Annotated, Self, get_args + +from wandb._pydantic import GQLBase, GQLId, SerializedToJson, Typename + +from ._generated import ( + AlertSeverity, + GenericWebhookActionFields, + GenericWebhookActionInput, + NoOpActionFields, + NoOpTriggeredActionInput, + NotificationActionFields, + NotificationActionInput, + QueueJobActionFields, +) +from ._validators import ( + LenientStrEnum, + default_if_none, + to_input_action, + to_saved_action, + upper_if_str, +) +from .integrations import SlackIntegration, WebhookIntegration + + +# NOTE: Name shortened for readability and defined publicly for easier access +class ActionType(LenientStrEnum): + """The type of action triggered by an automation.""" + + QUEUE_JOB = "QUEUE_JOB" # NOTE: Deprecated for creation + NOTIFICATION = "NOTIFICATION" + GENERIC_WEBHOOK = "GENERIC_WEBHOOK" + NO_OP = "NO_OP" + + +# ------------------------------------------------------------------------------ +# Saved types: for parsing response data from saved automations + + +# NOTE: `QueueJobActionInput` for defining a Launch job is deprecated, +# so while we allow parsing it from previously saved Automations, we deliberately +# don't currently expose it in the API for creating automations. +class SavedLaunchJobAction(QueueJobActionFields): + action_type: Literal[ActionType.QUEUE_JOB] = ActionType.QUEUE_JOB + + +# FIXME: Find a better place to put these OR a better way to handle the +# conversion from `InputAction` -> `SavedAction`. +# +# Necessary placeholder class defs for converting: +# - `SendNotification -> SavedNotificationAction` +# - `SendWebhook -> SavedWebhookAction` +# +# The "input" types (`Send{Notification,Webhook}`) will only have an `integration_id`, +# and we don't want/need to fetch the other `{Slack,Webhook}Integration` fields if +# we can avoid it. +class _SavedActionSlackIntegration(GQLBase, extra="allow"): + typename__: Typename[Literal["SlackIntegration"]] = "SlackIntegration" + id: GQLId + + +class _SavedActionWebhookIntegration(GQLBase, extra="allow"): + typename__: Typename[Literal["GenericWebhookIntegration"]] = ( + "GenericWebhookIntegration" + ) + id: GQLId + + +class SavedNotificationAction(NotificationActionFields): + action_type: Literal[ActionType.NOTIFICATION] = ActionType.NOTIFICATION + integration: _SavedActionSlackIntegration + + +class SavedWebhookAction(GenericWebhookActionFields): + action_type: Literal[ActionType.GENERIC_WEBHOOK] = ActionType.GENERIC_WEBHOOK + integration: _SavedActionWebhookIntegration + + # We override the type of the `requestPayload` field since the original GraphQL + # schema (and generated class) effectively defines it as a string, when we know + # and need to anticipate the expected structure of the JSON-serialized data. + request_payload: Annotated[ + Optional[SerializedToJson[dict[str, Any]]], + Field(alias="requestPayload"), + ] = None # type: ignore[assignment] + + +class SavedNoOpAction(NoOpActionFields, frozen=True): + action_type: Literal[ActionType.NO_OP] = ActionType.NO_OP + + no_op: Annotated[bool, BeforeValidator(default_if_none)] = True + """Placeholder field, only needed to conform to schema requirements. + + There should never be a need to set this field explicitly, as its value is ignored. + """ + + +# for type annotations +SavedAction = Annotated[ + Union[ + SavedLaunchJobAction, + SavedNotificationAction, + SavedWebhookAction, + SavedNoOpAction, + ], + BeforeValidator(to_saved_action), + Field(discriminator="typename__"), +] +# for runtime type checks +SavedActionTypes: tuple[type, ...] = get_args(SavedAction.__origin__) # type: ignore[attr-defined] + + +# ------------------------------------------------------------------------------ +# Input types: for creating or updating automations +class _BaseActionInput(GQLBase): + action_type: Annotated[ActionType, Field(frozen=True)] + """The kind of action to be triggered.""" + + +class SendNotification(_BaseActionInput, NotificationActionInput): + """Defines an automation action that sends a (Slack) notification.""" + + action_type: Literal[ActionType.NOTIFICATION] = ActionType.NOTIFICATION + + integration_id: GQLId + """The ID of the Slack integration that will be used to send the notification.""" + + # Note: Validation aliases are meant to provide continuity with prior `wandb.alert()` API. + title: str = "" + """The title of the sent notification.""" + + message: Annotated[str, Field(validation_alias="text")] = "" + """The message body of the sent notification.""" + + severity: Annotated[ + AlertSeverity, + BeforeValidator(upper_if_str), # Be helpful by ensuring uppercase strings + Field(validation_alias="level"), + ] = AlertSeverity.INFO + """The severity (`INFO`, `WARN`, `ERROR`) of the sent notification.""" + + @classmethod + def from_integration( + cls, + integration: SlackIntegration, + *, + title: str = "", + text: str = "", + level: AlertSeverity = AlertSeverity.INFO, + ) -> Self: + """Define a notification action that sends to the given (Slack) integration.""" + return cls( + integration_id=integration.id, + title=title, + message=text, + severity=level, + ) + + +class SendWebhook(_BaseActionInput, GenericWebhookActionInput): + """Defines an automation action that sends a webhook request.""" + + action_type: Literal[ActionType.GENERIC_WEBHOOK] = ActionType.GENERIC_WEBHOOK + + integration_id: GQLId + """The ID of the webhook integration that will be used to send the request.""" + + # overrides the generated field type to parse/serialize JSON strings + request_payload: Optional[SerializedToJson[dict[str, Any]]] = Field( # type: ignore[assignment] + default=None, alias="requestPayload" + ) + """The payload, possibly with template variables, to send in the webhook request.""" + + @classmethod + def from_integration( + cls, + integration: WebhookIntegration, + *, + payload: Optional[SerializedToJson[dict[str, Any]]] = None, + ) -> Self: + """Define a webhook action that sends to the given (webhook) integration.""" + return cls(integration_id=integration.id, request_payload=payload) + + +class DoNothing(_BaseActionInput, NoOpTriggeredActionInput, frozen=True): + """Defines an automation action that intentionally does nothing.""" + + action_type: Literal[ActionType.NO_OP] = ActionType.NO_OP + + no_op: Annotated[bool, BeforeValidator(default_if_none)] = True + """Placeholder field which exists only to satisfy backend schema requirements. + + There should never be a need to set this field explicitly, as its value is ignored. + """ + + +# for type annotations +InputAction = Annotated[ + Union[ + SendNotification, + SendWebhook, + DoNothing, + ], + BeforeValidator(to_input_action), + Field(discriminator="action_type"), +] +# for runtime type checks +InputActionTypes: tuple[type, ...] = get_args(InputAction.__origin__) # type: ignore[attr-defined] + +__all__ = [ + "ActionType", + *(cls.__name__ for cls in InputActionTypes), +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/events.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/events.py new file mode 100644 index 0000000000000000000000000000000000000000..8666e7faafa9b7c1de3c05d2888eb8ed9011c2a2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/automations/events.py @@ -0,0 +1,285 @@ +"""Events that trigger W&B Automations.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Optional, Union + +from pydantic import Field +from typing_extensions import Annotated, Self, get_args + +from wandb._pydantic import ( + GQLBase, + SerializedToJson, + ensure_json, + field_validator, + model_validator, + pydantic_isinstance, +) + +from ._filters import And, MongoLikeFilter, Or +from ._filters.expressions import FilterableField +from ._filters.run_metrics import MetricChangeFilter, MetricThresholdFilter, MetricVal +from ._generated import FilterEventFields +from ._validators import LenientStrEnum, simplify_op +from .actions import InputAction, InputActionTypes, SavedActionTypes +from .scopes import ArtifactCollectionScope, AutomationScope, ProjectScope + +if TYPE_CHECKING: + from .automations import NewAutomation + + +# NOTE: Re-defined publicly with a more readable name for easier access +class EventType(LenientStrEnum): + """The type of event that triggers an automation.""" + + # --------------------------------------------------------------------------- + # Events triggered by GraphQL mutations + UPDATE_ARTIFACT_ALIAS = "UPDATE_ARTIFACT_ALIAS" # NOTE: Avoid in new automations + + CREATE_ARTIFACT = "CREATE_ARTIFACT" + ADD_ARTIFACT_ALIAS = "ADD_ARTIFACT_ALIAS" + LINK_ARTIFACT = "LINK_MODEL" + # Note: "LINK_MODEL" is the (legacy) value expected by the backend, but we + # name it "LINK_ARTIFACT" here in the public API for clarity and consistency. + + # --------------------------------------------------------------------------- + # Events triggered by Run conditions + RUN_METRIC_THRESHOLD = "RUN_METRIC" + RUN_METRIC_CHANGE = "RUN_METRIC_CHANGE" + + +# ------------------------------------------------------------------------------ +# Saved types: for parsing response data from saved automations + + +# Note: In GQL responses containing saved automation data, the filter is wrapped in an extra `filter` key. +class _WrappedSavedEventFilter(GQLBase): # from: TriggeringFilterEvent + filter: SerializedToJson[MongoLikeFilter] = And() + + +class _WrappedMetricFilter(GQLBase): # from: RunMetricFilter + threshold_filter: Optional[MetricThresholdFilter] = None + change_filter: Optional[MetricChangeFilter] = None + + @model_validator(mode="before") + @classmethod + def _wrap_metric_filter(cls, v: Any) -> Any: + if pydantic_isinstance(v, MetricThresholdFilter): + return cls(threshold_filter=v) + if pydantic_isinstance(v, MetricChangeFilter): + return cls(change_filter=v) + return v + + @model_validator(mode="after") + def _ensure_exactly_one_set(self) -> Self: + set_fields = [name for name, val in self if (val is not None)] + + if not set_fields: + all_names = ", ".join(map(repr, type(self).model_fields)) + raise ValueError(f"Expected one of: {all_names}") + + if len(set_fields) > 1: + set_names = ", ".join(map(repr, set_fields)) + raise ValueError(f"Expected exactly one metric filter, got: {set_names}") + + return self + + @property + def event_type(self) -> EventType: + if self.threshold_filter is not None: + return EventType.RUN_METRIC_THRESHOLD + if self.change_filter is not None: + return EventType.RUN_METRIC_CHANGE + raise RuntimeError("Expected one of: `threshold_filter` or `change_filter`") + + +class RunMetricFilter(GQLBase): # from: TriggeringRunMetricEvent + run: Annotated[SerializedToJson[MongoLikeFilter], Field(alias="run_filter")] = And() + metric: Annotated[_WrappedMetricFilter, Field(alias="run_metric_filter")] + + # ------------------------------------------------------------------------------ + legacy_metric_filter: Annotated[ + Optional[SerializedToJson[MetricThresholdFilter]], + Field(alias="metric_filter", deprecated=True), + ] = None + """Deprecated legacy field that was previously used to define run metric threshold events. + + For new automations, use the `metric` field (`run_metric_filter` JSON alias) instead. + """ + + @model_validator(mode="before") + @classmethod + def _wrap_metric_filter(cls, v: Any) -> Any: + if pydantic_isinstance(v, (MetricThresholdFilter, MetricChangeFilter)): + # If only an (unnested) metric filter is given, nest it under the + # `metric` field, delegating to inner validator(s) for further + # wrapping/nesting, if needed. + # This is necessary to conform to the expected backend schema. + return cls(metric=v) + return v + + @field_validator("run", mode="after") + def _wrap_run_filter(cls, v: MongoLikeFilter) -> Any: + v_new = simplify_op(v) + return v_new if pydantic_isinstance(v_new, And) else And(and_=[v_new]) + + +class SavedEvent(FilterEventFields): # from: FilterEventTriggeringCondition + """A triggering event from a saved automation.""" + + event_type: Annotated[EventType, Field(frozen=True)] # type: ignore[assignment] + + # We override the type of the `filter` field in order to enforce the expected + # structure for the JSON data when validating and serializing. + filter: SerializedToJson[Union[_WrappedSavedEventFilter, RunMetricFilter]] + """The condition(s) under which this event triggers an automation.""" + + +# ------------------------------------------------------------------------------ +# Input types: for creating or updating automations + + +# Note: The GQL input for "eventFilter" does NOT wrap the filter in an extra `filter` key, unlike the +# eventFilter returned in responses for saved automations. +class _BaseEventInput(GQLBase): + event_type: EventType + + scope: AutomationScope + """The scope of the event.""" + + filter: SerializedToJson[Any] + + def then(self, action: InputAction) -> NewAutomation: + """Define a new Automation in which this event triggers the given action.""" + from .automations import NewAutomation + + if isinstance(action, (InputActionTypes, SavedActionTypes)): + return NewAutomation(event=self, action=action) + + raise TypeError(f"Expected a valid action, got: {type(action).__qualname__!r}") + + def __rshift__(self, other: InputAction) -> NewAutomation: + """Implements `event >> action` to define an Automation with this event and action.""" + return self.then(other) + + +# ------------------------------------------------------------------------------ +# Events that trigger on specific mutations in the backend +class _BaseMutationEventInput(_BaseEventInput): + filter: SerializedToJson[MongoLikeFilter] = And() + """Additional condition(s), if any, that must be met for this event to trigger an automation.""" + + @field_validator("filter", mode="after") + def _wrap_filter(cls, v: Any) -> Any: + """Ensure the given filter is wrapped like: `{"$or": [{"$and": []}]}`. + + This is awkward but necessary, because the frontend expects this format. + """ + v_new = simplify_op(v) + v_new = v_new if pydantic_isinstance(v_new, And) else And(and_=[v_new]) + return Or(or_=[v_new]) + + +class OnLinkArtifact(_BaseMutationEventInput): + """A new artifact is linked to a collection.""" + + event_type: Literal[EventType.LINK_ARTIFACT] = EventType.LINK_ARTIFACT + + +class OnAddArtifactAlias(_BaseMutationEventInput): + """A new alias is assigned to an artifact.""" + + event_type: Literal[EventType.ADD_ARTIFACT_ALIAS] = EventType.ADD_ARTIFACT_ALIAS + + +class OnCreateArtifact(_BaseMutationEventInput): + """A new artifact is created.""" + + event_type: Literal[EventType.CREATE_ARTIFACT] = EventType.CREATE_ARTIFACT + + scope: ArtifactCollectionScope + """The scope of the event: only artifact collections are valid scopes for this event.""" + + +# ------------------------------------------------------------------------------ +# Events that trigger on run conditions +class _BaseRunEventInput(_BaseEventInput): + scope: ProjectScope + """The scope of the event: only projects are valid scopes for this event.""" + + +class OnRunMetric(_BaseRunEventInput): + """A run metric satisfies a user-defined condition.""" + + event_type: Literal[EventType.RUN_METRIC_THRESHOLD, EventType.RUN_METRIC_CHANGE] + + filter: SerializedToJson[RunMetricFilter] + """Run and/or metric condition(s) that must be satisfied for this event to trigger an automation.""" + + @model_validator(mode="before") + @classmethod + def _infer_event_type(cls, data: Any) -> Any: + """Infer the event type at validation time from the inner filter. + + This allows this class to accommodate both "threshold" and "change" metric + filter types, which are can only be determined after parsing and validating + the inner JSON data. + """ + if isinstance(data, dict) and (raw_filter := data.get("filter")): + # At this point, `raw_filter` may or may not be JSON-serialized + parsed_filter = RunMetricFilter.model_validate_json(ensure_json(raw_filter)) + return {**data, "event_type": parsed_filter.metric.event_type} + + return data + + +# for type annotations +InputEvent = Annotated[ + Union[ + OnLinkArtifact, + OnAddArtifactAlias, + OnCreateArtifact, + OnRunMetric, + ], + Field(discriminator="event_type"), +] +# for runtime type checks +InputEventTypes: tuple[type, ...] = get_args(InputEvent.__origin__) # type: ignore[attr-defined] + + +# ---------------------------------------------------------------------------- + + +class RunEvent: + name = FilterableField(server_name="display_name") + # `Run.name` is actually filtered on `Run.display_name` in the backend. + # We can't reasonably expect users to know this a priori, so + # automatically fix it here. + + @staticmethod + def metric(name: str) -> MetricVal: + """Define a metric filter condition.""" + return MetricVal(name=name) + + +class ArtifactEvent: + alias = FilterableField() + + +MetricThresholdFilter.model_rebuild() +RunMetricFilter.model_rebuild() +_WrappedSavedEventFilter.model_rebuild() + +OnLinkArtifact.model_rebuild() +OnAddArtifactAlias.model_rebuild() +OnCreateArtifact.model_rebuild() +OnRunMetric.model_rebuild() + +__all__ = [ + "EventType", + *(cls.__name__ for cls in InputEventTypes), + "RunEvent", + "ArtifactEvent", + "MetricThresholdFilter", + "MetricChangeFilter", +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/beta/__pycache__/workflows.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/beta/__pycache__/workflows.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93cc51fa6f05b4a5b628474f6abb0b14ecae4df8 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/beta/__pycache__/workflows.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/beta/workflows.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/beta/workflows.py new file mode 100644 index 0000000000000000000000000000000000000000..7e3b98cc70fbb27da48a72b1a7c7a9797fabe027 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/beta/workflows.py @@ -0,0 +1,324 @@ +from __future__ import annotations + +import json +import os +import warnings +from typing import Any + +from typing_extensions import deprecated + +import wandb +from wandb.data_types import WBValue, _SavedModel +from wandb.proto.wandb_deprecated import Deprecated +from wandb.sdk import wandb_setup +from wandb.sdk.artifacts.artifact import Artifact +from wandb.sdk.artifacts.artifact_manifest_entry import ArtifactManifestEntry +from wandb.sdk.lib.deprecate import deprecate as wandb_deprecate + +warnings.warn( + message=f"The {__name__!r} module is deprecated and will be removed in a future version. Please use the equivalent 'wandb.Run' methods instead.", + category=DeprecationWarning, + stacklevel=2, +) + + +def _add_any( + artifact: Artifact, + path_or_obj: str | ArtifactManifestEntry | WBValue, # todo: add dataframe + name: str | None, +) -> Any: + """Add an object to an artifact. + + High-level wrapper to add object(s) to an artifact - calls any of the .add* methods + under Artifact depending on the type of object that's passed in. This will probably + be moved to the Artifact class in the future. + + Args: + artifact: artifact created with `wandb.Artifact(...)` + path_or_obj: either a str or valid object which indicates what to add + to an artifact. + name: the name of the object which is added to an artifact. + + Returns: + Type[Any] - Union[None, ArtifactManifestEntry, etc] + + """ + if isinstance(path_or_obj, ArtifactManifestEntry): + return artifact.add_reference(path_or_obj, name) + elif isinstance(path_or_obj, WBValue): + return artifact.add(path_or_obj, name) + elif isinstance(path_or_obj, str): + if os.path.isdir(path_or_obj): + return artifact.add_dir(path_or_obj) + elif os.path.isfile(path_or_obj): + return artifact.add_file(path_or_obj) + else: + with artifact.new_file(name) as f: + f.write(json.dumps(path_or_obj, sort_keys=True)) + else: + raise TypeError( + "Expected `path_or_obj` to be instance of `ArtifactManifestEntry`," + f" `WBValue`, or `str, found {type(path_or_obj)}" + ) + + +def _log_artifact_version( + name: str, + type: str, + entries: dict[str, str | ArtifactManifestEntry | WBValue], + aliases: str | list[str] | None = None, + description: str | None = None, + metadata: dict | None = None, + project: str | None = None, + scope_project: bool | None = None, + job_type: str = "auto", +) -> Artifact: + """Create an artifact, populate it, and log it with a run. + + If a run is not present, we create one. + + Args: + name: `str` - name of the artifact. If not scoped to a project, name will be + suffixed by "-{run_id}". + type: `str` - type of the artifact, used in the UI to group artifacts of the + same type. + entries: `Dict` - dictionary containing the named objects we want added to this + artifact. + description: `str` - text description of artifact. + metadata: `Dict` - users can pass in artifact-specific metadata here, will be + visible in the UI. + project: `str` - project under which to place this artifact. + scope_project: `bool` - if True, we will not suffix `name` with "-{run_id}". + job_type: `str` - Only applied if run is not present and we create one. + Used to identify runs of a certain job type, i.e "evaluation". + + Returns: + Artifact + + """ + run = wandb_setup.singleton().most_recent_active_run + if not run: + run = wandb.init( + project=project, + job_type=job_type, + settings=wandb.Settings(silent=True), + ) + + if not scope_project: + name = f"{name}-{run.id}" + + if metadata is None: + metadata = {} + + art = wandb.Artifact(name, type, description, metadata, False, None) + + for path in entries: + _add_any(art, entries[path], path) + + # "latest" should always be present as an alias + aliases = wandb.util._resolve_aliases(aliases) + run.log_artifact(art, aliases=aliases) + + return art + + +_LOG_MODEL_DEPRECATION_MSG = "`log_model` is deprecated and will be removed in a future version. Please use `Run.log_artifact` instead." + + +@deprecated(_LOG_MODEL_DEPRECATION_MSG) +def log_model( + model_obj: Any, + name: str = "model", + aliases: str | list[str] | None = None, + description: str | None = None, + metadata: dict | None = None, + project: str | None = None, + scope_project: bool | None = None, + **kwargs: dict[str, Any], +) -> _SavedModel: + """Log a model object to enable model-centric workflows in the UI. + + Supported frameworks include PyTorch, Keras, Tensorflow, Scikit-learn, etc. Under + the hood, we create a model artifact, bind it to the run that produced this model, + associate it with the latest metrics logged with `run.log(...)` and more. + + Args: + model_obj: any model object created with the following ML frameworks: PyTorch, + Keras, Tensorflow, Scikit-learn. name: `str` - name of the model artifact + that will be created to house this model_obj. + aliases: `str, List[str]` - optional alias(es) that will be applied on this + model and allow for unique identification. The alias "latest" will always be + applied to the latest version of a model. + description: `str` - text description/notes about the model - will be visible in + the Model Card UI. + metadata: `Dict` - model-specific metadata goes here - will be visible the UI. + project: `str` - project under which to place this artifact. + scope_project: `bool` - If true, name of this model artifact will not be + suffixed by `-{run_id}`. + + Returns: + _SavedModel instance + + Example: + ```python + import torch.nn as nn + import torch.nn.functional as F + + + class Net(nn.Module): + def __init__(self): + super(Net, self).__init__() + self.fc1 = nn.Linear(10, 10) + + def forward(self, x): + x = self.fc1(x) + x = F.relu(x) + return x + + + model = Net() + sm = log_model(model, "my-simple-model", aliases=["best"]) + ``` + + """ + wandb_deprecate( + field_name=Deprecated.beta__workflows__log_model, + warning_message=_LOG_MODEL_DEPRECATION_MSG, + ) + + model = _SavedModel.init(model_obj, **kwargs) + _ = _log_artifact_version( + name=name, + type="model", + entries={ + "index": model, + }, + aliases=aliases, + description=description, + metadata=metadata, + project=project, + scope_project=scope_project, + job_type="log_model", + ) + # TODO: handle offline mode appropriately. + return model + + +_USE_MODEL_DEPRECATION_MSG = "`use_model` is deprecated and will be removed in a future version. Please update your code to use `Run.use_artifact` instead." + + +@deprecated(_USE_MODEL_DEPRECATION_MSG) +def use_model(aliased_path: str, unsafe: bool = False) -> _SavedModel: + """Fetch a saved model from an alias. + + Under the hood, we use the alias to fetch the model artifact containing the + serialized model files and rebuild the model object from these files. We also + declare the fetched model artifact as an input to the run (with `run.use_artifact`). + + Args: + aliased_path: `str` - the following forms are valid: "name:version", + "name:alias". May be prefixed with "entity/project". + unsafe: `bool` - must be True to indicate the user understands the risks + associated with loading external models. + + Returns: + _SavedModel instance + + Example: + ```python + # Assuming the model with the name "my-simple-model" is trusted: + sm = use_model("my-simple-model:latest", unsafe=True) + model = sm.model_obj() + ``` + """ + wandb_deprecate( + field_name=Deprecated.beta__workflows__use_model, + warning_message=_USE_MODEL_DEPRECATION_MSG, + ) + + if not unsafe: + raise ValueError("The 'unsafe' parameter must be set to True to load a model.") + + if ":" not in aliased_path: + raise ValueError( + "aliased_path must be of the form 'name:alias' or 'name:version'." + ) + + # Returns a _SavedModel instance + if run := wandb_setup.singleton().most_recent_active_run: + artifact = run.use_artifact(aliased_path) + sm = artifact.get("index") + + if sm is None or not isinstance(sm, _SavedModel): + raise ValueError( + "Deserialization into model object failed: _SavedModel instance could not be initialized properly." + ) + + return sm + else: + raise ValueError( + "use_model can only be called inside a run. Please call wandb.init() before use_model(...)" + ) + + +_LINK_MODEL_DEPRECATION_MSG = "`link_model` is deprecated and will be removed in a future version. Please use `Run.link_artifact` instead." + + +@deprecated(_LINK_MODEL_DEPRECATION_MSG) +def link_model( + model: _SavedModel, + target_path: str, + aliases: str | list[str] | None = None, +) -> None: + """Link the given model to a portfolio. + + A portfolio is a promoted collection which contains (in this case) model artifacts. + Linking to a portfolio allows for useful model-centric workflows in the UI. + + Args: + model: `_SavedModel` - an instance of _SavedModel, most likely from the output + of `log_model` or `use_model`. + target_path: `str` - the target portfolio. The following forms are valid for the + string: {portfolio}, {project/portfolio},{entity}/{project}/{portfolio}. + aliases: `str, List[str]` - optional alias(es) that will only be applied on this + linked model inside the portfolio. The alias "latest" will always be applied + to the latest version of a model. + + Returns: + None + + Example: + sm = use_model("my-simple-model:latest") + link_model(sm, "my-portfolio") + + """ + wandb_deprecate( + field_name=Deprecated.beta__workflows__link_model, + warning_message=_LINK_MODEL_DEPRECATION_MSG, + ) + + aliases = wandb.util._resolve_aliases(aliases) + + if run := wandb_setup.singleton().most_recent_active_run: + # _artifact_source, if it exists, points to a Public Artifact. + # Its existence means that _SavedModel was deserialized from a logged artifact, most likely from `use_model`. + if model._artifact_source: + artifact = model._artifact_source.artifact + # If the _SavedModel has been added to a Local Artifact (most likely through `.add(WBValue)`), then + # model._artifact_target will point to that Local Artifact. + elif model._artifact_target and model._artifact_target.artifact._final: + artifact = model._artifact_target.artifact + else: + raise ValueError( + "Linking requires that the given _SavedModel belongs to an artifact" + ) + + run.link_artifact(artifact, target_path, aliases) + + else: + if model._artifact_source is not None: + model._artifact_source.artifact.link(target_path, aliases) + else: + raise ValueError( + "Linking requires that the given _SavedModel belongs to a logged artifact." + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/cli/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/cli/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ece3e3311568da103ab6d459e8fb95a7cd97a48 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/cli/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/cli/cli.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/cli/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..5f7477f17d4c921f703083b721a8ee9036d93b17 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/cli/cli.py @@ -0,0 +1,2838 @@ +import asyncio +import configparser +import datetime +import getpass +import json +import logging +import os +import shlex +import shutil +import subprocess +import sys +import tempfile +import textwrap +import time +import traceback +from functools import wraps +from typing import Any, Dict, Optional, Tuple + +import click +import yaml +from click.exceptions import ClickException + +import wandb +import wandb.env +import wandb.errors +import wandb.sdk.verify.verify as wandb_verify +from wandb import Config, Error, env, util, wandb_agent, wandb_sdk +from wandb.apis import InternalApi, PublicApi +from wandb.apis.public import RunQueue +from wandb.errors.links import url_registry +from wandb.sdk import wandb_setup +from wandb.sdk.artifacts._validators import is_artifact_registry_project +from wandb.sdk.artifacts.artifact_file_cache import get_artifact_file_cache +from wandb.sdk.internal.internal_api import Api as SDKInternalApi +from wandb.sdk.launch import utils as launch_utils +from wandb.sdk.launch._launch_add import _launch_add +from wandb.sdk.launch.errors import ExecutionError, LaunchError +from wandb.sdk.launch.sweeps import utils as sweep_utils +from wandb.sdk.launch.sweeps.scheduler import Scheduler +from wandb.sdk.lib import filesystem +from wandb.sync import SyncManager, get_run_from_path, get_runs + +from .beta import beta + +# Send cli logs to wandb/debug-cli..log by default and fallback to a temp dir. +_wandb_dir = wandb.old.core.wandb_dir(env.get_dir()) +if not os.path.exists(_wandb_dir): + _wandb_dir = tempfile.gettempdir() + +try: + _username = getpass.getuser() +except KeyError: + # getuser() could raise KeyError in restricted environments like + # chroot jails or docker containers. Return user id in these cases. + _username = str(os.getuid()) + +_wandb_log_path = os.path.join(_wandb_dir, f"debug-cli.{_username}.log") + +logging.basicConfig( + filename=_wandb_log_path, + level=logging.INFO, + format="%(asctime)s %(levelname)s %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", +) +logging.basicConfig(stream=sys.stdout, level=logging.INFO) +logger = logging.getLogger("wandb") + +_HAS_DOCKER = bool(shutil.which("docker")) +_HAS_NVIDIA_DOCKER = bool(shutil.which("nvidia-docker")) + +# Click Contexts +CONTEXT = {"default_map": {}} +RUN_CONTEXT = { + "default_map": {}, + "allow_extra_args": True, + "ignore_unknown_options": True, +} + + +def cli_unsupported(argument): + wandb.termerror(f"Unsupported argument `{argument}`") + sys.exit(1) + + +class ClickWandbException(ClickException): + def format_message(self): + orig_type = f"{self.orig_type.__module__}.{self.orig_type.__name__}" + if issubclass(self.orig_type, Error): + return click.style(str(self.message), fg="red") + else: + return ( + f"An Exception was raised, see {_wandb_log_path} for full" + " traceback.\n" + f"{orig_type}: {self.message}" + ) + + +def parse_service_config( + ctx: Optional[click.Context], + param: Optional[click.Parameter], + value: Optional[Tuple[str, ...]], +) -> Dict[str, str]: + """Parse service configurations in format serviceName=policy.""" + if not value: + return {} + + result = {} + for config in value: + if "=" not in config: + raise click.BadParameter( + f"Service must be in format 'serviceName=policy', got '{config}'" + ) + + service_name, policy = config.split("=", 1) + service_name = service_name.strip() + policy = policy.strip() + if not service_name: + raise click.BadParameter("Service name cannot be empty") + + # Simple validation for two policies + if policy not in ["always", "never"]: + raise click.BadParameter( + f"Policy must be 'always' or 'never', got '{policy}'" + ) + + result[service_name] = policy + + return result + + +def display_error(func): + """Function decorator for catching common errors and re-raising as wandb.Error.""" + + @wraps(func) + def wrapper(*args, **kwargs): + try: + return func(*args, **kwargs) + except wandb.Error as e: + exc_type, exc_value, exc_traceback = sys.exc_info() + lines = traceback.format_exception(exc_type, exc_value, exc_traceback) + logger.exception("".join(lines)) + wandb.termerror(f"Find detailed error logs at: {_wandb_log_path}") + click_exc = ClickWandbException(e) + click_exc.orig_type = exc_type + raise click_exc.with_traceback(sys.exc_info()[2]) + + return wrapper + + +_api = None # caching api instance allows patching from unit tests + + +def _get_cling_api(reset=None): + """Get a reference to the internal api with cling settings.""" + global _api + if reset: + _api = None + wandb.teardown() + if _api is None: + # TODO(jhr): make a settings object that is better for non runs. + # only override the necessary setting + wandb_setup.singleton().settings.x_cli_only_mode = True + _api = InternalApi() + return _api + + +def prompt_for_project(ctx, entity): + """Ask the user for a project, creating one if necessary.""" + result = ctx.invoke(projects, entity=entity, display=False) + api = _get_cling_api() + try: + if len(result) == 0: + project = click.prompt("Enter a name for your first project") + # description = editor() + project = api.upsert_project(project, entity=entity)["name"] + else: + project_names = [project["name"] for project in result] + ["Create New"] + wandb.termlog("Which project should we use?") + result = util.prompt_choices(project_names) + if result: + project = result + else: + project = "Create New" + # TODO: check with the server if the project exists + if project == "Create New": + project = click.prompt( + "Enter a name for your new project", value_proc=api.format_project + ) + # description = editor() + project = api.upsert_project(project, entity=entity)["name"] + + except wandb.errors.CommError as e: + raise ClickException(str(e)) + + return project + + +class RunGroup(click.Group): + @display_error + def get_command(self, ctx, cmd_name): + # TODO: check if cmd_name is a file in the current dir and not require `run`? + rv = click.Group.get_command(self, ctx, cmd_name) + if rv is not None: + return rv + return None + + +@click.command(cls=RunGroup, invoke_without_command=True) +@click.version_option(version=wandb.__version__) +@click.pass_context +def cli(ctx): + if ctx.invoked_subcommand is None: + click.echo(ctx.get_help()) + + +@cli.command(context_settings=CONTEXT, help="List projects", hidden=True) +@click.option( + "--entity", + "-e", + default=None, + envvar=env.ENTITY, + help="The entity to scope the listing to.", +) +@display_error +def projects(entity, display=True): + api = _get_cling_api() + projects = api.list_projects(entity=entity) + if len(projects) == 0: + message = f"No projects found for {entity}" + else: + message = f'Latest projects for "{entity}"' + if display: + click.echo(click.style(message, bold=True)) + for project in projects: + click.echo( + "".join( + ( + click.style(project["name"], fg="blue", bold=True), + " - ", + str(project["description"] or "").split("\n")[0], + ) + ) + ) + return projects + + +@cli.command(context_settings=CONTEXT, help="Login to Weights & Biases") +@click.argument("key", nargs=-1) +@click.option("--cloud", is_flag=True, help="Login to the cloud instead of local") +@click.option( + "--host", "--base-url", default=None, help="Login to a specific instance of W&B" +) +@click.option( + "--relogin", default=None, is_flag=True, help="Force relogin if already logged in." +) +@click.option("--anonymously", default=False, is_flag=True, help="Log in anonymously") +@click.option( + "--verify/--no-verify", + default=False, + is_flag=True, + help="Verify login credentials", +) +@display_error +def login(key, host, cloud, relogin, anonymously, verify, no_offline=False): + # TODO: handle no_offline + anon_mode = "must" if anonymously else "never" + + wandb_sdk.wandb_login._handle_host_wandb_setting(host, cloud) + # A change in click or the test harness means key can be none... + key = key[0] if key is not None and len(key) > 0 else None + relogin = True if key or relogin else False + + global_settings = wandb_setup.singleton().settings + global_settings.x_cli_only_mode = True + global_settings.x_disable_viewer = relogin and not verify + + wandb.login( + anonymous=anon_mode, + force=True, + host=host, + key=key, + relogin=relogin, + verify=verify, + referrer="models", + ) + + +@cli.command( + context_settings=CONTEXT, help="Configure a directory with Weights & Biases" +) +@click.option("--project", "-p", help="The project to use.") +@click.option("--entity", "-e", help="The entity to scope the project to.") +# TODO(jhr): Enable these with settings rework +# @click.option("--setting", "-s", help="enable an arbitrary setting.", multiple=True) +# @click.option('--show', is_flag=True, help="Show settings") +@click.option("--reset", is_flag=True, help="Reset settings") +@click.option( + "--mode", + "-m", + help=' Can be "online", "offline" or "disabled". Defaults to online.', +) +@click.pass_context +@display_error +def init(ctx, project, entity, reset, mode): + from wandb.old.core import __stage_dir__, _set_stage_dir, wandb_dir + + if __stage_dir__ is None: + _set_stage_dir("wandb") + + # non-interactive init + if reset or project or entity or mode: + api = InternalApi() + if reset: + api.clear_setting("entity", persist=True) + api.clear_setting("project", persist=True) + api.clear_setting("mode", persist=True) + # TODO(jhr): clear more settings? + if entity: + api.set_setting("entity", entity, persist=True) + if project: + api.set_setting("project", project, persist=True) + if mode: + api.set_setting("mode", mode, persist=True) + return + + if os.path.isdir(wandb_dir()) and os.path.exists( + os.path.join(wandb_dir(), "settings") + ): + click.confirm( + click.style( + "This directory has been configured previously, should we re-configure it?", + bold=True, + ), + abort=True, + ) + else: + click.echo( + click.style("Let's setup this directory for W&B!", fg="green", bold=True) + ) + api = _get_cling_api() + if api.api_key is None: + ctx.invoke(login) + api = _get_cling_api(reset=True) + + viewer = api.viewer() + + # Viewer can be `None` in case your API information became invalid, or + # in testing if you switch hosts. + if not viewer: + click.echo( + click.style( + "Your login information seems to be invalid: can you log in again please?", + fg="red", + bold=True, + ) + ) + ctx.invoke(login) + api = _get_cling_api(reset=True) + + # This shouldn't happen. + viewer = api.viewer() + if not viewer: + click.echo( + click.style( + "We're sorry, there was a problem logging you in. " + "Please send us a note at support@wandb.com and tell us how this happened.", + fg="red", + bold=True, + ) + ) + sys.exit(1) + + # At this point we should be logged in successfully. + if len(viewer["teams"]["edges"]) > 1: + team_names = [e["node"]["name"] for e in viewer["teams"]["edges"]] + [ + "Manual entry" + ] + wandb.termlog( + "Which team should we use?", + ) + result = util.prompt_choices(team_names) + # result can be empty on click + if result: + entity = result + else: + entity = "Manual Entry" + if entity == "Manual Entry": + entity = click.prompt("Enter the name of the team you want to use") + else: + entity = viewer.get("entity") or click.prompt( + "What username or team should we use?" + ) + + # TODO: this error handling sucks and the output isn't pretty + try: + project = prompt_for_project(ctx, entity) + except ClickWandbException: + raise ClickException(f"Could not find team: {entity}") + + api.set_setting("entity", entity, persist=True) + api.set_setting("project", project, persist=True) + api.set_setting("base_url", api.settings().get("base_url"), persist=True) + + filesystem.mkdir_exists_ok(wandb_dir()) + with open(os.path.join(wandb_dir(), ".gitignore"), "w") as file: + file.write("*\n!settings") + + click.echo( + click.style("This directory is configured! Next, track a run:\n", fg="green") + + textwrap.dedent( + """\ + * In your training script: + {code1} + {code2} + * then `{run}`. + """ + ).format( + code1=click.style("import wandb", bold=True), + code2=click.style(f'wandb.init(project="{project}")', bold=True), + run=click.style("python ", bold=True), + ) + ) + + +@cli.command( + context_settings=CONTEXT, help="Upload an offline training directory to W&B" +) +@click.pass_context +@click.argument("path", nargs=-1, type=click.Path(exists=True)) +@click.option("--view", is_flag=True, default=False, help="View runs", hidden=True) +@click.option("--verbose", is_flag=True, default=False, help="Verbose", hidden=True) +@click.option("--id", "run_id", help="The run you want to upload to.") +@click.option("--project", "-p", help="The project you want to upload to.") +@click.option("--entity", "-e", help="The entity to scope to.") +@click.option( + "--job_type", + "job_type", + help="Specifies the type of run for grouping related runs together.", +) +@click.option( + "--sync-tensorboard/--no-sync-tensorboard", + is_flag=True, + default=None, + help="Stream tfevent files to wandb.", +) +@click.option("--include-globs", help="Comma separated list of globs to include.") +@click.option("--exclude-globs", help="Comma separated list of globs to exclude.") +@click.option( + "--include-online/--no-include-online", + is_flag=True, + default=None, + help="Include online runs", +) +@click.option( + "--include-offline/--no-include-offline", + is_flag=True, + default=None, + help="Include offline runs", +) +@click.option( + "--include-synced/--no-include-synced", + is_flag=True, + default=None, + help="Include synced runs", +) +@click.option( + "--mark-synced/--no-mark-synced", + is_flag=True, + default=True, + help="Mark runs as synced", +) +@click.option("--sync-all", is_flag=True, default=False, help="Sync all runs") +@click.option("--clean", is_flag=True, default=False, help="Delete synced runs") +@click.option( + "--clean-old-hours", + default=24, + help="Delete runs created before this many hours. To be used alongside --clean flag.", + type=int, +) +@click.option( + "--clean-force", + is_flag=True, + default=False, + help="Clean without confirmation prompt.", +) +@click.option("--ignore", hidden=True) +@click.option("--show", default=5, help="Number of runs to show") +@click.option("--append", is_flag=True, default=False, help="Append run") +@click.option("--skip-console", is_flag=True, default=False, help="Skip console logs") +@click.option( + "--replace-tags", + help="Replace tags in the format 'old_tag1=new_tag1,old_tag2=new_tag2'", +) +@display_error +def sync( + ctx, + path=None, + view=None, + verbose=None, + run_id=None, + project=None, + entity=None, + job_type=None, # trace this back to SyncManager + sync_tensorboard=None, + include_globs=None, + exclude_globs=None, + include_online=None, + include_offline=None, + include_synced=None, + mark_synced=None, + sync_all=None, + ignore=None, + show=None, + clean=None, + clean_old_hours=24, + clean_force=None, + append=None, + skip_console=None, + replace_tags=None, +): + api = _get_cling_api() + if not api.is_authenticated: + wandb.termlog("Login to W&B to sync offline runs") + ctx.invoke(login, no_offline=True) + api = _get_cling_api(reset=True) + + if ignore: + exclude_globs = ignore + if include_globs: + include_globs = include_globs.split(",") + if exclude_globs: + exclude_globs = exclude_globs.split(",") + + replace_tags_dict = _parse_sync_replace_tags(replace_tags) + if replace_tags and replace_tags_dict is None: + return # Error already printed by helper function + + def _summary(): + all_items = get_runs( + include_online=True, + include_offline=True, + include_synced=True, + include_unsynced=True, + ) + sync_items = get_runs( + include_online=include_online if include_online is not None else True, + include_offline=include_offline if include_offline is not None else True, + include_synced=include_synced if include_synced is not None else False, + include_unsynced=True, + exclude_globs=exclude_globs, + include_globs=include_globs, + ) + synced = [] + unsynced = [] + for item in all_items: + (synced if item.synced else unsynced).append(item) + if sync_items: + wandb.termlog(f"Number of runs to be synced: {len(sync_items)}") + if show and show < len(sync_items): + wandb.termlog(f"Showing {show} runs to be synced:") + for item in sync_items[: (show or len(sync_items))]: + wandb.termlog(f" {item}") + else: + wandb.termlog("No runs to be synced.") + if synced: + clean_cmd = click.style("wandb sync --clean", fg="yellow") + wandb.termlog( + f"NOTE: use {clean_cmd} to delete {len(synced)} synced runs from local directory." + ) + if unsynced: + sync_cmd = click.style("wandb sync --sync-all", fg="yellow") + wandb.termlog( + f"NOTE: use {sync_cmd} to sync {len(unsynced)} unsynced runs from local directory." + ) + + def _sync_path(_path, _sync_tensorboard): + if run_id and len(_path) > 1: + wandb.termerror("id can only be set for a single run.") + sys.exit(1) + sm = SyncManager( + project=project, + entity=entity, + run_id=run_id, + job_type=job_type, + mark_synced=mark_synced, + app_url=api.app_url, + view=view, + verbose=verbose, + sync_tensorboard=_sync_tensorboard, + log_path=_wandb_log_path, + append=append, + skip_console=skip_console, + replace_tags=replace_tags_dict, + ) + for p in _path: + sm.add(p) + sm.start() + while not sm.is_done(): + _ = sm.poll() + + def _sync_all(): + sync_items = get_runs( + include_online=include_online if include_online is not None else True, + include_offline=include_offline if include_offline is not None else True, + include_synced=include_synced if include_synced is not None else False, + include_unsynced=True, + exclude_globs=exclude_globs, + include_globs=include_globs, + ) + if not sync_items: + wandb.termerror("Nothing to sync.") + else: + # When syncing run directories, default to not syncing tensorboard + sync_tb = sync_tensorboard if sync_tensorboard is not None else False + _sync_path(sync_items, sync_tb) + + def _clean(): + if path: + runs = list(map(get_run_from_path, path)) + if not clean_force: + click.confirm( + click.style( + f"Are you sure you want to remove {len(runs)} runs?", + bold=True, + ), + abort=True, + ) + for run in runs: + shutil.rmtree(run.path) + click.echo(click.style("Success!", fg="green")) + return + runs = get_runs( + include_online=include_online if include_online is not None else True, + include_offline=include_offline if include_offline is not None else True, + include_synced=include_synced if include_synced is not None else True, + include_unsynced=False, + exclude_globs=exclude_globs, + include_globs=include_globs, + ) + since = datetime.datetime.now() - datetime.timedelta(hours=clean_old_hours) + old_runs = [run for run in runs if run.datetime < since] + old_runs.sort(key=lambda _run: _run.datetime) + if old_runs: + click.echo( + f"Found {len(runs)} runs, {len(old_runs)} are older than {clean_old_hours} hours" + ) + for run in old_runs: + click.echo(run.path) + if not clean_force: + click.confirm( + click.style( + f"Are you sure you want to remove {len(old_runs)} runs?", + bold=True, + ), + abort=True, + ) + for run in old_runs: + shutil.rmtree(run.path) + click.echo(click.style("Success!", fg="green")) + else: + click.echo( + click.style( + f"No runs older than {clean_old_hours} hours found", fg="red" + ) + ) + + if sync_all: + _sync_all() + elif clean: + _clean() + elif path: + # When syncing a specific path, default to syncing tensorboard + sync_tb = sync_tensorboard if sync_tensorboard is not None else True + _sync_path(path, sync_tb) + else: + _summary() + + +def _parse_sync_replace_tags(replace_tags: str) -> Optional[Dict[str, str]]: + """Parse replace_tags string into a dictionary. + + Args: + replace_tags: String in format 'old_tag1=new_tag1,old_tag2=new_tag2' + + Returns: + Mapping of old tags to new tags, or None if format is invalid + """ + if not replace_tags: + return {} + + replace_tags_dict = {} + for pair in replace_tags.split(","): + if "=" not in pair: + wandb.termerror( + f"Invalid replace-tags format: {pair}. Use 'old_tag=new_tag' format." + ) + return None + old_tag, new_tag = pair.split("=", 1) + replace_tags_dict[old_tag.strip()] = new_tag.strip() + + return replace_tags_dict + + +@cli.command( + context_settings=CONTEXT, + help="Initialize a hyperparameter sweep. Search for hyperparameters that optimizes a cost function of a machine learning model by testing various combinations.", +) +@click.option( + "--project", + "-p", + default=None, + help="""The name of the project where W&B runs created from the sweep are sent to. If the project is not specified, the run is sent to a project labeled Uncategorized.""", +) +@click.option( + "--entity", + "-e", + default=None, + help="""The username or team name where you want to send W&B runs created by the sweep to. Ensure that the entity you specify already exists. If you don't specify an entity, the run will be sent to your default entity, which is usually your username.""", +) +@click.option("--controller", is_flag=True, default=False, help="Run local controller") +@click.option("--verbose", is_flag=True, default=False, help="Display verbose output") +@click.option( + "--name", + default=None, + help="The name of the sweep. The sweep ID is used if no name is specified.", +) +@click.option("--program", default=None, help="Set sweep program") +@click.option("--settings", default=None, help="Set sweep settings", hidden=True) +@click.option("--update", default=None, help="Update pending sweep") +@click.option( + "--stop", + is_flag=True, + default=False, + help="Finish a sweep to stop running new runs and let currently running runs finish.", +) +@click.option( + "--cancel", + is_flag=True, + default=False, + help="Cancel a sweep to kill all running runs and stop running new runs.", +) +@click.option( + "--pause", + is_flag=True, + default=False, + help="Pause a sweep to temporarily stop running new runs.", +) +@click.option( + "--resume", + is_flag=True, + default=False, + help="Resume a sweep to continue running new runs.", +) +@click.option( + "--prior_run", + "-R", + "prior_runs", + multiple=True, + default=None, + help="ID of an existing run to add to this sweep", +) +@click.argument("config_yaml_or_sweep_id") +@click.pass_context +@display_error +def sweep( + ctx, + project, + entity, + controller, + verbose, + name, + program, + settings, + update, + stop, + cancel, + pause, + resume, + prior_runs, + config_yaml_or_sweep_id, +): + state_args = "stop", "cancel", "pause", "resume" + lcls = locals() + is_state_change_command = sum(lcls[k] for k in state_args) + if is_state_change_command > 1: + raise Exception("Only one state flag (stop/cancel/pause/resume) is allowed.") + elif is_state_change_command == 1: + sweep_id = config_yaml_or_sweep_id + api = _get_cling_api() + if not api.is_authenticated: + wandb.termlog("Login to W&B to use the sweep feature") + ctx.invoke(login, no_offline=True) + api = _get_cling_api(reset=True) + parts = dict(entity=entity, project=project, name=sweep_id) + err = sweep_utils.parse_sweep_id(parts) + if err: + wandb.termerror(err) + return + entity = parts.get("entity") or entity + project = parts.get("project") or project + sweep_id = parts.get("name") or sweep_id + state = [s for s in state_args if lcls[s]][0] + ings = { + "stop": "Stopping", + "cancel": "Cancelling", + "pause": "Pausing", + "resume": "Resuming", + } + wandb.termlog(f"{ings[state]} sweep {entity}/{project}/{sweep_id}") + getattr(api, f"{state}_sweep")(sweep_id, entity=entity, project=project) + wandb.termlog("Done.") + return + else: + config_yaml = config_yaml_or_sweep_id + + def _parse_settings(settings): + """Parse settings from json or comma separated assignments.""" + ret = {} + # TODO(jhr): merge with magic:_parse_magic + if settings.find("=") > 0: + for item in settings.split(","): + kv = item.split("=") + if len(kv) != 2: + wandb.termwarn( + "Unable to parse sweep settings key value pair", repeat=False + ) + ret.update(dict([kv])) + return ret + wandb.termwarn("Unable to parse settings parameter", repeat=False) + return ret + + api = _get_cling_api() + if not api.is_authenticated: + wandb.termlog("Login to W&B to use the sweep feature") + ctx.invoke(login, no_offline=True) + api = _get_cling_api(reset=True) + + sweep_obj_id = None + if update: + parts = dict(entity=entity, project=project, name=update) + err = sweep_utils.parse_sweep_id(parts) + if err: + wandb.termerror(err) + return + entity = parts.get("entity") or entity + project = parts.get("project") or project + sweep_id = parts.get("name") or update + + has_project = (project or api.settings("project")) is not None + has_entity = (entity or api.settings("entity")) is not None + + termerror_msg = ( + "Sweep lookup requires a valid %s, and none was specified. \n" + "Either set a default %s in wandb/settings, or, if invoking \n`wandb sweep` " + "from the command line, specify the full sweep path via: \n\n" + " wandb sweep {username}/{projectname}/{sweepid}\n\n" + ) + + if not has_entity: + wandb.termerror(termerror_msg % (("entity",) * 2)) + return + + if not has_project: + wandb.termerror(termerror_msg % (("project",) * 2)) + return + + found = api.sweep(sweep_id, "{}", entity=entity, project=project) + if not found: + wandb.termerror(f"Could not find sweep {entity}/{project}/{sweep_id}") + return + sweep_obj_id = found["id"] + + action = "Updating" if sweep_obj_id else "Creating" + wandb.termlog(f"{action} sweep from: {config_yaml}") + config = sweep_utils.load_sweep_config(config_yaml) + + # Set or override parameters + if name: + config["name"] = name + if program: + config["program"] = program + if settings: + settings = _parse_settings(settings) + if settings: + config.setdefault("settings", {}) + config["settings"].update(settings) + if controller: + config.setdefault("controller", {}) + config["controller"]["type"] = "local" + + is_local = config.get("controller", {}).get("type") == "local" + if is_local: + from wandb import controller as wandb_controller + + tuner = wandb_controller() + err = tuner._validate(config) + if err: + wandb.termerror(f"Error in sweep file: {err}") + return + + env = os.environ + entity = ( + entity + or env.get("WANDB_ENTITY") + or config.get("entity") + or api.settings("entity") + ) + project = ( + project + or env.get("WANDB_PROJECT") + or config.get("project") + or api.settings("project") + or util.auto_project_name(config.get("program")) + ) + + sweep_id, warnings = api.upsert_sweep( + config, + project=project, + entity=entity, + obj_id=sweep_obj_id, + prior_runs=prior_runs, + ) + sweep_utils.handle_sweep_config_violations(warnings) + + # Log nicely formatted sweep information + styled_id = click.style(sweep_id, fg="yellow") + wandb.termlog(f"{action} sweep with ID: {styled_id}") + + sweep_url = wandb_sdk.wandb_sweep._get_sweep_url(api, sweep_id) + if sweep_url: + styled_url = click.style(sweep_url, underline=True, fg="blue") + wandb.termlog(f"View sweep at: {styled_url}") + + # re-probe entity and project if it was auto-detected by upsert_sweep + entity = entity or env.get("WANDB_ENTITY") + project = project or env.get("WANDB_PROJECT") + + if entity and project: + sweep_path = f"{entity}/{project}/{sweep_id}" + elif project: + sweep_path = f"{project}/{sweep_id}" + else: + sweep_path = sweep_id + + if sweep_path.find(" ") >= 0: + sweep_path = f"{sweep_path!r}" + + styled_path = click.style(f"wandb agent {sweep_path}", fg="yellow") + wandb.termlog(f"Run sweep agent with: {styled_path}") + if controller: + wandb.termlog("Starting wandb controller...") + from wandb import controller as wandb_controller + + tuner = wandb_controller(sweep_id) + tuner.run(verbose=verbose) + + +@cli.command( + context_settings=CONTEXT, + no_args_is_help=True, + help="Run a W&B launch sweep (Experimental).", +) +@click.option( + "--queue", + "-q", + default=None, + help="The name of a queue to push the sweep to", +) +@click.option( + "--project", + "-p", + default=None, + help="Name of the project which the agent will watch. " + "If passed in, will override the project value passed in using a config file", +) +@click.option( + "--entity", + "-e", + default=None, + help="The entity to use. Defaults to current logged-in user", +) +@click.option( + "--resume_id", + "-r", + default=None, + help="Resume a launch sweep by passing an 8-char sweep id. Queue required", +) +@click.option( + "--prior_run", + "-R", + "prior_runs", + multiple=True, + default=None, + help="ID of an existing run to add to this sweep", +) +@click.argument("config", required=False, type=click.Path(exists=True)) +@click.pass_context +@display_error +def launch_sweep( + ctx, + project, + entity, + queue, + config, + resume_id, + prior_runs, +): + api = _get_cling_api() + env = os.environ + if not api.is_authenticated: + wandb.termlog("Login to W&B to use the sweep feature") + ctx.invoke(login, no_offline=True) + api = _get_cling_api(reset=True) + + entity = entity or env.get("WANDB_ENTITY") or api.settings("entity") + if entity is None: + wandb.termerror("Must specify entity when using launch") + return + + project = project or env.get("WANDB_PROJECT") or api.settings("project") + if project is None: + wandb.termerror("A project must be configured when using launch") + return + + # get personal username, not team name or service account, default to entity + author = api.viewer().get("username") or entity + + # if not sweep_config XOR resume_id + if not (config or resume_id): + wandb.termerror("'config' and/or 'resume_id' required") + return + + parsed_user_config = sweep_utils.load_launch_sweep_config(config) + # Rip special keys out of config, store in scheduler run_config + launch_args: Dict[str, Any] = parsed_user_config.pop("launch", {}) + scheduler_args: Dict[str, Any] = parsed_user_config.pop("scheduler", {}) + settings: Dict[str, Any] = scheduler_args.pop("settings", {}) + + scheduler_job: Optional[str] = scheduler_args.get("job") + if scheduler_job: + wandb.termwarn( + "Using a scheduler job for launch sweeps is *experimental* and may change without warning" + ) + queue: Optional[str] = queue or launch_args.get("queue") + + sweep_config, sweep_obj_id = None, None + if not resume_id: + sweep_config = parsed_user_config + + # check method + method = sweep_config.get("method") + if scheduler_job and not method: + sweep_config["method"] = "custom" + elif scheduler_job and method != "custom": + # TODO(gst): Check if using Anaconda2 + wandb.termwarn( + "Use 'method': 'custom' in the sweep config when using scheduler jobs, " + "or omit it entirely. For jobs using the wandb optimization engine (WandbScheduler), " + "set the method in the sweep config under scheduler.settings.method " + ) + settings["method"] = method + + if settings.get("method"): + # assume WandbScheduler, and user is using this right + sweep_config["method"] = settings["method"] + + else: # Resuming an existing sweep + found = api.sweep(resume_id, "{}", entity=entity, project=project) + if not found: + wandb.termerror(f"Could not find sweep {entity}/{project}/{resume_id}") + return + + if found.get("state") == "RUNNING": + wandb.termerror( + f"Cannot resume sweep {entity}/{project}/{resume_id}, it is already running" + ) + return + + sweep_obj_id = found["id"] + sweep_config = yaml.safe_load(found["config"]) + wandb.termlog(f"Resuming from existing sweep {entity}/{project}/{resume_id}") + if len(parsed_user_config.keys()) > 0: + wandb.termwarn( + "Sweep parameters loaded from resumed sweep, ignoring provided config" + ) + + prev_scheduler = json.loads(found.get("scheduler") or "{}") + run_spec = json.loads(prev_scheduler.get("run_spec", "{}")) + if ( + scheduler_job + and run_spec.get("job") + and run_spec.get("job") != scheduler_job + ): + wandb.termerror( + f"Resuming a launch sweep with a different scheduler job is not supported. Job loaded from sweep: {run_spec.get('job')}, job in config: {scheduler_job}" + ) + return + + prev_scheduler_args, prev_settings = sweep_utils.get_previous_args(run_spec) + # Passed in scheduler_args and settings override previous + scheduler_args.update(prev_scheduler_args) + settings.update(prev_settings) + if not queue: + wandb.termerror( + "Launch-sweeps require setting a 'queue', use --queue option or a 'queue' key in the 'launch' section in the config" + ) + return + + entrypoint = Scheduler.ENTRYPOINT if not scheduler_job else None + args = sweep_utils.construct_scheduler_args( + return_job=scheduler_job is not None, + sweep_config=sweep_config, + queue=queue, + project=project, + author=author, + ) + if not args: + return + + # validate training job existence + if not sweep_utils.check_job_exists(PublicApi(), sweep_config.get("job")): + return False + + # validate scheduler job existence, if present + if not sweep_utils.check_job_exists(PublicApi(), scheduler_job): + return False + + # Set run overrides for the Scheduler + overrides = {"run_config": {}} + if launch_args: + overrides["run_config"]["launch"] = launch_args + if scheduler_args: + overrides["run_config"]["scheduler"] = scheduler_args + if settings: + overrides["run_config"]["settings"] = settings + + if scheduler_job: + overrides["run_config"]["sweep_args"] = args + else: + overrides["args"] = args + + # configure scheduler job resource + resource = scheduler_args.get("resource") + if resource: + if resource == "local-process" and scheduler_job: + wandb.termerror( + "Scheduler jobs cannot be run with the 'local-process' resource" + ) + return + if resource == "local-process" and scheduler_args.get("docker_image"): + wandb.termerror( + "Scheduler jobs cannot be run with the 'local-process' resource and a docker image" + ) + return + else: # no resource set, default local-process if not scheduler job, else container + resource = "local-process" if not scheduler_job else "local-container" + + # Launch job spec for the Scheduler + launch_scheduler_spec = launch_utils.construct_launch_spec( + uri=Scheduler.PLACEHOLDER_URI, + api=api, + name="Scheduler.WANDB_SWEEP_ID", + project=project, + entity=entity, + docker_image=scheduler_args.get("docker_image"), + resource=resource, + entry_point=entrypoint, + resource_args=scheduler_args.get("resource_args", {}), + repository=launch_args.get("registry", {}).get("url", None), + job=scheduler_job, + version=None, + launch_config={"overrides": overrides}, + run_id="WANDB_SWEEP_ID", # scheduler inits run with sweep_id=run_id + author=None, # author gets passed into scheduler override args + ) + launch_scheduler_with_queue = json.dumps( + { + "queue": queue, + "run_queue_project": launch_utils.LAUNCH_DEFAULT_PROJECT, + "run_spec": json.dumps(launch_scheduler_spec), + } + ) + + sweep_id, warnings = api.upsert_sweep( + sweep_config, + project=project, + entity=entity, + obj_id=sweep_obj_id, # if resuming + launch_scheduler=launch_scheduler_with_queue, + state="PENDING", + prior_runs=prior_runs, + template_variable_values=scheduler_args.get("template_variables", None), + ) + sweep_utils.handle_sweep_config_violations(warnings) + # Log nicely formatted sweep information + styled_id = click.style(sweep_id, fg="yellow") + wandb.termlog(f"{'Resumed' if resume_id else 'Created'} sweep with ID: {styled_id}") + sweep_url = wandb_sdk.wandb_sweep._get_sweep_url(api, sweep_id) + if sweep_url: + styled_url = click.style(sweep_url, underline=True, fg="blue") + wandb.termlog(f"View sweep at: {styled_url}") + wandb.termlog(f"Scheduler added to launch queue ({queue})") + + +@cli.command(help=f"Launch or queue a W&B Job. See {url_registry.url('wandb-launch')}") +@click.option( + "--uri", + "-u", + metavar="(str)", + default=None, + help="Local path or git repo uri to launch. If provided this command will " + "create a job from the specified uri.", +) +@click.option( + "--job", + "-j", + metavar="(str)", + default=None, + help="Name of the job to launch. If passed in, launch does not require a uri.", +) +@click.option( + "--entry-point", + "-E", + metavar="NAME", + default=None, + help="""Entry point within project. [default: main]. If the entry point is not found, + attempts to run the project file with the specified name as a script, + using 'python' to run .py files and the default shell (specified by + environment variable $SHELL) to run .sh files. If passed in, will override the entrypoint value passed in using a config file.""", +) +@click.option( + "--git-version", + "-g", + metavar="GIT-VERSION", + hidden=True, + help="Version of the project to run, as a Git commit reference for Git projects.", +) +@click.option( + "--build-context", + metavar="(str)", + help="Path to the build context within the source code. Defaults to the " + "root of the source code. Compatible only with -u.", +) +@click.option( + "--job-name", + "-J", + metavar="(str)", + default=None, + hidden=True, + help="Name for the job created if the -u,--uri flag is passed in.", +) +@click.option( + "--name", + envvar="WANDB_NAME", + help="""Name of the run under which to launch the run. If not + specified, a random run name will be used to launch run. If passed in, will override the name passed in using a config file.""", +) +@click.option( + "--entity", + "-e", + metavar="(str)", + default=None, + help="""Name of the target entity which the new run will be sent to. Defaults to using the entity set by local wandb/settings folder. + If passed in, will override the entity value passed in using a config file.""", +) +@click.option( + "--project", + "-p", + metavar="(str)", + default=None, + help="""Name of the target project which the new run will be sent to. Defaults to using the project name given by the source uri + or for github runs, the git repo name. If passed in, will override the project value passed in using a config file.""", +) +@click.option( + "--resource", + "-r", + metavar="BACKEND", + default=None, + help="""Execution resource to use for run. Supported values: 'local-process', 'local-container', 'kubernetes', 'sagemaker', 'gcp-vertex'. + This is now a required parameter if pushing to a queue with no resource configuration. + If passed in, will override the resource value passed in using a config file.""", +) +@click.option( + "--docker-image", + "-d", + default=None, + metavar="DOCKER IMAGE", + help="""Specific docker image you'd like to use. In the form name:tag. + If passed in, will override the docker image value passed in using a config file.""", +) +@click.option( + "--base-image", + "-B", + default=None, + metavar="BASE IMAGE", + help="""Docker image to run job code in. Incompatible with --docker-image.""", +) +@click.option( + "--config", + "-c", + metavar="FILE", + help="""Path to JSON file (must end in '.json') or JSON string which will be passed + as a launch config. Dictation how the launched run will be configured.""", +) +@click.option( + "--set-var", + "-v", + "cli_template_vars", + default=None, + multiple=True, + help="""Set template variable values for queues with allow listing enabled, + as key-value pairs e.g. `--set-var key1=value1 --set-var key2=value2`""", +) +@click.option( + "--queue", + "-q", + is_flag=False, + flag_value="default", + default=None, + help="""Name of run queue to push to. If none, launches single run directly. If supplied without + an argument (`--queue`), defaults to queue 'default'. Else, if name supplied, specified run queue must exist under the + project and entity supplied.""", +) +@click.option( + "--async", + "run_async", + is_flag=True, + help="""Flag to run the job asynchronously. Defaults to false, i.e. unless --async is set, wandb launch will wait for + the job to finish. This option is incompatible with --queue; asynchronous options when running with an agent should be + set on wandb launch-agent.""", +) +@click.option( + "--resource-args", + "-R", + metavar="FILE", + help="""Path to JSON file (must end in '.json') or JSON string which will be passed + as resource args to the compute resource. The exact content which should be + provided is different for each execution backend. See documentation for layout of this file.""", +) +@click.option( + "--build", + "-b", + is_flag=True, + hidden=True, + help="Flag to build an associated job and push to queue as an image job.", +) +@click.option( + "--repository", + "-rg", + is_flag=False, + default=None, + hidden=True, + help="Name of a remote repository. Will be used to push a built image to.", +) +# TODO: this is only included for back compat. But we should remove this in the future +@click.option( + "--project-queue", + "-pq", + default=None, + hidden=True, + help="Name of the project containing the queue to push to. If none, defaults to entity level queues.", +) +@click.option( + "--dockerfile", + "-D", + default=None, + help="Path to the Dockerfile used to build the job, relative to the job's root", +) +@click.option( + "--priority", + "-P", + default=None, + type=click.Choice(["critical", "high", "medium", "low"]), + help="""When --queue is passed, set the priority of the job. Launch jobs with higher priority + are served first. The order, from highest to lowest priority, is: critical, high, medium, low""", +) +@display_error +def launch( + uri, + job, + entry_point, + git_version, + build_context, + name, + resource, + entity, + project, + docker_image, + base_image, + config, + cli_template_vars, + queue, + run_async, + resource_args, + build, + repository, + project_queue, + dockerfile, + priority, + job_name, +): + """Start a W&B run from the given URI. + + The URI can bea wandb URI, a GitHub repo uri, or a local path). In the case of a + wandb URI the arguments used in the original run will be used by default. These + arguments can be overridden using the args option, or specifying those arguments in + the config's 'overrides' key, 'args' field as a list of strings. + + Running `wandb launch [URI]` will launch the run directly. To add the run to a + queue, run `wandb launch [URI] --queue [optional queuename]`. + """ + logger.info( + f"=== Launch called with kwargs {locals()} CLI Version: {wandb.__version__}===" + ) + from wandb.sdk.launch._launch import _launch + from wandb.sdk.launch.create_job import _create_job + from wandb.sdk.launch.utils import _is_git_uri + + api = _get_cling_api() + wandb._sentry.configure_scope(process_context="launch_cli") + + if run_async and queue is not None: + raise LaunchError( + "Cannot use both --async and --queue with wandb launch, see help for details." + ) + + if queue and docker_image and not project: + raise LaunchError( + "Cannot use --queue and --docker together without a project. Please specify a project with --project or -p." + ) + + if priority is not None and queue is None: + raise LaunchError("--priority flag requires --queue to be set") + + if resource_args is not None: + resource_args = util.load_json_yaml_dict(resource_args) + if resource_args is None: + raise LaunchError("Invalid format for resource-args") + else: + resource_args = {} + + if entry_point is not None: + entry_point = shlex.split(entry_point) + + if config is not None: + config = util.load_json_yaml_dict(config) + if config is None: + raise LaunchError("Invalid format for config") + else: + config = {} + + resource = resource or config.get("resource") + + if build and queue is None: + raise LaunchError("Build flag requires a queue to be set") + + try: + launch_utils.check_logged_in(api) + except Exception: + wandb.termerror(f"Error running job: {traceback.format_exc()}") + + run_id = config.get("run_id") + + # If URI was provided, we need to create a job from it. + if uri: + if entry_point is None: + raise LaunchError( + "Cannot provide a uri without an entry point. Please provide an " + "entry point with --entry-point or -E." + ) + if job is not None: + raise LaunchError("Cannot provide both a uri and a job name.") + job_type = ( + "git" if _is_git_uri(uri) else "code" + ) # TODO: Add support for local URIs with git. + if entity is None: + entity = launch_utils.get_default_entity(api, config) + artifact, _, _ = _create_job( + api, + job_type, + uri, + entrypoint=" ".join(entry_point), + git_hash=git_version, + name=job_name, + project=project, + base_image=base_image, + build_context=build_context, + dockerfile=dockerfile, + entity=entity, + ) + if artifact is None: + raise LaunchError(f"Failed to create job from uri: {uri}") + job = f"{entity}/{project}/{artifact.name}" + + if dockerfile: + if "overrides" in config: + config["overrides"]["dockerfile"] = dockerfile + else: + config["overrides"] = {"dockerfile": dockerfile} + + if priority is not None: + priority_map = { + "critical": 0, + "high": 1, + "medium": 2, + "low": 3, + } + priority = priority_map[priority.lower()] + + template_variables = None + if cli_template_vars: + if queue is None: + raise LaunchError("'--set-var' flag requires queue to be set") + if entity is None: + entity = launch_utils.get_default_entity(api, config) + public_api = PublicApi() + runqueue = RunQueue(client=public_api.client, name=queue, entity=entity) + template_variables = launch_utils.fetch_and_validate_template_variables( + runqueue, cli_template_vars + ) + + if queue is None: + # direct launch + try: + run = asyncio.run( + _launch( + api, + job, + project=project, + entity=entity, + docker_image=docker_image, + name=name, + entry_point=entry_point, + version=git_version, + resource=resource, + resource_args=resource_args, + launch_config=config, + synchronous=(not run_async), + run_id=run_id, + repository=repository, + ) + ) + if asyncio.run(run.get_status()).state in [ + "failed", + "stopped", + "preempted", + ]: + wandb.termerror("Launched run exited with non-zero status") + sys.exit(1) + except LaunchError as e: + logger.exception("An error occurred.") + wandb._sentry.exception(e) + sys.exit(e) + except ExecutionError as e: + logger.exception("An error occurred.") + wandb._sentry.exception(e) + sys.exit(e) + except asyncio.CancelledError: + sys.exit(0) + else: + try: + _launch_add( + api, + job, + config, + template_variables, + project, + entity, + queue, + resource, + entry_point, + name, + git_version, + docker_image, + project_queue, + resource_args, + build=build, + run_id=run_id, + repository=repository, + priority=priority, + ) + + except Exception as e: + wandb._sentry.exception(e) + raise + + +@cli.command( + context_settings=CONTEXT, + help="Run a W&B launch agent.", +) +@click.pass_context +@click.option( + "--queue", + "-q", + "queues", + default=None, + multiple=True, + help="The name of a queue for the agent to watch. Multiple -q flags supported.", +) +@click.option( + "--entity", + "-e", + default=None, + help="The entity to use. Defaults to current logged-in user", +) +@click.option( + "--log-file", + "-l", + default=None, + help=( + "Destination for internal agent logs. Use - for stdout. " + "By default all agents logs will go to debug.log in your wandb/ " + "subdirectory or WANDB_DIR if set." + ), +) +@click.option( + "--max-jobs", + "-j", + default=None, + help="The maximum number of launch jobs this agent can run in parallel. Defaults to 1. Set to -1 for no upper limit", +) +@click.option( + "--config", "-c", default=None, help="path to the agent config yaml to use" +) +@click.option( + "--url", + "-u", + default=None, + hidden=True, + help="a wandb client registration URL, this is generated in the UI", +) +@click.option("--verbose", "-v", count=True, help="Display verbose output") +@display_error +def launch_agent( + ctx, + entity=None, + queues=None, + max_jobs=None, + config=None, + url=None, + log_file=None, + verbose=0, +): + logger.info( + f"=== Launch-agent called with kwargs {locals()} CLI Version: {wandb.__version__} ===" + ) + if url is not None: + raise LaunchError( + "--url is not supported in this version, upgrade with: pip install -u wandb" + ) + + import wandb.sdk.launch._launch as _launch + + if log_file is not None: + _launch.set_launch_logfile(log_file) + + api = _get_cling_api() + wandb._sentry.configure_scope(process_context="launch_agent") + agent_config, api = _launch.resolve_agent_config( + entity, max_jobs, queues, config, verbose + ) + + if len(agent_config.get("queues")) == 0: + raise LaunchError( + "To launch an agent please specify a queue or a list of queues in the configuration file or cli." + ) + + launch_utils.check_logged_in(api) + + wandb.termlog("Starting launch agent ✨") + try: + _launch.create_and_run_agent(api, agent_config) + except Exception as e: + wandb._sentry.exception(e) + raise + + +@cli.command(context_settings=CONTEXT, help="Run the W&B agent") +@click.pass_context +@click.option( + "--project", + "-p", + default=None, + help="""The name of the project where W&B runs created from the sweep are sent to. If the project is not specified, the run is sent to a project labeled 'Uncategorized'.""", +) +@click.option( + "--entity", + "-e", + default=None, + help="""The username or team name where you want to send W&B runs created by the sweep to. Ensure that the entity you specify already exists. If you don't specify an entity, the run will be sent to your default entity, which is usually your username.""", +) +@click.option( + "--count", default=None, type=int, help="The max number of runs for this agent." +) +@click.argument("sweep_id") +@display_error +def agent(ctx, project, entity, count, sweep_id): + api = _get_cling_api() + if not api.is_authenticated: + wandb.termlog("Login to W&B to use the sweep agent feature") + ctx.invoke(login, no_offline=True) + api = _get_cling_api(reset=True) + + wandb.termlog("Starting wandb agent 🕵️") + wandb_agent.agent(sweep_id, entity=entity, project=project, count=count) + + # you can send local commands like so: + # agent_api.command({'type': 'run', 'program': 'train.py', + # 'args': ['--max_epochs=10']}) + + +@cli.command( + context_settings=RUN_CONTEXT, help="Run a W&B launch sweep scheduler (Experimental)" +) +@click.pass_context +@click.argument("sweep_id") +@display_error +def scheduler( + ctx, + sweep_id, +): + api = InternalApi() + if not api.is_authenticated: + wandb.termlog("Login to W&B to use the sweep scheduler feature") + ctx.invoke(login, no_offline=True) + api = InternalApi(reset=True) + + wandb._sentry.configure_scope(process_context="sweep_scheduler") + wandb.termlog("Starting a Launch Scheduler 🚀") + from wandb.sdk.launch.sweeps import load_scheduler + + # TODO(gst): remove this monstrosity + # Future-proofing hack to pull any kwargs that get passed in through the CLI + kwargs = {} + for i, _arg in enumerate(ctx.args): + if isinstance(_arg, str) and _arg.startswith("--"): + # convert input kwargs from hyphens to underscores + _key = _arg[2:].replace("-", "_") + _args = ctx.args[i + 1] + if str.isdigit(_args): + _args = int(_args) + kwargs[_key] = _args + try: + sweep_type = kwargs.get("sweep_type", "wandb") + _scheduler = load_scheduler(scheduler_type=sweep_type)( + api, + sweep_id=sweep_id, + **kwargs, + ) + _scheduler.start() + except Exception as e: + wandb._sentry.exception(e) + raise + + +@cli.group(help="Commands for managing and viewing W&B jobs") +def job() -> None: + pass + + +@job.command("list", help="List jobs in a project") +@click.option( + "--project", + "-p", + envvar=env.PROJECT, + help="The project you want to list jobs from.", +) +@click.option( + "--entity", + "-e", + default="models", + envvar=env.ENTITY, + help="The entity the jobs belong to", +) +def _list(project, entity): + wandb.termlog(f"Listing jobs in {entity}/{project}") + public_api = PublicApi() + try: + jobs = public_api.list_jobs(entity=entity, project=project) + except wandb.errors.CommError as e: + wandb.termerror(f"{e}") + return + + if len(jobs) == 0: + wandb.termlog("No jobs found") + return + + for job in jobs: + aliases = [] + if len(job["edges"]) == 0: + # deleted? + continue + + name = job["edges"][0]["node"]["artifactSequence"]["name"] + for version in job["edges"]: + aliases += [x["alias"] for x in version["node"]["aliases"]] + + # only list the most recent 10 job versions + aliases_str = ",".join(aliases[::-1]) + wandb.termlog(f"{name} -- versions ({len(aliases)}): {aliases_str}") + + +@job.command( + help="Describe a launch job. Provide the launch job in the form of: entity/project/job-name:alias-or-version" +) +@click.argument("job") +def describe(job): + public_api = PublicApi() + try: + job = public_api.job(name=job) + except wandb.errors.CommError as e: + wandb.termerror(f"{e}") + return + + for key in job._job_info: + if key.startswith("_"): + continue + wandb.termlog(f"{key}: {job._job_info[key]}") + + +@job.command( + no_args_is_help=True, +) +@click.option( + "--project", + "-p", + envvar=env.PROJECT, + help="The project you want to list jobs from.", +) +@click.option( + "--entity", + "-e", + envvar=env.ENTITY, + help="The entity the jobs belong to", +) +@click.option( + "--name", + "-n", + help="Name for the job", +) +@click.option( + "--description", + "-d", + help="Description for the job", +) +@click.option( + "--alias", + "-a", + "aliases", + help="Alias for the job", + multiple=True, + default=tuple(), +) +@click.option( + "--entry-point", + "-E", + "entrypoint", + help="Entrypoint to the script, including an executable and an entrypoint " + "file. Required for code or repo jobs. If --build-context is provided, " + "paths in the entrypoint command will be relative to the build context.", +) +@click.option( + "--git-hash", + "-g", + "git_hash", + type=str, + help="Commit reference to use as the source for git jobs", +) +@click.option( + "--runtime", + "-r", + type=str, + help="Python runtime to execute the job", +) +@click.option( + "--build-context", + "-b", + type=str, + help="Path to the build context from the root of the job source code. If " + "provided, this is used as the base path for the Dockerfile and entrypoint.", +) +@click.option( + "--base-image", + "-B", + type=str, + help="Base image to use for the job. Incompatible with image jobs.", +) +@click.option( + "--dockerfile", + "-D", + type=str, + help="Path to the Dockerfile for the job. If --build-context is provided, " + "the Dockerfile path will be relative to the build context.", +) +@click.argument( + "job_type", + type=click.Choice(("git", "code", "image")), +) +@click.option( + "--service", + "-s", + "services", + multiple=True, + callback=parse_service_config, + help="Service configurations in format serviceName=policy. Valid policies: always, never", + hidden=True, +) +@click.argument("path") +def create( + path, + project, + entity, + name, + job_type, + description, + aliases, + entrypoint, + git_hash, + runtime, + build_context, + base_image, + dockerfile, + services, +): + """Create a job from a source, without a wandb run. + + Jobs can be of three types, git, code, or image. + + git: A git source, with an entrypoint either in the path or provided explicitly pointing to the main python executable. + code: A code path, containing a requirements.txt file. + image: A docker image. + """ + from wandb.sdk.launch.create_job import _create_job + + api = _get_cling_api() + wandb._sentry.configure_scope(process_context="job_create") + + entity = entity or os.getenv("WANDB_ENTITY") or api.default_entity + if not entity: + wandb.termerror("No entity provided, use --entity or set WANDB_ENTITY") + return + + project = project or os.getenv("WANDB_PROJECT") + if not project: + wandb.termerror("No project provided, use --project or set WANDB_PROJECT") + return + + if entrypoint is None and job_type in ["git", "code"]: + wandb.termwarn( + f"No entrypoint provided for {job_type} job, defaulting to main.py" + ) + entrypoint = "main.py" + + if job_type == "image" and base_image: + wandb.termerror("Cannot provide --base-image/-B for an `image` job") + return + + 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, + ) + if not artifact: + wandb.termerror("Job creation failed") + return + + artifact_path = f"{entity}/{project}/{artifact.name}" + msg = f"{action} job: {click.style(artifact_path, fg='yellow')}" + if len(aliases) == 1: + alias_str = click.style(aliases[0], fg="yellow") + msg += f", with alias: {alias_str}" + elif len(aliases) > 1: + alias_str = click.style(", ".join(aliases), fg="yellow") + msg += f", with aliases: {alias_str}" + + wandb.termlog(msg) + web_url = util.app_url(api.settings().get("base_url")) + url = click.style(f"{web_url}/{entity}/{project}/jobs", underline=True) + wandb.termlog(f"View all jobs in project '{project}' here: {url}\n") + + +@cli.command(context_settings=CONTEXT, help="Run the W&B local sweep controller") +@click.option("--verbose", is_flag=True, default=False, help="Display verbose output") +@click.argument("sweep_id") +@display_error +def controller(verbose, sweep_id): + click.echo("Starting wandb controller...") + from wandb import controller as wandb_controller + + tuner = wandb_controller(sweep_id) + tuner.run(verbose=verbose) + + +@cli.command(context_settings=RUN_CONTEXT, name="docker-run") +@click.pass_context +@click.argument("docker_run_args", nargs=-1) +def docker_run(ctx, docker_run_args): + """Wrap `docker run` and adds WANDB_API_KEY and WANDB_DOCKER environment variables. + + This will also set the runtime to nvidia if the nvidia-docker executable is present + on the system and --runtime wasn't set. + + See `docker run --help` for more details. + """ + import wandb.docker + + api = InternalApi() + args = list(docker_run_args) + if len(args) > 0 and args[0] == "run": + args.pop(0) + if len([a for a in args if a.startswith("--runtime")]) == 0 and _HAS_NVIDIA_DOCKER: + args = ["--runtime", "nvidia"] + args + # TODO: image_from_docker_args uses heuristics to find the docker image arg, there are likely cases + # where this won't work + image = util.image_from_docker_args(args) + resolved_image = None + if image: + resolved_image = wandb.docker.image_id(image) + if resolved_image: + args = ["-e", f"WANDB_DOCKER={resolved_image}"] + args + else: + wandb.termlog( + "Couldn't detect image argument, running command without the WANDB_DOCKER env variable" + ) + if api.api_key: + args = ["-e", f"WANDB_API_KEY={api.api_key}"] + args + else: + wandb.termlog( + "Not logged in, run `wandb login` from the host machine to enable result logging" + ) + subprocess.call(["docker", "run"] + args) + + +@cli.command(context_settings=RUN_CONTEXT) +@click.pass_context +@click.argument("docker_run_args", nargs=-1) +@click.argument("docker_image", required=False) +@click.option( + "--nvidia/--no-nvidia", + default=_HAS_NVIDIA_DOCKER, + help="Use the nvidia runtime, defaults to nvidia if nvidia-docker is present", +) +@click.option( + "--digest", is_flag=True, default=False, help="Output the image digest and exit" +) +@click.option( + "--jupyter/--no-jupyter", default=False, help="Run jupyter lab in the container" +) +@click.option( + "--dir", default="/app", help="Which directory to mount the code in the container" +) +@click.option("--no-dir", is_flag=True, help="Don't mount the current directory") +@click.option( + "--shell", default="/bin/bash", help="The shell to start the container with" +) +@click.option("--port", default="8888", help="The host port to bind jupyter on") +@click.option("--cmd", help="The command to run in the container") +@click.option( + "--no-tty", is_flag=True, default=False, help="Run the command without a tty" +) +@display_error +def docker( + ctx, + docker_run_args, + docker_image, + nvidia, + digest, + jupyter, + dir, + no_dir, + shell, + port, + cmd, + no_tty, +): + """Run your code in a docker container. + + W&B docker lets you run your code in a docker image ensuring wandb is configured. It + adds the WANDB_DOCKER and WANDB_API_KEY environment variables to your container and + mounts the current directory in /app by default. You can pass additional args which + will be added to `docker run` before the image name is declared, we'll choose a + default image for you if one isn't passed: + + ```sh + wandb docker -v /mnt/dataset:/app/data + wandb docker gcr.io/kubeflow-images-public/tensorflow-1.12.0-notebook-cpu:v0.4.0 --jupyter + wandb docker wandb/deepo:keras-gpu --no-tty --cmd "python train.py --epochs=5" + ``` + + By default, we override the entrypoint to check for the existence of wandb and + install it if not present. If you pass the --jupyter flag we will ensure jupyter is + installed and start jupyter lab on port 8888. If we detect nvidia-docker on your + system we will use the nvidia runtime. If you just want wandb to set environment + variable to an existing docker run command, see the wandb docker-run command. + """ + api = InternalApi() + if not _HAS_DOCKER: + raise ClickException("Docker not installed, install it from https://docker.com") + + import wandb.docker + + args = list(docker_run_args) + image = docker_image or "" + # remove run for users used to nvidia-docker + if len(args) > 0 and args[0] == "run": + args.pop(0) + if image == "" and len(args) > 0: + image = args.pop(0) + # If the user adds docker args without specifying an image (should be rare) + if not util.docker_image_regex(image.split("@")[0]): + if image: + args = args + [image] + image = wandb.docker.default_image(gpu=nvidia) + subprocess.call(["docker", "pull", image]) + _, repo_name, tag = wandb.docker.parse(image) + + resolved_image = wandb.docker.image_id(image) + if resolved_image is None: + raise ClickException( + f"Couldn't find image locally or in a registry, try running `docker pull {image}`" + ) + if digest: + sys.stdout.write(resolved_image) + exit(0) + + existing = wandb.docker.shell(["ps", "-f", f"ancestor={resolved_image}", "-q"]) + if existing: + if click.confirm( + "Found running container with the same image, do you want to attach?" + ): + subprocess.call(["docker", "attach", existing.split("\n")[0]]) + exit(0) + cwd = os.getcwd() + command = [ + "docker", + "run", + "-e", + "LANG=C.UTF-8", + "-e", + f"WANDB_DOCKER={resolved_image}", + "--ipc=host", + "-v", + wandb.docker.entrypoint + ":/wandb-entrypoint.sh", + "--entrypoint", + "/wandb-entrypoint.sh", + ] + if nvidia: + command.extend(["--runtime", "nvidia"]) + if not no_dir: + # TODO: We should default to the working directory if defined + command.extend(["-v", cwd + ":" + dir, "-w", dir]) + if api.api_key: + command.extend(["-e", f"WANDB_API_KEY={api.api_key}"]) + else: + wandb.termlog( + "Couldn't find WANDB_API_KEY, run `wandb login` to enable streaming metrics" + ) + if jupyter: + command.extend(["-e", "WANDB_ENSURE_JUPYTER=1", "-p", port + ":8888"]) + no_tty = True + cmd = f"jupyter lab --no-browser --ip=0.0.0.0 --allow-root --NotebookApp.token= --notebook-dir {dir}" + command.extend(args) + if no_tty: + command.extend([image, shell, "-c", cmd]) + else: + if cmd: + command.extend(["-e", f"WANDB_COMMAND={cmd}"]) + command.extend(["-it", image, shell]) + wandb.termlog("Launching docker container \U0001f6a2") + subprocess.call(command) + + +@cli.command( + context_settings=RUN_CONTEXT, + help="Start a local W&B container (deprecated, see wandb server --help)", + hidden=True, +) +@click.pass_context +@click.option("--port", "-p", default="8080", help="The host port to bind W&B local on") +@click.option( + "--env", "-e", default=[], multiple=True, help="Env vars to pass to wandb/local" +) +@click.option( + "--daemon/--no-daemon", default=True, help="Run or don't run in daemon mode" +) +@click.option( + "--upgrade", is_flag=True, default=False, help="Upgrade to the most recent version" +) +@click.option( + "--edge", is_flag=True, default=False, help="Run the bleeding edge", hidden=True +) +@display_error +def local(ctx, *args, **kwargs): + wandb.termwarn("`wandb local` has been replaced with `wandb server start`.") + ctx.invoke(start, *args, **kwargs) + + +@cli.group(help="Commands for operating a local W&B server") +def server(): + pass + + +@server.command(context_settings=RUN_CONTEXT, help="Start a local W&B server") +@click.pass_context +@click.option( + "--port", "-p", default="8080", help="The host port to bind W&B server on" +) +@click.option( + "--env", "-e", default=[], multiple=True, help="Env vars to pass to wandb/local" +) +@click.option( + "--daemon/--no-daemon", default=True, help="Run or don't run in daemon mode" +) +@click.option( + "--upgrade", + is_flag=True, + default=False, + help="Upgrade to the most recent version", + hidden=True, +) +@click.option( + "--edge", is_flag=True, default=False, help="Run the bleeding edge", hidden=True +) +@display_error +def start(ctx, port, env, daemon, upgrade, edge): + api = InternalApi() + if not _HAS_DOCKER: + raise ClickException("Docker not installed, install it from https://docker.com") + + import wandb.docker + + local_image_sha = wandb.docker.image_id("wandb/local").split("wandb/local")[-1] + registry_image_sha = wandb.docker.image_id_from_registry("wandb/local").split( + "wandb/local" + )[-1] + if local_image_sha != registry_image_sha: + if upgrade: + subprocess.call(["docker", "pull", "wandb/local"]) + else: + wandb.termlog( + "A new version of the W&B server is available, upgrade by calling `wandb server start --upgrade`" + ) + running = subprocess.check_output( + ["docker", "ps", "--filter", "name=^wandb-local$", "--format", "{{.ID}}"] + ) + if running != b"": + if upgrade: + subprocess.call(["docker", "stop", "wandb-local"]) + else: + wandb.termerror( + "A container named wandb-local is already running, run `docker stop wandb-local` if you want to start a new instance" + ) + exit(1) + image = "docker.pkg.github.com/wandb/core/local" if edge else "wandb/local" + username = getpass.getuser() + env_vars = ["-e", f"LOCAL_USERNAME={username}"] + for e in env: + env_vars.append("-e") + env_vars.append(e) + command = [ + "docker", + "run", + "--rm", + "-v", + "wandb:/vol", + "-p", + port + ":8080", + "--name", + "wandb-local", + ] + env_vars + host = f"http://localhost:{port}" + api.set_setting("base_url", host, globally=True, persist=True) + if daemon: + command += ["-d"] + command += [image] + + # DEVNULL is only in py3 + try: + from subprocess import DEVNULL + except ImportError: + DEVNULL = open(os.devnull, "wb") # noqa: N806 + code = subprocess.call(command, stdout=DEVNULL) + if daemon: + if code != 0: + wandb.termerror( + "Failed to launch the W&B server container, see the above error." + ) + exit(1) + else: + wandb.termlog(f"W&B server started at http://localhost:{port} \U0001f680") + wandb.termlog("You can stop the server by running `wandb server stop`") + if not api.api_key: + # Let the server start before potentially launching a browser + time.sleep(2) + ctx.invoke(login, host=host) + + +@server.command(context_settings=RUN_CONTEXT, help="Stop a local W&B server") +def stop(): + if not _HAS_DOCKER: + raise ClickException("Docker not installed, install it from https://docker.com") + subprocess.call(["docker", "stop", "wandb-local"]) + + +@cli.group(help="Commands for interacting with artifacts") +def artifact(): + pass + + +@artifact.command(context_settings=CONTEXT, help="Upload an artifact to wandb") +@click.argument("path") +@click.option( + "--name", "-n", help="The name of the artifact to push: project/artifact_name" +) +@click.option("--description", "-d", help="A description of this artifact") +@click.option("--type", "-t", default="dataset", help="The type of the artifact") +@click.option( + "--alias", + "-a", + default=["latest"], + multiple=True, + help="An alias to apply to this artifact", +) +@click.option("--id", "run_id", help="The run you want to upload to.") +@click.option( + "--resume", + is_flag=True, + default=None, + help="Resume the last run from your current directory.", +) +@click.option( + "--skip_cache", + is_flag=True, + default=False, + help="Skip caching while uploading artifact files.", +) +@click.option( + "--policy", + default="mutable", + type=click.Choice(["mutable", "immutable"]), + help="Set the storage policy while uploading artifact files.", +) +@display_error +def put( + path, + name, + description, + type, + alias, + run_id, + resume, + skip_cache, + policy, +): + if name is None: + name = os.path.basename(path) + public_api = PublicApi() + entity, project, artifact_name = public_api._parse_artifact_path(name) + if project is None: + project = click.prompt("Enter the name of the project you want to use") + # TODO: settings nightmare... + api = InternalApi() + api.set_setting("entity", entity) + api.set_setting("project", project) + artifact = wandb.Artifact(name=artifact_name, type=type, description=description) + artifact_path = f"{entity}/{project}/{artifact_name}:{alias[0]}" + if os.path.isdir(path): + wandb.termlog(f'Uploading directory {path} to: "{artifact_path}" ({type})') + artifact.add_dir(path, skip_cache=skip_cache, policy=policy) + elif os.path.isfile(path): + wandb.termlog(f'Uploading file {path} to: "{artifact_path}" ({type})') + artifact.add_file(path, skip_cache=skip_cache, policy=policy) + elif "://" in path: + wandb.termlog( + f'Logging reference artifact from {path} to: "{artifact_path}" ({type})' + ) + artifact.add_reference(path) + else: + raise ClickException("Path argument must be a file or directory") + + with wandb.init( + entity=entity, + project=project, + config={"path": path}, + job_type="cli_put", + id=run_id, + resume=resume, + ) as run: + run.log_artifact(artifact, aliases=alias) + artifact.wait() + + wandb.termlog( + "Artifact uploaded, use this artifact in a run by adding:\n", prefix=False + ) + wandb.termlog( + f' artifact = run.use_artifact("{artifact.source_qualified_name}")\n', + prefix=False, + ) + + +@artifact.command(context_settings=CONTEXT, help="Download an artifact from wandb") +@click.argument("path") +@click.option("--root", help="The directory you want to download the artifact to") +@click.option("--type", help="The type of artifact you are downloading") +@display_error +def get(path, root, type): + public_api = PublicApi() + entity, project, artifact_name = public_api._parse_artifact_path(path) + if project is None: + project = click.prompt("Enter the name of the project you want to use") + + try: + artifact_parts = artifact_name.split(":") + if len(artifact_parts) > 1: + version = artifact_parts[1] + artifact_name = artifact_parts[0] + else: + version = "latest" + if is_artifact_registry_project(project): + organization = path.split("/")[0] if path.count("/") == 2 else "" + # set entity to match the settings since in above code it was potentially set to an org + settings_entity = public_api.settings["entity"] or public_api.default_entity + # Registry artifacts are under the org entity. Because we offer a shorthand and alias for this path, + # we need to fetch the org entity to for the user behind the scenes. + entity = SDKInternalApi()._resolve_org_entity_name( + entity=settings_entity, organization=organization + ) + full_path = f"{entity}/{project}/{artifact_name}:{version}" + wandb.termlog( + "Downloading {type} artifact {full_path}".format( + type=type or "dataset", full_path=full_path + ) + ) + artifact = public_api.artifact(full_path, type=type) + path = artifact.download(root=root) + wandb.termlog(f"Artifact downloaded to {path}") + except ValueError: + raise ClickException("Unable to download artifact") + + +@artifact.command( + context_settings=CONTEXT, help="List all artifacts in a wandb project" +) +@click.argument("path") +@click.option("--type", "-t", help="The type of artifacts to list") +@display_error +def ls(path, type): + public_api = PublicApi() + if type is not None: + types = [public_api.artifact_type(type, path)] + else: + types = public_api.artifact_types(path) + + for kind in types: + for collection in kind.collections(): + versions = public_api.artifact_versions( + kind.type, + "/".join([kind.entity, kind.project, collection.name]), + per_page=1, + ) + latest = next(versions) + wandb.termlog( + f"{kind.type:<15s}{latest.updated_at:<15s}{util.to_human_size(latest.size):>15s} {latest.name:<20s}" + ) + + +@artifact.group(help="Commands for interacting with the artifact cache") +def cache(): + pass + + +@cache.command( + context_settings=CONTEXT, + help="Clean up less frequently used files from the artifacts cache", +) +@click.argument("target_size") +@click.option("--remove-temp/--no-remove-temp", default=False, help="Remove temp files") +@display_error +def cleanup(target_size, remove_temp): + target_size = util.from_human_size(target_size) + cache = get_artifact_file_cache() + reclaimed_bytes = cache.cleanup(target_size, remove_temp) + wandb.termlog(f"Reclaimed {util.to_human_size(reclaimed_bytes)} of space") + + +@cli.command(context_settings=CONTEXT, help="Pull files from Weights & Biases") +@click.argument("run", envvar=env.RUN_ID) +@click.option( + "--project", "-p", envvar=env.PROJECT, help="The project you want to download." +) +@click.option( + "--entity", + "-e", + default="models", + envvar=env.ENTITY, + help="The entity to scope the listing to.", +) +@display_error +def pull(run, project, entity): + api = InternalApi() + project, run = api.parse_slug(run, project=project) + urls = api.download_urls(project, run=run, entity=entity) + if len(urls) == 0: + raise ClickException("Run has no files") + click.echo(f"Downloading: {click.style(project, bold=True)}/{run}") + + for name in urls: + if api.file_current(name, urls[name]["md5"]): + click.echo(f"File {name} is up to date") + else: + length, response = api.download_file(urls[name]["url"]) + # TODO: I had to add this because some versions in CI broke click.progressbar + sys.stdout.write(f"File {name}\r") + dirname = os.path.dirname(name) + if dirname != "": + filesystem.mkdir_exists_ok(dirname) + with click.progressbar( + length=length, + label=f"File {name}", + fill_char=click.style("&", fg="green"), + ) as bar: + with open(name, "wb") as f: + for data in response.iter_content(chunk_size=4096): + f.write(data) + bar.update(len(data)) + + +@cli.command( + context_settings=CONTEXT, help="Restore code, config and docker state for a run" +) +@click.pass_context +@click.argument("run", envvar=env.RUN_ID) +@click.option("--no-git", is_flag=True, default=False, help="Don't restore git state") +@click.option( + "--branch/--no-branch", + default=True, + help="Whether to create a branch or checkout detached", +) +@click.option( + "--project", "-p", envvar=env.PROJECT, help="The project you wish to upload to." +) +@click.option( + "--entity", "-e", envvar=env.ENTITY, help="The entity to scope the listing to." +) +@display_error +def restore(ctx, run, no_git, branch, project, entity): + from wandb.old.core import wandb_dir + + api = _get_cling_api() + if ":" in run: + if "/" in run: + entity, rest = run.split("/", 1) + else: + rest = run + project, run = rest.split(":", 1) + elif run.count("/") > 1: + entity, run = run.split("/", 1) + + project, run = api.parse_slug(run, project=project) + commit, json_config, patch_content, metadata = api.run_config( + project, run=run, entity=entity + ) + repo = metadata.get("git", {}).get("repo") + image = metadata.get("docker") + restore_message = f"""`wandb restore` needs to be run from the same git repository as the original run. +Run `git clone {repo}` and restore from there or pass the --no-git flag.""" + if no_git: + commit = None + elif not api.git.enabled: + if repo: + raise ClickException(restore_message) + elif image: + wandb.termlog( + "Original run has no git history. Just restoring config and docker" + ) + + if commit and api.git.enabled: + wandb.termlog(f"Fetching origin and finding commit: {commit}") + subprocess.check_call(["git", "fetch", "--all"]) + try: + api.git.repo.commit(commit) + except ValueError: + wandb.termlog(f"Couldn't find original commit: {commit}") + commit = None + files = api.download_urls(project, run=run, entity=entity) + for filename in files: + if filename.startswith("upstream_diff_") and filename.endswith( + ".patch" + ): + commit = filename[len("upstream_diff_") : -len(".patch")] + try: + api.git.repo.commit(commit) + except ValueError: + commit = None + else: + break + + if commit: + wandb.termlog(f"Falling back to upstream commit: {commit}") + patch_path, _ = api.download_write_file(files[filename]) + else: + raise ClickException(restore_message) + else: + if patch_content: + patch_path = os.path.join(wandb_dir(), "diff.patch") + with open(patch_path, "w") as f: + f.write(patch_content) + else: + patch_path = None + + branch_name = f"wandb/{run}" + if branch and branch_name not in api.git.repo.branches: + api.git.repo.git.checkout(commit, b=branch_name) + wandb.termlog(f"Created branch {click.style(branch_name, bold=True)}") + elif branch: + wandb.termlog( + f"Using existing branch, run `git branch -D {branch_name}` from master for a clean checkout" + ) + api.git.repo.git.checkout(branch_name) + else: + wandb.termlog(f"Checking out {commit} in detached mode") + api.git.repo.git.checkout(commit) + + if patch_path: + # we apply the patch from the repository root so git doesn't exclude + # things outside the current directory + root = api.git.root + patch_rel_path = os.path.relpath(patch_path, start=root) + # --reject is necessary or else this fails any time a binary file + # occurs in the diff + exit_code = subprocess.call( + ["git", "apply", "--reject", patch_rel_path], cwd=root + ) + if exit_code == 0: + wandb.termlog("Applied patch") + else: + wandb.termerror( + "Failed to apply patch, try un-staging any un-committed changes" + ) + + filesystem.mkdir_exists_ok(wandb_dir()) + config_path = os.path.join(wandb_dir(), "config.yaml") + config = Config() + for k, v in json_config.items(): + if k not in ("_wandb", "wandb_version"): + config[k] = v + s = b"wandb_version: 1" + s += b"\n\n" + yaml.dump( + config._as_dict(), + Dumper=yaml.SafeDumper, + default_flow_style=False, + allow_unicode=True, + encoding="utf-8", + ) + s = s.decode("utf-8") + with open(config_path, "w") as f: + f.write(s) + + wandb.termlog(f"Restored config variables to {config_path}") + if image: + if not metadata["program"].startswith("<") and metadata.get("args") is not None: + # TODO: we may not want to default to python here. + runner = util.find_runner(metadata["program"]) or ["python"] + command = runner + [metadata["program"]] + metadata["args"] + cmd = " ".join(command) + else: + wandb.termlog("Couldn't find original command, just restoring environment") + cmd = None + wandb.termlog("Docker image found, attempting to start") + ctx.invoke(docker, docker_run_args=[image], cmd=cmd) + + return commit, json_config, patch_content, repo, metadata + + +@cli.command("online", help="Enable W&B sync") +@display_error +def online(): + api = InternalApi() + try: + api.clear_setting("mode", persist=True) + except configparser.Error: + pass + click.echo( + "W&B online. Running your script from this directory will now sync to the cloud." + ) + + +@cli.command("offline", help="Disable W&B sync") +@display_error +def offline(): + api = InternalApi() + try: + api.set_setting("mode", "offline", persist=True) + click.echo( + "W&B offline. Running your script from this directory will only write metadata locally. Use wandb disabled to completely turn off W&B." + ) + except configparser.Error: + click.echo( + "Unable to write config, copy and paste the following in your terminal to turn off W&B:\nexport WANDB_MODE=offline" + ) + + +@cli.command("on", hidden=True) +@click.pass_context +@display_error +def on(ctx): + ctx.invoke(online) + + +@cli.command("off", hidden=True) +@click.pass_context +@display_error +def off(ctx): + ctx.invoke(offline) + + +@cli.command("status", help="Show configuration settings") +@click.option( + "--settings/--no-settings", help="Show the current settings", default=True +) +def status(settings): + api = _get_cling_api() + if settings: + click.echo(click.style("Current Settings", bold=True)) + settings = api.settings() + click.echo( + json.dumps(settings, sort_keys=True, indent=2, separators=(",", ": ")) + ) + + +@cli.command("disabled", help="Disable W&B.") +@click.option( + "--service", + is_flag=True, + show_default=True, + default=True, + help="Disable W&B service", +) +def disabled(service): + api = InternalApi() + try: + api.set_setting("mode", "disabled", persist=True) + click.echo("W&B disabled.") + except configparser.Error: + click.echo( + "Unable to write config, copy and paste the following in your terminal to turn off W&B:\nexport WANDB_MODE=disabled" + ) + + +@cli.command("enabled", help="Enable W&B.") +@click.option( + "--service", + is_flag=True, + show_default=True, + default=True, + help="Enable W&B service", +) +def enabled(service): + api = InternalApi() + try: + api.set_setting("mode", "online", persist=True) + click.echo("W&B enabled.") + except configparser.Error: + click.echo( + "Unable to write config, copy and paste the following in your terminal to turn on W&B:\nexport WANDB_MODE=online" + ) + + +@cli.command(context_settings=CONTEXT, help="Verify your local instance") +@click.option("--host", default=None, help="Test a specific instance of W&B") +def verify(host): + # TODO: (kdg) Build this all into a WandbVerify object, and clean this up. + os.environ["WANDB_SILENT"] = "true" + os.environ["WANDB_PROJECT"] = "verify" + api = _get_cling_api() + reinit = False + if host is None: + host = api.settings("base_url") + wandb.termlog(f"Default host selected: {host}") + # if the given host does not match the default host, re-run init + elif host != api.settings("base_url"): + reinit = True + + tmp_dir = tempfile.mkdtemp() + wandb.termlog( + "Find detailed logs for this test at: {}".format(os.path.join(tmp_dir, "wandb")) + ) + os.chdir(tmp_dir) + os.environ["WANDB_BASE_URL"] = host + wandb.login(host=host) + if reinit: + api = _get_cling_api(reset=True) + if not wandb_verify.check_host(host): + sys.exit(1) + if not wandb_verify.check_logged_in(api, host): + sys.exit(1) + url_success, url = wandb_verify.check_graphql_put(api, host) + large_post_success = wandb_verify.check_large_post() + wandb_verify.check_secure_requests( + api.settings("base_url"), + "Checking requests to base url", + "Connections are not made over https. SSL required for secure communications.", + ) + if url: + wandb_verify.check_secure_requests( + url, + "Checking requests made over signed URLs", + "Signed URL requests not made over https. SSL is required for secure communications.", + ) + wandb_verify.check_cors_configuration(url, host) + wandb_verify.check_wandb_version(api) + check_run_success = wandb_verify.check_run(api) + check_artifacts_success = wandb_verify.check_artifacts() + check_sweeps_success = wandb_verify.check_sweeps(api) + if not ( + check_artifacts_success + and check_run_success + and large_post_success + and url_success + and check_sweeps_success + ): + sys.exit(1) + + +cli.add_command(beta) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/docker/names.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/docker/names.py new file mode 100644 index 0000000000000000000000000000000000000000..384d39a9e21329bcb71abfbcacdcfa9b3c78bbd2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/docker/wandb-entrypoint.sh b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/docker/wandb-entrypoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2d4af61de2eb53973f8ee5eb6e619521d66a63a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/errors/__pycache__/errors.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/errors/__pycache__/errors.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..209f2d480f5a7d202542db3f495a1719736437f0 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/errors/__pycache__/errors.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/errors/__pycache__/links.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/errors/__pycache__/links.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23a7c8f5d560a25b3f3a30f28ae14b3a6a9847e2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/errors/__pycache__/links.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/errors/__pycache__/util.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/errors/__pycache__/util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..607108976931813a15f20b257d1bd542d09b0933 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/errors/__pycache__/util.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/errors/util.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/errors/util.py new file mode 100644 index 0000000000000000000000000000000000000000..0dd207c9e59f6ad15405b753c29f8b241238941a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/errors/util.py @@ -0,0 +1,57 @@ +from typing import Optional + +from wandb.proto import wandb_internal_pb2 as pb + +from . import AuthenticationError, CommError, Error, UnsupportedError, UsageError + +to_exception_map = { + pb.ErrorInfo.UNKNOWN: Error, + pb.ErrorInfo.COMMUNICATION: CommError, + pb.ErrorInfo.AUTHENTICATION: AuthenticationError, + pb.ErrorInfo.USAGE: UsageError, + pb.ErrorInfo.UNSUPPORTED: UnsupportedError, +} + +from_exception_map = {v: k for k, v in to_exception_map.items()} + + +class ProtobufErrorHandler: + """Converts protobuf errors to exceptions and vice versa.""" + + @staticmethod + def to_exception(error: pb.ErrorInfo) -> Optional[Error]: + """Convert a protobuf error to an exception. + + Args: + error: The protobuf error to convert. + + Returns: + The corresponding exception. + + """ + if not error.SerializeToString(): + return None + + if error.code in to_exception_map: + return to_exception_map[error.code](error.message) + return Error(error.message) + + @classmethod + def from_exception(cls, exc: Error) -> "pb.ErrorInfo": + """Convert an wandb error to a protobuf error message. + + Args: + exc: The exception to convert. + + Returns: + The corresponding protobuf error message. + """ + if not isinstance(exc, Error): + raise TypeError("exc must be a subclass of wandb.errors.Error") + + code = None + for subclass in type(exc).__mro__: + if subclass in from_exception_map: + code = from_exception_map[subclass] # type: ignore + break + return pb.ErrorInfo(code=code, message=str(exc)) # type: ignore diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/filesync/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/filesync/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/filesync/__pycache__/step_upload.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/filesync/__pycache__/step_upload.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83c3fccab4252ac1dc879217670f6a0c8e2413f2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/filesync/__pycache__/step_upload.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/filesync/__pycache__/upload_job.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/filesync/__pycache__/upload_job.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12f2a406401e9f6c722363af489932fba6782af8 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/filesync/__pycache__/upload_job.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/cohere/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/cohere/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42765fe46daaeecd6538ecc52793443254470278 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/cohere/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/cohere/__pycache__/cohere.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/cohere/__pycache__/cohere.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a37a3980c7883bb02b612e65d6da731e48695ad8 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/cohere/__pycache__/cohere.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/cohere/cohere.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/cohere/cohere.py new file mode 100644 index 0000000000000000000000000000000000000000..91f9a43e23150a6882dbb87512e6fbe657a7b8d4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/cohere/cohere.py @@ -0,0 +1,21 @@ +import logging + +from wandb.sdk.integration_utils.auto_logging import AutologAPI + +from .resolver import CohereRequestResponseResolver + +logger = logging.getLogger(__name__) + + +autolog = AutologAPI( + name="Cohere", + symbols=( + "Client.generate", + "Client.chat", + "Client.classify", + "Client.summarize", + "Client.rerank", + ), + resolver=CohereRequestResponseResolver(), + telemetry_feature="cohere_autolog", +) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/diffusers/autologger.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/diffusers/autologger.py new file mode 100644 index 0000000000000000000000000000000000000000..ad21a77edc6a1125f8d2f5621c046c6bbe1f0b9b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/diffusers/autologger.py @@ -0,0 +1,76 @@ +import logging + +from wandb.sdk.integration_utils.auto_logging import AutologAPI + +from .pipeline_resolver import DiffusersPipelineResolver + +logger = logging.getLogger(__name__) + +autolog = AutologAPI( + name="diffusers", + symbols=( + "DiffusionPipeline.__call__", + "AutoPipelineForText2Image.__call__", + "AutoPipelineForImage2Image.__call__", + "AutoPipelineForInpainting.__call__", + "StableDiffusionPipeline.__call__", + "KandinskyCombinedPipeline.__call__", + "KandinskyV22CombinedPipeline.__call__", + "LatentConsistencyModelPipeline.__call__", + "LDMTextToImagePipeline.__call__", + "StableDiffusionPanoramaPipeline.__call__", + "StableDiffusionParadigmsPipeline.__call__", + "PixArtAlphaPipeline.__call__", + "StableDiffusionSAGPipeline.__call__", + "SemanticStableDiffusionPipeline.__call__", + "WuerstchenCombinedPipeline.__call__", + "AltDiffusionPipeline.__call__", + "StableDiffusionAttendAndExcitePipeline.__call__", + "StableDiffusionXLPipeline.__call__", + "StableDiffusionXLImg2ImgPipeline.__call__", + "IFPipeline.__call__", + "BlipDiffusionPipeline.__call__", + "BlipDiffusionControlNetPipeline.__call__", + "StableDiffusionControlNetPipeline.__call__", + "StableDiffusionControlNetImg2ImgPipeline.__call__", + "StableDiffusionControlNetInpaintPipeline.__call__", + "CycleDiffusionPipeline.__call__", + "StableDiffusionInstructPix2PixPipeline.__call__", + "PaintByExamplePipeline.__call__", + "RePaintPipeline.__call__", + "KandinskyImg2ImgCombinedPipeline.__call__", + "KandinskyInpaintCombinedPipeline.__call__", + "KandinskyV22Img2ImgCombinedPipeline.__call__", + "KandinskyV22InpaintCombinedPipeline.__call__", + "Kandinsky3Pipeline.__call__", + "Kandinsky3Img2ImgPipeline.__call__", + "AnimateDiffPipeline.__call__", + "AudioLDMPipeline.__call__", + "AudioLDM2Pipeline.__call__", + "MusicLDMPipeline.__call__", + "StableDiffusionPix2PixZeroPipeline.__call__", + "PNDMPipeline.__call__", + "ShapEPipeline.__call__", + "StableDiffusionImg2ImgPipeline.__call__", + "StableDiffusionInpaintPipeline.__call__", + "StableDiffusionDepth2ImgPipeline.__call__", + "StableDiffusionImageVariationPipeline.__call__", + "StableDiffusionPipelineSafe.__call__", + "StableDiffusionUpscalePipeline.__call__", + "StableDiffusionAdapterPipeline.__call__", + "StableDiffusionGLIGENPipeline.__call__", + "StableDiffusionModelEditingPipeline.__call__", + "VersatileDiffusionTextToImagePipeline.__call__", + "VersatileDiffusionImageVariationPipeline.__call__", + "VersatileDiffusionDualGuidedPipeline.__call__", + "LDMPipeline.__call__", + "TextToVideoSDPipeline.__call__", + "TextToVideoZeroPipeline.__call__", + "StableVideoDiffusionPipeline.__call__", + "AmusedPipeline.__call__", + "StableDiffusionXLControlNetPipeline.__call__", + "StableDiffusionXLControlNetImg2ImgPipeline.__call__", + ), + resolver=DiffusersPipelineResolver(), + telemetry_feature="diffusers_autolog", +) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/diffusers/resolvers/__pycache__/multimodal.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/diffusers/resolvers/__pycache__/multimodal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67ff565d43ae44acba0e9cbccfd32e69b45232c0 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/diffusers/resolvers/__pycache__/multimodal.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/diffusers/resolvers/multimodal.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/diffusers/resolvers/multimodal.py new file mode 100644 index 0000000000000000000000000000000000000000..34ef33e8639193b8f87a65434e6261ff112fbd7a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/diffusers/resolvers/multimodal.py @@ -0,0 +1,881 @@ +import logging +from typing import Any, Dict, List, Sequence + +import wandb +from wandb.sdk.integration_utils.auto_logging import Response + +from .utils import ( + chunkify, + decode_sdxl_t2i_latents, + get_updated_kwargs, + postprocess_np_arrays_for_video, + postprocess_pils_to_np, +) + +logger = logging.getLogger(__name__) + + +SUPPORTED_MULTIMODAL_PIPELINES = { + "BlipDiffusionPipeline": { + "table-schema": [ + "Reference-Image", + "Prompt", + "Negative-Prompt", + "Source-Subject-Category", + "Target-Subject-Category", + "Generated-Image", + ], + "kwarg-logging": [ + "reference_image", + "prompt", + "neg_prompt", + "source_subject_category", + "target_subject_category", + ], + "kwarg-actions": [wandb.Image, None, None, None, None], + }, + "BlipDiffusionControlNetPipeline": { + "table-schema": [ + "Reference-Image", + "Control-Image", + "Prompt", + "Negative-Prompt", + "Source-Subject-Category", + "Target-Subject-Category", + "Generated-Image", + ], + "kwarg-logging": [ + "reference_image", + "condtioning_image", + "prompt", + "neg_prompt", + "source_subject_category", + "target_subject_category", + ], + "kwarg-actions": [wandb.Image, wandb.Image, None, None, None, None], + }, + "StableDiffusionControlNetPipeline": { + "table-schema": [ + "Control-Image", + "Prompt", + "Negative-Prompt", + "Generated-Image", + ], + "kwarg-logging": ["image", "prompt", "negative_prompt"], + "kwarg-actions": [wandb.Image, None, None], + }, + "StableDiffusionControlNetImg2ImgPipeline": { + "table-schema": [ + "Source-Image", + "Control-Image", + "Prompt", + "Negative-Prompt", + "Generated-Image", + ], + "kwarg-logging": ["image", "control_image", "prompt", "negative_prompt"], + "kwarg-actions": [wandb.Image, wandb.Image, None, None], + }, + "StableDiffusionControlNetInpaintPipeline": { + "table-schema": [ + "Source-Image", + "Mask-Image", + "Control-Image", + "Prompt", + "Negative-Prompt", + "Generated-Image", + ], + "kwarg-logging": [ + "image", + "mask_image", + "control_image", + "prompt", + "negative_prompt", + ], + "kwarg-actions": [wandb.Image, wandb.Image, wandb.Image, None, None], + }, + "CycleDiffusionPipeline": { + "table-schema": [ + "Source-Image", + "Prompt", + "Source-Prompt", + "Generated-Image", + ], + "kwarg-logging": [ + "image", + "prompt", + "source_prompt", + ], + "kwarg-actions": [wandb.Image, None, None], + }, + "StableDiffusionInstructPix2PixPipeline": { + "table-schema": [ + "Source-Image", + "Prompt", + "Negative-Prompt", + "Generated-Image", + ], + "kwarg-logging": [ + "image", + "prompt", + "negative_prompt", + ], + "kwarg-actions": [wandb.Image, None, None], + }, + "PaintByExamplePipeline": { + "table-schema": [ + "Source-Image", + "Example-Image", + "Mask-Prompt", + "Generated-Image", + ], + "kwarg-logging": [ + "image", + "example_image", + "mask_image", + ], + "kwarg-actions": [wandb.Image, wandb.Image, wandb.Image], + }, + "RePaintPipeline": { + "table-schema": [ + "Source-Image", + "Mask-Prompt", + "Generated-Image", + ], + "kwarg-logging": [ + "image", + "mask_image", + ], + "kwarg-actions": [wandb.Image, wandb.Image], + }, + "StableDiffusionPipeline": { + "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"], + "kwarg-logging": ["prompt", "negative_prompt"], + "kwarg-actions": [None, None], + }, + "KandinskyCombinedPipeline": { + "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"], + "kwarg-logging": ["prompt", "negative_prompt"], + "kwarg-actions": [None, None], + }, + "KandinskyV22CombinedPipeline": { + "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"], + "kwarg-logging": ["prompt", "negative_prompt"], + "kwarg-actions": [None, None], + }, + "LatentConsistencyModelPipeline": { + "table-schema": ["Prompt", "Generated-Image"], + "kwarg-logging": ["prompt"], + "kwarg-actions": [None], + }, + "LDMTextToImagePipeline": { + "table-schema": ["Prompt", "Generated-Image"], + "kwarg-logging": ["prompt"], + "kwarg-actions": [None], + }, + "StableDiffusionPanoramaPipeline": { + "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"], + "kwarg-logging": ["prompt", "negative_prompt"], + "kwarg-actions": [None, None], + }, + "PixArtAlphaPipeline": { + "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"], + "kwarg-logging": ["prompt", "negative_prompt"], + "kwarg-actions": [None, None], + }, + "StableDiffusionSAGPipeline": { + "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"], + "kwarg-logging": ["prompt", "negative_prompt"], + "kwarg-actions": [None, None], + }, + "SemanticStableDiffusionPipeline": { + "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"], + "kwarg-logging": ["prompt", "negative_prompt"], + "kwarg-actions": [None, None], + }, + "WuerstchenCombinedPipeline": { + "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"], + "kwarg-logging": ["prompt", "negative_prompt"], + "kwarg-actions": [None, None], + }, + "IFPipeline": { + "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"], + "kwarg-logging": ["prompt", "negative_prompt"], + "kwarg-actions": [None, None], + }, + "AltDiffusionPipeline": { + "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"], + "kwarg-logging": ["prompt", "negative_prompt"], + "kwarg-actions": [None, None], + }, + "StableDiffusionAttendAndExcitePipeline": { + "table-schema": ["Prompt", "Negative-Prompt", "Generated-Image"], + "kwarg-logging": ["prompt", "negative_prompt"], + "kwarg-actions": [None, None], + }, + "KandinskyImg2ImgCombinedPipeline": { + "table-schema": [ + "Source-Image", + "Prompt", + "Negative-Prompt", + "Generated-Image", + ], + "kwarg-logging": ["image", "prompt", "negative_prompt"], + "kwarg-actions": [wandb.Image, None, None], + }, + "KandinskyInpaintCombinedPipeline": { + "table-schema": [ + "Source-Image", + "Prompt", + "Negative-Prompt", + "Generated-Image", + ], + "kwarg-logging": ["image", "prompt", "negative_prompt"], + "kwarg-actions": [wandb.Image, None, None], + }, + "KandinskyV22Img2ImgCombinedPipeline": { + "table-schema": [ + "Source-Image", + "Prompt", + "Negative-Prompt", + "Generated-Image", + ], + "kwarg-logging": ["image", "prompt", "negative_prompt"], + "kwarg-actions": [wandb.Image, None, None], + }, + "KandinskyV22InpaintCombinedPipeline": { + "table-schema": [ + "Source-Image", + "Prompt", + "Negative-Prompt", + "Generated-Image", + ], + "kwarg-logging": ["image", "prompt", "negative_prompt"], + "kwarg-actions": [wandb.Image, None, None], + }, + "AnimateDiffPipeline": { + "table-schema": [ + "Prompt", + "Negative-Prompt", + "Number-of-Frames", + "Generated-Video", + ], + "kwarg-logging": ["prompt", "negative_prompt", "num_frames"], + "kwarg-actions": [None, None, None], + "output-type": "video", + }, + "StableVideoDiffusionPipeline": { + "table-schema": [ + "Input-Image", + "Frames-Per-Second", + "Generated-Video", + ], + "kwarg-logging": ["image", "fps"], + "kwarg-actions": [wandb.Image, None], + "output-type": "video", + }, + "AudioLDMPipeline": { + "table-schema": [ + "Prompt", + "Negative-Prompt", + "Audio-Length-in-Seconds", + "Generated-Audio", + ], + "kwarg-logging": ["prompt", "negative_prompt", "audio_length_in_s"], + "kwarg-actions": [None, None, None], + "output-type": "audio", + }, + "AudioLDM2Pipeline": { + "table-schema": [ + "Prompt", + "Negative-Prompt", + "Audio-Length-in-Seconds", + "Generated-Audio", + ], + "kwarg-logging": ["prompt", "negative_prompt", "audio_length_in_s"], + "kwarg-actions": [None, None, None], + "output-type": "audio", + }, + "MusicLDMPipeline": { + "table-schema": [ + "Prompt", + "Negative-Prompt", + "Audio-Length-in-Seconds", + "Generated-Audio", + ], + "kwarg-logging": ["prompt", "negative_prompt", "audio_length_in_s"], + "kwarg-actions": [None, None, None], + "output-type": "audio", + }, + "StableDiffusionPix2PixZeroPipeline": { + "table-schema": [ + "Prompt", + "Negative-Prompt", + "Generated-Image", + ], + "kwarg-logging": ["prompt", "negative_prompt"], + "kwarg-actions": [None, None], + }, + "PNDMPipeline": { + "table-schema": [ + "Batch-Size", + "Number-of-Inference-Steps", + "Generated-Image", + ], + "kwarg-logging": ["batch_size", "num_inference_steps"], + "kwarg-actions": [None, None], + }, + "ShapEPipeline": { + "table-schema": [ + "Prompt", + "Generated-Video", + ], + "kwarg-logging": ["prompt"], + "kwarg-actions": [None], + "output-type": "video", + }, + "StableDiffusionImg2ImgPipeline": { + "table-schema": [ + "Source-Image", + "Prompt", + "Negative-Prompt", + "Generated-Image", + ], + "kwarg-logging": ["image", "prompt", "negative_prompt"], + "kwarg-actions": [wandb.Image, None, None], + }, + "StableDiffusionInpaintPipeline": { + "table-schema": [ + "Source-Image", + "Mask-Image", + "Prompt", + "Negative-Prompt", + "Generated-Image", + ], + "kwarg-logging": ["image", "mask_image", "prompt", "negative_prompt"], + "kwarg-actions": [wandb.Image, wandb.Image, None, None], + }, + "StableDiffusionDepth2ImgPipeline": { + "table-schema": [ + "Source-Image", + "Prompt", + "Negative-Prompt", + "Generated-Image", + ], + "kwarg-logging": ["image", "prompt", "negative_prompt"], + "kwarg-actions": [wandb.Image, None, None], + }, + "StableDiffusionImageVariationPipeline": { + "table-schema": [ + "Source-Image", + "Generated-Image", + ], + "kwarg-logging": [ + "image", + ], + "kwarg-actions": [wandb.Image], + }, + "StableDiffusionPipelineSafe": { + "table-schema": [ + "Prompt", + "Negative-Prompt", + "Generated-Image", + ], + "kwarg-logging": ["prompt", "negative_prompt"], + "kwarg-actions": [None, None], + }, + "StableDiffusionUpscalePipeline": { + "table-schema": [ + "Source-Image", + "Prompt", + "Negative-Prompt", + "Upscaled-Image", + ], + "kwarg-logging": ["image", "prompt", "negative_prompt"], + "kwarg-actions": [wandb.Image, None, None], + }, + "StableDiffusionAdapterPipeline": { + "table-schema": [ + "Source-Image", + "Prompt", + "Negative-Prompt", + "Generated-Image", + ], + "kwarg-logging": ["image", "prompt", "negative_prompt"], + "kwarg-actions": [wandb.Image, None, None], + }, + "StableDiffusionGLIGENPipeline": { + "table-schema": [ + "Prompt", + "GLIGEN-Phrases", + "GLIGEN-Boxes", + "GLIGEN-Inpaint-Image", + "Negative-Prompt", + "Generated-Image", + ], + "kwarg-logging": [ + "prompt", + "gligen_phrases", + "gligen_boxes", + "gligen_inpaint_image", + "negative_prompt", + ], + "kwarg-actions": [None, None, None, wandb.Image, None], + }, + "VersatileDiffusionTextToImagePipeline": { + "table-schema": [ + "Prompt", + "Negative-Prompt", + "Generated-Image", + ], + "kwarg-logging": ["prompt", "negative_prompt"], + "kwarg-actions": [None, None], + }, + "VersatileDiffusionImageVariationPipeline": { + "table-schema": [ + "Source-Image", + "Negative-Prompt", + "Generated-Image", + ], + "kwarg-logging": ["image", "negative_prompt"], + "kwarg-actions": [wandb.Image, None], + }, + "VersatileDiffusionDualGuidedPipeline": { + "table-schema": [ + "Source-Image", + "Prompt", + "Negative-Prompt", + "Generated-Image", + ], + "kwarg-logging": ["image", "prompt", "negative_prompt"], + "kwarg-actions": [wandb.Image, None, None], + }, + "LDMPipeline": { + "table-schema": [ + "Batch-Size", + "Number-of-Inference-Steps", + "Generated-Image", + ], + "kwarg-logging": ["batch_size", "num_inference_steps"], + "kwarg-actions": [None, None], + }, + "TextToVideoSDPipeline": { + "table-schema": [ + "Prompt", + "Negative-Prompt", + "Number-of-Frames", + "Generated-Video", + ], + "kwarg-logging": ["prompt", "negative_prompt", "num_frames"], + "output-type": "video", + }, + "TextToVideoZeroPipeline": { + "table-schema": [ + "Prompt", + "Negative-Prompt", + "Number-of-Frames", + "Generated-Video", + ], + "kwarg-logging": ["prompt", "negative_prompt", "video_length"], + }, + "AmusedPipeline": { + "table-schema": [ + "Prompt", + "Guidance Scale", + "Generated-Image", + ], + "kwarg-logging": [ + "prompt", + "guidance_scale", + ], + "kwarg-actions": [None, None], + }, + "StableDiffusionXLControlNetPipeline": { + "table-schema": [ + "Prompt-1", + "Prompt-2", + "Control-Image", + "Negative-Prompt-1", + "Negative-Prompt-2", + "Generated-Image", + ], + "kwarg-logging": [ + "prompt", + "prompt_2", + "image", + "negative_prompt", + "negative_prompt_2", + ], + "kwarg-actions": [None, None, wandb.Image, None, None], + }, + "StableDiffusionXLControlNetImg2ImgPipeline": { + "table-schema": [ + "Prompt-1", + "Prompt-2", + "Input-Image", + "Control-Image", + "Negative-Prompt-1", + "Negative-Prompt-2", + "Generated-Image", + ], + "kwarg-logging": [ + "prompt", + "prompt_2", + "image", + "control_image", + "negative_prompt", + "negative_prompt_2", + ], + "kwarg-actions": [None, None, wandb.Image, wandb.Image, None, None], + }, + "Kandinsky3Pipeline": { + "table-schema": [ + "Prompt", + "Negative-Prompt", + "Generated-Image", + ], + "kwarg-logging": [ + "prompt", + "negative_prompt", + ], + "kwarg-actions": [None, None], + }, + "Kandinsky3Img2ImgPipeline": { + "table-schema": [ + "Prompt", + "Negative-Prompt", + "Input-Image", + "Generated-Image", + ], + "kwarg-logging": [ + "prompt", + "negative_prompt", + "image", + ], + "kwarg-actions": [None, None, wandb.Image], + }, + "StableDiffusionXLPipeline": { + "table-schema": [ + "Prompt", + "Negative-Prompt", + "Prompt-2", + "Negative-Prompt-2", + "Generated-Image", + ], + "kwarg-logging": [ + "prompt", + "negative_prompt", + "prompt_2", + "negative_prompt_2", + ], + "kwarg-actions": [None, None, None, None], + }, + "StableDiffusionXLImg2ImgPipeline": { + "table-schema": [ + "Prompt", + "Negative-Prompt", + "Prompt-2", + "Negative-Prompt-2", + "Input-Image", + "Generated-Image", + ], + "kwarg-logging": [ + "prompt", + "negative_prompt", + "prompt_2", + "negative_prompt_2", + "image", + ], + "kwarg-actions": [None, None, None, None, wandb.Image], + }, +} + + +class DiffusersMultiModalPipelineResolver: + """Resolver for request and responses from [HuggingFace Diffusers](https://huggingface.co/docs/diffusers/index) multi-modal Diffusion Pipelines, providing necessary data transformations, formatting, and logging. + + This resolver is internally involved in the + `__call__` for `wandb.integration.diffusers.pipeline_resolver.DiffusersPipelineResolver`. + This is based on `wandb.sdk.integration_utils.auto_logging.RequestResponseResolver`. + + Args: + pipeline_name: (str) The name of the Diffusion Pipeline. + """ + + def __init__(self, pipeline_name: str, pipeline_call_count: int) -> None: + self.pipeline_name = pipeline_name + self.pipeline_call_count = pipeline_call_count + columns = [] + if pipeline_name in SUPPORTED_MULTIMODAL_PIPELINES: + columns += SUPPORTED_MULTIMODAL_PIPELINES[pipeline_name]["table-schema"] + else: + wandb.Error("Pipeline not supported for logging") + self.wandb_table = wandb.Table(columns=columns) + + def __call__( + self, + args: Sequence[Any], + kwargs: Dict[str, Any], + response: Response, + start_time: float, + time_elapsed: float, + ) -> Any: + """Main call method for the `DiffusersPipelineResolver` class. + + Args: + args: (Sequence[Any]) List of arguments. + kwargs: (Dict[str, Any]) Dictionary of keyword arguments. + response: (wandb.sdk.integration_utils.auto_logging.Response) The response from + the request. + start_time: (float) Time when request started. + time_elapsed: (float) Time elapsed for the request. + + Returns: + Packed data as a dictionary for logging to wandb, None if an exception occurred. + """ + try: + # Get the pipeline and the args + pipeline, args = args[0], args[1:] + + # Update the Kwargs so that they can be logged easily + kwargs = get_updated_kwargs(pipeline, args, kwargs) + + # Get the pipeline configs + pipeline_configs = dict(pipeline.config) + pipeline_configs["pipeline-name"] = self.pipeline_name + + if "workflow" not in wandb.config: + wandb.config.update( + { + "workflow": [ + { + "pipeline": pipeline_configs, + "params": kwargs, + "stage": f"Pipeline-Call-{self.pipeline_call_count}", + } + ] + } + ) + else: + existing_workflow = wandb.config.workflow + updated_workflow = existing_workflow + [ + { + "pipeline": pipeline_configs, + "params": kwargs, + "stage": f"Pipeline-Call-{self.pipeline_call_count}", + } + ] + wandb.config.update( + {"workflow": updated_workflow}, allow_val_change=True + ) + + # Return the WandB loggable dict + return self.prepare_loggable_dict(pipeline, response, kwargs) + except Exception as e: + logger.warning(e) + return None + + def get_output_images(self, response: Response) -> List: + """Unpack the generated images, audio, video, etc. from the Diffusion Pipeline's response. + + Args: + response: (wandb.sdk.integration_utils.auto_logging.Response) The response from + the request. + + Returns: + List of generated images, audio, video, etc. + """ + if "output-type" not in SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]: + return response.images + else: + if ( + SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]["output-type"] + == "video" + ): + if self.pipeline_name in ["ShapEPipeline"]: + return response.images + return response.frames + elif ( + SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]["output-type"] + == "audio" + ): + return response.audios + + def log_media(self, image: Any, loggable_kwarg_chunks: List, idx: int) -> None: + """Log the generated images, audio, video, etc. from the Diffusion Pipeline's response along with an optional caption to a media panel in the run. + + Args: + image: (Any) The generated images, audio, video, etc. from the Diffusion + Pipeline's response. + loggable_kwarg_chunks: (List) Loggable chunks of kwargs. + """ + if "output-type" not in SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]: + try: + caption = "" + if self.pipeline_name in [ + "StableDiffusionXLPipeline", + "StableDiffusionXLImg2ImgPipeline", + ]: + prompt_index = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][ + "kwarg-logging" + ].index("prompt") + prompt2_index = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][ + "kwarg-logging" + ].index("prompt_2") + caption = f"Prompt-1: {loggable_kwarg_chunks[prompt_index][idx]}\nPrompt-2: {loggable_kwarg_chunks[prompt2_index][idx]}" + else: + prompt_index = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][ + "kwarg-logging" + ].index("prompt") + caption = loggable_kwarg_chunks[prompt_index][idx] + except ValueError: + caption = None + wandb.log( + { + f"Generated-Image/Pipeline-Call-{self.pipeline_call_count}": wandb.Image( + image, caption=caption + ) + } + ) + else: + if ( + SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]["output-type"] + == "video" + ): + try: + prompt_index = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][ + "kwarg-logging" + ].index("prompt") + caption = loggable_kwarg_chunks[prompt_index][idx] + except ValueError: + caption = None + wandb.log( + { + f"Generated-Video/Pipeline-Call-{self.pipeline_call_count}": wandb.Video( + postprocess_pils_to_np(image), fps=4, caption=caption + ) + } + ) + elif ( + SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]["output-type"] + == "audio" + ): + try: + prompt_index = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][ + "kwarg-logging" + ].index("prompt") + caption = loggable_kwarg_chunks[prompt_index][idx] + except ValueError: + caption = None + wandb.log( + { + f"Generated-Audio/Pipeline-Call-{self.pipeline_call_count}": wandb.Audio( + image, sample_rate=16000, caption=caption + ) + } + ) + + def add_data_to_table( + self, image: Any, loggable_kwarg_chunks: List, idx: int + ) -> None: + """Populate the row of the `wandb.Table`. + + Args: + image: (Any) The generated images, audio, video, etc. from the Diffusion + Pipeline's response. + loggable_kwarg_chunks: (List) Loggable chunks of kwargs. + idx: (int) Chunk index. + """ + table_row = [] + kwarg_actions = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][ + "kwarg-actions" + ] + for column_idx, loggable_kwarg_chunk in enumerate(loggable_kwarg_chunks): + if kwarg_actions[column_idx] is None: + table_row.append( + loggable_kwarg_chunk[idx] + if loggable_kwarg_chunk[idx] is not None + else "" + ) + else: + table_row.append(kwarg_actions[column_idx](loggable_kwarg_chunk[idx])) + if "output-type" not in SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]: + table_row.append(wandb.Image(image)) + else: + if ( + SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]["output-type"] + == "video" + ): + table_row.append(wandb.Video(postprocess_pils_to_np(image), fps=4)) + elif ( + SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name]["output-type"] + == "audio" + ): + table_row.append(wandb.Audio(image, sample_rate=16000)) + self.wandb_table.add_data(*table_row) + + def prepare_loggable_dict( + self, pipeline: Any, response: Response, kwargs: Dict[str, Any] + ) -> Dict[str, Any]: + """Prepare the loggable dictionary, which is the packed data as a dictionary for logging to wandb, None if an exception occurred. + + Args: + pipeline: (Any) The Diffusion Pipeline. + response: (wandb.sdk.integration_utils.auto_logging.Response) The response from + the request. + kwargs: (Dict[str, Any]) Dictionary of keyword arguments. + + Returns: + Packed data as a dictionary for logging to wandb, None if an exception occurred. + """ + # Unpack the generated images, audio, video, etc. from the Diffusion Pipeline's response. + images = self.get_output_images(response) + if ( + self.pipeline_name == "StableDiffusionXLPipeline" + and kwargs["output_type"] == "latent" + ): + images = decode_sdxl_t2i_latents(pipeline, response.images) + + # Account for exception pipelines for text-to-video + if self.pipeline_name in ["TextToVideoSDPipeline", "TextToVideoZeroPipeline"]: + video = postprocess_np_arrays_for_video( + images, normalize=self.pipeline_name == "TextToVideoZeroPipeline" + ) + wandb.log( + { + f"Generated-Video/Pipeline-Call-{self.pipeline_call_count}": wandb.Video( + video, fps=4, caption=kwargs["prompt"] + ) + } + ) + loggable_kwarg_ids = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][ + "kwarg-logging" + ] + table_row = [ + kwargs[loggable_kwarg_ids[idx]] + for idx in range(len(loggable_kwarg_ids)) + ] + table_row.append(wandb.Video(video, fps=4)) + self.wandb_table.add_data(*table_row) + else: + loggable_kwarg_ids = SUPPORTED_MULTIMODAL_PIPELINES[self.pipeline_name][ + "kwarg-logging" + ] + # chunkify loggable kwargs + loggable_kwarg_chunks = [] + for loggable_kwarg_id in loggable_kwarg_ids: + loggable_kwarg_chunks.append( + kwargs[loggable_kwarg_id] + if isinstance(kwargs[loggable_kwarg_id], list) + else [kwargs[loggable_kwarg_id]] + ) + # chunkify the generated media + images = chunkify(images, len(loggable_kwarg_chunks[0])) + for idx in range(len(loggable_kwarg_chunks[0])): + for image in images[idx]: + # Log media to media panel + self.log_media(image, loggable_kwarg_chunks, idx) + # Populate the row of the wandb_table + self.add_data_to_table(image, loggable_kwarg_chunks, idx) + return { + f"Result-Table/Pipeline-Call-{self.pipeline_call_count}": self.wandb_table + } diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/fastai/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/fastai/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d12d71d58183b0ce679c2bbb0e4e917fed791e2c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/fastai/__init__.py @@ -0,0 +1,243 @@ +"""Hooks that add fast.ai v1 Learners to Weights & Biases through a callback. + +Requested logged data can be configured through the callback constructor. + +Examples: + WandbCallback can be used when initializing the Learner:: + + ``` + from wandb.fastai import WandbCallback + [...] + learn = Learner(data, ..., callback_fns=WandbCallback) + learn.fit(epochs) + ``` + + Custom parameters can be given using functools.partial:: + + ``` + from wandb.fastai import WandbCallback + from functools import partial + [...] + learn = Learner(data, ..., callback_fns=partial(WandbCallback, ...)) + learn.fit(epochs) + ``` + + Finally, it is possible to use WandbCallback only when starting + training. In this case it must be instantiated:: + + ``` + learn.fit(..., callbacks=WandbCallback(learn)) + ``` + + or, with custom parameters:: + + ``` + learn.fit(..., callbacks=WandbCallback(learn, ...)) + ``` +""" + +import random +import sys +from pathlib import Path +from typing import Any, Literal, Optional + +import fastai +from fastai.callbacks import TrackerCallback + +import wandb +from wandb.sdk.lib import ipython + +try: + import matplotlib + + if not ipython.in_jupyter(): + matplotlib.use("Agg") # non-interactive backend (avoid tkinter issues) + import matplotlib.pyplot as plt +except ImportError: + wandb.termwarn("matplotlib required if logging sample image predictions") + + +class WandbCallback(TrackerCallback): + """Callback for saving model topology, losses & metrics. + + Optionally logs weights, gradients, sample predictions and best trained model. + + Args: + learn (fastai.basic_train.Learner): the fast.ai learner to hook. + log (str): "gradients", "parameters", "all", or None. Losses & metrics are always logged. + save_model (bool): save model at the end of each epoch. It will also load best model at the end of training. + monitor (str): metric to monitor for saving best model. None uses default TrackerCallback monitor value. + mode (str): "auto", "min" or "max" to compare "monitor" values and define best model. + input_type (str): "images" or None. Used to display sample predictions. + validation_data (list): data used for sample predictions if input_type is set. + predictions (int): number of predictions to make if input_type is set and validation_data is None. + seed (int): initialize random generator for sample predictions if input_type is set and validation_data is None. + """ + + # Record if watch has been called previously (even in another instance) + _watch_called = False + + def __init__( + self, + learn: "fastai.basic_train.Learner", + log: Optional[Literal["gradients", "parameters", "all"]] = "gradients", + save_model: bool = True, + monitor: Optional[str] = None, + mode: Literal["auto", "min", "max"] = "auto", + input_type: Optional[Literal["images"]] = None, + validation_data: Optional[list] = None, + predictions: int = 36, + seed: int = 12345, + ) -> None: + # Check if wandb.init has been called + if wandb.run is None: + raise ValueError("You must call wandb.init() before WandbCallback()") + + # Adapted from fast.ai "SaveModelCallback" + if monitor is None: + # use default TrackerCallback monitor value + super().__init__(learn, mode=mode) + else: + super().__init__(learn, monitor=monitor, mode=mode) + self.save_model = save_model + self.model_path = Path(wandb.run.dir) / "bestmodel.pth" + + self.log = log + self.input_type = input_type + self.best = None + + # Select items for sample predictions to see evolution along training + self.validation_data = validation_data + if input_type and not self.validation_data: + wandb_random = random.Random(seed) # For repeatability + predictions = min(predictions, len(learn.data.valid_ds)) + indices = wandb_random.sample(range(len(learn.data.valid_ds)), predictions) + self.validation_data = [learn.data.valid_ds[i] for i in indices] + + def on_train_begin(self, **kwargs: Any) -> None: + """Call watch method to log model topology, gradients & weights.""" + # Set self.best, method inherited from "TrackerCallback" by "SaveModelCallback" + super().on_train_begin() + + # Ensure we don't call "watch" multiple times + if not WandbCallback._watch_called: + WandbCallback._watch_called = True + + # Logs model topology and optionally gradients and weights + wandb.watch(self.learn.model, log=self.log) + + def on_epoch_end( + self, epoch: int, smooth_loss: float, last_metrics: list, **kwargs: Any + ) -> None: + """Log training loss, validation loss and custom metrics & log prediction samples & save model.""" + if self.save_model: + # Adapted from fast.ai "SaveModelCallback" + current = self.get_monitor_value() + if current is not None and self.operator(current, self.best): + wandb.termlog( + f"Better model found at epoch {epoch} with {self.monitor} value: {current}." + ) + self.best = current + + # Save within wandb folder + with self.model_path.open("wb") as model_file: + self.learn.save(model_file) + + # Log sample predictions if learn.predict is available + if self.validation_data: + try: + self._wandb_log_predictions() + except FastaiError as e: + wandb.termwarn(e.message) + self.validation_data = None # prevent from trying again on next loop + except Exception as e: + wandb.termwarn(f"Unable to log prediction samples.\n{e}") + self.validation_data = None # prevent from trying again on next loop + + # Log losses & metrics + # Adapted from fast.ai "CSVLogger" + logs = { + name: stat + for name, stat in list( + zip(self.learn.recorder.names, [epoch, smooth_loss] + last_metrics) + ) + } + wandb.log(logs) + + def on_train_end(self, **kwargs: Any) -> None: + """Load the best model.""" + if self.save_model: + # Adapted from fast.ai "SaveModelCallback" + if self.model_path.is_file(): + with self.model_path.open("rb") as model_file: + self.learn.load(model_file, purge=False) + wandb.termlog(f"Loaded best saved model from {self.model_path}") + + def _wandb_log_predictions(self) -> None: + """Log prediction samples.""" + pred_log = [] + + if self.validation_data is None: + return + + for x, y in self.validation_data: + try: + pred = self.learn.predict(x) + except Exception: + raise FastaiError( + 'Unable to run "predict" method from Learner to log prediction samples.' + ) + + # scalar -> likely to be a category + # tensor of dim 1 -> likely to be multicategory + if not pred[1].shape or pred[1].dim() == 1: + pred_log.append( + wandb.Image( + x.data, + caption=f"Ground Truth: {y}\nPrediction: {pred[0]}", + ) + ) + + # most vision datasets have a "show" function we can use + elif hasattr(x, "show"): + # log input data + pred_log.append(wandb.Image(x.data, caption="Input data", grouping=3)) + + # log label and prediction + for im, capt in ((pred[0], "Prediction"), (y, "Ground Truth")): + # Resize plot to image resolution + # from https://stackoverflow.com/a/13714915 + my_dpi = 100 + fig = plt.figure(frameon=False, dpi=my_dpi) + h, w = x.size + fig.set_size_inches(w / my_dpi, h / my_dpi) + ax = plt.Axes(fig, [0.0, 0.0, 1.0, 1.0]) + ax.set_axis_off() + fig.add_axes(ax) + + # Superpose label or prediction to input image + x.show(ax=ax, y=im) + pred_log.append(wandb.Image(fig, caption=capt)) + plt.close(fig) + + # likely to be an image + elif hasattr(y, "shape") and ( + (len(y.shape) == 2) or (len(y.shape) == 3 and y.shape[0] in [1, 3, 4]) + ): + pred_log.extend( + [ + wandb.Image(x.data, caption="Input data", grouping=3), + wandb.Image(pred[0].data, caption="Prediction"), + wandb.Image(y.data, caption="Ground Truth"), + ] + ) + + # we just log input data + else: + pred_log.append(wandb.Image(x.data, caption="Input data")) + + wandb.log({"Prediction Samples": pred_log}, commit=False) + + +class FastaiError(wandb.Error): + pass diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/gym/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/gym/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ec7aba187ddfeb067b9238d6d6641ca98e75c1f Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/gym/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/huggingface/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/huggingface/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..943249ebe22686fcbdfaa6708c33e15ec875bccc --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/huggingface/__init__.py @@ -0,0 +1,3 @@ +__all__ = ("autolog",) + +from .huggingface import autolog diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/huggingface/__pycache__/resolver.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/huggingface/__pycache__/resolver.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7ba79fc84ccd03d08079d124dddad59e88a836d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/huggingface/__pycache__/resolver.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/huggingface/huggingface.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/huggingface/huggingface.py new file mode 100644 index 0000000000000000000000000000000000000000..d44cf2cbb51d009821e26924ab944a953a1ff866 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/huggingface/huggingface.py @@ -0,0 +1,18 @@ +import logging + +from wandb.sdk.integration_utils.auto_logging import AutologAPI + +from .resolver import HuggingFacePipelineRequestResponseResolver + +logger = logging.getLogger(__name__) + +resolver = HuggingFacePipelineRequestResponseResolver() + +autolog = AutologAPI( + name="transformers", + symbols=("Pipeline.__call__",), + resolver=resolver, + telemetry_feature="hf_pipeline_autolog", +) + +autolog.get_latest_id = resolver.get_latest_id diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/huggingface/resolver.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/huggingface/resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..2acbdabe56e5e86c1d4442c99b7e9232d5621a48 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/huggingface/resolver.py @@ -0,0 +1,213 @@ +import logging +import os +from datetime import datetime +from typing import Any, Dict, List, Optional, Sequence, Tuple, Union + +import pytz + +import wandb +from wandb.sdk.integration_utils.auto_logging import Response +from wandb.sdk.lib.runid import generate_id + +logger = logging.getLogger(__name__) + +SUPPORTED_PIPELINE_TASKS = [ + "text-classification", + "sentiment-analysis", + "question-answering", + "summarization", + "translation", + "text2text-generation", + "text-generation", + # "conversational", +] + +PIPELINES_WITH_TOP_K = [ + "text-classification", + "sentiment-analysis", + "question-answering", +] + + +class HuggingFacePipelineRequestResponseResolver: + """Resolver for HuggingFace's pipeline request and responses, providing necessary data transformations and formatting. + + This is based off (from wandb.sdk.integration_utils.auto_logging import RequestResponseResolver) + """ + + autolog_id = None + + def __call__( + self, + args: Sequence[Any], + kwargs: Dict[str, Any], + response: Response, + start_time: float, + time_elapsed: float, + ) -> Optional[Dict[str, Any]]: + """Main call method for this class. + + :param args: list of arguments + :param kwargs: dictionary of keyword arguments + :param response: the response from the request + :param start_time: time when request started + :param time_elapsed: time elapsed for the request + :returns: packed data as a dictionary for logging to wandb, None if an exception occurred + """ + try: + pipe, input_data = args[:2] + task = pipe.task + + # Translation tasks are in the form of `translation_x_to_y` + if task in SUPPORTED_PIPELINE_TASKS or task.startswith("translation"): + model = self._get_model(pipe) + if model is None: + return None + model_alias = model.name_or_path + timestamp = datetime.now(pytz.utc) + + input_data, response = self._transform_task_specific_data( + task, input_data, response + ) + formatted_data = self._format_data(task, input_data, response, kwargs) + packed_data = self._create_table( + formatted_data, model_alias, timestamp, time_elapsed + ) + table_name = os.environ.get("WANDB_AUTOLOG_TABLE_NAME", f"{task}") + # TODO: Let users decide the name in a way that does not use an environment variable + + return { + table_name: wandb.Table( + columns=packed_data[0], data=packed_data[1:] + ) + } + + logger.warning( + f"The task: `{task}` is not yet supported.\nPlease contact `wandb` to notify us if you would like support for this task" + ) + except Exception as e: + logger.warning(e) + return None + + # TODO: This should have a dependency on PreTrainedModel. i.e. isinstance(PreTrainedModel) + # from transformers.modeling_utils import PreTrainedModel + # We do not want this dependency explicitly in our codebase so we make a very general + # assumption about the structure of the pipeline which may have unintended consequences + def _get_model(self, pipe) -> Optional[Any]: + """Extracts model from the pipeline. + + :param pipe: the HuggingFace pipeline + :returns: Model if available, None otherwise + """ + model = pipe.model + try: + return model.model + except AttributeError: + logger.info( + "Model does not have a `.model` attribute. Assuming `pipe.model` is the correct model." + ) + return model + + @staticmethod + def _transform_task_specific_data( + task: str, input_data: Union[List[Any], Any], response: Union[List[Any], Any] + ) -> Tuple[Union[List[Any], Any], Union[List[Any], Any]]: + """Transform input and response data based on specific tasks. + + :param task: the task name + :param input_data: the input data + :param response: the response data + :returns: tuple of transformed input_data and response + """ + if task == "question-answering": + input_data = input_data if isinstance(input_data, list) else [input_data] + input_data = [data.__dict__ for data in input_data] + elif task == "conversational": + # We only grab the latest input/output pair from the conversation + # Logging the whole conversation renders strangely. + input_data = input_data if isinstance(input_data, list) else [input_data] + input_data = [data.__dict__["past_user_inputs"][-1] for data in input_data] + + response = response if isinstance(response, list) else [response] + response = [data.__dict__["generated_responses"][-1] for data in response] + return input_data, response + + def _format_data( + self, + task: str, + input_data: Union[List[Any], Any], + response: Union[List[Any], Any], + kwargs: Dict[str, Any], + ) -> List[Dict[str, Any]]: + """Formats input data, response, and kwargs into a list of dictionaries. + + :param task: the task name + :param input_data: the input data + :param response: the response data + :param kwargs: dictionary of keyword arguments + :returns: list of dictionaries containing formatted data + """ + input_data = input_data if isinstance(input_data, list) else [input_data] + response = response if isinstance(response, list) else [response] + + formatted_data = [] + for i_text, r_text in zip(input_data, response): + # Unpack single element responses for better rendering in wandb UI when it is a task without top_k + # top_k = 1 would unpack the response into a single element while top_k > 1 would be a list + # this would cause the UI to not properly concatenate the tables of the same task by omitting the elements past the first + if ( + (isinstance(r_text, list)) + and (len(r_text) == 1) + and task not in PIPELINES_WITH_TOP_K + ): + r_text = r_text[0] + formatted_data.append( + {"input": i_text, "response": r_text, "kwargs": kwargs} + ) + return formatted_data + + def _create_table( + self, + formatted_data: List[Dict[str, Any]], + model_alias: str, + timestamp: float, + time_elapsed: float, + ) -> List[List[Any]]: + """Creates a table from formatted data, model alias, timestamp, and elapsed time. + + :param formatted_data: list of dictionaries containing formatted data + :param model_alias: alias of the model + :param timestamp: timestamp of the data + :param time_elapsed: time elapsed from the beginning + :returns: list of lists, representing a table of data. [0]th element = columns. [1]st element = data + """ + header = [ + "ID", + "Model Alias", + "Timestamp", + "Elapsed Time", + "Input", + "Response", + "Kwargs", + ] + table = [header] + autolog_id = generate_id(length=16) + + for data in formatted_data: + row = [ + autolog_id, + model_alias, + timestamp, + time_elapsed, + data["input"], + data["response"], + data["kwargs"], + ] + table.append(row) + + self.autolog_id = autolog_id + + return table + + def get_latest_id(self): + return self.autolog_id diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/keras/__pycache__/keras.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/keras/__pycache__/keras.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0351df1bc412782dc2916a655e75124af6025bac Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/keras/__pycache__/keras.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/keras/callbacks/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/keras/callbacks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6035bd4c9c5067e553404a5a4bb818ef582a36a8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/keras/callbacks/__init__.py @@ -0,0 +1,5 @@ +__all__ = ("WandbMetricsLogger", "WandbModelCheckpoint", "WandbEvalCallback") + +from .metrics_logger import WandbMetricsLogger +from .model_checkpoint import WandbModelCheckpoint +from .tables_builder import WandbEvalCallback diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/keras/callbacks/__pycache__/metrics_logger.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/keras/callbacks/__pycache__/metrics_logger.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3388f61361ed6864f05479bdca3ed953f5bd6f92 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/keras/callbacks/__pycache__/metrics_logger.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/keras/callbacks/__pycache__/model_checkpoint.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/keras/callbacks/__pycache__/model_checkpoint.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4d9af7a9960d80b6964d86f3a61dd899769896d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/keras/callbacks/__pycache__/model_checkpoint.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/keras/callbacks/__pycache__/tables_builder.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/keras/callbacks/__pycache__/tables_builder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7349fcdf8ade0d7660c31d1127399a2ba14f40b0 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/keras/callbacks/__pycache__/tables_builder.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/keras/callbacks/metrics_logger.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/keras/callbacks/metrics_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..b51f5bfd7af7a134268529d617fd68daf5adcce9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/keras/callbacks/metrics_logger.py @@ -0,0 +1,129 @@ +from typing import Any, Dict, Literal, Optional, Union + +import tensorflow as tf # type: ignore +from tensorflow.keras import callbacks + +import wandb +from wandb.integration.keras.keras import patch_tf_keras +from wandb.sdk.lib import telemetry + +LogStrategy = Literal["epoch", "batch"] + + +patch_tf_keras() + + +class WandbMetricsLogger(callbacks.Callback): + """Logger that sends system metrics to W&B. + + `WandbMetricsLogger` automatically logs the `logs` dictionary that callback methods + take as argument to wandb. + + This callback automatically logs the following to a W&B run page: + * system (CPU/GPU/TPU) metrics, + * train and validation metrics defined in `model.compile`, + * learning rate (both for a fixed value or a learning rate scheduler) + + Notes: + If you resume training by passing `initial_epoch` to `model.fit` and you are using a + learning rate scheduler, make sure to pass `initial_global_step` to + `WandbMetricsLogger`. The `initial_global_step` is `step_size * initial_step`, where + `step_size` is number of training steps per epoch. `step_size` can be calculated as + the product of the cardinality of the training dataset and the batch size. + + Args: + log_freq: ("epoch", "batch", or int) if "epoch", logs metrics + at the end of each epoch. If "batch", logs metrics at the end + of each batch. If an integer, logs metrics at the end of that + many batches. Defaults to "epoch". + initial_global_step: (int) Use this argument to correctly log the + learning rate when you resume training from some `initial_epoch`, + and a learning rate scheduler is used. This can be computed as + `step_size * initial_step`. Defaults to 0. + """ + + def __init__( + self, + log_freq: Union[LogStrategy, int] = "epoch", + initial_global_step: int = 0, + *args: Any, + **kwargs: Any, + ) -> None: + super().__init__(*args, **kwargs) + + if wandb.run is None: + raise wandb.Error( + "You must call `wandb.init()` before WandbMetricsLogger()" + ) + + with telemetry.context(run=wandb.run) as tel: + tel.feature.keras_metrics_logger = True + + if log_freq == "batch": + log_freq = 1 + + self.logging_batch_wise = isinstance(log_freq, int) + self.log_freq: Any = log_freq if self.logging_batch_wise else None + self.global_batch = 0 + self.global_step = initial_global_step + + if self.logging_batch_wise: + # define custom x-axis for batch logging. + wandb.define_metric("batch/batch_step") + # set all batch metrics to be logged against batch_step. + wandb.define_metric("batch/*", step_metric="batch/batch_step") + else: + # define custom x-axis for epoch-wise logging. + wandb.define_metric("epoch/epoch") + # set all epoch-wise metrics to be logged against epoch. + wandb.define_metric("epoch/*", step_metric="epoch/epoch") + + def _get_lr(self) -> Union[float, None]: + if isinstance( + self.model.optimizer.learning_rate, + (tf.Variable, tf.Tensor), + ) or ( + hasattr(self.model.optimizer.learning_rate, "shape") + and self.model.optimizer.learning_rate.shape == () + ): + return float(self.model.optimizer.learning_rate.numpy().item()) + try: + return float( + self.model.optimizer.learning_rate(step=self.global_step).numpy().item() + ) + except Exception as e: + wandb.termerror(f"Unable to log learning rate: {e}", repeat=False) + return None + + def on_epoch_end(self, epoch: int, logs: Optional[Dict[str, Any]] = None) -> None: + """Called at the end of an epoch.""" + logs = dict() if logs is None else {f"epoch/{k}": v for k, v in logs.items()} + + logs["epoch/epoch"] = epoch + + lr = self._get_lr() + if lr is not None: + logs["epoch/learning_rate"] = lr + + wandb.log(logs) + + def on_batch_end(self, batch: int, logs: Optional[Dict[str, Any]] = None) -> None: + self.global_step += 1 + """An alias for `on_train_batch_end` for backwards compatibility.""" + if self.logging_batch_wise and batch % self.log_freq == 0: + logs = {f"batch/{k}": v for k, v in logs.items()} if logs else {} + logs["batch/batch_step"] = self.global_batch + + lr = self._get_lr() + if lr is not None: + logs["batch/learning_rate"] = lr + + wandb.log(logs) + + self.global_batch += self.log_freq + + def on_train_batch_end( + self, batch: int, logs: Optional[Dict[str, Any]] = None + ) -> None: + """Called at the end of a training batch in `fit` methods.""" + self.on_batch_end(batch, logs if logs else {}) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/kfp/__pycache__/helpers.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/kfp/__pycache__/helpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55ccb7aa22e6c5c2bb0d4b621e889607659235a2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/kfp/__pycache__/helpers.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/kfp/helpers.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/kfp/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..feebcc62ea3688a2a93818adb445f6454a6d9dc2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/kfp/helpers.py @@ -0,0 +1,28 @@ +import json + + +def add_wandb_visualization(run, mlpipeline_ui_metadata_path): + """NOTE: To use this, you must modify your component to have an output called `mlpipeline_ui_metadata_path` AND call `wandb.init` yourself inside that component. + + Example usage: + + def my_component(..., mlpipeline_ui_metadata_path: OutputPath()): + import wandb + from wandb.integration.kfp.helpers import add_wandb_visualization + + with wandb.init() as run: + add_wandb_visualization(run, mlpipeline_ui_metadata_path) + + ... # the rest of your code here + """ + + def get_iframe_html(run): + return f'' + + iframe_html = get_iframe_html(run) + metadata = { + "outputs": [{"type": "markdown", "storage": "inline", "source": iframe_html}] + } + + with open(mlpipeline_ui_metadata_path, "w") as metadata_file: + json.dump(metadata, metadata_file) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/kfp/wandb_logging.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/kfp/wandb_logging.py new file mode 100644 index 0000000000000000000000000000000000000000..5d0edf3eac211b59908bc3aa4849a459c2da2148 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/kfp/wandb_logging.py @@ -0,0 +1,182 @@ +def wandb_log( # noqa: C901 + func=None, + # /, # py38 only + log_component_file=True, +): + """Wrap a standard python function and log to W&B.""" + import json + import os + from functools import wraps + from inspect import Parameter, signature + + from kfp import components + from kfp.components import ( + InputArtifact, + InputBinaryFile, + InputPath, + InputTextFile, + OutputArtifact, + OutputBinaryFile, + OutputPath, + OutputTextFile, + ) + + import wandb + from wandb.sdk.lib import telemetry as wb_telemetry + + output_types = (OutputArtifact, OutputBinaryFile, OutputPath, OutputTextFile) + input_types = (InputArtifact, InputBinaryFile, InputPath, InputTextFile) + + def isinstance_namedtuple(x): + t = type(x) + b = t.__bases__ + if len(b) != 1 or b[0] is not tuple: + return False + f = getattr(t, "_fields", None) + if not isinstance(f, tuple): + return False + return all(isinstance(n, str) for n in f) + + def get_iframe_html(run): + return f'' + + def get_link_back_to_kubeflow(): + wandb_kubeflow_url = os.getenv("WANDB_KUBEFLOW_URL") + return f"{wandb_kubeflow_url}/#/runs/details/{{workflow.uid}}" + + def log_input_scalar(name, data, run=None): + run.config[name] = data + wandb.termlog(f"Setting config: {name} to {data}") + + def log_input_artifact(name, data, type, run=None): + artifact = wandb.Artifact(name, type=type) + artifact.add_file(data) + run.use_artifact(artifact) + wandb.termlog(f"Using artifact: {name}") + + def log_output_scalar(name, data, run=None): + if isinstance_namedtuple(data): + for k, v in zip(data._fields, data): + run.log({f"{func.__name__}.{k}": v}) + else: + run.log({name: data}) + + def log_output_artifact(name, data, type, run=None): + artifact = wandb.Artifact(name, type=type) + artifact.add_file(data) + run.log_artifact(artifact) + wandb.termlog(f"Logging artifact: {name}") + + def _log_component_file(func, run=None): + name = func.__name__ + output_component_file = f"{name}.yml" + components._python_op.func_to_component_file(func, output_component_file) + artifact = wandb.Artifact(name, type="kubeflow_component_file") + artifact.add_file(output_component_file) + run.log_artifact(artifact) + wandb.termlog(f"Logging component file: {output_component_file}") + + # Add `mlpipeline_ui_metadata_path` to signature to show W&B run in "ML Visualizations tab" + sig = signature(func) + no_default = [] + has_default = [] + + for param in sig.parameters.values(): + if param.default is param.empty: + no_default.append(param) + else: + has_default.append(param) + + new_params = tuple( + ( + *no_default, + Parameter( + "mlpipeline_ui_metadata_path", + annotation=OutputPath(), + kind=Parameter.POSITIONAL_OR_KEYWORD, + ), + *has_default, + ) + ) + new_sig = sig.replace(parameters=new_params) + new_anns = {param.name: param.annotation for param in new_params} + if "return" in func.__annotations__: + new_anns["return"] = func.__annotations__["return"] + + def decorator(func): + input_scalars = {} + input_artifacts = {} + output_scalars = {} + output_artifacts = {} + + for name, ann in func.__annotations__.items(): + if name == "return": + output_scalars[name] = ann + elif isinstance(ann, output_types): + output_artifacts[name] = ann + elif isinstance(ann, input_types): + input_artifacts[name] = ann + else: + input_scalars[name] = ann + + @wraps(func) + def wrapper(*args, **kwargs): + bound = new_sig.bind(*args, **kwargs) + bound.apply_defaults() + + mlpipeline_ui_metadata_path = bound.arguments["mlpipeline_ui_metadata_path"] + del bound.arguments["mlpipeline_ui_metadata_path"] + + with wandb.init( + job_type=func.__name__, + group="{{workflow.annotations.pipelines.kubeflow.org/run_name}}", + ) as run: + # Link back to the kfp UI + kubeflow_url = get_link_back_to_kubeflow() + run.notes = kubeflow_url + run.config["LINK_TO_KUBEFLOW_RUN"] = kubeflow_url + + iframe_html = get_iframe_html(run) + metadata = { + "outputs": [ + { + "type": "markdown", + "storage": "inline", + "source": iframe_html, + } + ] + } + + with open(mlpipeline_ui_metadata_path, "w") as metadata_file: + json.dump(metadata, metadata_file) + + if log_component_file: + _log_component_file(func, run=run) + + for name, _ in input_scalars.items(): + log_input_scalar(name, kwargs[name], run) + + for name, ann in input_artifacts.items(): + log_input_artifact(name, kwargs[name], ann.type, run) + + with wb_telemetry.context(run=run) as tel: + tel.feature.kfp_wandb_log = True + + result = func(*bound.args, **bound.kwargs) + + for name, _ in output_scalars.items(): + log_output_scalar(name, result, run) + + for name, ann in output_artifacts.items(): + log_output_artifact(name, kwargs[name], ann.type, run) + + return result + + wrapper.__signature__ = new_sig + wrapper.__annotations__ = new_anns + return wrapper + + if func is None: + return decorator + else: + return decorator(func) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/langchain/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/langchain/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f2b2597b7e74003f558bc8ec4b534d5035cdd12 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/langchain/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/langchain/__pycache__/wandb_tracer.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/langchain/__pycache__/wandb_tracer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b0aa04a032f00b6d6a3b0119b2ff6a5710da4f2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/langchain/__pycache__/wandb_tracer.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/lightgbm/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/lightgbm/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4af918da6fa6fb122b03dda4877121d0955f7d9 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/lightgbm/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/lightning/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/lightning/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/lightning/fabric/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/lightning/fabric/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eff7554e1131034c637c8cfef591756211b8a898 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/lightning/fabric/__init__.py @@ -0,0 +1,3 @@ +from wandb.integration.lightning.fabric.logger import WandbLogger + +__all__ = ("WandbLogger",) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/lightning/fabric/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/lightning/fabric/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c19fd800cb3c015bac63728aefeef551e1e7e2f2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/lightning/fabric/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/lightning/fabric/logger.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/lightning/fabric/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..21e326241c75ecfedb2ceb5cd8e39b0bc1c0b0f2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/lightning/fabric/logger.py @@ -0,0 +1,763 @@ +import os +from argparse import Namespace +from pathlib import Path +from typing import TYPE_CHECKING, Any, Dict, List, Literal, Mapping, Optional, Union + +from packaging import version +from typing_extensions import override + +import wandb +from wandb import Artifact +from wandb.sdk.lib import telemetry + +try: + import lightning + import torch.nn as nn + from lightning.fabric.loggers.logger import Logger, rank_zero_experiment + from lightning.fabric.utilities.exceptions import MisconfigurationException + from lightning.fabric.utilities.logger import ( + _add_prefix, + _convert_params, + _sanitize_callable_params, + ) + from lightning.fabric.utilities.rank_zero import rank_zero_only, rank_zero_warn + from lightning.fabric.utilities.types import _PATH + from torch import Tensor + from torch.nn import Module + + if version.parse(lightning.__version__) > version.parse("2.1.3"): + wandb.termwarn( + """This integration is tested and supported for lightning Fabric 2.1.3. + Please report any issues to https://github.com/wandb/wandb/issues with the tag `lightning-fabric`.""", + repeat=False, + ) + + if TYPE_CHECKING: + from lightning.pytorch.callbacks.model_checkpoint import ModelCheckpoint + +except ImportError as e: + wandb.Error(e) + + +class WandbLogger(Logger): + r"""Log using `Weights and Biases `_. + + **Installation and set-up** + + Install with pip: + + .. code-block:: bash + + pip install wandb + + Create a `WandbLogger` instance: + + .. code-block:: python + + from lightning.fabric.loggers import WandbLogger + + wandb_logger = WandbLogger(project="MNIST") + + Pass the logger instance to the `Trainer`: + + .. code-block:: python + + trainer = Trainer(logger=wandb_logger) + + A new W&B run will be created when training starts if you have not created one manually before with `wandb.init()`. + + **Log metrics** + + Log from :class:`~lightning.pytorch.core.LightningModule`: + + .. code-block:: python + + class LitModule(LightningModule): + def training_step(self, batch, batch_idx): + self.log("train/loss", loss) + + Use directly wandb module: + + .. code-block:: python + + wandb.log({"train/loss": loss}) + + **Log hyper-parameters** + + Save :class:`~lightning.pytorch.core.LightningModule` parameters: + + .. code-block:: python + + class LitModule(LightningModule): + def __init__(self, *args, **kwarg): + self.save_hyperparameters() + + Add other config parameters: + + .. code-block:: python + + # add one parameter + wandb_logger.experiment.config["key"] = value + + # add multiple parameters + wandb_logger.experiment.config.update({key1: val1, key2: val2}) + + # use directly wandb module + wandb.config["key"] = value + wandb.config.update() + + **Log gradients, parameters and model topology** + + Call the `watch` method for automatically tracking gradients: + + .. code-block:: python + + # log gradients and model topology + wandb_logger.watch(model) + + # log gradients, parameter histogram and model topology + wandb_logger.watch(model, log="all") + + # change log frequency of gradients and parameters (100 steps by default) + wandb_logger.watch(model, log_freq=500) + + # do not log graph (in case of errors) + wandb_logger.watch(model, log_graph=False) + + The `watch` method adds hooks to the model which can be removed at the end of training: + + .. code-block:: python + + wandb_logger.experiment.unwatch(model) + + **Log model checkpoints** + + Log model checkpoints at the end of training: + + .. code-block:: python + + wandb_logger = WandbLogger(log_model=True) + + Log model checkpoints as they get created during training: + + .. code-block:: python + + wandb_logger = WandbLogger(log_model="all") + + Custom checkpointing can be set up through :class:`~lightning.pytorch.callbacks.ModelCheckpoint`: + + .. code-block:: python + + # log model only if `val_accuracy` increases + wandb_logger = WandbLogger(log_model="all") + checkpoint_callback = ModelCheckpoint(monitor="val_accuracy", mode="max") + trainer = Trainer(logger=wandb_logger, callbacks=[checkpoint_callback]) + + `latest` and `best` aliases are automatically set to easily retrieve a model checkpoint: + + .. code-block:: python + + # reference can be retrieved in artifacts panel + # "VERSION" can be a version (ex: "v2") or an alias ("latest or "best") + checkpoint_reference = "USER/PROJECT/MODEL-RUN_ID:VERSION" + + # download checkpoint locally (if not already cached) + run = wandb.init(project="MNIST") + artifact = run.use_artifact(checkpoint_reference, type="model") + artifact_dir = artifact.download() + + # load checkpoint + model = LitModule.load_from_checkpoint(Path(artifact_dir) / "model.ckpt") + + **Log media** + + Log text with: + + .. code-block:: python + + # using columns and data + columns = ["input", "label", "prediction"] + data = [["cheese", "english", "english"], ["fromage", "french", "spanish"]] + wandb_logger.log_text(key="samples", columns=columns, data=data) + + # using a pandas DataFrame + wandb_logger.log_text(key="samples", dataframe=my_dataframe) + + Log images with: + + .. code-block:: python + + # using tensors, numpy arrays or PIL images + wandb_logger.log_image(key="samples", images=[img1, img2]) + + # adding captions + wandb_logger.log_image( + key="samples", images=[img1, img2], caption=["tree", "person"] + ) + + # using file path + wandb_logger.log_image(key="samples", images=["img_1.jpg", "img_2.jpg"]) + + More arguments can be passed for logging segmentation masks and bounding boxes. Refer to + `Image Overlays documentation `_. + + **Log Tables** + + `W&B Tables `_ can be used to log, + query and analyze tabular data. + + They support any type of media (text, image, video, audio, molecule, html, etc) and are great for storing, + understanding and sharing any form of data, from datasets to model predictions. + + .. code-block:: python + + columns = ["caption", "image", "sound"] + data = [ + ["cheese", wandb.Image(img_1), wandb.Audio(snd_1)], + ["wine", wandb.Image(img_2), wandb.Audio(snd_2)], + ] + wandb_logger.log_table(key="samples", columns=columns, data=data) + + + **Downloading and Using Artifacts** + + To download an artifact without starting a run, call the ``download_artifact`` + function on the class: + + .. code-block:: python + + artifact_dir = wandb_logger.download_artifact(artifact="path/to/artifact") + + To download an artifact and link it to an ongoing run call the ``download_artifact`` + function on the logger instance: + + .. code-block:: python + + class MyModule(LightningModule): + def any_lightning_module_function_or_hook(self): + self.logger.download_artifact(artifact="path/to/artifact") + + To link an artifact from a previous run you can use ``use_artifact`` function: + + .. code-block:: python + + wandb_logger.use_artifact(artifact="path/to/artifact") + + See Also: + - `Demo in Google Colab `__ with hyperparameter search and model logging + - `W&B Documentation `__ + + Args: + name: Display name for the run. + save_dir: Path where data is saved. + version: Sets the version, mainly used to resume a previous run. + offline: Run offline (data can be streamed later to wandb servers). + dir: Same as save_dir. + id: Same as version. + anonymous: Enables or explicitly disables anonymous logging. + project: The name of the project to which this run will belong. If not set, the environment variable + `WANDB_PROJECT` will be used as a fallback. If both are not set, it defaults to ``'lightning_logs'``. + log_model: Log checkpoints created by :class:`~lightning.pytorch.callbacks.ModelCheckpoint` + as W&B artifacts. `latest` and `best` aliases are automatically set. + + * if ``log_model == 'all'``, checkpoints are logged during training. + * if ``log_model == True``, checkpoints are logged at the end of training, except when + `~lightning.pytorch.callbacks.ModelCheckpoint.save_top_k` ``== -1`` + which also logs every checkpoint during training. + * if ``log_model == False`` (default), no checkpoint is logged. + + prefix: A string to put at the beginning of metric keys. + experiment: WandB experiment object. Automatically set when creating a run. + checkpoint_name: Name of the model checkpoint artifact being logged. + log_checkpoint_on: When to log model checkpoints as W&B artifacts. Only used if ``log_model`` is ``True``. + Options: ``"success"``, ``"all"``. Default: ``"success"``. + \**kwargs: Arguments passed to :func:`wandb.init` like `entity`, `group`, `tags`, etc. + + Raises: + ModuleNotFoundError: + If required WandB package is not installed on the device. + MisconfigurationException: + If both ``log_model`` and ``offline`` is set to ``True``. + + """ + + LOGGER_JOIN_CHAR = "-" + + def __init__( + self, + name: Optional[str] = None, + save_dir: _PATH = ".", + version: Optional[str] = None, + offline: bool = False, + dir: Optional[_PATH] = None, + id: Optional[str] = None, + anonymous: Optional[bool] = None, + project: Optional[str] = None, + log_model: Union[Literal["all"], bool] = False, + experiment: Optional["wandb.Run"] = None, + prefix: str = "", + checkpoint_name: Optional[str] = None, + log_checkpoint_on: Union[Literal["success"], Literal["all"]] = "success", + **kwargs: Any, + ) -> None: + if offline and log_model: + raise MisconfigurationException( + f"Providing log_model={log_model} and offline={offline} is an invalid configuration" + " since model checkpoints cannot be uploaded in offline mode.\n" + "Hint: Set `offline=False` to log your model." + ) + + super().__init__() + self._offline = offline + self._log_model = log_model + self._prefix = prefix + self._experiment = experiment + self._logged_model_time: Dict[str, float] = {} + self._checkpoint_callback: Optional[ModelCheckpoint] = None + + # paths are processed as strings + if save_dir is not None: + save_dir = os.fspath(save_dir) + elif dir is not None: + dir = os.fspath(dir) + + project = project or os.environ.get("WANDB_PROJECT", "lightning_fabric_logs") + + # set wandb init arguments + self._wandb_init: Dict[str, Any] = { + "name": name, + "project": project, + "dir": save_dir or dir, + "id": version or id, + "resume": "allow", + "anonymous": ("allow" if anonymous else None), + } + self._wandb_init.update(**kwargs) + # extract parameters + self._project = self._wandb_init.get("project") + self._save_dir = self._wandb_init.get("dir") + self._name = self._wandb_init.get("name") + self._id = self._wandb_init.get("id") + self._checkpoint_name = checkpoint_name + self._log_checkpoint_on = log_checkpoint_on + + def __getstate__(self) -> Dict[str, Any]: + # Hack: If the 'spawn' launch method is used, the logger will get pickled and this `__getstate__` gets called. + # We create an experiment here in the main process, and attach to it in the worker process. + # Using wandb-service, we persist the same experiment even if multiple `Trainer.fit/test/validate` calls + # are made. + _ = self.experiment + + state = self.__dict__.copy() + # args needed to reload correct experiment + if self._experiment is not None: + state["_id"] = getattr(self._experiment, "id", None) + state["_attach_id"] = getattr(self._experiment, "_attach_id", None) + state["_name"] = self._experiment.name + + # cannot be pickled + state["_experiment"] = None + return state + + @property + @rank_zero_experiment + def experiment(self) -> "wandb.Run": + r"""Actual wandb object. + + To use wandb features in your :class:`~lightning.pytorch.core.LightningModule`, do the + following. + + Example:: + + .. code-block:: python + + self.logger.experiment.some_wandb_function() + + """ + if self._experiment is None: + if self._offline: + os.environ["WANDB_MODE"] = "dryrun" + + attach_id = getattr(self, "_attach_id", None) + if wandb.run is not None: + # wandb process already created in this instance + rank_zero_warn( + "There is a wandb run already in progress and newly created instances of `WandbLogger` will reuse" + " this run. If this is not desired, call `wandb.finish()` before instantiating `WandbLogger`." + ) + self._experiment = wandb.run + elif attach_id is not None and hasattr(wandb, "_attach"): + # attach to wandb process referenced + self._experiment = wandb._attach(attach_id) + else: + # create new wandb process + self._experiment = wandb.init(**self._wandb_init) + + # define default x-axis + if isinstance(self._experiment, wandb.Run) and getattr( + self._experiment, "define_metric", None + ): + self._experiment.define_metric("trainer/global_step") + self._experiment.define_metric( + "*", step_metric="trainer/global_step", step_sync=True + ) + + self._experiment._label(repo="lightning_fabric_logger") # pylint: disable=protected-access + with telemetry.context(run=self._experiment) as tel: + tel.feature.lightning_fabric_logger = True + return self._experiment + + def watch( + self, + model: nn.Module, + log: str = "gradients", + log_freq: int = 100, + log_graph: bool = True, + ) -> None: + self.experiment.watch(model, log=log, log_freq=log_freq, log_graph=log_graph) + + @override + @rank_zero_only + def log_hyperparams(self, params: Union[Dict[str, Any], Namespace]) -> None: # type: ignore[override] + params = _convert_params(params) + params = _sanitize_callable_params(params) + self.experiment.config.update(params, allow_val_change=True) + + @override + @rank_zero_only + def log_metrics( + self, metrics: Mapping[str, float], step: Optional[int] = None + ) -> None: + assert rank_zero_only.rank == 0, "experiment tried to log from global_rank != 0" + + metrics = _add_prefix(metrics, self._prefix, self.LOGGER_JOIN_CHAR) + if step is not None: + self.experiment.log(dict(metrics, **{"trainer/global_step": step})) + else: + self.experiment.log(metrics) + + @rank_zero_only + def log_table( + self, + key: str, + columns: Optional[List[str]] = None, + data: Optional[List[List[Any]]] = None, + dataframe: Any = None, + step: Optional[int] = None, + ) -> None: + """Log a Table containing any object type (text, image, audio, video, molecule, html, etc). + + Can be defined either with `columns` and `data` or with `dataframe`. + + """ + metrics = {key: wandb.Table(columns=columns, data=data, dataframe=dataframe)} + self.log_metrics(metrics, step) + + @rank_zero_only + def log_text( + self, + key: str, + columns: Optional[List[str]] = None, + data: Optional[List[List[str]]] = None, + dataframe: Any = None, + step: Optional[int] = None, + ) -> None: + """Log text as a Table. + + Can be defined either with `columns` and `data` or with `dataframe`. + + """ + self.log_table(key, columns, data, dataframe, step) + + @rank_zero_only + def log_html( + self, key: str, htmls: List[Any], step: Optional[int] = None, **kwargs: Any + ) -> None: + """Log html files. + + Optional kwargs are lists passed to each html (ex: inject). + + """ + if not isinstance(htmls, list): + raise TypeError(f'Expected a list as "htmls", found {type(htmls)}') + n = len(htmls) + for k, v in kwargs.items(): + if len(v) != n: + raise ValueError(f"Expected {n} items but only found {len(v)} for {k}") + kwarg_list = [{k: kwargs[k][i] for k in kwargs} for i in range(n)] + + metrics = { + key: [wandb.Html(html, **kwarg) for html, kwarg in zip(htmls, kwarg_list)] + } + self.log_metrics(metrics, step) # type: ignore[arg-type] + + @rank_zero_only + def log_image( + self, key: str, images: List[Any], step: Optional[int] = None, **kwargs: Any + ) -> None: + """Log images (tensors, numpy arrays, PIL Images or file paths). + + Optional kwargs are lists passed to each image (ex: caption, masks, boxes). + + """ + if not isinstance(images, list): + raise TypeError(f'Expected a list as "images", found {type(images)}') + n = len(images) + for k, v in kwargs.items(): + if len(v) != n: + raise ValueError(f"Expected {n} items but only found {len(v)} for {k}") + kwarg_list = [{k: kwargs[k][i] for k in kwargs} for i in range(n)] + + metrics = { + key: [wandb.Image(img, **kwarg) for img, kwarg in zip(images, kwarg_list)] + } + self.log_metrics(metrics, step) # type: ignore[arg-type] + + @rank_zero_only + def log_audio( + self, key: str, audios: List[Any], step: Optional[int] = None, **kwargs: Any + ) -> None: + r"""Log audios (numpy arrays, or file paths). + + Args: + key: The key to be used for logging the audio files + audios: The list of audio file paths, or numpy arrays to be logged + step: The step number to be used for logging the audio files + \**kwargs: Optional kwargs are lists passed to each ``Wandb.Audio`` instance (ex: caption, sample_rate). + + Optional kwargs are lists passed to each audio (ex: caption, sample_rate). + + """ + if not isinstance(audios, list): + raise TypeError(f'Expected a list as "audios", found {type(audios)}') + n = len(audios) + for k, v in kwargs.items(): + if len(v) != n: + raise ValueError(f"Expected {n} items but only found {len(v)} for {k}") + kwarg_list = [{k: kwargs[k][i] for k in kwargs} for i in range(n)] + + metrics = { + key: [ + wandb.Audio(audio, **kwarg) for audio, kwarg in zip(audios, kwarg_list) + ] + } + self.log_metrics(metrics, step) # type: ignore[arg-type] + + @rank_zero_only + def log_video( + self, key: str, videos: List[Any], step: Optional[int] = None, **kwargs: Any + ) -> None: + """Log videos (numpy arrays, or file paths). + + Args: + key: The key to be used for logging the video files + videos: The list of video file paths, or numpy arrays to be logged + step: The step number to be used for logging the video files + **kwargs: Optional kwargs are lists passed to each Wandb.Video instance (ex: caption, fps, format). + + Optional kwargs are lists passed to each video (ex: caption, fps, format). + + """ + if not isinstance(videos, list): + raise TypeError(f'Expected a list as "videos", found {type(videos)}') + n = len(videos) + for k, v in kwargs.items(): + if len(v) != n: + raise ValueError(f"Expected {n} items but only found {len(v)} for {k}") + kwarg_list = [{k: kwargs[k][i] for k in kwargs} for i in range(n)] + + metrics = { + key: [ + wandb.Video(video, **kwarg) for video, kwarg in zip(videos, kwarg_list) + ] + } + self.log_metrics(metrics, step) # type: ignore[arg-type] + + @property + @override + def save_dir(self) -> Optional[str]: + """Gets the save directory. + + Returns: + The path to the save directory. + + """ + return self._save_dir + + @property + @override + def name(self) -> Optional[str]: + """The project name of this experiment. + + Returns: + The name of the project the current experiment belongs to. This name is not the same as `wandb.Run`'s + name. To access wandb's internal experiment name, use ``logger.experiment.name`` instead. + + """ + return self._project + + @property + @override + def version(self) -> Optional[str]: + """Gets the id of the experiment. + + Returns: + The id of the experiment if the experiment exists else the id given to the constructor. + + """ + # don't create an experiment if we don't have one + return self._experiment.id if self._experiment else self._id + + @property + def log_dir(self) -> Optional[str]: + """Gets the save directory. + + Returns: + The path to the save directory. + + """ + return self.save_dir + + @property + def group_separator(self) -> str: + """Return the default separator used by the logger to group the data into subfolders.""" + return self.LOGGER_JOIN_CHAR + + @property + def root_dir(self) -> Optional[str]: + """Return the root directory. + + Return the root directory where all versions of an experiment get saved, or `None` if the logger does not + save data locally. + """ + return self.save_dir.parent if self.save_dir else None + + def log_graph(self, model: Module, input_array: Optional[Tensor] = None) -> None: + """Record model graph. + + Args: + model: the model with an implementation of ``forward``. + input_array: input passes to `model.forward` + + This is a noop function and does not perform any operation. + """ + return + + @override + def after_save_checkpoint(self, checkpoint_callback: "ModelCheckpoint") -> None: + # log checkpoints as artifacts + if ( + self._log_model == "all" + or self._log_model is True + and checkpoint_callback.save_top_k == -1 + ): + # TODO: Replace with new Fabric Checkpoints system + self._scan_and_log_pytorch_checkpoints(checkpoint_callback) + elif self._log_model is True: + self._checkpoint_callback = checkpoint_callback + + @staticmethod + @rank_zero_only + def download_artifact( + artifact: str, + save_dir: Optional[_PATH] = None, + artifact_type: Optional[str] = None, + use_artifact: Optional[bool] = True, + ) -> str: + """Downloads an artifact from the wandb server. + + Args: + artifact: The path of the artifact to download. + save_dir: The directory to save the artifact to. + artifact_type: The type of artifact to download. + use_artifact: Whether to add an edge between the artifact graph. + + Returns: + The path to the downloaded artifact. + + """ + if wandb.run is not None and use_artifact: + artifact = wandb.run.use_artifact(artifact) + else: + api = wandb.Api() + artifact = api.artifact(artifact, type=artifact_type) + + save_dir = None if save_dir is None else os.fspath(save_dir) + return artifact.download(root=save_dir) + + def use_artifact( + self, artifact: str, artifact_type: Optional[str] = None + ) -> "Artifact": + """Logs to the wandb dashboard that the mentioned artifact is used by the run. + + Args: + artifact: The path of the artifact. + artifact_type: The type of artifact being used. + + Returns: + wandb Artifact object for the artifact. + + """ + return self.experiment.use_artifact(artifact, type=artifact_type) + + @override + @rank_zero_only + def save(self) -> None: + """Save log data.""" + self.experiment.log({}, commit=True) + + @override + @rank_zero_only + def finalize(self, status: str) -> None: + if self._log_checkpoint_on == "success" and status != "success": + # Currently, checkpoints only get logged on success + return + # log checkpoints as artifacts + if ( + self._checkpoint_callback + and self._experiment is not None + and self._log_checkpoint_on in ["success", "all"] + ): + self._scan_and_log_pytorch_checkpoints(self._checkpoint_callback) + + def _scan_and_log_pytorch_checkpoints( + self, checkpoint_callback: "ModelCheckpoint" + ) -> None: + from lightning.pytorch.loggers.utilities import _scan_checkpoints + + # get checkpoints to be saved with associated score + checkpoints = _scan_checkpoints(checkpoint_callback, self._logged_model_time) + + # log iteratively all new checkpoints + for t, p, s, _ in checkpoints: + metadata = { + "score": s.item() if isinstance(s, Tensor) else s, + "original_filename": Path(p).name, + checkpoint_callback.__class__.__name__: { + k: getattr(checkpoint_callback, k) + for k in [ + "monitor", + "mode", + "save_last", + "save_top_k", + "save_weights_only", + "_every_n_train_steps", + ] + # ensure it does not break if `ModelCheckpoint` args change + if hasattr(checkpoint_callback, k) + }, + } + if not self._checkpoint_name: + self._checkpoint_name = f"model-{self.experiment.id}" + artifact = wandb.Artifact( + name=self._checkpoint_name, type="model", metadata=metadata + ) + artifact.add_file(p, name="model.ckpt") + aliases = ( + ["latest", "best"] + if p == checkpoint_callback.best_model_path + else ["latest"] + ) + self.experiment.log_model(artifact, aliases=aliases) + # remember logged models - timestamp needed in case filename didn't change (lastkckpt or custom name) + self._logged_model_time[p] = t diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/metaflow/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/metaflow/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65b688b438f8e7d0a70a785086db980a0c120e1e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/metaflow/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/metaflow/__pycache__/errors.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/metaflow/__pycache__/errors.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5be6725ae1784f8fa3a69042938a6b095167d5fe Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/metaflow/__pycache__/errors.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/metaflow/__pycache__/metaflow.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/metaflow/__pycache__/metaflow.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa3ca271ef77bac2d2eb84b235ad80c43070403a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/metaflow/__pycache__/metaflow.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/metaflow/errors.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/metaflow/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..3b0a3ae962cdadde195fa31c6efb4f3d0cc07d5b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/metaflow/errors.py @@ -0,0 +1,13 @@ +import wandb + + +class MissingDependencyError(Exception): + """An optional dependency is missing.""" + + def __init__(self, *args: object, warning: str) -> None: + super().__init__(*args) + self._wb_warning = warning + + def warn(self) -> None: + """Print a warning for the problem.""" + wandb.termwarn(self._wb_warning) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/metaflow/metaflow.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/metaflow/metaflow.py new file mode 100644 index 0000000000000000000000000000000000000000..1aa5579eebb05f308e78dab56b48c35e8e621cbb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/metaflow/metaflow.py @@ -0,0 +1,398 @@ +import inspect +import pickle +from functools import wraps +from pathlib import Path +from typing import Optional, Union + +import wandb +from wandb.sdk.lib import telemetry as wb_telemetry + +from . import errors + +try: + from metaflow import current +except ImportError as e: + raise Exception( + "Error: `metaflow` not installed >> This integration requires metaflow!" + " To fix, please `pip install -Uqq metaflow`" + ) from e + + +# Classes for isinstance() checks. +_NN_MODULE = None +_BASE_ESTIMATOR = None + +try: + from . import data_pandas +except errors.MissingDependencyError as e: + e.warn() + data_pandas = None + +try: + import torch + import torch.nn as nn + + _NN_MODULE = nn.Module + + def _use_torch_module( + name: str, + data: nn.Module, + run, + testing: bool = False, + ) -> Optional[str]: + if testing: + return "models" + + run.use_artifact(f"{name}:latest") + wandb.termlog(f"Using artifact: {name} ({type(data)})") + return None + + def _track_torch_module( + name: str, + data: nn.Module, + run, + testing: bool = False, + ) -> Optional[str]: + if testing: + return "nn.Module" + + artifact = wandb.Artifact(name, type="model") + with artifact.new_file(f"{name}.pkl", "wb") as f: + torch.save(data, f) + run.log_artifact(artifact) + wandb.termlog(f"Logging artifact: {name} ({type(data)})") + return None + +except ImportError: + wandb.termwarn( + "`pytorch` not installed >> @wandb_log(models=True) may not auto log your model!" + ) + +try: + from sklearn.base import BaseEstimator + + _BASE_ESTIMATOR = BaseEstimator + + def _use_sklearn_estimator( + name: str, + data: BaseEstimator, + run, + testing: bool = False, + ) -> Optional[str]: + if testing: + return "models" + + run.use_artifact(f"{name}:latest") + wandb.termlog(f"Using artifact: {name} ({type(data)})") + return None + + def _track_sklearn_estimator( + name: str, + data: BaseEstimator, + run, + testing: bool = False, + ) -> Optional[str]: + if testing: + return "BaseEstimator" + + artifact = wandb.Artifact(name, type="model") + with artifact.new_file(f"{name}.pkl", "wb") as f: + pickle.dump(data, f) + run.log_artifact(artifact) + wandb.termlog(f"Logging artifact: {name} ({type(data)})") + return None + +except ImportError: + wandb.termwarn( + "`sklearn` not installed >> @wandb_log(models=True) may not auto log your model!" + ) + + +class ArtifactProxy: + def __init__(self, flow): + # do this to avoid recursion problem with __setattr__ + self.__dict__.update( + { + "flow": flow, + "inputs": {}, + "outputs": {}, + "base": set(dir(flow)), + "params": {p: getattr(flow, p) for p in current.parameter_names}, + } + ) + + def __setattr__(self, key, val): + self.outputs[key] = val + return setattr(self.flow, key, val) + + def __getattr__(self, key): + if key not in self.base and key not in self.outputs: + self.inputs[key] = getattr(self.flow, key) + return getattr(self.flow, key) + + +def _track_scalar( + name: str, + data: Union[dict, list, set, str, int, float, bool], + run, + testing: bool = False, +) -> Optional[str]: + if testing: + return "scalar" + + run.log({name: data}) + return None + + +def _track_path( + name: str, + data: Path, + run, + testing: bool = False, +) -> Optional[str]: + if testing: + return "Path" + + artifact = wandb.Artifact(name, type="dataset") + if data.is_dir(): + artifact.add_dir(data) + elif data.is_file(): + artifact.add_file(data) + run.log_artifact(artifact) + wandb.termlog(f"Logging artifact: {name} ({type(data)})") + return None + + +def _track_generic( + name: str, + data, + run, + testing: bool = False, +) -> Optional[str]: + if testing: + return "generic" + + artifact = wandb.Artifact(name, type="other") + with artifact.new_file(f"{name}.pkl", "wb") as f: + pickle.dump(data, f) + run.log_artifact(artifact) + wandb.termlog(f"Logging artifact: {name} ({type(data)})") + return None + + +def wandb_track( + name: str, + data, + datasets: bool = False, + models: bool = False, + others: bool = False, + run: Optional[wandb.Run] = None, + testing: bool = False, +) -> Optional[str]: + """Track data as wandb artifacts based on type and flags.""" + # Check for pandas DataFrame + if data_pandas and data_pandas.is_dataframe(data) and datasets: + return data_pandas.track_dataframe(name, data, run, testing) + + # Check for PyTorch Module + if _NN_MODULE and isinstance(data, _NN_MODULE) and models: + return _track_torch_module(name, data, run, testing) + + # Check for scikit-learn BaseEstimator + if _BASE_ESTIMATOR and isinstance(data, _BASE_ESTIMATOR) and models: + return _track_sklearn_estimator(name, data, run, testing) + + # Check for Path objects + if isinstance(data, Path) and datasets: + return _track_path(name, data, run, testing) + + # Check for scalar types + if isinstance(data, (dict, list, set, str, int, float, bool)): + return _track_scalar(name, data, run, testing) + + # Generic fallback + if others: + return _track_generic(name, data, run, testing) + + # No action taken + return None + + +def wandb_use( + name: str, + data, + datasets: bool = False, + models: bool = False, + others: bool = False, + run=None, + testing: bool = False, +) -> Optional[str]: + """Use wandb artifacts based on data type and flags.""" + # Skip scalar types - nothing to use + if isinstance(data, (dict, list, set, str, int, float, bool)): + return None + + try: + # Check for pandas DataFrame + if data_pandas and data_pandas.is_dataframe(data) and datasets: + return data_pandas.use_dataframe(name, run, testing) + + # Check for PyTorch Module + elif _NN_MODULE and isinstance(data, _NN_MODULE) and models: + return _use_torch_module(name, data, run, testing) + + # Check for scikit-learn BaseEstimator + elif _BASE_ESTIMATOR and isinstance(data, _BASE_ESTIMATOR) and models: + return _use_sklearn_estimator(name, data, run, testing) + + # Check for Path objects + elif isinstance(data, Path) and datasets: + return _use_path(name, data, run, testing) + + # Generic fallback + elif others: + return _use_generic(name, data, run, testing) + + else: + return None + + except wandb.CommError: + wandb.termwarn( + f"This artifact ({name}, {type(data)}) does not exist in the wandb datastore!" + " If you created an instance inline (e.g. sklearn.ensemble.RandomForestClassifier)," + " then you can safely ignore this. Otherwise you may want to check your internet connection!" + ) + return None + + +def _use_path( + name: str, + data: Path, + run, + testing: bool = False, +) -> Optional[str]: + if testing: + return "datasets" + + run.use_artifact(f"{name}:latest") + wandb.termlog(f"Using artifact: {name} ({type(data)})") + return None + + +def _use_generic( + name: str, + data, + run, + testing: bool = False, +) -> Optional[str]: + if testing: + return "others" + + run.use_artifact(f"{name}:latest") + wandb.termlog(f"Using artifact: {name} ({type(data)})") + return None + + +def coalesce(*arg): + return next((a for a in arg if a is not None), None) + + +def wandb_log( + func=None, + /, + datasets: bool = False, + models: bool = False, + others: bool = False, + settings: Optional[wandb.Settings] = None, +): + """Automatically log parameters and artifacts to W&B. + + This decorator can be applied to a flow, step, or both: + + - Decorating a step enables or disables logging within that step + - Decorating a flow is equivalent to decorating all steps + - Decorating a step after decorating its flow overwrites the flow decoration + + Args: + func: The step method or flow class to decorate. + datasets: Whether to log `pd.DataFrame` and `pathlib.Path` + types. Defaults to False. + models: Whether to log `nn.Module` and `sklearn.base.BaseEstimator` + types. Defaults to False. + others: If `True`, log anything pickle-able. Defaults to False. + settings: Custom settings to pass to `wandb.init`. + If `run_group` is `None`, it is set to `{flow_name}/{run_id}`. + If `run_job_type` is `None`, it is set to `{run_job_type}/{step_name}`. + """ + + @wraps(func) + def decorator(func): + # If you decorate a class, apply the decoration to all methods in that class + if inspect.isclass(func): + cls = func + for attr in cls.__dict__: + if callable(getattr(cls, attr)): + if not hasattr(attr, "_base_func"): + setattr(cls, attr, decorator(getattr(cls, attr))) + return cls + + # prefer the earliest decoration (i.e. method decoration overrides class decoration) + if hasattr(func, "_base_func"): + return func + + @wraps(func) + def wrapper(self, *args, settings=settings, **kwargs): + if not isinstance(settings, wandb.sdk.wandb_settings.Settings): + settings = wandb.Settings() + + settings.update_from_dict( + { + "run_group": coalesce( + settings.run_group, f"{current.flow_name}/{current.run_id}" + ), + "run_job_type": coalesce(settings.run_job_type, current.step_name), + } + ) + + with wandb.init(settings=settings) as run: + with wb_telemetry.context(run=run) as tel: + tel.feature.metaflow = True + proxy = ArtifactProxy(self) + run.config.update(proxy.params) + func(proxy, *args, **kwargs) + + for name, data in proxy.inputs.items(): + wandb_use( + name, + data, + datasets=datasets, + models=models, + others=others, + run=run, + ) + + for name, data in proxy.outputs.items(): + wandb_track( + name, + data, + datasets=datasets, + models=models, + others=others, + run=run, + ) + + wrapper._base_func = func + + # Add for testing visibility + wrapper._kwargs = { + "datasets": datasets, + "models": models, + "others": others, + "settings": settings, + } + return wrapper + + if func is None: + return decorator + else: + return decorator(func) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/openai/__pycache__/openai.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/openai/__pycache__/openai.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..263e67a607dcfca497e2221fc6306155a5138b25 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/openai/__pycache__/openai.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/openai/__pycache__/resolver.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/openai/__pycache__/resolver.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2e2cc725c18a5ed667ab2568ba787ba88dfb625 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/openai/__pycache__/resolver.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/openai/resolver.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/openai/resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..500c58ce2f4b33a6a987243169bc998cf387fef4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/openai/resolver.py @@ -0,0 +1,240 @@ +import datetime +import io +import logging +from dataclasses import asdict, dataclass +from typing import Any, Dict, List, Optional, Sequence + +import wandb +from wandb.sdk.data_types import trace_tree +from wandb.sdk.integration_utils.auto_logging import Response + +logger = logging.getLogger(__name__) + + +@dataclass +class UsageMetrics: + elapsed_time: float = None + prompt_tokens: int = None + completion_tokens: int = None + total_tokens: int = None + + +@dataclass +class Metrics: + usage: UsageMetrics = None + stats: wandb.Table = None + trace: trace_tree.WBTraceTree = None + + +usage_metric_keys = {f"usage/{k}" for k in asdict(UsageMetrics())} + + +class OpenAIRequestResponseResolver: + def __init__(self): + self.define_metrics_called = False + + def __call__( + self, + args: Sequence[Any], + kwargs: Dict[str, Any], + response: Response, + start_time: float, # pass to comply with the protocol, but use response["created"] instead + time_elapsed: float, + ) -> Optional[Dict[str, Any]]: + request = kwargs + + if not self.define_metrics_called: + # define metrics on first call + for key in usage_metric_keys: + wandb.define_metric(key, step_metric="_timestamp") + self.define_metrics_called = True + + try: + if response.get("object") == "edit": + return self._resolve_edit(request, response, time_elapsed) + elif response.get("object") == "text_completion": + return self._resolve_completion(request, response, time_elapsed) + elif response.get("object") == "chat.completion": + return self._resolve_chat_completion(request, response, time_elapsed) + else: + # todo: properly treat failed requests + logger.info( + f"Unsupported OpenAI response object: {response.get('object')}" + ) + except Exception as e: + logger.warning(f"Failed to resolve request/response: {e}") + return None + + @staticmethod + def results_to_trace_tree( + request: Dict[str, Any], + response: Response, + results: List[trace_tree.Result], + time_elapsed: float, + ) -> trace_tree.WBTraceTree: + """Converts the request, response, and results into a trace tree. + + params: + request: The request dictionary + response: The response object + results: A list of results object + time_elapsed: The time elapsed in seconds + returns: + A wandb trace tree object. + """ + start_time_ms = int(round(response["created"] * 1000)) + end_time_ms = start_time_ms + int(round(time_elapsed * 1000)) + span = trace_tree.Span( + name=f"{response.get('model', 'openai')}_{response['object']}_{response.get('created')}", + attributes=dict(response), # type: ignore + start_time_ms=start_time_ms, + end_time_ms=end_time_ms, + span_kind=trace_tree.SpanKind.LLM, + results=results, + ) + model_obj = {"request": request, "response": response, "_kind": "openai"} + return trace_tree.WBTraceTree(root_span=span, model_dict=model_obj) + + def _resolve_edit( + self, + request: Dict[str, Any], + response: Response, + time_elapsed: float, + ) -> Dict[str, Any]: + """Resolves the request and response objects for `openai.Edit`.""" + request_str = ( + f"\n\n**Instruction**: {request['instruction']}\n\n" + f"**Input**: {request['input']}\n" + ) + choices = [ + f"\n\n**Edited**: {choice['text']}\n" for choice in response["choices"] + ] + + return self._resolve_metrics( + request=request, + response=response, + request_str=request_str, + choices=choices, + time_elapsed=time_elapsed, + ) + + def _resolve_completion( + self, + request: Dict[str, Any], + response: Response, + time_elapsed: float, + ) -> Dict[str, Any]: + """Resolves the request and response objects for `openai.Completion`.""" + request_str = f"\n\n**Prompt**: {request['prompt']}\n" + choices = [ + f"\n\n**Completion**: {choice['text']}\n" for choice in response["choices"] + ] + + return self._resolve_metrics( + request=request, + response=response, + request_str=request_str, + choices=choices, + time_elapsed=time_elapsed, + ) + + def _resolve_chat_completion( + self, + request: Dict[str, Any], + response: Response, + time_elapsed: float, + ) -> Dict[str, Any]: + """Resolves the request and response objects for `openai.Completion`.""" + prompt = io.StringIO() + for message in request["messages"]: + prompt.write(f"\n\n**{message['role']}**: {message['content']}\n") + request_str = prompt.getvalue() + + choices = [ + f"\n\n**{choice['message']['role']}**: {choice['message']['content']}\n" + for choice in response["choices"] + ] + + return self._resolve_metrics( + request=request, + response=response, + request_str=request_str, + choices=choices, + time_elapsed=time_elapsed, + ) + + def _resolve_metrics( + self, + request: Dict[str, Any], + response: Response, + request_str: str, + choices: List[str], + time_elapsed: float, + ) -> Dict[str, Any]: + """Resolves the request and response objects for `openai.Completion`.""" + results = [ + trace_tree.Result( + inputs={"request": request_str}, + outputs={"response": choice}, + ) + for choice in choices + ] + metrics = self._get_metrics_to_log(request, response, results, time_elapsed) + return self._convert_metrics_to_dict(metrics) + + @staticmethod + def _get_usage_metrics(response: Response, time_elapsed: float) -> UsageMetrics: + """Gets the usage stats from the response object.""" + if response.get("usage"): + usage_stats = UsageMetrics(**response["usage"]) + else: + usage_stats = UsageMetrics() + usage_stats.elapsed_time = time_elapsed + return usage_stats + + def _get_metrics_to_log( + self, + request: Dict[str, Any], + response: Response, + results: List[Any], + time_elapsed: float, + ) -> Metrics: + model = response.get("model") or request.get("model") + usage_metrics = self._get_usage_metrics(response, time_elapsed) + + usage = [] + for result in results: + row = { + "request": result.inputs["request"], + "response": result.outputs["response"], + "model": model, + "start_time": datetime.datetime.fromtimestamp(response["created"]), + "end_time": datetime.datetime.fromtimestamp( + response["created"] + time_elapsed + ), + "request_id": response.get("id", None), + "api_type": response.get("api_type", "openai"), + "session_id": wandb.run.id, + } + row.update(asdict(usage_metrics)) + usage.append(row) + usage_table = wandb.Table( + columns=list(usage[0].keys()), + data=[(item.values()) for item in usage], + ) + + trace = self.results_to_trace_tree(request, response, results, time_elapsed) + + metrics = Metrics(stats=usage_table, trace=trace, usage=usage_metrics) + return metrics + + @staticmethod + def _convert_metrics_to_dict(metrics: Metrics) -> Dict[str, Any]: + """Converts metrics to a dict.""" + metrics_dict = { + "stats": metrics.stats, + "trace": metrics.trace, + } + usage_stats = {f"usage/{k}": v for k, v in asdict(metrics.usage).items()} + metrics_dict.update(usage_stats) + return metrics_dict diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/prodigy/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/prodigy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..94ed0ea26bc5f886cf90db26da37dc8f08f9b18e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/prodigy/__init__.py @@ -0,0 +1,3 @@ +from .prodigy import upload_dataset + +__all__ = ["upload_dataset"] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/prodigy/__pycache__/prodigy.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/prodigy/__pycache__/prodigy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e54862b563b3b09bfb40822d90be62dc192693c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/prodigy/__pycache__/prodigy.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sacred/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sacred/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dabcc47afd726c57cf269e698096e399a1574b3a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sacred/__init__.py @@ -0,0 +1,117 @@ +import warnings + +import numpy +from sacred.dependencies import get_digest +from sacred.observers import RunObserver + +import wandb + + +class WandbObserver(RunObserver): + """Log sacred experiment data to W&B. + + Args: + Accepts all the arguments accepted by wandb.init(). + + name — A display name for this run, which shows up in the UI and is editable, doesn't have to be unique + notes — A multiline string description associated with the run + config — a dictionary-like object to set as initial config + project — the name of the project to which this run will belong + tags — a list of strings to associate with this run as tags + dir — the path to a directory where artifacts will be written (default: ./wandb) + entity — the team posting this run (default: your username or your default team) + job_type — the type of job you are logging, e.g. eval, worker, ps (default: training) + save_code — save the main python or notebook file to wandb to enable diffing (default: editable from your settings page) + group — a string by which to group other runs; see Grouping + reinit — Shorthand for the reinit setting that defines what to do when `wandb.init()` is called while a run is active. See the setting's documentation. + id — A unique ID for this run primarily used for Resuming. It must be globally unique, and if you delete a run you can't reuse the ID. Use the name field for a descriptive, useful name for the run. The ID cannot contain special characters. + resume — if set to True, the run auto resumes; can also be a unique string for manual resuming; see Resuming (default: False) + anonymous — can be "allow", "never", or "must". This enables or explicitly disables anonymous logging. (default: never) + force — whether to force a user to be logged into wandb when running a script (default: False) + magic — (bool, dict, or str, optional): magic configuration as bool, dict, json string, yaml filename. If set to True will attempt to auto-instrument your script. (default: None) + sync_tensorboard — A boolean indicating whether or not copy all TensorBoard logs wandb; see Tensorboard (default: False) + monitor_gym — A boolean indicating whether or not to log videos generated by OpenAI Gym; see Ray Tune (default: False) + allow_val_change — whether to allow wandb.config values to change, by default we throw an exception if config values are overwritten. (default: False) + + Examples: + Create sacred experiment:: + from wandb.sacred import WandbObserver + ex.observers.append(WandbObserver(project='sacred_test', + name='test1')) + @ex.config + def cfg(): + C = 1.0 + gamma = 0.7 + @ex.automain + def run(C, gamma, _run): + iris = datasets.load_iris() + per = permutation(iris.target.size) + iris.data = iris.data[per] + iris.target = iris.target[per] + clf = svm.SVC(C, 'rbf', gamma=gamma) + clf.fit(iris.data[:90], + iris.target[:90]) + return clf.score(iris.data[90:], + iris.target[90:]) + """ + + def __init__(self, **kwargs): + self.run = wandb.init(**kwargs) + self.resources = {} + + def started_event( + self, ex_info, command, host_info, start_time, config, meta_info, _id + ): + # TODO: add the source code file + # TODO: add dependencies and metadata. + self.__update_config(config) + + def completed_event(self, stop_time, result): + if result: + if not isinstance(result, tuple): + result = ( + result, + ) # transform single result to tuple so that both single & multiple results use same code + + for i, r in enumerate(result): + if isinstance(r, float) or isinstance(r, int): + wandb.log({f"result_{i}": float(r)}) + elif isinstance(r, dict): + wandb.log(r) + elif isinstance(r, object): + artifact = wandb.Artifact(f"result_{i}.pkl", type="result") + artifact.add_file(r) + self.run.log_artifact(artifact) + elif isinstance(r, numpy.ndarray): + wandb.log({f"result_{i}": wandb.Image(r)}) + else: + warnings.warn( + f"logging results does not support type '{type(r)}' results. Ignoring this result", + stacklevel=2, + ) + + def artifact_event(self, name, filename, metadata=None, content_type=None): + if content_type is None: + content_type = "file" + artifact = wandb.Artifact(name, type=content_type) + artifact.add_file(filename) + self.run.log_artifact(artifact) + + def resource_event(self, filename): + """TODO: Maintain resources list.""" + if filename not in self.resources: + md5 = get_digest(filename) + self.resources[filename] = md5 + + def log_metrics(self, metrics_by_name, info): + for metric_name, metric_ptr in metrics_by_name.items(): + for _step, value in zip(metric_ptr["steps"], metric_ptr["values"]): + if isinstance(value, numpy.ndarray): + wandb.log({metric_name: wandb.Image(value)}) + else: + wandb.log({metric_name: value}) + + def __update_config(self, config): + for k, v in config.items(): + self.run.config[k] = v + self.run.config["resources"] = [] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sacred/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sacred/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87309bf5e9a2959fde8d30c126c9388eb20e434f Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sacred/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sagemaker/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sagemaker/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..989e04c6d799e9a6e8eb68fe7155761b2b5a37ed Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sagemaker/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sagemaker/__pycache__/config.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sagemaker/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4a11ef9d60b72bd82bb656c78386962d5bfe0da Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sagemaker/__pycache__/config.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sagemaker/__pycache__/files.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sagemaker/__pycache__/files.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c2049148a476c7008b821578df5cf3eeb0f5e5f Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sagemaker/__pycache__/files.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sagemaker/auth.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sagemaker/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..fc82952db6dd710c1e474640cf939476ca171c8d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sagemaker/auth.py @@ -0,0 +1,29 @@ +import os + +import wandb +from wandb import env +from wandb.sdk import wandb_setup + + +def sagemaker_auth(overrides=None, path=".", api_key=None): + """Write a secrets.env file with the W&B ApiKey and any additional secrets passed. + + Args: + overrides (dict, optional): Additional environment variables to write + to secrets.env + path (str, optional): The path to write the secrets file. + """ + settings = wandb_setup.singleton().settings + current_api_key = wandb.wandb_lib.apikey.api_key(settings=settings) + + overrides = overrides or dict() + api_key = overrides.get(env.API_KEY, api_key or current_api_key) + if api_key is None: + raise ValueError( + "Can't find W&B ApiKey, set the WANDB_API_KEY env variable " + "or run `wandb login`" + ) + overrides[env.API_KEY] = api_key + with open(os.path.join(path, "secrets.env"), "w") as file: + for k, v in overrides.items(): + file.write(f"{k}={v}\n") diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sb3/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sb3/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80555f9292270752fd6319d87f0c99c616607823 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sb3/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sb3/__pycache__/sb3.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sb3/__pycache__/sb3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0277a25fd34e89a97183810c0269a79a7084d679 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sb3/__pycache__/sb3.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sb3/sb3.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sb3/sb3.py new file mode 100644 index 0000000000000000000000000000000000000000..2eec145d0fc052575ca6ba65d68283dcaa0ea69b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sb3/sb3.py @@ -0,0 +1,147 @@ +"""W&B callback for sb3. + +Really simple callback to get logging for each tree + +Example usage: + +```python +import gym +from stable_baselines3 import PPO +from stable_baselines3.common.monitor import Monitor +from stable_baselines3.common.vec_env import DummyVecEnv, VecVideoRecorder +import wandb +from wandb.integration.sb3 import WandbCallback + + +config = { + "policy_type": "MlpPolicy", + "total_timesteps": 25000, + "env_name": "CartPole-v1", +} +run = wandb.init( + project="sb3", + config=config, + sync_tensorboard=True, # auto-upload sb3's tensorboard metrics + monitor_gym=True, # auto-upload the videos of agents playing the game + save_code=True, # optional +) + + +def make_env(): + env = gym.make(config["env_name"]) + env = Monitor(env) # record stats such as returns + return env + + +env = DummyVecEnv([make_env]) +env = VecVideoRecorder( + env, "videos", record_video_trigger=lambda x: x % 2000 == 0, video_length=200 +) +model = PPO(config["policy_type"], env, verbose=1, tensorboard_log=f"runs") +model.learn( + total_timesteps=config["total_timesteps"], + callback=WandbCallback( + model_save_path=f"models/{run.id}", + gradient_save_freq=100, + log="all", + ), +) +``` +""" + +import logging +import os +from typing import Literal, Optional + +from stable_baselines3.common.callbacks import BaseCallback # type: ignore + +import wandb +from wandb.sdk.lib import telemetry as wb_telemetry + +logger = logging.getLogger(__name__) + + +class WandbCallback(BaseCallback): + """Callback for logging experiments to Weights and Biases. + + Log SB3 experiments to Weights and Biases + - Added model tracking and uploading + - Added complete hyperparameters recording + - Added gradient logging + - Note that `wandb.init(...)` must be called before the WandbCallback can be used. + + Args: + verbose: The verbosity of sb3 output + model_save_path: Path to the folder where the model will be saved, The default value is `None` so the model is not logged + model_save_freq: Frequency to save the model + gradient_save_freq: Frequency to log gradient. The default value is 0 so the gradients are not logged + log: What to log. One of "gradients", "parameters", or "all". + """ + + def __init__( + self, + verbose: int = 0, + model_save_path: Optional[str] = None, + model_save_freq: int = 0, + gradient_save_freq: int = 0, + log: Optional[Literal["gradients", "parameters", "all"]] = "all", + ) -> None: + super().__init__(verbose) + if wandb.run is None: + raise wandb.Error("You must call wandb.init() before WandbCallback()") + with wb_telemetry.context() as tel: + tel.feature.sb3 = True + self.model_save_freq = model_save_freq + self.model_save_path = model_save_path + self.gradient_save_freq = gradient_save_freq + if log not in ["gradients", "parameters", "all", None]: + wandb.termwarn( + "`log` must be one of `None`, 'gradients', 'parameters', or 'all', " + "falling back to 'all'" + ) + log = "all" + self.log = log + # Create folder if needed + if self.model_save_path is not None: + os.makedirs(self.model_save_path, exist_ok=True) + self.path = os.path.join(self.model_save_path, "model.zip") + else: + assert self.model_save_freq == 0, ( + "to use the `model_save_freq` you have to set the `model_save_path` parameter" + ) + + def _init_callback(self) -> None: + d = {} + if "algo" not in d: + d["algo"] = type(self.model).__name__ + for key in self.model.__dict__: + if key in wandb.config: + continue + if type(self.model.__dict__[key]) in [float, int, str]: + d[key] = self.model.__dict__[key] + else: + d[key] = str(self.model.__dict__[key]) + if self.gradient_save_freq > 0: + wandb.watch( + self.model.policy, + log_freq=self.gradient_save_freq, + log=self.log, + ) + wandb.config.setdefaults(d) + + def _on_step(self) -> bool: + if self.model_save_freq > 0: + if self.model_save_path is not None: + if self.n_calls % self.model_save_freq == 0: + self.save_model() + return True + + def _on_training_end(self) -> None: + if self.model_save_path is not None: + self.save_model() + + def save_model(self) -> None: + self.model.save(self.path) + wandb.save(self.path, base_path=self.model_save_path) + if self.verbose > 1: + logger.info(f"Saving model checkpoint to {self.path}") diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e73dd46058f6d97c3dd617dff202f624fcbc46d0 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/__pycache__/utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5d4f309eec7f4fc3871d35faef24e2d6040b4d1 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/__pycache__/utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0d22d629bbc7dced6da390f885a4d327049491ff --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__init__.py @@ -0,0 +1,32 @@ +"""Calculates and formats metrics and charts for introspecting sklearn models. + +The functions in these modules are designed to be called by functions from the +plot submodule that have been exported into the namespace of the wandb.sklearn +submodule, rather than being called directly. +""" + +from .calibration_curves import calibration_curves +from .class_proportions import class_proportions +from .confusion_matrix import confusion_matrix +from .decision_boundaries import decision_boundaries +from .elbow_curve import elbow_curve +from .feature_importances import feature_importances +from .learning_curve import learning_curve +from .outlier_candidates import outlier_candidates +from .residuals import residuals +from .silhouette import silhouette +from .summary_metrics import summary_metrics + +__all__ = [ + "calibration_curves", + "class_proportions", + "confusion_matrix", + "decision_boundaries", + "elbow_curve", + "feature_importances", + "learning_curve", + "outlier_candidates", + "residuals", + "silhouette", + "summary_metrics", +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21971693c09d10b53728376019c81584c4f41d72 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__pycache__/class_proportions.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__pycache__/class_proportions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca7ddd6c473f9eebade0a38f40bdda822a033a09 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__pycache__/class_proportions.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__pycache__/decision_boundaries.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__pycache__/decision_boundaries.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d5792224f0ef78e04f6aea4b6c667d101276c36 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__pycache__/decision_boundaries.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__pycache__/elbow_curve.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__pycache__/elbow_curve.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34ed0d3492fa482ba3bf148e865f6b2b9d2835fe Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__pycache__/elbow_curve.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__pycache__/feature_importances.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__pycache__/feature_importances.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0d273ff6d7627ce8b751478033163b2a43ba677 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__pycache__/feature_importances.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__pycache__/learning_curve.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__pycache__/learning_curve.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7cd04bb9d01641b35982b93abf1b52004d9483fb Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__pycache__/learning_curve.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__pycache__/silhouette.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__pycache__/silhouette.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db96ed73aff6f7b43622bbb32a6e080864b9f6a5 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/__pycache__/silhouette.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/calibration_curves.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/calibration_curves.py new file mode 100644 index 0000000000000000000000000000000000000000..b59aa25d7d8c984ca30529d497eb0e263570c365 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/calibration_curves.py @@ -0,0 +1,125 @@ +from warnings import simplefilter + +import numpy as np +import sklearn +from sklearn import model_selection, naive_bayes +from sklearn.calibration import CalibratedClassifierCV +from sklearn.linear_model import LogisticRegression + +import wandb +from wandb.integration.sklearn import utils + +# ignore all future warnings +simplefilter(action="ignore", category=FutureWarning) + + +def calibration_curves(clf, X, y, clf_name): # noqa: N803 + # ComplementNB (introduced in 0.20.0) requires non-negative features + if int(sklearn.__version__.split(".")[1]) >= 20 and isinstance( + clf, naive_bayes.ComplementNB + ): + X = X - X.min() # noqa:N806 + + # Calibrated with isotonic calibration + isotonic = CalibratedClassifierCV(clf, cv=2, method="isotonic") + + # Calibrated with sigmoid calibration + sigmoid = CalibratedClassifierCV(clf, cv=2, method="sigmoid") + + # Logistic regression with no calibration as baseline + lr = LogisticRegression(C=1.0) + + model_column = [] # color + frac_positives_column = [] # y axis + mean_pred_value_column = [] # x axis + hist_column = [] # barchart y + edge_column = [] # barchart x + + # Add curve for perfectly calibrated model + # format: model, fraction_of_positives, mean_predicted_value + model_column.append("Perfectly calibrated") + frac_positives_column.append(0) + mean_pred_value_column.append(0) + hist_column.append(0) + edge_column.append(0) + model_column.append("Perfectly calibrated") + hist_column.append(0) + edge_column.append(0) + frac_positives_column.append(1) + mean_pred_value_column.append(1) + + x_train, x_test, y_train, y_test = model_selection.train_test_split( + X, y, test_size=0.9, random_state=42 + ) + + # Add curve for LogisticRegression baseline and other models + + models = [lr, isotonic, sigmoid] + names = ["Logistic", f"{clf_name} Isotonic", f"{clf_name} Sigmoid"] + + for model, name in zip(models, names): + model.fit(x_train, y_train) + if hasattr(model, "predict_proba"): + prob_pos = model.predict_proba(x_test)[:, 1] + else: # use decision function + prob_pos = model.decision_function(x_test) + prob_pos = (prob_pos - prob_pos.min()) / (prob_pos.max() - prob_pos.min()) + + hist, edges = np.histogram(prob_pos, bins=10, density=False) + frac_positives, mean_pred_value = sklearn.calibration.calibration_curve( + y_test, prob_pos, n_bins=10 + ) + + # format: model, fraction_of_positives, mean_predicted_value + num_entries = len(frac_positives) + for i in range(num_entries): + hist_column.append(hist[i]) + edge_column.append(edges[i]) + model_column.append(name) + frac_positives_column.append(utils.round_3(frac_positives[i])) + mean_pred_value_column.append(utils.round_3(mean_pred_value[i])) + if utils.check_against_limit( + i, + "calibration_curve", + utils.chart_limit - 2, + ): + break + + table = make_table( + model_column, + frac_positives_column, + mean_pred_value_column, + hist_column, + edge_column, + ) + chart = wandb.visualize("wandb/calibration/v1", table) + + return chart + + +def make_table( + model_column, + frac_positives_column, + mean_pred_value_column, + hist_column, + edge_column, +): + columns = [ + "model", + "fraction_of_positives", + "mean_predicted_value", + "hist_dict", + "edge_dict", + ] + + data = list( + zip( + model_column, + frac_positives_column, + mean_pred_value_column, + hist_column, + edge_column, + ) + ) + + return wandb.Table(columns=columns, data=data) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/class_proportions.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/class_proportions.py new file mode 100644 index 0000000000000000000000000000000000000000..183bf785a2fb62e2efe20fbdfde68f7a0fc45024 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/class_proportions.py @@ -0,0 +1,68 @@ +from warnings import simplefilter + +import numpy as np +from sklearn.utils.multiclass import unique_labels + +import wandb +from wandb.integration.sklearn import utils + +# ignore all future warnings +simplefilter(action="ignore", category=FutureWarning) + + +def class_proportions(y_train, y_test, labels): + # Get the unique values from the dataset + targets = (y_train,) if y_test is None else (y_train, y_test) + class_ids = np.array(unique_labels(*targets)) + + # Compute the class counts + counts_train = np.array([(y_train == c).sum() for c in class_ids]) + counts_test = np.array([(y_test == c).sum() for c in class_ids]) + + class_column, dataset_column, count_column = make_columns( + class_ids, counts_train, counts_test + ) + + if labels is not None and ( + isinstance(class_column[0], int) or isinstance(class_column[0], np.integer) + ): + class_column = get_named_labels(labels, class_column) + + table = make_table(class_column, dataset_column, count_column) + chart = wandb.visualize("wandb/class_proportions/v1", table) + + return chart + + +def make_table(class_column, dataset_column, count_column): + columns = ["class", "dataset", "count"] + data = list(zip(class_column, dataset_column, count_column)) + + return wandb.Table(data=data, columns=columns) + + +def make_columns(class_ids, counts_train, counts_test): + class_column, dataset_column, count_column = [], [], [] + + for i in range(len(class_ids)): + # add class counts from training set + class_column.append(class_ids[i]) + dataset_column.append("train") + count_column.append(counts_train[i]) + # add class counts from test set + class_column.append(class_ids[i]) + dataset_column.append("test") + count_column.append(counts_test[i]) + + if utils.check_against_limit( + i, + "class_proportions", + utils.chart_limit, + ): + break + + return class_column, dataset_column, count_column + + +def get_named_labels(labels, numeric_labels): + return np.array([labels[num_label] for num_label in numeric_labels]) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/confusion_matrix.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/confusion_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..777c84ada92237222e0a058c5facd7b761313b12 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/confusion_matrix.py @@ -0,0 +1,93 @@ +import itertools +from warnings import simplefilter + +import numpy as np +from sklearn import metrics +from sklearn.utils.multiclass import unique_labels + +import wandb + +from .. import utils + +# ignore all future warnings +simplefilter(action="ignore", category=FutureWarning) + + +def validate_labels(*args, **kwargs): # FIXME + raise AssertionError() + + +def confusion_matrix( + y_true=None, + y_pred=None, + labels=None, + true_labels=None, + pred_labels=None, + normalize=False, +): + """Compute the confusion matrix to evaluate the performance of a classification. + + Called by plot_confusion_matrix to visualize roc curves. Please use the function + plot_confusion_matrix() if you wish to visualize your confusion matrix. + """ + cm = metrics.confusion_matrix(y_true, y_pred) + + if labels is None: + classes = unique_labels(y_true, y_pred) + else: + classes = np.asarray(labels) + + if normalize: + cm = cm.astype("float") / cm.sum(axis=1)[:, np.newaxis] + cm = np.around(cm, decimals=2) + cm[np.isnan(cm)] = 0.0 + + if true_labels is None: + true_classes = classes + else: + validate_labels(classes, true_labels, "true_labels") + + true_label_indexes = np.in1d(classes, true_labels) + + true_classes = classes[true_label_indexes] + cm = cm[true_label_indexes] + + if pred_labels is None: + pred_classes = classes + else: + validate_labels(classes, pred_labels, "pred_labels") + + pred_label_indexes = np.in1d(classes, pred_labels) + + pred_classes = classes[pred_label_indexes] + cm = cm[:, pred_label_indexes] + + table = make_table(cm, pred_classes, true_classes, labels) + chart = wandb.visualize("wandb/confusion_matrix/v1", table) + + return chart + + +def make_table(cm, pred_classes, true_classes, labels): + data, count = [], 0 + for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): + if labels is not None and ( + isinstance(pred_classes[i], int) or isinstance(pred_classes[0], np.integer) + ): + pred = labels[pred_classes[i]] + true = labels[true_classes[j]] + else: + pred = pred_classes[i] + true = true_classes[j] + data.append([pred, true, cm[i, j]]) + count += 1 + if utils.check_against_limit( + count, + "confusion_matrix", + utils.chart_limit, + ): + break + + table = wandb.Table(columns=["Predicted", "Actual", "Count"], data=data) + + return table diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/decision_boundaries.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/decision_boundaries.py new file mode 100644 index 0000000000000000000000000000000000000000..a7a849b86b151270adf2437e4f2e72a03ce6c1a9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/decision_boundaries.py @@ -0,0 +1,40 @@ +from warnings import simplefilter + +import wandb + +# ignore all future warnings +simplefilter(action="ignore", category=FutureWarning) + + +def decision_boundaries( + decision_boundary_x, + decision_boundary_y, + decision_boundary_color, + train_x, + train_y, + train_color, + test_x, + test_y, + test_color, +): + x_dict, y_dict, color_dict = [], [], [] + for i in range(min(len(decision_boundary_x), 100)): + x_dict.append(decision_boundary_x[i]) + y_dict.append(decision_boundary_y[i]) + color_dict.append(decision_boundary_color) + for i in range(300): + x_dict.append(test_x[i]) + y_dict.append(test_y[i]) + color_dict.append(test_color[i]) + for i in range(min(len(train_x), 600)): + x_dict.append(train_x[i]) + y_dict.append(train_y[i]) + color_dict.append(train_color[i]) + + return wandb.visualize( + "wandb/decision_boundaries/v1", + wandb.Table( + columns=["x", "y", "color"], + data=[[x_dict[i], y_dict[i], color_dict[i]] for i in range(len(x_dict))], + ), + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/elbow_curve.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/elbow_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..731102d75adabf238d44de00b8d79bca59f0a87a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/elbow_curve.py @@ -0,0 +1,55 @@ +import time +from warnings import simplefilter + +import numpy as np +from joblib import Parallel, delayed +from sklearn.base import clone + +import wandb + +# ignore all future warnings +simplefilter(action="ignore", category=FutureWarning) + + +def elbow_curve(clusterer, X, cluster_ranges, n_jobs, show_cluster_time): # noqa: N803 + if cluster_ranges is None: + cluster_ranges = range(1, 10, 2) + else: + cluster_ranges = sorted(cluster_ranges) + + clfs, times = _compute_results_parallel(n_jobs, clusterer, X, cluster_ranges) + + clfs = np.absolute(clfs) + + table = make_table(cluster_ranges, clfs, times) + chart = wandb.visualize("wandb/elbow/v1", table) + + return chart + + +def make_table(cluster_ranges, clfs, times): + columns = ["cluster_ranges", "errors", "clustering_time"] + + data = list(zip(cluster_ranges, clfs, times)) + + table = wandb.Table(columns=columns, data=data) + + return table + + +def _compute_results_parallel(n_jobs, clusterer, x, cluster_ranges): + parallel_runner = Parallel(n_jobs=n_jobs) + _cluster_scorer = delayed(_clone_and_score_clusterer) + results = parallel_runner(_cluster_scorer(clusterer, x, i) for i in cluster_ranges) + + clfs, times = zip(*results) + + return clfs, times + + +def _clone_and_score_clusterer(clusterer, x, n_clusters): + start = time.time() + clusterer = clone(clusterer) + clusterer.n_clusters = n_clusters + + return clusterer.fit(x).score(x), time.time() - start diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/feature_importances.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/feature_importances.py new file mode 100644 index 0000000000000000000000000000000000000000..fac0452b944fd31d3bf611df054f4f6c0dbc0895 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/feature_importances.py @@ -0,0 +1,67 @@ +from warnings import simplefilter + +import numpy as np + +import wandb + +# ignore all future warnings +simplefilter(action="ignore", category=FutureWarning) + + +def feature_importances(model, feature_names): + attributes_to_check = ["feature_importances_", "feature_log_prob_", "coef_"] + found_attribute = check_for_attribute_on(model, attributes_to_check) + if found_attribute is None: + wandb.termwarn( + f"could not find any of attributes {', '.join(attributes_to_check)} on classifier. Cannot plot feature importances." + ) + return + elif found_attribute == "feature_importances_": + importances = model.feature_importances_ + elif found_attribute == "coef_": # ElasticNet-like models + importances = model.coef_ + elif found_attribute == "feature_log_prob_": + # coef_ was deprecated in sklearn 0.24, replaced with + # feature_log_prob_ + importances = model.feature_log_prob_ + + if len(importances.shape) > 1: + n_significant_dims = sum(i > 1 for i in importances.shape) + if n_significant_dims > 1: + nd = len(importances.shape) + wandb.termwarn( + f"{nd}-dimensional feature importances array passed to plot_feature_importances. " + f"{nd}-dimensional and higher feature importances arrays are not currently supported. " + f"These importances will not be plotted." + ) + return + else: + importances = np.squeeze(importances) + + indices = np.argsort(importances)[::-1] + importances = importances[indices] + + if feature_names is None: + feature_names = indices + else: + feature_names = np.array(feature_names)[indices] + + table = make_table(feature_names, importances) + chart = wandb.visualize("wandb/feature_importances/v1", table) + + return chart + + +def make_table(feature_names, importances): + table = wandb.Table( + columns=["feature_names", "importances"], + data=[[feature_names[i], importances[i]] for i in range(len(feature_names))], + ) + return table + + +def check_for_attribute_on(model, attributes_to_check): + for attr in attributes_to_check: + if hasattr(model, attr): + return attr + return None diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/learning_curve.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/learning_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..296c7d7780fec21e5f9e3a7a346301c3c38b7de8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/learning_curve.py @@ -0,0 +1,64 @@ +from warnings import simplefilter + +import numpy as np +from sklearn import model_selection + +import wandb +from wandb.integration.sklearn import utils + +# ignore all future warnings +simplefilter(action="ignore", category=FutureWarning) + + +def learning_curve( + model, + X, # noqa: N803 + y, + cv=None, + shuffle=False, + random_state=None, + train_sizes=None, + n_jobs=1, + scoring=None, +): + """Train model on datasets of varying size and generates plot of score vs size. + + Called by plot_learning_curve to visualize learning curve. Please use the function + plot_learning_curve() if you wish to visualize your learning curves. + """ + train_sizes, train_scores, test_scores = model_selection.learning_curve( + model, + X, + y, + cv=cv, + n_jobs=n_jobs, + train_sizes=train_sizes, + scoring=scoring, + shuffle=shuffle, + random_state=random_state, + ) + train_scores_mean = np.mean(train_scores, axis=1) + test_scores_mean = np.mean(test_scores, axis=1) + + table = make_table(train_scores_mean, test_scores_mean, train_sizes) + chart = wandb.visualize("wandb/learning_curve/v1", table) + + return chart + + +def make_table(train, test, train_sizes): + data = [] + for i in range(len(train)): + if utils.check_against_limit( + i, + "learning_curve", + utils.chart_limit / 2, + ): + break + train_set = ["train", utils.round_2(train[i]), train_sizes[i]] + test_set = ["test", utils.round_2(test[i]), train_sizes[i]] + data.append(train_set) + data.append(test_set) + + table = wandb.Table(columns=["dataset", "score", "train_size"], data=data) + return table diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/outlier_candidates.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/outlier_candidates.py new file mode 100644 index 0000000000000000000000000000000000000000..5fb0a29f4e7c49939e2d34420c02f9d82d08570b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/outlier_candidates.py @@ -0,0 +1,69 @@ +from warnings import simplefilter + +import numpy as np + +import wandb +from wandb.integration.sklearn import utils + +# ignore all future warnings +simplefilter(action="ignore", category=FutureWarning) + + +def outlier_candidates(regressor, X, y): # noqa: N803 + # Fit a linear model to X and y to compute MSE + regressor.fit(X, y) + + # Leverage is computed as the diagonal of the projection matrix of X + leverage = (X * np.linalg.pinv(X).T).sum(1) + + # Compute the rank and the degrees of freedom of the OLS model + rank = np.linalg.matrix_rank(X) + df = X.shape[0] - rank + + # Compute the MSE from the residuals + residuals = y - regressor.predict(X) + mse = np.dot(residuals, residuals) / df + + # Compute Cook's distance + residuals_studentized = residuals / np.sqrt(mse) / np.sqrt(1 - leverage) + distance_ = residuals_studentized**2 / X.shape[1] + distance_ *= leverage / (1 - leverage) + + # Compute the influence threshold rule of thumb + influence_threshold_ = 4 / X.shape[0] + outlier_percentage_ = sum(distance_ >= influence_threshold_) / X.shape[0] + outlier_percentage_ *= 100.0 + + distance_dict, count = [], 0 + for d in distance_: + distance_dict.append(d) + count += 1 + if utils.check_against_limit( + count, + "outlier_candidates", + utils.chart_limit, + ): + break + + table = make_table(distance_dict, outlier_percentage_, influence_threshold_) + chart = wandb.visualize("wandb/outliers/v1", table) + + return chart + + +def make_table(distance, outlier_percentage, influence_threshold): + columns = [ + "distance", + "instance_indicies", + "outlier_percentage", + "influence_threshold", + ] + + data = [ + [distance[i], i, utils.round_3(outlier_percentage), influence_threshold] + for i in range(len(distance)) + ] + + table = wandb.Table(columns=columns, data=data) + + return table diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/residuals.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/residuals.py new file mode 100644 index 0000000000000000000000000000000000000000..b45df7b84fa5b3824f99425800bbf0039f7cacd8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/residuals.py @@ -0,0 +1,86 @@ +from warnings import simplefilter + +from sklearn import model_selection + +import wandb +from wandb.integration.sklearn import utils + +# ignore all future warnings +simplefilter(action="ignore", category=FutureWarning) + + +def residuals(regressor, X, y): # noqa: N803 + # Create the train and test splits + x_train, x_test, y_train, y_test = model_selection.train_test_split( + X, y, test_size=0.2 + ) + + # Store labels and colors for the legend ordered by call + regressor.fit(x_train, y_train) + train_score_ = regressor.score(x_train, y_train) + test_score_ = regressor.score(x_test, y_test) + + y_pred_train = regressor.predict(x_train) + residuals_train = y_pred_train - y_train + + y_pred_test = regressor.predict(x_test) + residuals_test = y_pred_test - y_test + + table = make_table( + y_pred_train, + residuals_train, + y_pred_test, + residuals_test, + train_score_, + test_score_, + ) + chart = wandb.visualize("wandb/residuals_plot/v1", table) + + return chart + + +def make_table( + y_pred_train, + residuals_train, + y_pred_test, + residuals_test, + train_score_, + test_score_, +): + y_pred_column, dataset_column, residuals_column = [], [], [] + + datapoints, max_datapoints_train = 0, 100 + for pred, residual in zip(y_pred_train, residuals_train): + # add class counts from training set + y_pred_column.append(pred) + dataset_column.append("train") + residuals_column.append(residual) + datapoints += 1 + if utils.check_against_limit(datapoints, "residuals", max_datapoints_train): + break + + datapoints = 0 + for pred, residual in zip(y_pred_test, residuals_test): + # add class counts from training set + y_pred_column.append(pred) + dataset_column.append("test") + residuals_column.append(residual) + datapoints += 1 + if utils.check_against_limit(datapoints, "residuals", max_datapoints_train): + break + + columns = ["dataset", "y_pred", "residuals", "train_score", "test_score"] + data = [ + [ + dataset_column[i], + y_pred_column[i], + residuals_column[i], + train_score_, + test_score_, + ] + for i in range(len(y_pred_column)) + ] + + table = wandb.Table(columns=columns, data=data) + + return table diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/summary_metrics.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/summary_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..e4b6f25ead2fd3c94c302db7693ca3fd529812d9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/calculate/summary_metrics.py @@ -0,0 +1,62 @@ +from warnings import simplefilter + +import numpy as np +import sklearn + +import wandb +from wandb.integration.sklearn import utils + +# ignore all future warnings +simplefilter(action="ignore", category=FutureWarning) + + +def summary_metrics(model=None, X=None, y=None, X_test=None, y_test=None): # noqa: N803 + """Calculate summary metrics for both regressors and classifiers. + + Called by plot_summary_metrics to visualize metrics. Please use the function + plot_summary_metrics() if you wish to visualize your summary metrics. + """ + y, y_test = np.asarray(y), np.asarray(y_test) + metrics = {} + model_name = model.__class__.__name__ + + y_pred = model.predict(X_test) + + if sklearn.base.is_classifier(model): + accuracy_score = sklearn.metrics.accuracy_score(y_test, y_pred) + metrics["accuracy_score"] = accuracy_score + + precision = sklearn.metrics.precision_score(y_test, y_pred, average="weighted") + metrics["precision"] = precision + + recall = sklearn.metrics.recall_score(y_test, y_pred, average="weighted") + metrics["recall"] = recall + + f1_score = sklearn.metrics.f1_score(y_test, y_pred, average="weighted") + metrics["f1_score"] = f1_score + + elif sklearn.base.is_regressor(model): + mae = sklearn.metrics.mean_absolute_error(y_test, y_pred) + metrics["mae"] = mae + + mse = sklearn.metrics.mean_squared_error(y_test, y_pred) + metrics["mse"] = mse + + r2_score = sklearn.metrics.r2_score(y_test, y_pred) + metrics["r2_score"] = r2_score + + metrics = {name: utils.round_2(metric) for name, metric in metrics.items()} + + table = make_table(metrics, model_name) + chart = wandb.visualize("wandb/metrics/v1", table) + + return chart + + +def make_table(metrics, model_name): + columns = ["metric_name", "metric_value", "model_name"] + table_content = [[name, value, model_name] for name, value in metrics.items()] + + table = wandb.Table(columns=columns, data=table_content) + + return table diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/plot/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/plot/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..710e24c010e108bb4f25d361092a55182ad26917 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/plot/__init__.py @@ -0,0 +1,35 @@ +"""Create and logs charts introspecting models built with scikit-learn to W&B.""" + +from .classifier import calibration_curve as plot_calibration_curve +from .classifier import class_proportions as plot_class_proportions +from .classifier import classifier as plot_classifier +from .classifier import confusion_matrix as plot_confusion_matrix +from .classifier import feature_importances as plot_feature_importances +from .classifier import precision_recall as plot_precision_recall +from .classifier import roc as plot_roc +from .clusterer import clusterer as plot_clusterer +from .clusterer import elbow_curve as plot_elbow_curve +from .clusterer import silhouette as plot_silhouette +from .regressor import outlier_candidates as plot_outlier_candidates +from .regressor import regressor as plot_regressor +from .regressor import residuals as plot_residuals +from .shared import learning_curve as plot_learning_curve +from .shared import summary_metrics as plot_summary_metrics + +__all__ = [ + "plot_classifier", + "plot_clusterer", + "plot_regressor", + "plot_summary_metrics", + "plot_learning_curve", + "plot_feature_importances", + "plot_class_proportions", + "plot_calibration_curve", + "plot_roc", + "plot_precision_recall", + "plot_confusion_matrix", + "plot_elbow_curve", + "plot_silhouette", + "plot_residuals", + "plot_outlier_candidates", +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/plot/__pycache__/classifier.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/plot/__pycache__/classifier.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa21928ffef8b86762eb8abfa66780b894a0392d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/plot/__pycache__/classifier.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/plot/__pycache__/shared.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/plot/__pycache__/shared.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55ac2543c1b9fb88ff8b44a90f6f4dc1276dc960 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/plot/__pycache__/shared.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/plot/classifier.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/plot/classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..e431c8090b565518315f7906c85314f7d4b0ad9b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/plot/classifier.py @@ -0,0 +1,329 @@ +"""Define plots for classification models built with scikit-learn.""" + +from warnings import simplefilter + +import numpy as np +from sklearn import naive_bayes + +import wandb +import wandb.plot +from wandb.integration.sklearn import calculate, utils + +from . import shared + +# ignore all future warnings +simplefilter(action="ignore", category=FutureWarning) + + +def classifier( + model, + X_train, # noqa: N803 + X_test, # noqa: N803 + y_train, + y_test, + y_pred, + y_probas, + labels, + is_binary=False, + model_name="Classifier", + feature_names=None, + log_learning_curve=False, +): + """Generate all sklearn classifier plots supported by W&B. + + The following plots are generated: + feature importances, confusion matrix, summary metrics, + class proportions, calibration curve, roc curve, precision-recall curve. + + Should only be called with a fitted classifier (otherwise an error is thrown). + + Args: + model: (classifier) Takes in a fitted classifier. + X_train: (arr) Training set features. + y_train: (arr) Training set labels. + X_test: (arr) Test set features. + y_test: (arr) Test set labels. + y_pred: (arr) Test set predictions by the model passed. + y_probas: (arr) Test set predicted probabilities by the model passed. + labels: (list) Named labels for target variable (y). Makes plots easier to + read by replacing target values with corresponding index. + For example if `labels=['dog', 'cat', 'owl']` all 0s are + replaced by dog, 1s by cat. + is_binary: (bool) Is the model passed a binary classifier? Defaults to False + model_name: (str) Model name. Defaults to 'Classifier' + feature_names: (list) Names for features. Makes plots easier to read by + replacing feature indexes with corresponding names. + log_learning_curve: (bool) Whether or not to log the learning curve. + Defaults to False. + + Returns: + None: To see plots, go to your W&B run page then expand the 'media' tab + under 'auto visualizations'. + + Example: + ```python + wandb.sklearn.plot_classifier( + model, + X_train, + X_test, + y_train, + y_test, + y_pred, + y_probas, + ["cat", "dog"], + False, + "RandomForest", + ["barks", "drools", "plays_fetch", "breed"], + ) + ``` + """ + wandb.termlog(f"\nPlotting {model_name}.") + + if not isinstance(model, naive_bayes.MultinomialNB): + feature_importances(model, feature_names) + wandb.termlog("Logged feature importances.") + + if log_learning_curve: + shared.learning_curve(model, X_train, y_train) + wandb.termlog("Logged learning curve.") + + confusion_matrix(y_test, y_pred, labels) + wandb.termlog("Logged confusion matrix.") + + shared.summary_metrics(model, X=X_train, y=y_train, X_test=X_test, y_test=y_test) + wandb.termlog("Logged summary metrics.") + + class_proportions(y_train, y_test, labels) + wandb.termlog("Logged class proportions.") + + if not isinstance(model, naive_bayes.MultinomialNB): + calibration_curve(model, X_train, y_train, model_name) + wandb.termlog("Logged calibration curve.") + + roc(y_test, y_probas, labels) + wandb.termlog("Logged roc curve.") + + precision_recall(y_test, y_probas, labels) + wandb.termlog("Logged precision-recall curve.") + + +def roc( + y_true=None, + y_probas=None, + labels=None, + plot_micro=True, + plot_macro=True, + classes_to_plot=None, +): + """Log the receiver-operating characteristic curve. + + Args: + y_true: (arr) Test set labels. + y_probas: (arr) Test set predicted probabilities. + labels: (list) Named labels for target variable (y). Makes plots easier to + read by replacing target values with corresponding index. + For example if `labels=['dog', 'cat', 'owl']` all 0s are + replaced by dog, 1s by cat. + + Returns: + None: To see plots, go to your W&B run page then expand the 'media' tab + under 'auto visualizations'. + + Example: + ```python + wandb.sklearn.plot_roc(y_true, y_probas, labels) + ``` + """ + roc_chart = wandb.plot.roc_curve(y_true, y_probas, labels, classes_to_plot) + wandb.log({"roc": roc_chart}) + + +def confusion_matrix( + y_true=None, + y_pred=None, + labels=None, + true_labels=None, + pred_labels=None, + normalize=False, +): + """Log a confusion matrix to W&B. + + Confusion matrices depict the pattern of misclassifications by a model. + + Args: + y_true: (arr) Test set labels. + y_probas: (arr) Test set predicted probabilities. + labels: (list) Named labels for target variable (y). Makes plots easier to + read by replacing target values with corresponding index. + For example if `labels=['dog', 'cat', 'owl']` all 0s are + replaced by dog, 1s by cat. + + Returns: + None: To see plots, go to your W&B run page then expand the 'media' tab + under 'auto visualizations'. + + Example: + ```python + wandb.sklearn.plot_confusion_matrix(y_true, y_probas, labels) + ``` + """ + y_true = np.asarray(y_true) + y_pred = np.asarray(y_pred) + + not_missing = utils.test_missing(y_true=y_true, y_pred=y_pred) + correct_types = utils.test_types(y_true=y_true, y_pred=y_pred) + + if not_missing and correct_types: + confusion_matrix_chart = calculate.confusion_matrix( + y_true, + y_pred, + labels, + true_labels, + pred_labels, + normalize, + ) + + wandb.log({"confusion_matrix": confusion_matrix_chart}) + + +def precision_recall( + y_true=None, y_probas=None, labels=None, plot_micro=True, classes_to_plot=None +): + """Log a precision-recall curve to W&B. + + Precision-recall curves depict the tradeoff between positive predictive value (precision) + and true positive rate (recall) as the threshold of a classifier is shifted. + + Args: + y_true: (arr) Test set labels. + y_probas: (arr) Test set predicted probabilities. + labels: (list) Named labels for target variable (y). Makes plots easier to + read by replacing target values with corresponding index. + For example if `labels=['dog', 'cat', 'owl']` all 0s are + replaced by dog, 1s by cat. + + Returns: + None: To see plots, go to your W&B run page then expand the 'media' tab + under 'auto visualizations'. + + Example: + ```python + wandb.sklearn.plot_precision_recall(y_true, y_probas, labels) + ``` + """ + precision_recall_chart = wandb.plot.pr_curve( + y_true, y_probas, labels, classes_to_plot + ) + + wandb.log({"precision_recall": precision_recall_chart}) + + +def feature_importances( + model=None, feature_names=None, title="Feature Importance", max_num_features=50 +): + """Log a plot depicting the relative importance of each feature for a classifier's decisions. + + Should only be called with a fitted classifier (otherwise an error is thrown). + Only works with classifiers that have a feature_importances_ attribute, like trees. + + Args: + model: (clf) Takes in a fitted classifier. + feature_names: (list) Names for features. Makes plots easier to read by + replacing feature indexes with corresponding names. + + Returns: + None: To see plots, go to your W&B run page then expand the 'media' tab + under 'auto visualizations'. + + Example: + ```python + wandb.sklearn.plot_feature_importances(model, ["width", "height", "length"]) + ``` + """ + not_missing = utils.test_missing(model=model) + correct_types = utils.test_types(model=model) + model_fitted = utils.test_fitted(model) + + if not_missing and correct_types and model_fitted: + feature_importance_chart = calculate.feature_importances(model, feature_names) + wandb.log({"feature_importances": feature_importance_chart}) + + +def class_proportions(y_train=None, y_test=None, labels=None): + """Plot the distribution of target classes in training and test sets. + + Useful for detecting imbalanced classes. + + Args: + y_train: (arr) Training set labels. + y_test: (arr) Test set labels. + labels: (list) Named labels for target variable (y). Makes plots easier to + read by replacing target values with corresponding index. + For example if `labels=['dog', 'cat', 'owl']` all 0s are + replaced by dog, 1s by cat. + + Returns: + None: To see plots, go to your W&B run page then expand the 'media' tab + under 'auto visualizations'. + + Example: + ```python + wandb.sklearn.plot_class_proportions(y_train, y_test, ["dog", "cat", "owl"]) + ``` + """ + not_missing = utils.test_missing(y_train=y_train, y_test=y_test) + correct_types = utils.test_types(y_train=y_train, y_test=y_test) + if not_missing and correct_types: + y_train, y_test = np.array(y_train), np.array(y_test) + class_proportions_chart = calculate.class_proportions(y_train, y_test, labels) + + wandb.log({"class_proportions": class_proportions_chart}) + + +def calibration_curve(clf=None, X=None, y=None, clf_name="Classifier"): # noqa: N803 + """Log a plot depicting how well-calibrated the predicted probabilities of a classifier are. + + Also suggests how to calibrate an uncalibrated classifier. Compares estimated predicted + probabilities by a baseline logistic regression model, the model passed as + an argument, and by both its isotonic calibration and sigmoid calibrations. + The closer the calibration curves are to a diagonal the better. + A sine wave like curve represents an overfitted classifier, while a cosine + wave like curve represents an underfitted classifier. + By training isotonic and sigmoid calibrations of the model and comparing + their curves we can figure out whether the model is over or underfitting and + if so which calibration (sigmoid or isotonic) might help fix this. + For more details, see https://scikit-learn.org/stable/auto_examples/calibration/plot_calibration_curve.html. + + Should only be called with a fitted classifier (otherwise an error is thrown). + + Please note this function fits variations of the model on the training set when called. + + Args: + clf: (clf) Takes in a fitted classifier. + X: (arr) Training set features. + y: (arr) Training set labels. + model_name: (str) Model name. Defaults to 'Classifier' + + Returns: + None: To see plots, go to your W&B run page then expand the 'media' tab + under 'auto visualizations'. + + Example: + ```python + wandb.sklearn.plot_calibration_curve(clf, X, y, "RandomForestClassifier") + ``` + """ + not_missing = utils.test_missing(clf=clf, X=X, y=y) + correct_types = utils.test_types(clf=clf, X=X, y=y) + is_fitted = utils.test_fitted(clf) + if not_missing and correct_types and is_fitted: + y = np.asarray(y) + if y.dtype.char == "U" or not ((y == 0) | (y == 1)).all(): + wandb.termwarn( + "This function only supports binary classification at the moment and therefore expects labels to be binary. Skipping calibration curve." + ) + return + + calibration_curve_chart = calculate.calibration_curves(clf, X, y, clf_name) + + wandb.log({"calibration_curve": calibration_curve_chart}) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/plot/clusterer.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/plot/clusterer.py new file mode 100644 index 0000000000000000000000000000000000000000..bced65ae105780961e434b78e6ef316297b5182e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/plot/clusterer.py @@ -0,0 +1,146 @@ +"""Define plots for clustering models built with scikit-learn.""" + +from warnings import simplefilter + +import pandas as pd +import sklearn + +import wandb +from wandb.integration.sklearn import calculate, utils + +# ignore all future warnings +simplefilter(action="ignore", category=FutureWarning) + + +def clusterer(model, X_train, cluster_labels, labels=None, model_name="Clusterer"): # noqa: N803 + """Generates all sklearn clusterer plots supported by W&B. + + The following plots are generated: + elbow curve, silhouette plot. + + Should only be called with a fitted clusterer (otherwise an error is thrown). + + Args: + model: (clusterer) Takes in a fitted clusterer. + X_train: (arr) Training set features. + cluster_labels: (list) Names for cluster labels. Makes plots easier to read + by replacing cluster indexes with corresponding names. + labels: (list) Named labels for target variable (y). Makes plots easier to + read by replacing target values with corresponding index. + For example if `labels=['dog', 'cat', 'owl']` all 0s are + replaced by dog, 1s by cat. + model_name: (str) Model name. Defaults to 'Clusterer' + + Returns: + None: To see plots, go to your W&B run page then expand the 'media' tab + under 'auto visualizations'. + + Example: + ```python + wandb.sklearn.plot_clusterer(kmeans, X, cluster_labels, labels, "KMeans") + ``` + """ + wandb.termlog(f"\nPlotting {model_name}.") + if isinstance(model, sklearn.cluster.KMeans): + elbow_curve(model, X_train) + wandb.termlog("Logged elbow curve.") + + silhouette(model, X_train, cluster_labels, labels=labels, kmeans=True) + + else: + silhouette(model, X_train, cluster_labels, kmeans=False) + + wandb.termlog("Logged silhouette plot.") + + +def elbow_curve( + clusterer=None, + X=None, # noqa: N803 + cluster_ranges=None, + n_jobs=1, + show_cluster_time=True, +): + """Measures and plots variance explained as a function of the number of clusters. + + Useful in picking the optimal number of clusters. + + Should only be called with a fitted clusterer (otherwise an error is thrown). + + Please note this function fits the model on the training set when called. + + Args: + model: (clusterer) Takes in a fitted clusterer. + X: (arr) Training set features. + + Returns: + None: To see plots, go to your W&B run page then expand the 'media' tab + under 'auto visualizations'. + + Example: + ```python + wandb.sklearn.plot_elbow_curve(model, X_train) + ``` + """ + if not hasattr(clusterer, "n_clusters"): + wandb.termlog( + "n_clusters attribute not in classifier. Cannot plot elbow method." + ) + return + + not_missing = utils.test_missing(clusterer=clusterer) + correct_types = utils.test_types + is_fitted = utils.test_fitted(clusterer) + + if not_missing and correct_types and is_fitted: + elbow_curve_chart = calculate.elbow_curve( + clusterer, X, cluster_ranges, n_jobs, show_cluster_time + ) + + wandb.log({"elbow_curve": elbow_curve_chart}) + + +def silhouette( + clusterer=None, + X=None, # noqa: N803 + cluster_labels=None, + labels=None, + metric="euclidean", + kmeans=True, +): + """Measures & plots silhouette coefficients. + + Silhouette coefficients near +1 indicate that the sample is far away from + the neighboring clusters. A value near 0 indicates that the sample is on or + very close to the decision boundary between two neighboring clusters and + negative values indicate that the samples might have been assigned to the wrong cluster. + + Should only be called with a fitted clusterer (otherwise an error is thrown). + + Please note this function fits the model on the training set when called. + + Args: + model: (clusterer) Takes in a fitted clusterer. + X: (arr) Training set features. + cluster_labels: (list) Names for cluster labels. Makes plots easier to read + by replacing cluster indexes with corresponding names. + + Returns: + None: To see plots, go to your W&B run page then expand the 'media' tab + under 'auto visualizations'. + + Example: + ```python + wandb.sklearn.plot_silhouette(model, X_train, ["spam", "not spam"]) + ``` + """ + not_missing = utils.test_missing(clusterer=clusterer) + correct_types = utils.test_types(clusterer=clusterer) + is_fitted = utils.test_fitted(clusterer) + + if not_missing and correct_types and is_fitted: + if isinstance(X, (pd.DataFrame)): + X = X.values # noqa: N806 + silhouette_chart = calculate.silhouette( + clusterer, X, cluster_labels, labels, metric, kmeans + ) + wandb.log({"silhouette_plot": silhouette_chart}) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/plot/regressor.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/plot/regressor.py new file mode 100644 index 0000000000000000000000000000000000000000..a2840a06dabfd27cbe0d980af2988f6cc1ef0604 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/plot/regressor.py @@ -0,0 +1,121 @@ +"""Define plots for regression models built with scikit-learn.""" + +from warnings import simplefilter + +import numpy as np + +import wandb +from wandb.integration.sklearn import calculate, utils + +from . import shared + +# ignore all future warnings +simplefilter(action="ignore", category=FutureWarning) + + +def regressor(model, X_train, X_test, y_train, y_test, model_name="Regressor"): # noqa: N803 + """Generates all sklearn regressor plots supported by W&B. + + The following plots are generated: + learning curve, summary metrics, residuals plot, outlier candidates. + + Should only be called with a fitted regressor (otherwise an error is thrown). + + Args: + model: (regressor) Takes in a fitted regressor. + X_train: (arr) Training set features. + y_train: (arr) Training set labels. + X_test: (arr) Test set features. + y_test: (arr) Test set labels. + model_name: (str) Model name. Defaults to 'Regressor' + + Returns: + None: To see plots, go to your W&B run page then expand the 'media' tab + under 'auto visualizations'. + + Example: + ```python + wandb.sklearn.plot_regressor(reg, X_train, X_test, y_train, y_test, "Ridge") + ``` + """ + wandb.termlog(f"\nPlotting {model_name}.") + + shared.summary_metrics(model, X_train, y_train, X_test, y_test) + wandb.termlog("Logged summary metrics.") + + shared.learning_curve(model, X_train, y_train) + wandb.termlog("Logged learning curve.") + + outlier_candidates(model, X_train, y_train) + wandb.termlog("Logged outlier candidates.") + + residuals(model, X_train, y_train) + wandb.termlog("Logged residuals.") + + +def outlier_candidates(regressor=None, X=None, y=None): # noqa: N803 + """Measures a datapoint's influence on regression model via cook's distance. + + Instances with high influences could potentially be outliers. + + Should only be called with a fitted regressor (otherwise an error is thrown). + + Please note this function fits the model on the training set when called. + + Args: + model: (regressor) Takes in a fitted regressor. + X: (arr) Training set features. + y: (arr) Training set labels. + + Returns: + None: To see plots, go to your W&B run page then expand the 'media' tab + under 'auto visualizations'. + + Example: + ```python + wandb.sklearn.plot_outlier_candidates(model, X, y) + ``` + """ + is_missing = utils.test_missing(regressor=regressor, X=X, y=y) + correct_types = utils.test_types(regressor=regressor, X=X, y=y) + is_fitted = utils.test_fitted(regressor) + + if is_missing and correct_types and is_fitted: + y = np.asarray(y) + + outliers_chart = calculate.outlier_candidates(regressor, X, y) + wandb.log({"outlier_candidates": outliers_chart}) + + +def residuals(regressor=None, X=None, y=None): # noqa: N803 + """Measures and plots the regressor's predicted value against the residual. + + The marginal distribution of residuals is also calculated and plotted. + + Should only be called with a fitted regressor (otherwise an error is thrown). + + Please note this function fits variations of the model on the training set when called. + + Args: + regressor: (regressor) Takes in a fitted regressor. + X: (arr) Training set features. + y: (arr) Training set labels. + + Returns: + None: To see plots, go to your W&B run page then expand the 'media' tab + under 'auto visualizations'. + + Example: + ```python + wandb.sklearn.plot_residuals(model, X, y) + ``` + """ + not_missing = utils.test_missing(regressor=regressor, X=X, y=y) + correct_types = utils.test_types(regressor=regressor, X=X, y=y) + is_fitted = utils.test_fitted(regressor) + + if not_missing and correct_types and is_fitted: + y = np.asarray(y) + + residuals_chart = calculate.residuals(regressor, X, y) + wandb.log({"residuals": residuals_chart}) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0b2ef628bbb4165e15d33cd26feb144bd2e40d11 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/sklearn/utils.py @@ -0,0 +1,184 @@ +"""Shared utilities for the modules in wandb.sklearn.""" + +from collections.abc import Iterable, Sequence + +import numpy as np +import pandas as pd +import scipy +import sklearn + +import wandb + +chart_limit = 1000 + + +def check_against_limit(count, chart, limit=None): + if limit is None: + limit = chart_limit + if count > limit: + warn_chart_limit(limit, chart) + return True + else: + return False + + +def warn_chart_limit(limit, chart): + warning = f"using only the first {limit} datapoints to create chart {chart}" + wandb.termwarn(warning) + + +def encode_labels(df): + le = sklearn.preprocessing.LabelEncoder() + # apply le on categorical feature columns + categorical_cols = df.select_dtypes( + exclude=["int", "float", "float64", "float32", "int32", "int64"] + ).columns + df[categorical_cols] = df[categorical_cols].apply(lambda col: le.fit_transform(col)) + + +def test_types(**kwargs): + test_passed = True + for k, v in kwargs.items(): + # check for incorrect types + if ( + (k == "X") + or (k == "X_test") + or (k == "y") + or (k == "y_test") + or (k == "y_true") + or (k == "y_probas") + ): + # FIXME: do this individually + if not isinstance( + v, + ( + Sequence, + Iterable, + np.ndarray, + np.generic, + pd.DataFrame, + pd.Series, + list, + ), + ): + wandb.termerror(f"{k} is not an array. Please try again.") + test_passed = False + # check for classifier types + if k == "model": + if (not sklearn.base.is_classifier(v)) and ( + not sklearn.base.is_regressor(v) + ): + wandb.termerror( + f"{k} is not a classifier or regressor. Please try again." + ) + test_passed = False + elif k == "clf" or k == "binary_clf": + if not (sklearn.base.is_classifier(v)): + wandb.termerror(f"{k} is not a classifier. Please try again.") + test_passed = False + elif k == "regressor": + if not sklearn.base.is_regressor(v): + wandb.termerror(f"{k} is not a regressor. Please try again.") + test_passed = False + elif k == "clusterer": + if not (getattr(v, "_estimator_type", None) == "clusterer"): + wandb.termerror(f"{k} is not a clusterer. Please try again.") + test_passed = False + return test_passed + + +def test_fitted(model): + try: + model.predict(np.zeros((7, 3))) + except sklearn.exceptions.NotFittedError: + wandb.termerror("Please fit the model before passing it in.") + return False + except AttributeError: + # Some clustering models (LDA, PCA, Agglomerative) don't implement ``predict`` + try: + sklearn.utils.validation.check_is_fitted( + model, + [ + "coef_", + "estimator_", + "labels_", + "n_clusters_", + "children_", + "components_", + "n_components_", + "n_iter_", + "n_batch_iter_", + "explained_variance_", + "singular_values_", + "mean_", + ], + all_or_any=any, + ) + except sklearn.exceptions.NotFittedError: + wandb.termerror("Please fit the model before passing it in.") + return False + else: + return True + except Exception: + # Assume it's fitted, since ``NotFittedError`` wasn't raised + return True + + +# Test Asummptions for plotting parameters and datasets +def test_missing(**kwargs): + test_passed = True + for k, v in kwargs.items(): + # Missing/empty params/datapoint arrays + if v is None: + wandb.termerror(f"{k} is None. Please try again.") + test_passed = False + if (k == "X") or (k == "X_test"): + if isinstance(v, scipy.sparse.csr.csr_matrix): + v = v.toarray() + elif isinstance(v, (pd.DataFrame, pd.Series)): + v = v.to_numpy() + elif isinstance(v, list): + v = np.asarray(v) + + # Warn the user about missing values + missing = 0 + missing = np.count_nonzero(pd.isnull(v)) + if missing > 0: + wandb.termwarn(f"{k} contains {missing} missing values. ") + test_passed = False + # Ensure the dataset contains only integers + non_nums = 0 + if v.ndim == 1: + non_nums = sum( + 1 + for val in v + if ( + not isinstance(val, (int, float, complex)) + and not isinstance(val, np.number) + ) + ) + else: + non_nums = sum( + 1 + for sl in v + for val in sl + if ( + not isinstance(val, (int, float, complex)) + and not isinstance(val, np.number) + ) + ) + if non_nums > 0: + wandb.termerror( + f"{k} contains values that are not numbers. Please vectorize, label encode or one hot encode {k} " + "and call the plotting function again." + ) + test_passed = False + return test_passed + + +def round_3(n): + return round(n, 3) + + +def round_2(n): + return round(n, 2) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/tensorboard/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/tensorboard/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d919067dda8553638b7a8bd1265ec148bd732de Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/tensorboard/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/tensorboard/__pycache__/log.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/tensorboard/__pycache__/log.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..900bcb8842817cb242cf10373d2be33c3a08356d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/tensorboard/__pycache__/log.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/tensorflow/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/tensorflow/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b220bf80c6dc7b5b3d826e1898724a290d1a47e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/tensorflow/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/torch/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/torch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f31f58141875ef3f39697198bd78a7e43e2fa89b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/torch/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/torch/__pycache__/wandb_torch.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/torch/__pycache__/wandb_torch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d731554b43445eb3d2d33977a2024658fe694c2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/torch/__pycache__/wandb_torch.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/torch/wandb_torch.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/torch/wandb_torch.py new file mode 100644 index 0000000000000000000000000000000000000000..28d5971f8fd640ef6315aa22cb795163bc9d0724 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/torch/wandb_torch.py @@ -0,0 +1,554 @@ +"""PyTorch-specific functionality.""" + +import itertools +from functools import reduce +from operator import mul +from typing import TYPE_CHECKING, List + +import wandb +from wandb import util +from wandb.data_types import Node + +torch = None + +if TYPE_CHECKING: + from torch import Tensor + from torch.nn import Module + + +def nested_shape(array_or_tuple, seen=None): + """Figure out the shape of tensors possibly embedded in tuples. + + for example: + - [0,0] returns (2) + - ([0,0], [0,0]) returns (2,2) + - (([0,0], [0,0]),[0,0]) returns ((2,2),2). + """ + if seen is None: + seen = set() + if hasattr(array_or_tuple, "size"): + # pytorch tensors use V.size() to get size of tensor + return list(array_or_tuple.size()) + elif hasattr(array_or_tuple, "get_shape"): + # tensorflow uses V.get_shape() to get size of tensor + return array_or_tuple.get_shape().as_list() + elif hasattr(array_or_tuple, "shape"): + return array_or_tuple.shape + + seen.add(id(array_or_tuple)) + try: + # treat object as iterable + return [ + nested_shape(item, seen) if id(item) not in seen else 0 + for item in list(array_or_tuple) + ] + except TypeError: + # object is not actually iterable + # LB: Maybe we should throw an error? + return [] + + +LOG_TRACK_COUNT, LOG_TRACK_THRESHOLD = range(2) + + +def log_track_init(log_freq: int) -> List[int]: + """Create tracking structure used by log_track_update.""" + log_track = [0, 0] + log_track[LOG_TRACK_THRESHOLD] = log_freq + return log_track + + +def log_track_update(log_track: int) -> bool: + """Count (log_track[0]) up to threshold (log_track[1]), reset count (log_track[0]) and return true when reached.""" + log_track[LOG_TRACK_COUNT] += 1 + if log_track[LOG_TRACK_COUNT] < log_track[LOG_TRACK_THRESHOLD]: + return False + log_track[LOG_TRACK_COUNT] = 0 + return True + + +class TorchHistory: + """History methods specific to PyTorch.""" + + def __init__(self): + global torch + torch = wandb.util.get_module("torch", "Could not import torch") + self._hook_handles = {} + self._num_bins = 64 + self._is_cuda_histc_supported = None + self.hook_torch = TorchGraph.hook_torch + + def add_log_parameters_hook( + self, + module: "Module", + name: str = "", + prefix: str = "", + log_freq: int = 0, + ) -> None: + """This instruments hooks into the pytorch module. + + log parameters after a forward pass + log_freq - log gradients/parameters every N batches. + """ + # if name is not None: + prefix = prefix + name + + if not hasattr(module, "_wandb_hook_names"): + module._wandb_hook_names = [] + + def parameter_log_hook(module, input_, output, log_track): + if not log_track_update(log_track): + return + for name, parameter in module.named_parameters(): + # for pytorch 0.3 Variables + if isinstance(parameter, torch.autograd.Variable): + data = parameter.data + else: + data = parameter + self.log_tensor_stats(data.cpu(), "parameters/" + prefix + name) + + log_track_params = log_track_init(log_freq) + try: + hook = module.register_forward_hook( + lambda mod, inp, outp: parameter_log_hook( + mod, inp, outp, log_track_params + ) + ) + self._hook_handles["parameters/" + prefix] = hook + module._wandb_hook_names.append("parameters/" + prefix) + except RuntimeError as e: + wandb.termwarn( + f"Trying to register forward_hook failed ({e}) - skipping parameter tracking." + ) + + def add_log_gradients_hook( + self, + module: "Module", + name: str = "", + prefix: str = "", + log_freq: int = 0, + ) -> None: + """This instruments hooks into the PyTorch module slog gradients after a backward pass. + + Args: + module: torch.nn.Module - the module to instrument + name: str - the name of the module + prefix: str - the prefix to add to the name + log_freq: log gradients/parameters every N batches + """ + # if name is not None: + prefix = prefix + name + + if not hasattr(module, "_wandb_hook_names"): + module._wandb_hook_names = [] + + for name, parameter in module.named_parameters(): + if parameter.requires_grad: + log_track_grad = log_track_init(log_freq) + module._wandb_hook_names.append("gradients/" + prefix + name) + self._hook_variable_gradient_stats( + parameter, "gradients/" + prefix + name, log_track_grad + ) + + def log_tensor_stats(self, tensor, name): # noqa: C901 + """Add distribution statistics on a tensor's elements to the current History entry.""" + # TODO Handle the case of duplicate names. + if isinstance(tensor, (tuple, list)): + while isinstance(tensor, (tuple, list)) and isinstance( + tensor[0], (tuple, list) + ): + tensor = [item for sublist in tensor for item in sublist] + tensor = torch.cat([t.detach().clone().reshape(-1) for t in tensor]) + + tensor = tensor.detach().clone() + # checking for inheritance from _TensorBase didn't work for some reason + if not hasattr(tensor, "shape"): + cls = type(tensor) + raise TypeError(f"Expected Tensor, not {cls.__module__}.{cls.__name__}") + + # Sparse tensors have a bunch of implicit zeros. In order to histo them correctly, + # we have to count them up and add them to the histo ourselves. + sparse_zeros = None + if tensor.is_sparse: + # Have to call this on a sparse tensor before most other ops. + tensor = tensor.cpu().coalesce() + + backing_values = tensor._values() + sparse_zeros = tensor.numel() - backing_values.numel() + tensor = backing_values + + flat = tensor.reshape(-1) + + if flat.is_cuda: + if self._is_cuda_histc_supported is None: + try: + flat.histc(bins=self._num_bins) + except RuntimeError: + self._is_cuda_histc_supported = False + else: + self._is_cuda_histc_supported = True + + # As of torch 1.0.1.post2+nightly, float16 cuda summary ops are not supported (convert to float32) + if not self._is_cuda_histc_supported: + flat = flat.cpu() + elif not isinstance( + flat, (torch.cuda.FloatTensor, torch.cuda.DoubleTensor) + ): + flat = flat.type(torch.cuda.FloatTensor) + + # Since we use histc, we need to make sure that torch supports the operation on CPU, + # otherwise we'll get a runtime error. Hence, we need to upcast to float32. + if not flat.is_cuda and not isinstance( + flat, (torch.FloatTensor, torch.DoubleTensor) + ): + flat = flat.type(torch.FloatTensor) + + # Skip logging if all values are nan or inf or the tensor is empty. + if self._no_finite_values(flat): + return + + # Remove nans and infs if present. There's no good way to represent that in histograms. + flat = self._remove_infs_nans(flat) + + tmin = flat.min().item() + tmax = flat.max().item() + if sparse_zeros: + # If we've got zeros to add in, make sure zero is in the hist range. + tmin = 0 if tmin > 0 else tmin + tmax = 0 if tmax < 0 else tmax + # Anecdotally, this can somehow happen sometimes. Maybe a precision error + # in min()/max() above. Swap here to prevent a runtime error. + # If all values are equal, just return a single bin. + if tmin > tmax: + tmin, tmax = tmax, tmin + if tmin == tmax: + tensor = torch.Tensor([flat.numel()]) + tensor = tensor.cpu().clone().detach() + bins = torch.Tensor([tmin, tmax]) + else: + tensor = flat.histc(bins=self._num_bins, min=tmin, max=tmax) + tensor = tensor.cpu().detach().clone() + bins = torch.linspace(tmin, tmax, steps=self._num_bins + 1) + + # Add back zeroes from a sparse tensor. + if sparse_zeros: + bins_np = bins.numpy() + tensor_np = tensor.numpy() + bin_idx = 0 + num_buckets = len(bins_np) - 1 + for i in range(num_buckets): + start = bins_np[i] + end = bins_np[i + 1] + # There are 3 cases to consider here, all of which mean we've found the right bucket + # 1. The bucket range contains zero. + # 2. The bucket range lower bound *is* zero. + # 3. This is the last bucket and the bucket range upper bound is zero. + if (start <= 0 and end > 0) or (i == num_buckets - 1 and end == 0): + bin_idx = i + break + + tensor_np[bin_idx] += sparse_zeros + tensor = torch.Tensor(tensor_np) + bins = torch.Tensor(bins_np) + + wandb.run._log( + {name: wandb.Histogram(np_histogram=(tensor.tolist(), bins.tolist()))}, + commit=False, + ) + + def _hook_variable_gradient_stats(self, var, name, log_track): + """Logs a Variable's gradient's distribution statistics next time backward() is called on it.""" + if not isinstance(var, torch.autograd.Variable): + cls = type(var) + raise TypeError( + f"Expected torch.Variable, not {cls.__module__}.{cls.__name__}" + ) + + handle = self._hook_handles.get(name) + if handle is not None and self._torch_hook_handle_is_valid(handle): + raise ValueError(f'A hook has already been set under name "{name}"') + + def _callback(grad, log_track): + if not log_track_update(log_track): + return + self.log_tensor_stats(grad.data, name) + + handle = var.register_hook(lambda grad: _callback(grad, log_track)) + self._hook_handles[name] = handle + return handle + + def unhook_all(self): + for handle in self._hook_handles.values(): + handle.remove() + self._hook_handles = {} + + def unhook(self, name): + handle = self._hook_handles.pop(name) + handle.remove() + + def _torch_hook_handle_is_valid(self, handle): + d = handle.hooks_dict_ref() + if d is None: + return False + else: + return handle.id in d + + def _no_finite_values(self, tensor: "Tensor") -> bool: + return tensor.shape == torch.Size([0]) or (~torch.isfinite(tensor)).all().item() + + def _remove_infs_nans(self, tensor: "Tensor") -> "Tensor": + if not torch.isfinite(tensor).all(): + tensor = tensor[torch.isfinite(tensor)] + + return tensor + + +class TorchGraph(wandb.data_types.Graph): + def __init__(self): + super().__init__("torch") + self._graph_hooks = set() + + @classmethod + def hook_torch(cls, model, criterion=None, graph_idx=0): + wandb.termlog("logging graph, to disable use `wandb.watch(log_graph=False)`") + graph = TorchGraph() + graph.hook_torch_modules(model, criterion, graph_idx=graph_idx) + return graph + + def create_forward_hook(self, name, graph_idx): + graph = self + + def after_forward_hook(module, input, output): + if id(module) not in self._graph_hooks: + # hook already processed -> noop + return + if not isinstance(output, tuple): + output = (output,) + parameters = [ + (pname, list(param.size())) + for pname, param in module.named_parameters() + ] + + node = Node( + id=id(module), + name=name, + class_name=str(module), + output_shape=nested_shape(output), + parameters=parameters, + num_parameters=[reduce(mul, size, 1) for (pname, size) in parameters], + ) + graph.nodes_by_id[id(module)] = node + for param in module.parameters(): + graph.nodes_by_id[id(param)] = node + graph.add_node(node) + if not graph.criterion_passed: + if hasattr(output[0], "grad_fn"): + graph.criterion = output[0].grad_fn + elif ( + isinstance(output[0], list) + and output[0] + and hasattr(output[0][0], "grad_fn") + ): + graph.criterion = output[0][0].grad_fn + + # hook has been processed + self._graph_hooks -= {id(module)} + + if not self._graph_hooks: + # we went through the entire graph + wandb.run.summary[f"graph_{graph_idx}"] = self + + return after_forward_hook + + def hook_torch_modules( + self, module, criterion=None, prefix=None, graph_idx=0, parent=None + ): + torch = util.get_module("torch", "Could not import torch") + layers = 0 + graph = self + if hasattr(module, "_wandb_watch_called") and module._wandb_watch_called: + raise ValueError( + "You can only call `wandb.watch` once per model. Pass a new instance of the model if you need to call wandb.watch again in your code." + ) + module._wandb_watch_called = True + if criterion: + graph.criterion = criterion + graph.criterion_passed = True + + for name, sub_module in module.named_children(): + name = name or str(layers) + if prefix: + name = prefix + "." + name + layers += 1 + if not isinstance(sub_module, torch.nn.Module): + # TODO: Why does this happen? + break + + # Trying to support torch >0.3 making this code complicated + # We want a list of types that we should recurse into + # Torch 0.3 uses containers + # 0.4 has ModuleList + # 0.4.1 has ModuleDict + module_types = [ + getattr(torch.nn, module_classname) + for module_classname in ( + "Container", + "Sequential", + "ModuleList", + "ModuleDict", + ) + if hasattr(torch.nn, module_classname) + ] + if parent is None: + parent = module + + if isinstance(sub_module, tuple(module_types)): + self.hook_torch_modules(sub_module, prefix=name, parent=parent) + else: + self._graph_hooks |= {id(sub_module)} + try: + graph_hook = sub_module.register_forward_hook( + self.create_forward_hook(name, graph_idx) + ) + wandb.run._torch._hook_handles[ + "topology/" + str(id(graph_hook)) + ] = graph_hook + if not hasattr(parent, "_wandb_hook_names"): + # should never happen but let's be extra safe + parent._wandb_hook_names = [] + parent._wandb_hook_names.append("topology/" + str(id(graph_hook))) + except RuntimeError as e: + wandb.termwarn( + f"Trying to register forward_hook failed ({e}) - skipping graph tracking.", + repeat=False, + ) + + @classmethod + def from_torch_layers(cls, module_graph, variable): + """Recover something like neural net layers from PyTorch Module's and the compute graph from a Variable. + + Example output for a multi-layer RNN. We confusingly assign shared embedding values + to the encoder, but ordered next to the decoder. + + rnns.0.linear.module.weight_raw rnns.0 + rnns.0.linear.module.bias rnns.0 + rnns.1.linear.module.weight_raw rnns.1 + rnns.1.linear.module.bias rnns.1 + rnns.2.linear.module.weight_raw rnns.2 + rnns.2.linear.module.bias rnns.2 + rnns.3.linear.module.weight_raw rnns.3 + rnns.3.linear.module.bias rnns.3 + decoder.weight encoder + decoder.bias decoder + """ + # TODO: We're currently not using this, but I left it here in case we want to resurrect! - CVP + torch = util.get_module("torch", "Could not import torch") + + module_nodes_by_hash = {id(n): n for n in module_graph.nodes} + module_parameter_nodes = [ + n for n in module_graph.nodes if isinstance(n.obj, torch.nn.Parameter) + ] + + names_by_pid = {id(n.obj): n.name for n in module_parameter_nodes} + + reachable_param_nodes = module_graph[0].reachable_descendents() + reachable_params = {} + module_reachable_params = {} + names = {} + for pid, reachable_nodes in reachable_param_nodes.items(): + node = module_nodes_by_hash[pid] + if not isinstance(node.obj, torch.nn.Module): + continue + module = node.obj + reachable_params = {} # by object id + module_reachable_params[id(module)] = reachable_params + names[node.name] = set() + for reachable_hash in reachable_nodes: + reachable = module_nodes_by_hash[reachable_hash] + if isinstance(reachable.obj, torch.nn.Parameter): + param = reachable.obj + reachable_params[id(param)] = param + names[node.name].add(names_by_pid[id(param)]) + + # we look for correspondences between sets of parameters used in subtrees of the + # computation graph and sets of parameters contained in subtrees of the module + # graph + node_depths = {id(n): d for n, d in module_graph[0].descendent_bfs()} + parameter_module_names = {} + parameter_modules = {} + for param_node in ( + n for n in module_graph.nodes if isinstance(n.obj, torch.nn.Parameter) + ): + pid = id(param_node.obj) + best_node = None + best_depth = None + best_reachable_params = None + for node in module_graph.nodes: + if not isinstance(node.obj, torch.nn.Module): + continue + module = node.obj + reachable_params = module_reachable_params[id(module)] + if pid in reachable_params: + depth = node_depths[id(node)] + if best_node is None or (len(reachable_params), depth) <= ( + len(best_reachable_params), + best_depth, + ): + best_node = node + best_depth = depth + best_reachable_params = reachable_params + + parameter_modules[pid] = best_node + parameter_module_names[param_node.name] = best_node.name + + # contains all parameters but only a minimal set of modules necessary + # to contain them (and which ideally correspond to conceptual layers) + reduced_module_graph = cls() + rmg_ids = itertools.count() + rmg_root = Node(id=next(rmg_ids), node=module_graph[0]) + reduced_module_graph.add_node(rmg_root) + reduced_module_graph.root = rmg_root + rmg_nodes_by_pid = {} + + module_nodes_by_pid = {id(n.obj): n for n in module_graph.nodes} + + compute_graph, compute_node_vars = cls.from_torch_compute_graph(variable) + for node, _ in reversed(list(compute_graph[0].ancestor_bfs())): + param = compute_node_vars.get(node.id) + pid = id(param) + if not isinstance(param, torch.nn.Parameter): + continue + if pid not in module_nodes_by_pid: + # not all Parameters that occur in the compute graph come from the Module graph + continue + + # add the nodes in the order we want to display them on the frontend + mid = id(parameter_modules[pid].obj) + if mid in rmg_nodes_by_pid: + rmg_module = rmg_nodes_by_pid[mid] + else: + rmg_module = rmg_nodes_by_pid[mid] = Node( + id=next(rmg_ids), node=module_nodes_by_pid[mid] + ) + reduced_module_graph.add_node(rmg_module) + reduced_module_graph.add_edge(rmg_root, rmg_module) + + rmg_param = Node(id=next(rmg_ids), node=module_nodes_by_pid[pid]) + rmg_nodes_by_pid[pid] = rmg_param + reduced_module_graph.add_node(rmg_param) + + reduced_module_graph.add_edge(rmg_module, rmg_param) + return reduced_module_graph + + @classmethod + def node_from_module(cls, nid, module): + numpy = util.get_module("numpy", "Could not import numpy") + + node = wandb.Node() + node.id = nid + node.child_parameters = 0 + for parameter in module.parameters(): + node.child_parameters += numpy.prod(parameter.size()) + node.class_name = type(module).__name__ + + return node diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/ultralytics/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/ultralytics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c25ae320c8c946a25150b870770710f58a8bf713 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/ultralytics/__init__.py @@ -0,0 +1,11 @@ +"""Tools for integrating with [`ultralytics`](https://docs.ultralytics.com/). + +Ultralytics is a computer vision framework for training and deploying YOLOv8 models. +""" + +from wandb.integration.ultralytics.callback import ( + WandBUltralyticsCallback, + add_wandb_callback, +) + +__all__ = ("WandBUltralyticsCallback", "add_wandb_callback") diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/ultralytics/__pycache__/pose_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/ultralytics/__pycache__/pose_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..721fc73227aa6d231ae017d732ed2e10f140c377 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/ultralytics/__pycache__/pose_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/xgboost/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/xgboost/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2209c1dccb883ddbee7314f27d4a1f9b8ce1f29e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/xgboost/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/xgboost/__pycache__/xgboost.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/xgboost/__pycache__/xgboost.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a80be9f76c77b13a60bf177bc893664d08bf888e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/xgboost/__pycache__/xgboost.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/xgboost/xgboost.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/xgboost/xgboost.py new file mode 100644 index 0000000000000000000000000000000000000000..2a8b63dfa2f39db9d40989dc8562cc732ba11d98 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/xgboost/xgboost.py @@ -0,0 +1,189 @@ +"""xgboost init!""" + +import json +import warnings +from pathlib import Path +from typing import TYPE_CHECKING, cast + +import xgboost as xgb # type: ignore +from xgboost import Booster + +import wandb +from wandb.sdk.lib import telemetry as wb_telemetry + +MINIMIZE_METRICS = [ + "rmse", + "rmsle", + "mae", + "mape", + "mphe", + "logloss", + "error", + "error@t", + "merror", +] + +MAXIMIZE_METRICS = ["auc", "aucpr", "ndcg", "map", "ndcg@n", "map@n"] + + +if TYPE_CHECKING: + from typing import Callable, List, NamedTuple + + class CallbackEnv(NamedTuple): + evaluation_result_list: List + + +def wandb_callback() -> "Callable": + """Old style callback that will be deprecated in favor of WandbCallback. Please try the new logger for more features.""" + warnings.warn( + "wandb_callback will be deprecated in favor of WandbCallback. Please use WandbCallback for more features.", + UserWarning, + stacklevel=2, + ) + + with wb_telemetry.context() as tel: + tel.feature.xgboost_old_wandb_callback = True + + def callback(env: "CallbackEnv") -> None: + for k, v in env.evaluation_result_list: + wandb.log({k: v}, commit=False) + wandb.log({}) + + return callback + + +class WandbCallback(xgb.callback.TrainingCallback): + """`WandbCallback` automatically integrates XGBoost with wandb. + + Args: + log_model: (boolean) if True save and upload the model to Weights & Biases Artifacts + log_feature_importance: (boolean) if True log a feature importance bar plot + importance_type: (str) one of {weight, gain, cover, total_gain, total_cover} for tree model. weight for linear model. + define_metric: (boolean) if True (default) capture model performance at the best step, instead of the last step, of training in your `wandb.summary`. + + Passing `WandbCallback` to XGBoost will: + + - log the booster model configuration to Weights & Biases + - log evaluation metrics collected by XGBoost, such as rmse, accuracy etc. to Weights & Biases + - log training metric collected by XGBoost (if you provide training data to eval_set) + - log the best score and the best iteration + - save and upload your trained model to Weights & Biases Artifacts (when `log_model = True`) + - log feature importance plot when `log_feature_importance=True` (default). + - Capture the best eval metric in `wandb.summary` when `define_metric=True` (default). + + Example: + ```python + bst_params = dict( + objective="reg:squarederror", + colsample_bytree=0.3, + learning_rate=0.1, + max_depth=5, + alpha=10, + n_estimators=10, + tree_method="hist", + callbacks=[WandbCallback()], + ) + + xg_reg = xgb.XGBRegressor(**bst_params) + xg_reg.fit( + X_train, + y_train, + eval_set=[(X_test, y_test)], + ) + ``` + """ + + def __init__( + self, + log_model: bool = False, + log_feature_importance: bool = True, + importance_type: str = "gain", + define_metric: bool = True, + ): + self.log_model: bool = log_model + self.log_feature_importance: bool = log_feature_importance + self.importance_type: str = importance_type + self.define_metric: bool = define_metric + + if wandb.run is None: + raise wandb.Error("You must call wandb.init() before WandbCallback()") + + with wb_telemetry.context() as tel: + tel.feature.xgboost_wandb_callback = True + + def before_training(self, model: Booster) -> Booster: + """Run before training is finished.""" + # Update W&B config + config = model.save_config() + wandb.config.update(json.loads(config)) + + return model + + def after_training(self, model: Booster) -> Booster: + """Run after training is finished.""" + # Log the booster model as artifacts + if self.log_model: + self._log_model_as_artifact(model) + + # Plot feature importance + if self.log_feature_importance: + self._log_feature_importance(model) + + # Log the best score and best iteration + if model.attr("best_score") is not None: + wandb.log( + { + "best_score": float(cast(str, model.attr("best_score"))), + "best_iteration": int(cast(str, model.attr("best_iteration"))), + } + ) + + return model + + def after_iteration(self, model: Booster, epoch: int, evals_log: dict) -> bool: + """Run after each iteration. Return True when training should stop.""" + # Log metrics + for data, metric in evals_log.items(): + for metric_name, log in metric.items(): + if self.define_metric: + self._define_metric(data, metric_name) + wandb.log({f"{data}-{metric_name}": log[-1]}, commit=False) + else: + wandb.log({f"{data}-{metric_name}": log[-1]}, commit=False) + + wandb.log({"epoch": epoch}) + + self.define_metric = False + + return False + + def _log_model_as_artifact(self, model: Booster) -> None: + model_name = f"{wandb.run.id}_model.json" # type: ignore + model_path = Path(wandb.run.dir) / model_name # type: ignore + model.save_model(str(model_path)) + + model_artifact = wandb.Artifact(name=model_name, type="model") + model_artifact.add_file(str(model_path)) + wandb.log_artifact(model_artifact) + + def _log_feature_importance(self, model: Booster) -> None: + fi = model.get_score(importance_type=self.importance_type) + fi_data = [[k, fi[k]] for k in fi] + table = wandb.Table(data=fi_data, columns=["Feature", "Importance"]) + wandb.log( + { + "Feature Importance": wandb.plot.bar( + table, "Feature", "Importance", title="Feature Importance" + ) + } + ) + + def _define_metric(self, data: str, metric_name: str) -> None: + if "loss" in str.lower(metric_name): + wandb.define_metric(f"{data}-{metric_name}", summary="min") + elif str.lower(metric_name) in MINIMIZE_METRICS: + wandb.define_metric(f"{data}-{metric_name}", summary="min") + elif str.lower(metric_name) in MAXIMIZE_METRICS: + wandb.define_metric(f"{data}-{metric_name}", summary="max") + else: + pass diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/yolov8/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/yolov8/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/yolov8/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/yolov8/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11679035d368eac9745534ff79a6b51866d1ef8e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/yolov8/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/yolov8/yolov8.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/yolov8/yolov8.py new file mode 100644 index 0000000000000000000000000000000000000000..1c5dbd0fe8de39f387b6427b4696f28f9c029b44 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/integration/yolov8/yolov8.py @@ -0,0 +1,284 @@ +from typing import Any, Callable, Dict, List, Optional + +from ultralytics.yolo.engine.model import YOLO +from ultralytics.yolo.engine.trainer import BaseTrainer + +try: + from ultralytics.yolo.utils import RANK + from ultralytics.yolo.utils.torch_utils import get_flops, get_num_params +except ModuleNotFoundError: + from ultralytics.utils import RANK + from ultralytics.utils.torch_utils import get_flops, get_num_params +from ultralytics.yolo.v8.classify.train import ClassificationTrainer + +import wandb +from wandb.sdk.lib import telemetry + + +class WandbCallback: + """An internal YOLO model wrapper that tracks metrics, and logs models to Weights & Biases. + + Usage: + ```python + from wandb.integration.yolov8.yolov8 import WandbCallback + + model = YOLO("yolov8n.pt") + wandb_logger = WandbCallback( + model, + ) + for event, callback_fn in wandb_logger.callbacks.items(): + model.add_callback(event, callback_fn) + ``` + """ + + def __init__( + self, + yolo: YOLO, + run_name: Optional[str] = None, + project: Optional[str] = None, + tags: Optional[List[str]] = None, + resume: Optional[str] = None, + **kwargs: Optional[Any], + ) -> None: + """A utility class to manage wandb run and various callbacks for the ultralytics YOLOv8 framework. + + Args: + yolo: A YOLOv8 model that's inherited from `:class:ultralytics.yolo.engine.model.YOLO` + run_name, str: The name of the Weights & Biases run, defaults to an auto generated run_name if `trainer.args.name` is not defined. + project, str: The name of the Weights & Biases project, defaults to `"YOLOv8"` if `trainer.args.project` is not defined. + tags, List[str]: A list of tags to be added to the Weights & Biases run, defaults to `["YOLOv8"]`. + resume, str: Whether to resume a previous run on Weights & Biases, defaults to `None`. + **kwargs: Additional arguments to be passed to `wandb.init()`. + """ + self.yolo = yolo + self.run_name = run_name + self.project = project + self.tags = tags + self.resume = resume + self.kwargs = kwargs + + def on_pretrain_routine_start(self, trainer: BaseTrainer) -> None: + """Starts a new wandb run to track the training process and log to Weights & Biases. + + Args: + trainer: A task trainer that's inherited from `:class:ultralytics.yolo.engine.trainer.BaseTrainer` + that contains the model training and optimization routine. + """ + if wandb.run is None: + self.run = wandb.init( + name=self.run_name if self.run_name else trainer.args.name, + project=self.project + if self.project + else trainer.args.project or "YOLOv8", + tags=self.tags if self.tags else ["YOLOv8"], + config=vars(trainer.args), + resume=self.resume if self.resume else None, + **self.kwargs, + ) + else: + self.run = wandb.run + assert self.run is not None + self.run.define_metric("epoch", hidden=True) + self.run.define_metric( + "train/*", step_metric="epoch", step_sync=True, summary="min" + ) + + self.run.define_metric( + "val/*", step_metric="epoch", step_sync=True, summary="min" + ) + + self.run.define_metric( + "metrics/*", step_metric="epoch", step_sync=True, summary="max" + ) + self.run.define_metric( + "lr/*", step_metric="epoch", step_sync=True, summary="last" + ) + + with telemetry.context(run=wandb.run) as tel: + tel.feature.ultralytics_yolov8 = True + + def on_pretrain_routine_end(self, trainer: BaseTrainer) -> None: + assert self.run is not None + self.run.summary.update( + { + "model/parameters": get_num_params(trainer.model), + "model/GFLOPs": round(get_flops(trainer.model), 3), + } + ) + + def on_train_epoch_start(self, trainer: BaseTrainer) -> None: + """On train epoch start we only log epoch number to the Weights & Biases run.""" + # We log the epoch number here to commit the previous step, + assert self.run is not None + self.run.log({"epoch": trainer.epoch + 1}) + + def on_train_epoch_end(self, trainer: BaseTrainer) -> None: + """On train epoch end we log all the metrics to the Weights & Biases run.""" + assert self.run is not None + self.run.log( + { + **trainer.metrics, + **trainer.label_loss_items(trainer.tloss, prefix="train"), + **trainer.lr, + }, + ) + # Currently only the detection and segmentation trainers save images to the save_dir + if not isinstance(trainer, ClassificationTrainer): + self.run.log( + { + "train_batch_images": [ + wandb.Image(str(image_path), caption=image_path.stem) + for image_path in trainer.save_dir.glob("train_batch*.jpg") + ] + } + ) + + def on_fit_epoch_end(self, trainer: BaseTrainer) -> None: + """On fit epoch end we log all the best metrics and model detail to Weights & Biases run summary.""" + assert self.run is not None + if trainer.epoch == 0: + speeds = [ + trainer.validator.speed.get( + key, + ) + for key in (1, "inference") + ] + speed = speeds[0] if speeds[0] else speeds[1] + if speed: + self.run.summary.update( + { + "model/speed(ms/img)": round(speed, 3), + } + ) + if trainer.best_fitness == trainer.fitness: + self.run.summary.update( + { + "best/epoch": trainer.epoch + 1, + **{f"best/{key}": val for key, val in trainer.metrics.items()}, + } + ) + + def on_train_end(self, trainer: BaseTrainer) -> None: + """On train end we log all the media, including plots, images and best model artifact to Weights & Biases.""" + # Currently only the detection and segmentation trainers save images to the save_dir + assert self.run is not None + if not isinstance(trainer, ClassificationTrainer): + assert self.run is not None + self.run.log( + { + "plots": [ + wandb.Image(str(image_path), caption=image_path.stem) + for image_path in trainer.save_dir.glob("*.png") + ], + "val_images": [ + wandb.Image(str(image_path), caption=image_path.stem) + for image_path in trainer.validator.save_dir.glob("val*.jpg") + ], + }, + ) + + if trainer.best.exists(): + assert self.run is not None + self.run.log_artifact( + str(trainer.best), + type="model", + name=f"{self.run.name}_{trainer.args.task}.pt", + aliases=["best", f"epoch_{trainer.epoch + 1}"], + ) + + def on_model_save(self, trainer: BaseTrainer) -> None: + """On model save we log the model as an artifact to Weights & Biases.""" + assert self.run is not None + self.run.log_artifact( + str(trainer.last), + type="model", + name=f"{self.run.name}_{trainer.args.task}.pt", + aliases=["last", f"epoch_{trainer.epoch + 1}"], + ) + + def teardown(self, _trainer: BaseTrainer) -> None: + """On teardown, we finish the Weights & Biases run and set it to None.""" + assert self.run is not None + self.run.finish() + self.run = None + + @property + def callbacks( + self, + ) -> Dict[str, Callable]: + """Property contains all the relevant callbacks to add to the YOLO model for the Weights & Biases logging.""" + return { + "on_pretrain_routine_start": self.on_pretrain_routine_start, + "on_pretrain_routine_end": self.on_pretrain_routine_end, + "on_train_epoch_start": self.on_train_epoch_start, + "on_train_epoch_end": self.on_train_epoch_end, + "on_fit_epoch_end": self.on_fit_epoch_end, + "on_train_end": self.on_train_end, + "on_model_save": self.on_model_save, + "teardown": self.teardown, + } + + +def add_callbacks( + yolo: YOLO, + run_name: Optional[str] = None, + project: Optional[str] = None, + tags: Optional[List[str]] = None, + resume: Optional[str] = None, + **kwargs: Optional[Any], +) -> YOLO: + """A YOLO model wrapper that tracks metrics, and logs models to Weights & Biases. + + Args: + yolo: A YOLOv8 model that's inherited from `:class:ultralytics.yolo.engine.model.YOLO` + run_name, str: The name of the Weights & Biases run, defaults to an auto generated name if `trainer.args.name` is not defined. + project, str: The name of the Weights & Biases project, defaults to `"YOLOv8"` if `trainer.args.project` is not defined. + tags, List[str]: A list of tags to be added to the Weights & Biases run, defaults to `["YOLOv8"]`. + resume, str: Whether to resume a previous run on Weights & Biases, defaults to `None`. + **kwargs: Additional arguments to be passed to `wandb.init()`. + + Usage: + ```python + from wandb.integration.yolov8 import add_callbacks as add_wandb_callbacks + + model = YOLO("yolov8n.pt") + add_wandb_callbacks( + model, + ) + model.train( + data="coco128.yaml", + epochs=3, + imgsz=640, + ) + ``` + """ + wandb.termwarn( + """The wandb callback is currently in beta and is subject to change based on updates to `ultralytics yolov8`. + The callback is tested and supported for ultralytics v8.0.43 and above. + Please report any issues to https://github.com/wandb/wandb/issues with the tag `yolov8`. + """, + repeat=False, + ) + wandb.termwarn( + """This wandb callback is no longer functional and would be deprecated in the near future. + We recommend you to use the updated callback using `from wandb.integration.ultralytics import add_wandb_callback`. + The updated callback is tested and supported for ultralytics 8.0.167 and above. + You can refer to https://docs.wandb.ai/guides/integrations/ultralytics for the updated documentation. + Please report any issues to https://github.com/wandb/wandb/issues with the tag `yolov8`. + """, + repeat=False, + ) + + if RANK in [-1, 0]: + wandb_logger = WandbCallback( + yolo, run_name=run_name, project=project, tags=tags, resume=resume, **kwargs + ) + for event, callback_fn in wandb_logger.callbacks.items(): + yolo.add_callback(event, callback_fn) + return yolo + else: + wandb.termerror( + "The RANK of the process to add the callbacks was neither 0 or -1." + "No Weights & Biases callbacks were added to this instance of the YOLO model." + ) + return yolo diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/mpmain/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/mpmain/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/old/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/old/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/old/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/old/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa344e66cff823dab55a3d9b17a869ea03470e15 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/old/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/old/settings.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/old/settings.py new file mode 100644 index 0000000000000000000000000000000000000000..b759447aefb7699f14b77604305a9e46ae883065 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/old/settings.py @@ -0,0 +1,176 @@ +import configparser +import getpass +import os +import tempfile +from typing import Any, Optional + +from wandb import env +from wandb.old import core +from wandb.sdk.lib import filesystem +from wandb.sdk.lib.runid import generate_id + + +class Settings: + """Global W&B settings stored under $WANDB_CONFIG_DIR/settings.""" + + DEFAULT_SECTION = "default" + + _UNSET = object() + + def __init__( + self, load_settings: bool = True, root_dir: Optional[str] = None + ) -> None: + self._global_settings = Settings._settings() + self._local_settings = Settings._settings() + self.root_dir = root_dir + + if load_settings: + global_path = Settings._global_path() + if global_path is not None: + self._global_settings.read([global_path]) + # Only attempt to read if there is a directory existing + if os.path.isdir(core.wandb_dir(self.root_dir)): + self._local_settings.read([Settings._local_path(self.root_dir)]) + + def get(self, section: str, key: str, fallback: Any = _UNSET) -> Any: + # Try the local settings first. If we can't find the key, then try the global settings. + # If a fallback is provided, return it if we can't find the key in either the local or global + # settings. + try: + return self._local_settings.get(section, key) + except configparser.NoOptionError: + try: + return self._global_settings.get(section, key) + except configparser.NoOptionError: + if fallback is not Settings._UNSET: + return fallback + else: + raise + + def _persist_settings(self, settings, settings_path) -> None: + # write a temp file and then move it to the settings path + target_dir = os.path.dirname(settings_path) + with tempfile.NamedTemporaryFile( + "w+", suffix=".tmp", delete=False, dir=target_dir + ) as fp: + path = os.path.abspath(fp.name) + with open(path, "w+") as f: + settings.write(f) + try: + os.replace(path, settings_path) + except AttributeError: + os.rename(path, settings_path) + + def set(self, section, key, value, globally=False, persist=False) -> None: + """Persist settings to disk if persist = True""" + + def write_setting(settings, settings_path, persist): + if not settings.has_section(section): + Settings._safe_add_section(settings, Settings.DEFAULT_SECTION) + settings.set(section, key, str(value)) + + if persist: + self._persist_settings(settings, settings_path) + + if globally: + global_path = Settings._global_path() + if global_path is not None: + write_setting(self._global_settings, global_path, persist) + else: + write_setting( + self._local_settings, Settings._local_path(self.root_dir), persist + ) + + def clear(self, section, key, globally=False, persist=False) -> None: + def clear_setting(settings, settings_path, persist): + settings.remove_option(section, key) + if persist: + self._persist_settings(settings, settings_path) + + if globally: + global_path = Settings._global_path() + if global_path is not None: + clear_setting(self._global_settings, global_path, persist) + else: + clear_setting( + self._local_settings, Settings._local_path(self.root_dir), persist + ) + + def items(self, section=None): + section = section if section is not None else Settings.DEFAULT_SECTION + + result = {"section": section} + + try: + if section in self._global_settings.sections(): + for option in self._global_settings.options(section): + result[option] = self._global_settings.get(section, option) + if section in self._local_settings.sections(): + for option in self._local_settings.options(section): + result[option] = self._local_settings.get(section, option) + except configparser.InterpolationSyntaxError: + core.termwarn("Unable to parse settings file") + + return result + + @staticmethod + def _safe_add_section(settings, section): + if not settings.has_section(section): + settings.add_section(section) + + @staticmethod + def _settings(default_settings={}): + settings = configparser.ConfigParser() + Settings._safe_add_section(settings, Settings.DEFAULT_SECTION) + for key, value in default_settings.items(): + settings.set(Settings.DEFAULT_SECTION, key, str(value)) + return settings + + @staticmethod + def _global_path() -> Optional[str]: + def try_create_dir(path) -> bool: + try: + os.makedirs(path, exist_ok=True) + if os.access(path, os.W_OK): + return True + except OSError: + pass + return False + + def get_username() -> str: + try: + return getpass.getuser() + except (ImportError, KeyError): + return generate_id() + + try: + home_config_dir = os.path.join(os.path.expanduser("~"), ".config", "wandb") + + if os.getenv(env.CONFIG_DIR): + try_create_dir(os.getenv(env.CONFIG_DIR)) + return os.path.join(os.getenv(env.CONFIG_DIR), "settings") + + if not try_create_dir(home_config_dir): + temp_config_dir = os.path.join( + tempfile.gettempdir(), ".config", "wandb" + ) + + if not try_create_dir(temp_config_dir): + username = get_username() + config_dir = os.path.join( + tempfile.gettempdir(), username, ".config", "wandb" + ) + try_create_dir(config_dir) + else: + config_dir = temp_config_dir + else: + config_dir = home_config_dir + + return os.path.join(config_dir, "settings") + except Exception: + return None + + @staticmethod + def _local_path(root_dir=None): + filesystem.mkdir_exists_ok(core.wandb_dir(root_dir)) + return os.path.join(core.wandb_dir(root_dir), "settings") diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/plot/__pycache__/histogram.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/plot/__pycache__/histogram.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de9048ce4ed6f68b234cb6055c8cdf2c0b7813a2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/plot/__pycache__/histogram.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/plot/__pycache__/line.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/plot/__pycache__/line.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..440d3886f405d18e85fea29b65b524b60ac1ae98 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/plot/__pycache__/line.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/plot/__pycache__/scatter.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/plot/__pycache__/scatter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eafc798707968fb08a3df2ea82c469399188f689 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/plot/__pycache__/scatter.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/plot/__pycache__/utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/plot/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d652ab66c6cbeb1fc54305c0f5f86f3a02f4b0b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/plot/__pycache__/utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/plot/__pycache__/viz.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/plot/__pycache__/viz.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1e54cf8fdb1474b7a922c3cff79b9c3dc146806 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/plot/__pycache__/viz.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/plot/line_series.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/plot/line_series.py new file mode 100644 index 0000000000000000000000000000000000000000..de43caa5495d4699d900521497498bd9cdfce259 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/plot/line_series.py @@ -0,0 +1,173 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Iterable + +import wandb +from wandb.plot.custom_chart import plot_table + +if TYPE_CHECKING: + from wandb.plot.custom_chart import CustomChart + + +def line_series( + xs: Iterable[Iterable[Any]] | Iterable[Any], + ys: Iterable[Iterable[Any]], + keys: Iterable[str] | None = None, + title: str = "", + xname: str = "x", + split_table: bool = False, +) -> CustomChart: + """Constructs a line series chart. + + Args: + xs: Sequence of x values. If a singular + array is provided, all y values are plotted against that x array. If + an array of arrays is provided, each y value is plotted against the + corresponding x array. + ys: Sequence of y values, where each iterable represents + a separate line series. + keys: Sequence of keys for labeling each line series. If + not provided, keys will be automatically generated as "line_1", + "line_2", etc. + title: Title of the chart. + xname: Label for the x-axis. + split_table: Whether the table should be split into a separate section + in the W&B UI. If `True`, the table will be displayed in a section named + "Custom Chart Tables". Default is `False`. + + Returns: + CustomChart: A custom chart object that can be logged to W&B. To log the + chart, pass it to `wandb.log()`. + + Examples: + Logging a single x array where all y series are plotted against the same x values: + + ```python + import wandb + + # Initialize W&B run + with wandb.init(project="line_series_example") as run: + # x values shared across all y series + xs = list(range(10)) + + # Multiple y series to plot + ys = [ + [i for i in range(10)], # y = x + [i**2 for i in range(10)], # y = x^2 + [i**3 for i in range(10)], # y = x^3 + ] + + # Generate and log the line series chart + line_series_chart = wandb.plot.line_series( + xs, + ys, + title="title", + xname="step", + ) + run.log({"line-series-single-x": line_series_chart}) + ``` + + In this example, a single `xs` series (shared x-values) is used for all + `ys` series. This results in each y-series being plotted against the + same x-values (0-9). + + Logging multiple x arrays where each y series is plotted against its corresponding x array: + + ```python + import wandb + + # Initialize W&B run + with wandb.init(project="line_series_example") as run: + # Separate x values for each y series + xs = [ + [i for i in range(10)], # x for first series + [2 * i for i in range(10)], # x for second series (stretched) + [3 * i for i in range(10)], # x for third series (stretched more) + ] + + # Corresponding y series + ys = [ + [i for i in range(10)], # y = x + [i**2 for i in range(10)], # y = x^2 + [i**3 for i in range(10)], # y = x^3 + ] + + # Generate and log the line series chart + line_series_chart = wandb.plot.line_series( + xs, ys, title="Multiple X Arrays Example", xname="Step" + ) + run.log({"line-series-multiple-x": line_series_chart}) + ``` + + In this example, each y series is plotted against its own unique x series. + This allows for more flexibility when the x values are not uniform across + the data series. + + Customizing line labels using `keys`: + + ```python + import wandb + + # Initialize W&B run + with wandb.init(project="line_series_example") as run: + xs = list(range(10)) # Single x array + ys = [ + [i for i in range(10)], # y = x + [i**2 for i in range(10)], # y = x^2 + [i**3 for i in range(10)], # y = x^3 + ] + + # Custom labels for each line + keys = ["Linear", "Quadratic", "Cubic"] + + # Generate and log the line series chart + line_series_chart = wandb.plot.line_series( + xs, + ys, + keys=keys, # Custom keys (line labels) + title="Custom Line Labels Example", + xname="Step", + ) + run.log({"line-series-custom-keys": line_series_chart}) + ``` + + This example shows how to provide custom labels for the lines using + the `keys` argument. The keys will appear in the legend as "Linear", + "Quadratic", and "Cubic". + """ + # If xs is a single array, repeat it for each y in ys + if not isinstance(xs[0], Iterable) or isinstance(xs[0], (str, bytes)): + xs = [xs] * len(ys) + + if len(xs) != len(ys): + msg = f"Number of x-series ({len(xs)}) must match y-series ({len(ys)})." + raise ValueError(msg) + + if keys is None: + keys = [f"line_{i}" for i in range(len(ys))] + + if len(keys) != len(ys): + msg = f"Number of keys ({len(keys)}) must match y-series ({len(ys)})." + raise ValueError(msg) + + data = [ + [x, keys[i], y] + for i, (xx, yy) in enumerate(zip(xs, ys)) + for x, y in zip(xx, yy) + ] + table = wandb.Table( + data=data, + columns=["step", "lineKey", "lineVal"], + ) + + return plot_table( + data_table=table, + vega_spec_name="wandb/lineseries/v0", + fields={ + "step": "step", + "lineKey": "lineKey", + "lineVal": "lineVal", + }, + string_fields={"title": title, "xname": xname}, + split_table=split_table, + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/plot/viz.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/plot/viz.py new file mode 100644 index 0000000000000000000000000000000000000000..ea6be2f8805891b5d0c77b557c040a4377e9f4f9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/__pycache__/wandb_base_pb2.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/__pycache__/wandb_base_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f18e0cc8c764a4cb8d2ca3aec24025ef3d724b39 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/__pycache__/wandb_base_pb2.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/__pycache__/wandb_deprecated.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/__pycache__/wandb_deprecated.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1cd57d78ecf8e7890f6f218987e87f6d76925c00 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/__pycache__/wandb_deprecated.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/__pycache__/wandb_generate_deprecated.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/__pycache__/wandb_generate_deprecated.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78f8ee97596ff8517d241b4dd116a4cbd2ba39fd Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/__pycache__/wandb_generate_deprecated.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/__pycache__/wandb_telemetry_pb2.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/__pycache__/wandb_telemetry_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe1a7ad384f7942498b7ff447e57b63759e87e2c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/__pycache__/wandb_telemetry_pb2.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v3/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v3/__pycache__/wandb_telemetry_pb2.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v3/__pycache__/wandb_telemetry_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f35aa9a26a0dc7a972b1126c21e380f5ee08db1c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v3/__pycache__/wandb_telemetry_pb2.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v3/wandb_settings_pb2.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v3/wandb_settings_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..748547a9fb9c0bdde9909d8aef4ad853f0d0c14e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v3/wandb_settings_pb2.py @@ -0,0 +1,122 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: wandb/proto/wandb_settings.proto +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import wrappers_pb2 as google_dot_protobuf_dot_wrappers__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n wandb/proto/wandb_settings.proto\x12\x0ewandb_internal\x1a\x1egoogle/protobuf/wrappers.proto\" \n\x0fListStringValue\x12\r\n\x05value\x18\x01 \x03(\t\"\x1d\n\x0cListIntValue\x12\r\n\x05value\x18\x01 \x03(\x05\"\x8a\x01\n\x17MapStringKeyStringValue\x12\x41\n\x05value\x18\x01 \x03(\x0b\x32\x32.wandb_internal.MapStringKeyStringValue.ValueEntry\x1a,\n\nValueEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xcb\x01\n#MapStringKeyMapStringKeyStringValue\x12M\n\x05value\x18\x01 \x03(\x0b\x32>.wandb_internal.MapStringKeyMapStringKeyStringValue.ValueEntry\x1aU\n\nValueEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x36\n\x05value\x18\x02 \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue:\x02\x38\x01\"\x9a\x01\n\x12OpenMetricsFilters\x12\x33\n\x08sequence\x18\x01 \x01(\x0b\x32\x1f.wandb_internal.ListStringValueH\x00\x12\x46\n\x07mapping\x18\x02 \x01(\x0b\x32\x33.wandb_internal.MapStringKeyMapStringKeyStringValueH\x00\x42\x07\n\x05value\"7\n\tRunMoment\x12\x0b\n\x03run\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x01\x12\x0e\n\x06metric\x18\x03 \x01(\t\"\x99N\n\x08Settings\x12-\n\x07\x61pi_key\x18\x37 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12:\n\x13identity_token_file\x18\xaa\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x37\n\x10\x63redentials_file\x18\xab\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x39\n\x14insecure_disable_ssl\x18\xb9\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12,\n\x08_offline\x18\x1e \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12*\n\x06x_sync\x18\x1f \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x30\n\tsync_file\x18\x86\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x07_shared\x18\xa2\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12,\n\x06run_id\x18k \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12-\n\x07run_url\x18q \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12-\n\x07project\x18\x61 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x06\x65ntity\x18\x45 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x33\n\x0corganization\x18\xbc\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0cx_start_time\x18) \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12.\n\x08root_dir\x18i \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12-\n\x07log_dir\x18U \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0clog_internal\x18V \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\tfiles_dir\x18\x46 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0bx_files_dir\x18\xb4\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0cignore_globs\x18N \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12.\n\x08\x62\x61se_url\x18\x39 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12=\n\x17x_file_stream_max_bytes\x18\xac\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x46\n\x1fx_file_stream_transmit_interval\x18\xaf\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x45\n\x14x_extra_http_headers\x18\x0e \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12=\n\x17x_file_stream_retry_max\x18\x93\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12K\n$x_file_stream_retry_wait_min_seconds\x18\x94\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12K\n$x_file_stream_retry_wait_max_seconds\x18\x95\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x43\n\x1dx_file_stream_timeout_seconds\x18\x0f \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x42\n\x1cx_file_stream_max_line_bytes\x18\xb2\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12?\n\x19x_file_transfer_retry_max\x18\x96\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12M\n&x_file_transfer_retry_wait_min_seconds\x18\x97\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12M\n&x_file_transfer_retry_wait_max_seconds\x18\x98\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x46\n\x1fx_file_transfer_timeout_seconds\x18\x99\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x39\n\x13x_graphql_retry_max\x18\x9a\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12G\n x_graphql_retry_wait_min_seconds\x18\x9b\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12G\n x_graphql_retry_wait_max_seconds\x18\x9c\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12@\n\x19x_graphql_timeout_seconds\x18\x9d\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x31\n\nhttp_proxy\x18\xa8\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0bhttps_proxy\x18\xa9\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12;\n\tx_proxies\x18\xc8\x01 \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12-\n\x07program\x18_ \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0fprogram_relpath\x18` \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x37\n\x10_code_path_local\x18\xa3\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x36\n\x0fprogram_abspath\x18\x9f\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x05_args\x18\x01 \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12)\n\x03_os\x18 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x06\x64ocker\x18\x43 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0cx_executable\x18\r \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12-\n\x07_python\x18\" \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x30\n\tcolab_url\x18\xa0\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12*\n\x04host\x18M \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x08username\x18\x8d\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12+\n\x05\x65mail\x18\x44 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x06resume\x18\x66 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x0bresume_from\x18\xa7\x01 \x01(\x0b\x32\x19.wandb_internal.RunMoment\x12-\n\tfork_from\x18\xa4\x01 \x01(\x0b\x32\x19.wandb_internal.RunMoment\x12\x38\n\x14\x64isable_job_creation\x18\x41 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x30\n\tsweep_url\x18\x83\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12;\n\x16x_disable_update_check\x18\xa5\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x32\n\x0ex_disable_meta\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12-\n\tsave_code\x18s \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\x0b\x64isable_git\x18? \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12;\n\x16x_disable_machine_info\x18\x9e\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x33\n\x0fx_disable_stats\x18\n \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x39\n\x13x_stats_buffer_size\x18\xa1\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12@\n\x19x_stats_sampling_interval\x18\xae\x01 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x30\n\x0bx_stats_pid\x18* \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12<\n\x12x_stats_disk_paths\x18\x92\x01 \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12H\n\"x_stats_neuron_monitor_config_path\x18. \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12<\n\x15x_stats_dcgm_exporter\x18\xbb\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12O\n\x1ex_stats_open_metrics_endpoints\x18/ \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12H\n\x1cx_stats_open_metrics_filters\x18\x30 \x01(\x0b\x32\".wandb_internal.OpenMetricsFilters\x12S\n!x_stats_open_metrics_http_headers\x18\xb8\x01 \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12=\n\x16x_stats_gpu_device_ids\x18\xba\x01 \x01(\x0b\x32\x1c.wandb_internal.ListIntValue\x12\x37\n\x11x_stats_cpu_count\x18\xc2\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12?\n\x19x_stats_cpu_logical_count\x18\xc3\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x37\n\x11x_stats_gpu_count\x18\xc4\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x37\n\x10x_stats_gpu_type\x18\xc5\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12?\n\x1ax_stats_track_process_tree\x18\xc6\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12.\n\x07x_label\x18\xb5\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\tx_primary\x18\xb6\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12:\n\x15x_update_finish_state\x18\xb7\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12<\n\x17\x61llow_offline_artifacts\x18\xb1\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12-\n\x07\x63onsole\x18< \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x36\n\x11\x63onsole_multipart\x18\xa6\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x35\n\x10sync_tensorboard\x18\xb3\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x42\n\x1dx_server_side_derived_summary\x18\xbd\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x46\n!x_server_side_expand_glob_metrics\x18\xbe\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12;\n\x16x_skip_transaction_log\x18\xbf\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12J\n#x_stats_coreweave_metadata_base_url\x18\xc0\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12J\n#x_stats_coreweave_metadata_endpoint\x18\xc1\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x0b_aws_lambda\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x33\n\x0fx_cli_only_mode\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12*\n\x06_colab\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x34\n\x10x_disable_viewer\x18\x0b \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x39\n\x15x_flow_control_custom\x18\x10 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12;\n\x17x_flow_control_disabled\x18\x11 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12>\n\x18x_internal_check_process\x18\x12 \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12,\n\x08_ipython\x18\x14 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12,\n\x08_jupyter\x18\x15 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x34\n\x0ex_jupyter_root\x18\x16 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12+\n\x07_kaggle\x18\x17 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12=\n\x18x_live_policy_rate_limit\x18\x18 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12<\n\x17x_live_policy_wait_time\x18\x19 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x30\n\x0bx_log_level\x18\x1a \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x35\n\x10x_network_buffer\x18\x1b \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12)\n\x05_noop\x18\x1c \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12-\n\t_notebook\x18\x1d \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\t_platform\x18! \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x38\n\x12x_runqueue_item_id\x18# \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x37\n\x13x_save_requirements\x18% \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x39\n\x13x_service_transport\x18& \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x34\n\x0ex_service_wait\x18\' \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12\x35\n\x0f_start_datetime\x18( \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x33\n\r_tmp_code_dir\x18\x31 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x08_windows\x18\x34 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x34\n\x10\x61llow_val_change\x18\x35 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\tanonymous\x18\x36 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12P\n\x1f\x61zure_account_url_to_access_key\x18\x38 \x01(\x0b\x32\'.wandb_internal.MapStringKeyStringValue\x12.\n\x08\x63ode_dir\x18: \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0c\x63onfig_paths\x18; \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12\x30\n\ndeployment\x18= \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x30\n\x0c\x64isable_code\x18> \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x31\n\rdisable_hints\x18@ \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12,\n\x08\x64isabled\x18\x42 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12)\n\x05\x66orce\x18G \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x30\n\ngit_commit\x18H \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x30\n\ngit_remote\x18I \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x34\n\x0egit_remote_url\x18J \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x08git_root\x18K \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x36\n\x11heartbeat_seconds\x18L \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x32\n\x0cinit_timeout\x18O \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12,\n\x08is_local\x18P \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x30\n\njob_source\x18Q \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x31\n\rlabel_disable\x18R \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12*\n\x06launch\x18S \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x38\n\x12launch_config_path\x18T \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12:\n\x14log_symlink_internal\x18W \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x36\n\x10log_symlink_user\x18X \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x08log_user\x18Y \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x33\n\rlogin_timeout\x18Z \x01(\x0b\x32\x1c.google.protobuf.DoubleValue\x12*\n\x04mode\x18\\ \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x33\n\rnotebook_name\x18] \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x31\n\x0bproject_url\x18\x62 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12)\n\x05quiet\x18\x63 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12+\n\x07relogin\x18\x65 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x32\n\x0cresume_fname\x18g \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12+\n\x07resumed\x18h \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\trun_group\x18j \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x32\n\x0crun_job_type\x18l \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x08run_mode\x18m \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x08run_name\x18n \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\trun_notes\x18o \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x31\n\x08run_tags\x18p \x01(\x0b\x32\x1f.wandb_internal.ListStringValue\x12\x35\n\x11sagemaker_disable\x18r \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x35\n\x0fsettings_system\x18t \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x38\n\x12settings_workspace\x18u \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x0bshow_colors\x18v \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12.\n\nshow_emoji\x18w \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\x0bshow_errors\x18x \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12-\n\tshow_info\x18y \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x31\n\rshow_warnings\x18z \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12*\n\x06silent\x18{ \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x32\n\x0cstart_method\x18| \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12*\n\x06strict\x18} \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12\x33\n\x0esummary_errors\x18~ \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x34\n\x0fsummary_timeout\x18\x7f \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12\x36\n\x10summary_warnings\x18\x80\x01 \x01(\x0b\x32\x1b.google.protobuf.Int32Value\x12/\n\x08sweep_id\x18\x81\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x37\n\x10sweep_param_path\x18\x82\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12,\n\x07symlink\x18\x84\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\x08sync_dir\x18\x85\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12:\n\x13sync_symlink_latest\x18\x87\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12J\n%table_raise_on_max_row_limit_exceeded\x18\x8a\x01 \x01(\x0b\x32\x1a.google.protobuf.BoolValue\x12/\n\x08timespec\x18\x8b\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12.\n\x07tmp_dir\x18\x8c\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x30\n\twandb_dir\x18\x8e\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0ex_jupyter_name\x18\x8f\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12\x35\n\x0ex_jupyter_path\x18\x90\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValue\x12/\n\x08job_name\x18\x91\x01 \x01(\x0b\x32\x1c.google.protobuf.StringValueJ\x04\x08\x03\x10\x04J\x04\x08\x06\x10\x07J\x04\x08\x08\x10\tJ\x04\x08\t\x10\nJ\x04\x08\x0c\x10\rJ\x04\x08\x13\x10\x14J\x04\x08$\x10%J\x04\x08+\x10,J\x04\x08,\x10-J\x04\x08-\x10.J\x04\x08\x32\x10\x33J\x04\x08\x33\x10\x34J\x04\x08[\x10\\J\x04\x08^\x10_J\x04\x08\x64\x10\x65J\x06\x08\x88\x01\x10\x89\x01J\x06\x08\x89\x01\x10\x8a\x01J\x06\x08\xad\x01\x10\xae\x01J\x06\x08\xb0\x01\x10\xb1\x01\x42\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3') + + + +_LISTSTRINGVALUE = DESCRIPTOR.message_types_by_name['ListStringValue'] +_LISTINTVALUE = DESCRIPTOR.message_types_by_name['ListIntValue'] +_MAPSTRINGKEYSTRINGVALUE = DESCRIPTOR.message_types_by_name['MapStringKeyStringValue'] +_MAPSTRINGKEYSTRINGVALUE_VALUEENTRY = _MAPSTRINGKEYSTRINGVALUE.nested_types_by_name['ValueEntry'] +_MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE = DESCRIPTOR.message_types_by_name['MapStringKeyMapStringKeyStringValue'] +_MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY = _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE.nested_types_by_name['ValueEntry'] +_OPENMETRICSFILTERS = DESCRIPTOR.message_types_by_name['OpenMetricsFilters'] +_RUNMOMENT = DESCRIPTOR.message_types_by_name['RunMoment'] +_SETTINGS = DESCRIPTOR.message_types_by_name['Settings'] +ListStringValue = _reflection.GeneratedProtocolMessageType('ListStringValue', (_message.Message,), { + 'DESCRIPTOR' : _LISTSTRINGVALUE, + '__module__' : 'wandb.proto.wandb_settings_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.ListStringValue) + }) +_sym_db.RegisterMessage(ListStringValue) + +ListIntValue = _reflection.GeneratedProtocolMessageType('ListIntValue', (_message.Message,), { + 'DESCRIPTOR' : _LISTINTVALUE, + '__module__' : 'wandb.proto.wandb_settings_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.ListIntValue) + }) +_sym_db.RegisterMessage(ListIntValue) + +MapStringKeyStringValue = _reflection.GeneratedProtocolMessageType('MapStringKeyStringValue', (_message.Message,), { + + 'ValueEntry' : _reflection.GeneratedProtocolMessageType('ValueEntry', (_message.Message,), { + 'DESCRIPTOR' : _MAPSTRINGKEYSTRINGVALUE_VALUEENTRY, + '__module__' : 'wandb.proto.wandb_settings_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.MapStringKeyStringValue.ValueEntry) + }) + , + 'DESCRIPTOR' : _MAPSTRINGKEYSTRINGVALUE, + '__module__' : 'wandb.proto.wandb_settings_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.MapStringKeyStringValue) + }) +_sym_db.RegisterMessage(MapStringKeyStringValue) +_sym_db.RegisterMessage(MapStringKeyStringValue.ValueEntry) + +MapStringKeyMapStringKeyStringValue = _reflection.GeneratedProtocolMessageType('MapStringKeyMapStringKeyStringValue', (_message.Message,), { + + 'ValueEntry' : _reflection.GeneratedProtocolMessageType('ValueEntry', (_message.Message,), { + 'DESCRIPTOR' : _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY, + '__module__' : 'wandb.proto.wandb_settings_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.MapStringKeyMapStringKeyStringValue.ValueEntry) + }) + , + 'DESCRIPTOR' : _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE, + '__module__' : 'wandb.proto.wandb_settings_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.MapStringKeyMapStringKeyStringValue) + }) +_sym_db.RegisterMessage(MapStringKeyMapStringKeyStringValue) +_sym_db.RegisterMessage(MapStringKeyMapStringKeyStringValue.ValueEntry) + +OpenMetricsFilters = _reflection.GeneratedProtocolMessageType('OpenMetricsFilters', (_message.Message,), { + 'DESCRIPTOR' : _OPENMETRICSFILTERS, + '__module__' : 'wandb.proto.wandb_settings_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.OpenMetricsFilters) + }) +_sym_db.RegisterMessage(OpenMetricsFilters) + +RunMoment = _reflection.GeneratedProtocolMessageType('RunMoment', (_message.Message,), { + 'DESCRIPTOR' : _RUNMOMENT, + '__module__' : 'wandb.proto.wandb_settings_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.RunMoment) + }) +_sym_db.RegisterMessage(RunMoment) + +Settings = _reflection.GeneratedProtocolMessageType('Settings', (_message.Message,), { + 'DESCRIPTOR' : _SETTINGS, + '__module__' : 'wandb.proto.wandb_settings_pb2' + # @@protoc_insertion_point(class_scope:wandb_internal.Settings) + }) +_sym_db.RegisterMessage(Settings) + +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'Z\031core/pkg/service_go_proto' + _MAPSTRINGKEYSTRINGVALUE_VALUEENTRY._options = None + _MAPSTRINGKEYSTRINGVALUE_VALUEENTRY._serialized_options = b'8\001' + _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY._options = None + _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY._serialized_options = b'8\001' + _LISTSTRINGVALUE._serialized_start=84 + _LISTSTRINGVALUE._serialized_end=116 + _LISTINTVALUE._serialized_start=118 + _LISTINTVALUE._serialized_end=147 + _MAPSTRINGKEYSTRINGVALUE._serialized_start=150 + _MAPSTRINGKEYSTRINGVALUE._serialized_end=288 + _MAPSTRINGKEYSTRINGVALUE_VALUEENTRY._serialized_start=244 + _MAPSTRINGKEYSTRINGVALUE_VALUEENTRY._serialized_end=288 + _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE._serialized_start=291 + _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE._serialized_end=494 + _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY._serialized_start=409 + _MAPSTRINGKEYMAPSTRINGKEYSTRINGVALUE_VALUEENTRY._serialized_end=494 + _OPENMETRICSFILTERS._serialized_start=497 + _OPENMETRICSFILTERS._serialized_end=651 + _RUNMOMENT._serialized_start=653 + _RUNMOMENT._serialized_end=708 + _SETTINGS._serialized_start=711 + _SETTINGS._serialized_end=10720 +# @@protoc_insertion_point(module_scope) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v4/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v4/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v4/wandb_base_pb2.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v4/wandb_base_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..e1df6042049011a6f2b2277569e2d6f011979a90 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v4/wandb_base_pb2.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: wandb/proto/wandb_base.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1cwandb/proto/wandb_base.proto\x12\x0ewandb_internal\"6\n\x0b_RecordInfo\x12\x11\n\tstream_id\x18\x01 \x01(\t\x12\x14\n\x0c_tracelog_id\x18\x64 \x01(\t\"!\n\x0c_RequestInfo\x12\x11\n\tstream_id\x18\x01 \x01(\t\"#\n\x0b_ResultInfo\x12\x14\n\x0c_tracelog_id\x18\x64 \x01(\tB\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_base_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'Z\031core/pkg/service_go_proto' + __RECORDINFO._serialized_start=48 + __RECORDINFO._serialized_end=102 + __REQUESTINFO._serialized_start=104 + __REQUESTINFO._serialized_end=137 + __RESULTINFO._serialized_start=139 + __RESULTINFO._serialized_end=174 +# @@protoc_insertion_point(module_scope) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v4/wandb_server_pb2.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v4/wandb_server_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..9f6f08921222b9f876a6775640a7134b1771c470 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v4/wandb_server_pb2.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: wandb/proto/wandb_server.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from wandb.proto import wandb_base_pb2 as wandb_dot_proto_dot_wandb__base__pb2 +from wandb.proto import wandb_internal_pb2 as wandb_dot_proto_dot_wandb__internal__pb2 +from wandb.proto import wandb_settings_pb2 as wandb_dot_proto_dot_wandb__settings__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1ewandb/proto/wandb_server.proto\x12\x0ewandb_internal\x1a\x1cwandb/proto/wandb_base.proto\x1a wandb/proto/wandb_internal.proto\x1a wandb/proto/wandb_settings.proto\"k\n\x19ServerAuthenticateRequest\x12\x0f\n\x07\x61pi_key\x18\x01 \x01(\t\x12\x10\n\x08\x62\x61se_url\x18\x02 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"w\n\x1aServerAuthenticateResponse\x12\x16\n\x0e\x64\x65\x66\x61ult_entity\x18\x01 \x01(\t\x12\x14\n\x0c\x65rror_status\x18\x02 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"D\n\x15ServerShutdownRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x18\n\x16ServerShutdownResponse\"B\n\x13ServerStatusRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x16\n\x14ServerStatusResponse\"r\n\x17ServerInformInitRequest\x12*\n\x08settings\x18\x01 \x01(\x0b\x32\x18.wandb_internal.Settings\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1a\n\x18ServerInformInitResponse\"s\n\x18ServerInformStartRequest\x12*\n\x08settings\x18\x01 \x01(\x0b\x32\x18.wandb_internal.Settings\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1b\n\x19ServerInformStartResponse\"H\n\x19ServerInformFinishRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1c\n\x1aServerInformFinishResponse\"H\n\x19ServerInformAttachRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"u\n\x1aServerInformAttachResponse\x12*\n\x08settings\x18\x01 \x01(\x0b\x32\x18.wandb_internal.Settings\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"H\n\x19ServerInformDetachRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1c\n\x1aServerInformDetachResponse\"]\n\x1bServerInformTeardownRequest\x12\x11\n\texit_code\x18\x01 \x01(\x05\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1e\n\x1cServerInformTeardownResponse\"\xfb\x04\n\rServerRequest\x12\x12\n\nrequest_id\x18\n \x01(\t\x12\x30\n\x0erecord_publish\x18\x01 \x01(\x0b\x32\x16.wandb_internal.RecordH\x00\x12\x34\n\x12record_communicate\x18\x02 \x01(\x0b\x32\x16.wandb_internal.RecordH\x00\x12>\n\x0binform_init\x18\x03 \x01(\x0b\x32\'.wandb_internal.ServerInformInitRequestH\x00\x12\x42\n\rinform_finish\x18\x04 \x01(\x0b\x32).wandb_internal.ServerInformFinishRequestH\x00\x12\x42\n\rinform_attach\x18\x05 \x01(\x0b\x32).wandb_internal.ServerInformAttachRequestH\x00\x12\x42\n\rinform_detach\x18\x06 \x01(\x0b\x32).wandb_internal.ServerInformDetachRequestH\x00\x12\x46\n\x0finform_teardown\x18\x07 \x01(\x0b\x32+.wandb_internal.ServerInformTeardownRequestH\x00\x12@\n\x0cinform_start\x18\x08 \x01(\x0b\x32(.wandb_internal.ServerInformStartRequestH\x00\x12\x41\n\x0c\x61uthenticate\x18\t \x01(\x0b\x32).wandb_internal.ServerAuthenticateRequestH\x00\x42\x15\n\x13server_request_type\"\x91\x05\n\x0eServerResponse\x12\x12\n\nrequest_id\x18\n \x01(\t\x12\x34\n\x12result_communicate\x18\x02 \x01(\x0b\x32\x16.wandb_internal.ResultH\x00\x12H\n\x14inform_init_response\x18\x03 \x01(\x0b\x32(.wandb_internal.ServerInformInitResponseH\x00\x12L\n\x16inform_finish_response\x18\x04 \x01(\x0b\x32*.wandb_internal.ServerInformFinishResponseH\x00\x12L\n\x16inform_attach_response\x18\x05 \x01(\x0b\x32*.wandb_internal.ServerInformAttachResponseH\x00\x12L\n\x16inform_detach_response\x18\x06 \x01(\x0b\x32*.wandb_internal.ServerInformDetachResponseH\x00\x12P\n\x18inform_teardown_response\x18\x07 \x01(\x0b\x32,.wandb_internal.ServerInformTeardownResponseH\x00\x12J\n\x15inform_start_response\x18\x08 \x01(\x0b\x32).wandb_internal.ServerInformStartResponseH\x00\x12K\n\x15\x61uthenticate_response\x18\t \x01(\x0b\x32*.wandb_internal.ServerAuthenticateResponseH\x00\x42\x16\n\x14server_response_typeB\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_server_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'Z\031core/pkg/service_go_proto' + _SERVERAUTHENTICATEREQUEST._serialized_start=148 + _SERVERAUTHENTICATEREQUEST._serialized_end=255 + _SERVERAUTHENTICATERESPONSE._serialized_start=257 + _SERVERAUTHENTICATERESPONSE._serialized_end=376 + _SERVERSHUTDOWNREQUEST._serialized_start=378 + _SERVERSHUTDOWNREQUEST._serialized_end=446 + _SERVERSHUTDOWNRESPONSE._serialized_start=448 + _SERVERSHUTDOWNRESPONSE._serialized_end=472 + _SERVERSTATUSREQUEST._serialized_start=474 + _SERVERSTATUSREQUEST._serialized_end=540 + _SERVERSTATUSRESPONSE._serialized_start=542 + _SERVERSTATUSRESPONSE._serialized_end=564 + _SERVERINFORMINITREQUEST._serialized_start=566 + _SERVERINFORMINITREQUEST._serialized_end=680 + _SERVERINFORMINITRESPONSE._serialized_start=682 + _SERVERINFORMINITRESPONSE._serialized_end=708 + _SERVERINFORMSTARTREQUEST._serialized_start=710 + _SERVERINFORMSTARTREQUEST._serialized_end=825 + _SERVERINFORMSTARTRESPONSE._serialized_start=827 + _SERVERINFORMSTARTRESPONSE._serialized_end=854 + _SERVERINFORMFINISHREQUEST._serialized_start=856 + _SERVERINFORMFINISHREQUEST._serialized_end=928 + _SERVERINFORMFINISHRESPONSE._serialized_start=930 + _SERVERINFORMFINISHRESPONSE._serialized_end=958 + _SERVERINFORMATTACHREQUEST._serialized_start=960 + _SERVERINFORMATTACHREQUEST._serialized_end=1032 + _SERVERINFORMATTACHRESPONSE._serialized_start=1034 + _SERVERINFORMATTACHRESPONSE._serialized_end=1151 + _SERVERINFORMDETACHREQUEST._serialized_start=1153 + _SERVERINFORMDETACHREQUEST._serialized_end=1225 + _SERVERINFORMDETACHRESPONSE._serialized_start=1227 + _SERVERINFORMDETACHRESPONSE._serialized_end=1255 + _SERVERINFORMTEARDOWNREQUEST._serialized_start=1257 + _SERVERINFORMTEARDOWNREQUEST._serialized_end=1350 + _SERVERINFORMTEARDOWNRESPONSE._serialized_start=1352 + _SERVERINFORMTEARDOWNRESPONSE._serialized_end=1382 + _SERVERREQUEST._serialized_start=1385 + _SERVERREQUEST._serialized_end=2020 + _SERVERRESPONSE._serialized_start=2023 + _SERVERRESPONSE._serialized_end=2680 +# @@protoc_insertion_point(module_scope) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v5/__pycache__/wandb_server_pb2.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v5/__pycache__/wandb_server_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94fc1a46be70310381f3c926682241d220f2cc17 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v5/__pycache__/wandb_server_pb2.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v5/__pycache__/wandb_telemetry_pb2.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v5/__pycache__/wandb_telemetry_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1102a9aebb3e9c5f5c5f360acd1282f286dcbb42 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v5/__pycache__/wandb_telemetry_pb2.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v5/wandb_internal_pb2.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v5/wandb_internal_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..fd09895f61d4653ade8de42ca0d5798f16da0664 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v5/wandb_internal_pb2.py @@ -0,0 +1,383 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: wandb/proto/wandb_internal.proto +# Protobuf Python Version: 5.26.1 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 +from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 +from wandb.proto import wandb_base_pb2 as wandb_dot_proto_dot_wandb__base__pb2 +from wandb.proto import wandb_telemetry_pb2 as wandb_dot_proto_dot_wandb__telemetry__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n wandb/proto/wandb_internal.proto\x12\x0ewandb_internal\x1a\x1bgoogle/protobuf/empty.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1cwandb/proto/wandb_base.proto\x1a!wandb/proto/wandb_telemetry.proto\"\xcf\t\n\x06Record\x12\x0b\n\x03num\x18\x01 \x01(\x03\x12\x30\n\x07history\x18\x02 \x01(\x0b\x32\x1d.wandb_internal.HistoryRecordH\x00\x12\x30\n\x07summary\x18\x03 \x01(\x0b\x32\x1d.wandb_internal.SummaryRecordH\x00\x12.\n\x06output\x18\x04 \x01(\x0b\x32\x1c.wandb_internal.OutputRecordH\x00\x12.\n\x06\x63onfig\x18\x05 \x01(\x0b\x32\x1c.wandb_internal.ConfigRecordH\x00\x12,\n\x05\x66iles\x18\x06 \x01(\x0b\x32\x1b.wandb_internal.FilesRecordH\x00\x12,\n\x05stats\x18\x07 \x01(\x0b\x32\x1b.wandb_internal.StatsRecordH\x00\x12\x32\n\x08\x61rtifact\x18\x08 \x01(\x0b\x32\x1e.wandb_internal.ArtifactRecordH\x00\x12,\n\x08tbrecord\x18\t \x01(\x0b\x32\x18.wandb_internal.TBRecordH\x00\x12,\n\x05\x61lert\x18\n \x01(\x0b\x32\x1b.wandb_internal.AlertRecordH\x00\x12\x34\n\ttelemetry\x18\x0b \x01(\x0b\x32\x1f.wandb_internal.TelemetryRecordH\x00\x12.\n\x06metric\x18\x0c \x01(\x0b\x32\x1c.wandb_internal.MetricRecordH\x00\x12\x35\n\noutput_raw\x18\r \x01(\x0b\x32\x1f.wandb_internal.OutputRawRecordH\x00\x12(\n\x03run\x18\x11 \x01(\x0b\x32\x19.wandb_internal.RunRecordH\x00\x12-\n\x04\x65xit\x18\x12 \x01(\x0b\x32\x1d.wandb_internal.RunExitRecordH\x00\x12,\n\x05\x66inal\x18\x14 \x01(\x0b\x32\x1b.wandb_internal.FinalRecordH\x00\x12.\n\x06header\x18\x15 \x01(\x0b\x32\x1c.wandb_internal.HeaderRecordH\x00\x12.\n\x06\x66ooter\x18\x16 \x01(\x0b\x32\x1c.wandb_internal.FooterRecordH\x00\x12\x39\n\npreempting\x18\x17 \x01(\x0b\x32#.wandb_internal.RunPreemptingRecordH\x00\x12\x34\n\x12noop_link_artifact\x18\x18 \x01(\x0b\x32\x16.google.protobuf.EmptyH\x00\x12\x39\n\x0cuse_artifact\x18\x19 \x01(\x0b\x32!.wandb_internal.UseArtifactRecordH\x00\x12\x38\n\x0b\x65nvironment\x18\x1a \x01(\x0b\x32!.wandb_internal.EnvironmentRecordH\x00\x12*\n\x07request\x18\x64 \x01(\x0b\x32\x17.wandb_internal.RequestH\x00\x12(\n\x07\x63ontrol\x18\x10 \x01(\x0b\x32\x17.wandb_internal.Control\x12\x0c\n\x04uuid\x18\x13 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfoB\r\n\x0brecord_type\"\xa8\x01\n\x07\x43ontrol\x12\x10\n\x08req_resp\x18\x01 \x01(\x08\x12\r\n\x05local\x18\x02 \x01(\x08\x12\x10\n\x08relay_id\x18\x03 \x01(\t\x12\x14\n\x0cmailbox_slot\x18\x04 \x01(\t\x12\x13\n\x0b\x61lways_send\x18\x05 \x01(\x08\x12\x14\n\x0c\x66low_control\x18\x06 \x01(\x08\x12\x12\n\nend_offset\x18\x07 \x01(\x03\x12\x15\n\rconnection_id\x18\x08 \x01(\t\"\xf3\x03\n\x06Result\x12\x35\n\nrun_result\x18\x11 \x01(\x0b\x32\x1f.wandb_internal.RunUpdateResultH\x00\x12\x34\n\x0b\x65xit_result\x18\x12 \x01(\x0b\x32\x1d.wandb_internal.RunExitResultH\x00\x12\x33\n\nlog_result\x18\x14 \x01(\x0b\x32\x1d.wandb_internal.HistoryResultH\x00\x12\x37\n\x0esummary_result\x18\x15 \x01(\x0b\x32\x1d.wandb_internal.SummaryResultH\x00\x12\x35\n\routput_result\x18\x16 \x01(\x0b\x32\x1c.wandb_internal.OutputResultH\x00\x12\x35\n\rconfig_result\x18\x17 \x01(\x0b\x32\x1c.wandb_internal.ConfigResultH\x00\x12,\n\x08response\x18\x64 \x01(\x0b\x32\x18.wandb_internal.ResponseH\x00\x12(\n\x07\x63ontrol\x18\x10 \x01(\x0b\x32\x17.wandb_internal.Control\x12\x0c\n\x04uuid\x18\x18 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._ResultInfoB\r\n\x0bresult_type\":\n\x0b\x46inalRecord\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"b\n\x0bVersionInfo\x12\x10\n\x08producer\x18\x01 \x01(\t\x12\x14\n\x0cmin_consumer\x18\x02 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"n\n\x0cHeaderRecord\x12\x31\n\x0cversion_info\x18\x01 \x01(\x0b\x32\x1b.wandb_internal.VersionInfo\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\";\n\x0c\x46ooterRecord\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"9\n\x0b\x42ranchPoint\x12\x0b\n\x03run\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x01\x12\x0e\n\x06metric\x18\x03 \x01(\t\"\x91\x05\n\tRunRecord\x12\x0e\n\x06run_id\x18\x01 \x01(\t\x12\x0e\n\x06\x65ntity\x18\x02 \x01(\t\x12\x0f\n\x07project\x18\x03 \x01(\t\x12,\n\x06\x63onfig\x18\x04 \x01(\x0b\x32\x1c.wandb_internal.ConfigRecord\x12.\n\x07summary\x18\x05 \x01(\x0b\x32\x1d.wandb_internal.SummaryRecord\x12\x11\n\trun_group\x18\x06 \x01(\t\x12\x10\n\x08job_type\x18\x07 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x08 \x01(\t\x12\r\n\x05notes\x18\t \x01(\t\x12\x0c\n\x04tags\x18\n \x03(\t\x12\x30\n\x08settings\x18\x0b \x01(\x0b\x32\x1e.wandb_internal.SettingsRecord\x12\x10\n\x08sweep_id\x18\x0c \x01(\t\x12\x0c\n\x04host\x18\r \x01(\t\x12\x15\n\rstarting_step\x18\x0e \x01(\x03\x12\x12\n\nstorage_id\x18\x10 \x01(\t\x12.\n\nstart_time\x18\x11 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0f\n\x07resumed\x18\x12 \x01(\x08\x12\x32\n\ttelemetry\x18\x13 \x01(\x0b\x32\x1f.wandb_internal.TelemetryRecord\x12\x0f\n\x07runtime\x18\x14 \x01(\x05\x12*\n\x03git\x18\x15 \x01(\x0b\x32\x1d.wandb_internal.GitRepoRecord\x12\x0e\n\x06\x66orked\x18\x16 \x01(\x08\x12\x31\n\x0c\x62ranch_point\x18\x17 \x01(\x0b\x32\x1b.wandb_internal.BranchPoint\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\";\n\rGitRepoRecord\x12\x1a\n\nremote_url\x18\x01 \x01(\tR\x06remote\x12\x0e\n\x06\x63ommit\x18\x02 \x01(\t\"c\n\x0fRunUpdateResult\x12&\n\x03run\x18\x01 \x01(\x0b\x32\x19.wandb_internal.RunRecord\x12(\n\x05\x65rror\x18\x02 \x01(\x0b\x32\x19.wandb_internal.ErrorInfo\"\xac\x01\n\tErrorInfo\x12\x0f\n\x07message\x18\x01 \x01(\t\x12\x31\n\x04\x63ode\x18\x02 \x01(\x0e\x32#.wandb_internal.ErrorInfo.ErrorCode\"[\n\tErrorCode\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x11\n\rCOMMUNICATION\x10\x01\x12\x12\n\x0e\x41UTHENTICATION\x10\x02\x12\t\n\x05USAGE\x10\x03\x12\x0f\n\x0bUNSUPPORTED\x10\x04\"`\n\rRunExitRecord\x12\x11\n\texit_code\x18\x01 \x01(\x05\x12\x0f\n\x07runtime\x18\x02 \x01(\x05\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x0f\n\rRunExitResult\"B\n\x13RunPreemptingRecord\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x15\n\x13RunPreemptingResult\"i\n\x0eSettingsRecord\x12*\n\x04item\x18\x01 \x03(\x0b\x32\x1c.wandb_internal.SettingsItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"/\n\x0cSettingsItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\x1a\n\x0bHistoryStep\x12\x0b\n\x03num\x18\x01 \x01(\x03\"\x92\x01\n\rHistoryRecord\x12)\n\x04item\x18\x01 \x03(\x0b\x32\x1b.wandb_internal.HistoryItem\x12)\n\x04step\x18\x02 \x01(\x0b\x32\x1b.wandb_internal.HistoryStep\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"B\n\x0bHistoryItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nnested_key\x18\x02 \x03(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\x0f\n\rHistoryResult\"\xdc\x01\n\x0cOutputRecord\x12<\n\x0boutput_type\x18\x01 \x01(\x0e\x32\'.wandb_internal.OutputRecord.OutputType\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0c\n\x04line\x18\x03 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"$\n\nOutputType\x12\n\n\x06STDERR\x10\x00\x12\n\n\x06STDOUT\x10\x01\"\x0e\n\x0cOutputResult\"\xe2\x01\n\x0fOutputRawRecord\x12?\n\x0boutput_type\x18\x01 \x01(\x0e\x32*.wandb_internal.OutputRawRecord.OutputType\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0c\n\x04line\x18\x03 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"$\n\nOutputType\x12\n\n\x06STDERR\x10\x00\x12\n\n\x06STDOUT\x10\x01\"\x11\n\x0fOutputRawResult\"\xb4\x03\n\x0cMetricRecord\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x11\n\tglob_name\x18\x02 \x01(\t\x12\x13\n\x0bstep_metric\x18\x04 \x01(\t\x12\x19\n\x11step_metric_index\x18\x05 \x01(\x05\x12.\n\x07options\x18\x06 \x01(\x0b\x32\x1d.wandb_internal.MetricOptions\x12.\n\x07summary\x18\x07 \x01(\x0b\x32\x1d.wandb_internal.MetricSummary\x12\x35\n\x04goal\x18\x08 \x01(\x0e\x32\'.wandb_internal.MetricRecord.MetricGoal\x12/\n\x08_control\x18\t \x01(\x0b\x32\x1d.wandb_internal.MetricControl\x12\x1a\n\x12\x65xpanded_from_glob\x18\n \x01(\x08\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"B\n\nMetricGoal\x12\x0e\n\nGOAL_UNSET\x10\x00\x12\x11\n\rGOAL_MINIMIZE\x10\x01\x12\x11\n\rGOAL_MAXIMIZE\x10\x02\"\x0e\n\x0cMetricResult\"C\n\rMetricOptions\x12\x11\n\tstep_sync\x18\x01 \x01(\x08\x12\x0e\n\x06hidden\x18\x02 \x01(\x08\x12\x0f\n\x07\x64\x65\x66ined\x18\x03 \x01(\x08\"\"\n\rMetricControl\x12\x11\n\toverwrite\x18\x01 \x01(\x08\"~\n\rMetricSummary\x12\x0b\n\x03min\x18\x01 \x01(\x08\x12\x0b\n\x03max\x18\x02 \x01(\x08\x12\x0c\n\x04mean\x18\x03 \x01(\x08\x12\x0c\n\x04\x62\x65st\x18\x04 \x01(\x08\x12\x0c\n\x04last\x18\x05 \x01(\x08\x12\x0c\n\x04none\x18\x06 \x01(\x08\x12\x0c\n\x04\x63opy\x18\x07 \x01(\x08\x12\r\n\x05\x66irst\x18\x08 \x01(\x08\"\x93\x01\n\x0c\x43onfigRecord\x12*\n\x06update\x18\x01 \x03(\x0b\x32\x1a.wandb_internal.ConfigItem\x12*\n\x06remove\x18\x02 \x03(\x0b\x32\x1a.wandb_internal.ConfigItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"A\n\nConfigItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nnested_key\x18\x02 \x03(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\x0e\n\x0c\x43onfigResult\"\x96\x01\n\rSummaryRecord\x12+\n\x06update\x18\x01 \x03(\x0b\x32\x1b.wandb_internal.SummaryItem\x12+\n\x06remove\x18\x02 \x03(\x0b\x32\x1b.wandb_internal.SummaryItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"B\n\x0bSummaryItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nnested_key\x18\x02 \x03(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\x0f\n\rSummaryResult\"d\n\x0b\x46ilesRecord\x12(\n\x05\x66iles\x18\x01 \x03(\x0b\x32\x19.wandb_internal.FilesItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\xec\x01\n\tFilesItem\x12\x0c\n\x04path\x18\x01 \x01(\t\x12\x34\n\x06policy\x18\x02 \x01(\x0e\x32$.wandb_internal.FilesItem.PolicyType\x12\x30\n\x04type\x18\x03 \x01(\x0e\x32\".wandb_internal.FilesItem.FileType\"(\n\nPolicyType\x12\x07\n\x03NOW\x10\x00\x12\x07\n\x03\x45ND\x10\x01\x12\x08\n\x04LIVE\x10\x02\"9\n\x08\x46ileType\x12\t\n\x05OTHER\x10\x00\x12\t\n\x05WANDB\x10\x01\x12\t\n\x05MEDIA\x10\x02\x12\x0c\n\x08\x41RTIFACT\x10\x03J\x04\x08\x10\x10\x11\"\r\n\x0b\x46ilesResult\"\xe6\x01\n\x0bStatsRecord\x12\x39\n\nstats_type\x18\x01 \x01(\x0e\x32%.wandb_internal.StatsRecord.StatsType\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\'\n\x04item\x18\x03 \x03(\x0b\x32\x19.wandb_internal.StatsItem\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x17\n\tStatsType\x12\n\n\x06SYSTEM\x10\x00\",\n\tStatsItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x10 \x01(\t\"\xe7\x03\n\x0e\x41rtifactRecord\x12\x0e\n\x06run_id\x18\x01 \x01(\t\x12\x0f\n\x07project\x18\x02 \x01(\t\x12\x0e\n\x06\x65ntity\x18\x03 \x01(\t\x12\x0c\n\x04type\x18\x04 \x01(\t\x12\x0c\n\x04name\x18\x05 \x01(\t\x12\x0e\n\x06\x64igest\x18\x06 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x07 \x01(\t\x12\x10\n\x08metadata\x18\x08 \x01(\t\x12\x14\n\x0cuser_created\x18\t \x01(\x08\x12\x18\n\x10use_after_commit\x18\n \x01(\x08\x12\x0f\n\x07\x61liases\x18\x0b \x03(\t\x12\x32\n\x08manifest\x18\x0c \x01(\x0b\x32 .wandb_internal.ArtifactManifest\x12\x16\n\x0e\x64istributed_id\x18\r \x01(\t\x12\x10\n\x08\x66inalize\x18\x0e \x01(\x08\x12\x11\n\tclient_id\x18\x0f \x01(\t\x12\x1a\n\x12sequence_client_id\x18\x10 \x01(\t\x12\x0f\n\x07\x62\x61se_id\x18\x11 \x01(\t\x12\x1c\n\x14ttl_duration_seconds\x18\x12 \x01(\x03\x12\x0c\n\x04tags\x18\x13 \x03(\t\x12\x19\n\x11incremental_beta1\x18\x64 \x01(\x08\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\xd8\x01\n\x10\x41rtifactManifest\x12\x0f\n\x07version\x18\x01 \x01(\x05\x12\x16\n\x0estorage_policy\x18\x02 \x01(\t\x12\x46\n\x15storage_policy_config\x18\x03 \x03(\x0b\x32\'.wandb_internal.StoragePolicyConfigItem\x12\x37\n\x08\x63ontents\x18\x04 \x03(\x0b\x32%.wandb_internal.ArtifactManifestEntry\x12\x1a\n\x12manifest_file_path\x18\x05 \x01(\t\"\xcf\x01\n\x15\x41rtifactManifestEntry\x12\x0c\n\x04path\x18\x01 \x01(\t\x12\x0e\n\x06\x64igest\x18\x02 \x01(\t\x12\x0b\n\x03ref\x18\x03 \x01(\t\x12\x0c\n\x04size\x18\x04 \x01(\x03\x12\x10\n\x08mimetype\x18\x05 \x01(\t\x12\x12\n\nlocal_path\x18\x06 \x01(\t\x12\x19\n\x11\x62irth_artifact_id\x18\x07 \x01(\t\x12\x12\n\nskip_cache\x18\x08 \x01(\x08\x12(\n\x05\x65xtra\x18\x10 \x03(\x0b\x32\x19.wandb_internal.ExtraItem\",\n\tExtraItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x02 \x01(\t\":\n\x17StoragePolicyConfigItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nvalue_json\x18\x02 \x01(\t\"\x10\n\x0e\x41rtifactResult\"\x14\n\x12LinkArtifactResult\"\xf0\x01\n\x13LinkArtifactRequest\x12\x11\n\tclient_id\x18\x01 \x01(\t\x12\x11\n\tserver_id\x18\x02 \x01(\t\x12\x16\n\x0eportfolio_name\x18\x03 \x01(\t\x12\x18\n\x10portfolio_entity\x18\x04 \x01(\t\x12\x19\n\x11portfolio_project\x18\x05 \x01(\t\x12\x19\n\x11portfolio_aliases\x18\x06 \x03(\t\x12\x1e\n\x16portfolio_organization\x18\x07 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"[\n\x14LinkArtifactResponse\x12\x15\n\rerror_message\x18\x01 \x01(\t\x12\x1a\n\rversion_index\x18\x02 \x01(\x05H\x00\x88\x01\x01\x42\x10\n\x0e_version_index\"h\n\x08TBRecord\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\x12\x0f\n\x07log_dir\x18\x01 \x01(\t\x12\x10\n\x08root_dir\x18\x03 \x01(\t\x12\x0c\n\x04save\x18\x02 \x01(\x08\"\n\n\x08TBResult\"}\n\x0b\x41lertRecord\x12\r\n\x05title\x18\x01 \x01(\t\x12\x0c\n\x04text\x18\x02 \x01(\t\x12\r\n\x05level\x18\x03 \x01(\t\x12\x15\n\rwait_duration\x18\x04 \x01(\x03\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\r\n\x0b\x41lertResult\"\xb3\x11\n\x07Request\x12\x38\n\x0bstop_status\x18\x01 \x01(\x0b\x32!.wandb_internal.StopStatusRequestH\x00\x12>\n\x0enetwork_status\x18\x02 \x01(\x0b\x32$.wandb_internal.NetworkStatusRequestH\x00\x12-\n\x05\x64\x65\x66\x65r\x18\x03 \x01(\x0b\x32\x1c.wandb_internal.DeferRequestH\x00\x12\x38\n\x0bget_summary\x18\x04 \x01(\x0b\x32!.wandb_internal.GetSummaryRequestH\x00\x12-\n\x05login\x18\x05 \x01(\x0b\x32\x1c.wandb_internal.LoginRequestH\x00\x12-\n\x05pause\x18\x06 \x01(\x0b\x32\x1c.wandb_internal.PauseRequestH\x00\x12/\n\x06resume\x18\x07 \x01(\x0b\x32\x1d.wandb_internal.ResumeRequestH\x00\x12\x34\n\tpoll_exit\x18\x08 \x01(\x0b\x32\x1f.wandb_internal.PollExitRequestH\x00\x12@\n\x0fsampled_history\x18\t \x01(\x0b\x32%.wandb_internal.SampledHistoryRequestH\x00\x12@\n\x0fpartial_history\x18\n \x01(\x0b\x32%.wandb_internal.PartialHistoryRequestH\x00\x12\x34\n\trun_start\x18\x0b \x01(\x0b\x32\x1f.wandb_internal.RunStartRequestH\x00\x12<\n\rcheck_version\x18\x0c \x01(\x0b\x32#.wandb_internal.CheckVersionRequestH\x00\x12:\n\x0clog_artifact\x18\r \x01(\x0b\x32\".wandb_internal.LogArtifactRequestH\x00\x12\x44\n\x11\x64ownload_artifact\x18\x0e \x01(\x0b\x32\'.wandb_internal.DownloadArtifactRequestH\x00\x12\x35\n\tkeepalive\x18\x11 \x01(\x0b\x32 .wandb_internal.KeepaliveRequestH\x00\x12>\n\x0eserver_feature\x18\x12 \x01(\x0b\x32$.wandb_internal.ServerFeatureRequestH\x00\x12\x36\n\nrun_status\x18\x14 \x01(\x0b\x32 .wandb_internal.RunStatusRequestH\x00\x12/\n\x06\x63\x61ncel\x18\x15 \x01(\x0b\x32\x1d.wandb_internal.CancelRequestH\x00\x12\x44\n\x11internal_messages\x18\x17 \x01(\x0b\x32\'.wandb_internal.InternalMessagesRequestH\x00\x12@\n\x0fpython_packages\x18\x18 \x01(\x0b\x32%.wandb_internal.PythonPackagesRequestH\x00\x12\x33\n\x08shutdown\x18@ \x01(\x0b\x32\x1f.wandb_internal.ShutdownRequestH\x00\x12/\n\x06\x61ttach\x18\x41 \x01(\x0b\x32\x1d.wandb_internal.AttachRequestH\x00\x12/\n\x06status\x18\x42 \x01(\x0b\x32\x1d.wandb_internal.StatusRequestH\x00\x12\x38\n\x0bserver_info\x18\x43 \x01(\x0b\x32!.wandb_internal.ServerInfoRequestH\x00\x12\x38\n\x0bsender_mark\x18\x44 \x01(\x0b\x32!.wandb_internal.SenderMarkRequestH\x00\x12\x38\n\x0bsender_read\x18\x45 \x01(\x0b\x32!.wandb_internal.SenderReadRequestH\x00\x12<\n\rstatus_report\x18\x46 \x01(\x0b\x32#.wandb_internal.StatusReportRequestH\x00\x12>\n\x0esummary_record\x18G \x01(\x0b\x32$.wandb_internal.SummaryRecordRequestH\x00\x12\x42\n\x10telemetry_record\x18H \x01(\x0b\x32&.wandb_internal.TelemetryRecordRequestH\x00\x12\x32\n\x08job_info\x18I \x01(\x0b\x32\x1e.wandb_internal.JobInfoRequestH\x00\x12\x45\n\x12get_system_metrics\x18J \x01(\x0b\x32\'.wandb_internal.GetSystemMetricsRequestH\x00\x12\x34\n\tjob_input\x18M \x01(\x0b\x32\x1f.wandb_internal.JobInputRequestH\x00\x12<\n\rlink_artifact\x18N \x01(\x0b\x32#.wandb_internal.LinkArtifactRequestH\x00\x12N\n\x17run_finish_without_exit\x18O \x01(\x0b\x32+.wandb_internal.RunFinishWithoutExitRequestH\x00\x12\x38\n\x0bsync_finish\x18Q \x01(\x0b\x32!.wandb_internal.SyncFinishRequestH\x00\x12;\n\noperations\x18R \x01(\x0b\x32%.wandb_internal.OperationStatsRequestH\x00\x12\x39\n\x0btest_inject\x18\xe8\x07 \x01(\x0b\x32!.wandb_internal.TestInjectRequestH\x00\x42\x0e\n\x0crequest_typeJ\x04\x08\x16\x10\x17J\x04\x08K\x10LJ\x04\x08L\x10MJ\x04\x08P\x10Q\"\x9b\x0e\n\x08Response\x12?\n\x12keepalive_response\x18\x12 \x01(\x0b\x32!.wandb_internal.KeepaliveResponseH\x00\x12\x42\n\x14stop_status_response\x18\x13 \x01(\x0b\x32\".wandb_internal.StopStatusResponseH\x00\x12H\n\x17network_status_response\x18\x14 \x01(\x0b\x32%.wandb_internal.NetworkStatusResponseH\x00\x12\x37\n\x0elogin_response\x18\x18 \x01(\x0b\x32\x1d.wandb_internal.LoginResponseH\x00\x12\x42\n\x14get_summary_response\x18\x19 \x01(\x0b\x32\".wandb_internal.GetSummaryResponseH\x00\x12>\n\x12poll_exit_response\x18\x1a \x01(\x0b\x32 .wandb_internal.PollExitResponseH\x00\x12J\n\x18sampled_history_response\x18\x1b \x01(\x0b\x32&.wandb_internal.SampledHistoryResponseH\x00\x12>\n\x12run_start_response\x18\x1c \x01(\x0b\x32 .wandb_internal.RunStartResponseH\x00\x12\x46\n\x16\x63heck_version_response\x18\x1d \x01(\x0b\x32$.wandb_internal.CheckVersionResponseH\x00\x12\x44\n\x15log_artifact_response\x18\x1e \x01(\x0b\x32#.wandb_internal.LogArtifactResponseH\x00\x12N\n\x1a\x64ownload_artifact_response\x18\x1f \x01(\x0b\x32(.wandb_internal.DownloadArtifactResponseH\x00\x12H\n\x17server_feature_response\x18 \x01(\x0b\x32%.wandb_internal.ServerFeatureResponseH\x00\x12@\n\x13run_status_response\x18# \x01(\x0b\x32!.wandb_internal.RunStatusResponseH\x00\x12\x39\n\x0f\x63\x61ncel_response\x18$ \x01(\x0b\x32\x1e.wandb_internal.CancelResponseH\x00\x12N\n\x1ainternal_messages_response\x18% \x01(\x0b\x32(.wandb_internal.InternalMessagesResponseH\x00\x12=\n\x11shutdown_response\x18@ \x01(\x0b\x32 .wandb_internal.ShutdownResponseH\x00\x12\x39\n\x0f\x61ttach_response\x18\x41 \x01(\x0b\x32\x1e.wandb_internal.AttachResponseH\x00\x12\x39\n\x0fstatus_response\x18\x42 \x01(\x0b\x32\x1e.wandb_internal.StatusResponseH\x00\x12\x42\n\x14server_info_response\x18\x43 \x01(\x0b\x32\".wandb_internal.ServerInfoResponseH\x00\x12<\n\x11job_info_response\x18\x44 \x01(\x0b\x32\x1f.wandb_internal.JobInfoResponseH\x00\x12O\n\x1bget_system_metrics_response\x18\x45 \x01(\x0b\x32(.wandb_internal.GetSystemMetricsResponseH\x00\x12\x46\n\x16link_artifact_response\x18G \x01(\x0b\x32$.wandb_internal.LinkArtifactResponseH\x00\x12\x35\n\rsync_response\x18\x46 \x01(\x0b\x32\x1c.wandb_internal.SyncResponseH\x00\x12X\n run_finish_without_exit_response\x18H \x01(\x0b\x32,.wandb_internal.RunFinishWithoutExitResponseH\x00\x12\x45\n\x13operations_response\x18J \x01(\x0b\x32&.wandb_internal.OperationStatsResponseH\x00\x12\x43\n\x14test_inject_response\x18\xe8\x07 \x01(\x0b\x32\".wandb_internal.TestInjectResponseH\x00\x42\x0f\n\rresponse_typeJ\x04\x08I\x10J\"\xc0\x02\n\x0c\x44\x65\x66\x65rRequest\x12\x36\n\x05state\x18\x01 \x01(\x0e\x32\'.wandb_internal.DeferRequest.DeferState\"\xf7\x01\n\nDeferState\x12\t\n\x05\x42\x45GIN\x10\x00\x12\r\n\tFLUSH_RUN\x10\x01\x12\x0f\n\x0b\x46LUSH_STATS\x10\x02\x12\x19\n\x15\x46LUSH_PARTIAL_HISTORY\x10\x03\x12\x0c\n\x08\x46LUSH_TB\x10\x04\x12\r\n\tFLUSH_SUM\x10\x05\x12\x13\n\x0f\x46LUSH_DEBOUNCER\x10\x06\x12\x10\n\x0c\x46LUSH_OUTPUT\x10\x07\x12\r\n\tFLUSH_JOB\x10\x08\x12\r\n\tFLUSH_DIR\x10\t\x12\x0c\n\x08\x46LUSH_FP\x10\n\x12\x0b\n\x07JOIN_FP\x10\x0b\x12\x0c\n\x08\x46LUSH_FS\x10\x0c\x12\x0f\n\x0b\x46LUSH_FINAL\x10\r\x12\x07\n\x03\x45ND\x10\x0e\"<\n\x0cPauseRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x0f\n\rPauseResponse\"=\n\rResumeRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x10\n\x0eResumeResponse\"M\n\x0cLoginRequest\x12\x0f\n\x07\x61pi_key\x18\x01 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"&\n\rLoginResponse\x12\x15\n\ractive_entity\x18\x01 \x01(\t\"A\n\x11GetSummaryRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"?\n\x12GetSummaryResponse\x12)\n\x04item\x18\x01 \x03(\x0b\x32\x1b.wandb_internal.SummaryItem\"G\n\x17GetSystemMetricsRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"R\n\x12SystemMetricSample\x12-\n\ttimestamp\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\r\n\x05value\x18\x02 \x01(\x02\"I\n\x13SystemMetricsBuffer\x12\x32\n\x06record\x18\x01 \x03(\x0b\x32\".wandb_internal.SystemMetricSample\"\xca\x01\n\x18GetSystemMetricsResponse\x12S\n\x0esystem_metrics\x18\x01 \x03(\x0b\x32;.wandb_internal.GetSystemMetricsResponse.SystemMetricsEntry\x1aY\n\x12SystemMetricsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x32\n\x05value\x18\x02 \x01(\x0b\x32#.wandb_internal.SystemMetricsBuffer:\x02\x38\x01\"=\n\rStatusRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\")\n\x0eStatusResponse\x12\x17\n\x0frun_should_stop\x18\x01 \x01(\x08\"A\n\x11StopStatusRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"-\n\x12StopStatusResponse\x12\x17\n\x0frun_should_stop\x18\x01 \x01(\x08\"D\n\x14NetworkStatusRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"P\n\x15NetworkStatusResponse\x12\x37\n\x11network_responses\x18\x01 \x03(\x0b\x32\x1c.wandb_internal.HttpResponse\"D\n\x0cHttpResponse\x12\x18\n\x10http_status_code\x18\x01 \x01(\x05\x12\x1a\n\x12http_response_text\x18\x02 \x01(\t\"G\n\x17InternalMessagesRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"N\n\x18InternalMessagesResponse\x12\x32\n\x08messages\x18\x01 \x01(\x0b\x32 .wandb_internal.InternalMessages\"#\n\x10InternalMessages\x12\x0f\n\x07warning\x18\x01 \x03(\t\"?\n\x0fPollExitRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\xf5\x01\n\x10PollExitResponse\x12\x0c\n\x04\x64one\x18\x01 \x01(\x08\x12\x32\n\x0b\x65xit_result\x18\x02 \x01(\x0b\x32\x1d.wandb_internal.RunExitResult\x12\x35\n\x0cpusher_stats\x18\x03 \x01(\x0b\x32\x1f.wandb_internal.FilePusherStats\x12/\n\x0b\x66ile_counts\x18\x04 \x01(\x0b\x32\x1a.wandb_internal.FileCounts\x12\x37\n\x0foperation_stats\x18\x05 \x01(\x0b\x32\x1e.wandb_internal.OperationStats\"E\n\x15OperationStatsRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"Q\n\x16OperationStatsResponse\x12\x37\n\x0foperation_stats\x18\x01 \x01(\x0b\x32\x1e.wandb_internal.OperationStats\"Y\n\x0eOperationStats\x12-\n\noperations\x18\x01 \x03(\x0b\x32\x19.wandb_internal.Operation\x12\x18\n\x10total_operations\x18\x02 \x01(\x03\"\x87\x01\n\tOperation\x12\x0c\n\x04\x64\x65sc\x18\x01 \x01(\t\x12\x17\n\x0fruntime_seconds\x18\x02 \x01(\x01\x12\x10\n\x08progress\x18\x03 \x01(\t\x12\x14\n\x0c\x65rror_status\x18\x04 \x01(\t\x12+\n\x08subtasks\x18\x05 \x03(\x0b\x32\x19.wandb_internal.Operation\"\x13\n\x11SenderMarkRequest\"\x13\n\x11SyncFinishRequest\"E\n\x0cSyncResponse\x12\x0b\n\x03url\x18\x01 \x01(\t\x12(\n\x05\x65rror\x18\x02 \x01(\x0b\x32\x19.wandb_internal.ErrorInfo\"?\n\x11SenderReadRequest\x12\x14\n\x0cstart_offset\x18\x01 \x01(\x03\x12\x14\n\x0c\x66inal_offset\x18\x02 \x01(\x03\"m\n\x13StatusReportRequest\x12\x12\n\nrecord_num\x18\x01 \x01(\x03\x12\x13\n\x0bsent_offset\x18\x02 \x01(\x03\x12-\n\tsync_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"F\n\x14SummaryRecordRequest\x12.\n\x07summary\x18\x01 \x01(\x0b\x32\x1d.wandb_internal.SummaryRecord\"L\n\x16TelemetryRecordRequest\x12\x32\n\ttelemetry\x18\x01 \x01(\x0b\x32\x1f.wandb_internal.TelemetryRecord\"A\n\x11ServerInfoRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"|\n\x12ServerInfoResponse\x12-\n\nlocal_info\x18\x01 \x01(\x0b\x32\x19.wandb_internal.LocalInfo\x12\x37\n\x0fserver_messages\x18\x02 \x01(\x0b\x32\x1e.wandb_internal.ServerMessages\"=\n\x0eServerMessages\x12+\n\x04item\x18\x01 \x03(\x0b\x32\x1d.wandb_internal.ServerMessage\"e\n\rServerMessage\x12\x12\n\nplain_text\x18\x01 \x01(\t\x12\x10\n\x08utf_text\x18\x02 \x01(\t\x12\x11\n\thtml_text\x18\x03 \x01(\t\x12\x0c\n\x04type\x18\x04 \x01(\t\x12\r\n\x05level\x18\x05 \x01(\x05\"c\n\nFileCounts\x12\x13\n\x0bwandb_count\x18\x01 \x01(\x05\x12\x13\n\x0bmedia_count\x18\x02 \x01(\x05\x12\x16\n\x0e\x61rtifact_count\x18\x03 \x01(\x05\x12\x13\n\x0bother_count\x18\x04 \x01(\x05\"U\n\x0f\x46ilePusherStats\x12\x16\n\x0euploaded_bytes\x18\x01 \x01(\x03\x12\x13\n\x0btotal_bytes\x18\x02 \x01(\x03\x12\x15\n\rdeduped_bytes\x18\x03 \x01(\x03\"\x1e\n\rFilesUploaded\x12\r\n\x05\x66iles\x18\x01 \x03(\t\"\xf4\x01\n\x17\x46ileTransferInfoRequest\x12\x42\n\x04type\x18\x01 \x01(\x0e\x32\x34.wandb_internal.FileTransferInfoRequest.TransferType\x12\x0c\n\x04path\x18\x02 \x01(\t\x12\x0b\n\x03url\x18\x03 \x01(\t\x12\x0c\n\x04size\x18\x04 \x01(\x03\x12\x11\n\tprocessed\x18\x05 \x01(\x03\x12/\n\x0b\x66ile_counts\x18\x06 \x01(\x0b\x32\x1a.wandb_internal.FileCounts\"(\n\x0cTransferType\x12\n\n\x06Upload\x10\x00\x12\x0c\n\x08\x44ownload\x10\x01\"1\n\tLocalInfo\x12\x0f\n\x07version\x18\x01 \x01(\t\x12\x13\n\x0bout_of_date\x18\x02 \x01(\x08\"?\n\x0fShutdownRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x12\n\x10ShutdownResponse\"P\n\rAttachRequest\x12\x11\n\tattach_id\x18\x14 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"b\n\x0e\x41ttachResponse\x12&\n\x03run\x18\x01 \x01(\x0b\x32\x19.wandb_internal.RunRecord\x12(\n\x05\x65rror\x18\x02 \x01(\x0b\x32\x19.wandb_internal.ErrorInfo\"\xd5\x02\n\x11TestInjectRequest\x12\x13\n\x0bhandler_exc\x18\x01 \x01(\x08\x12\x14\n\x0chandler_exit\x18\x02 \x01(\x08\x12\x15\n\rhandler_abort\x18\x03 \x01(\x08\x12\x12\n\nsender_exc\x18\x04 \x01(\x08\x12\x13\n\x0bsender_exit\x18\x05 \x01(\x08\x12\x14\n\x0csender_abort\x18\x06 \x01(\x08\x12\x0f\n\x07req_exc\x18\x07 \x01(\x08\x12\x10\n\x08req_exit\x18\x08 \x01(\x08\x12\x11\n\treq_abort\x18\t \x01(\x08\x12\x10\n\x08resp_exc\x18\n \x01(\x08\x12\x11\n\tresp_exit\x18\x0b \x01(\x08\x12\x12\n\nresp_abort\x18\x0c \x01(\x08\x12\x10\n\x08msg_drop\x18\r \x01(\x08\x12\x10\n\x08msg_hang\x18\x0e \x01(\x08\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x14\n\x12TestInjectResponse\"\x1e\n\rHistoryAction\x12\r\n\x05\x66lush\x18\x01 \x01(\x08\"\xca\x01\n\x15PartialHistoryRequest\x12)\n\x04item\x18\x01 \x03(\x0b\x32\x1b.wandb_internal.HistoryItem\x12)\n\x04step\x18\x02 \x01(\x0b\x32\x1b.wandb_internal.HistoryStep\x12-\n\x06\x61\x63tion\x18\x03 \x01(\x0b\x32\x1d.wandb_internal.HistoryAction\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x18\n\x16PartialHistoryResponse\"E\n\x15SampledHistoryRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"_\n\x12SampledHistoryItem\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x12\n\nnested_key\x18\x02 \x03(\t\x12\x14\n\x0cvalues_float\x18\x03 \x03(\x02\x12\x12\n\nvalues_int\x18\x04 \x03(\x03\"J\n\x16SampledHistoryResponse\x12\x30\n\x04item\x18\x01 \x03(\x0b\x32\".wandb_internal.SampledHistoryItem\"@\n\x10RunStatusRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"x\n\x11RunStatusResponse\x12\x18\n\x10sync_items_total\x18\x01 \x01(\x03\x12\x1a\n\x12sync_items_pending\x18\x02 \x01(\x03\x12-\n\tsync_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"g\n\x0fRunStartRequest\x12&\n\x03run\x18\x01 \x01(\x0b\x32\x19.wandb_internal.RunRecord\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x12\n\x10RunStartResponse\"K\n\x1bRunFinishWithoutExitRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x1e\n\x1cRunFinishWithoutExitResponse\"\\\n\x13\x43heckVersionRequest\x12\x17\n\x0f\x63urrent_version\x18\x01 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"]\n\x14\x43heckVersionResponse\x12\x17\n\x0fupgrade_message\x18\x01 \x01(\t\x12\x14\n\x0cyank_message\x18\x02 \x01(\t\x12\x16\n\x0e\x64\x65lete_message\x18\x03 \x01(\t\">\n\x0eJobInfoRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"6\n\x0fJobInfoResponse\x12\x12\n\nsequenceId\x18\x01 \x01(\t\x12\x0f\n\x07version\x18\x02 \x01(\t\"\x9f\x01\n\x12LogArtifactRequest\x12\x30\n\x08\x61rtifact\x18\x01 \x01(\x0b\x32\x1e.wandb_internal.ArtifactRecord\x12\x14\n\x0chistory_step\x18\x02 \x01(\x03\x12\x13\n\x0bstaging_dir\x18\x03 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"A\n\x13LogArtifactResponse\x12\x13\n\x0b\x61rtifact_id\x18\x01 \x01(\t\x12\x15\n\rerror_message\x18\x02 \x01(\t\"\xbe\x01\n\x17\x44ownloadArtifactRequest\x12\x13\n\x0b\x61rtifact_id\x18\x01 \x01(\t\x12\x15\n\rdownload_root\x18\x02 \x01(\t\x12 \n\x18\x61llow_missing_references\x18\x04 \x01(\x08\x12\x12\n\nskip_cache\x18\x05 \x01(\x08\x12\x13\n\x0bpath_prefix\x18\x06 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"1\n\x18\x44ownloadArtifactResponse\x12\x15\n\rerror_message\x18\x01 \x01(\t\"@\n\x10KeepaliveRequest\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x13\n\x11KeepaliveResponse\"q\n\x0c\x41rtifactInfo\x12\x10\n\x08\x61rtifact\x18\x01 \x01(\t\x12\x12\n\nentrypoint\x18\x02 \x03(\t\x12\x10\n\x08notebook\x18\x03 \x01(\x08\x12\x15\n\rbuild_context\x18\x04 \x01(\t\x12\x12\n\ndockerfile\x18\x05 \x01(\t\")\n\x07GitInfo\x12\x0e\n\x06remote\x18\x01 \x01(\t\x12\x0e\n\x06\x63ommit\x18\x02 \x01(\t\"\x87\x01\n\tGitSource\x12)\n\x08git_info\x18\x01 \x01(\x0b\x32\x17.wandb_internal.GitInfo\x12\x12\n\nentrypoint\x18\x02 \x03(\t\x12\x10\n\x08notebook\x18\x03 \x01(\x08\x12\x15\n\rbuild_context\x18\x04 \x01(\t\x12\x12\n\ndockerfile\x18\x05 \x01(\t\"\x1c\n\x0bImageSource\x12\r\n\x05image\x18\x01 \x01(\t\"\x8c\x01\n\x06Source\x12&\n\x03git\x18\x01 \x01(\x0b\x32\x19.wandb_internal.GitSource\x12.\n\x08\x61rtifact\x18\x02 \x01(\x0b\x32\x1c.wandb_internal.ArtifactInfo\x12*\n\x05image\x18\x03 \x01(\x0b\x32\x1b.wandb_internal.ImageSource\"k\n\tJobSource\x12\x10\n\x08_version\x18\x01 \x01(\t\x12\x13\n\x0bsource_type\x18\x02 \x01(\t\x12&\n\x06source\x18\x03 \x01(\x0b\x32\x16.wandb_internal.Source\x12\x0f\n\x07runtime\x18\x04 \x01(\t\"V\n\x12PartialJobArtifact\x12\x10\n\x08job_name\x18\x01 \x01(\t\x12.\n\x0bsource_info\x18\x02 \x01(\x0b\x32\x19.wandb_internal.JobSource\"\x9d\x01\n\x11UseArtifactRecord\x12\n\n\x02id\x18\x01 \x01(\t\x12\x0c\n\x04type\x18\x02 \x01(\t\x12\x0c\n\x04name\x18\x03 \x01(\t\x12\x33\n\x07partial\x18\x04 \x01(\x0b\x32\".wandb_internal.PartialJobArtifact\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x13\n\x11UseArtifactResult\"R\n\rCancelRequest\x12\x13\n\x0b\x63\x61ncel_slot\x18\x01 \x01(\t\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"\x10\n\x0e\x43\x61ncelResponse\"\'\n\x08\x44iskInfo\x12\r\n\x05total\x18\x01 \x01(\x04\x12\x0c\n\x04used\x18\x02 \x01(\x04\"\x1b\n\nMemoryInfo\x12\r\n\x05total\x18\x01 \x01(\x04\"/\n\x07\x43puInfo\x12\r\n\x05\x63ount\x18\x01 \x01(\r\x12\x15\n\rcount_logical\x18\x02 \x01(\r\"\x9a\x01\n\tAppleInfo\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\necpu_cores\x18\x02 \x01(\r\x12\x12\n\npcpu_cores\x18\x03 \x01(\r\x12\x11\n\tgpu_cores\x18\x04 \x01(\r\x12\x11\n\tmemory_gb\x18\x05 \x01(\r\x12\x18\n\x10swap_total_bytes\x18\x06 \x01(\x04\x12\x17\n\x0fram_total_bytes\x18\x07 \x01(\x04\"k\n\rGpuNvidiaInfo\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0cmemory_total\x18\x02 \x01(\x04\x12\x12\n\ncuda_cores\x18\x03 \x01(\r\x12\x14\n\x0c\x61rchitecture\x18\x04 \x01(\t\x12\x0c\n\x04uuid\x18\x05 \x01(\t\"\x89\x02\n\nGpuAmdInfo\x12\n\n\x02id\x18\x01 \x01(\t\x12\x11\n\tunique_id\x18\x02 \x01(\t\x12\x15\n\rvbios_version\x18\x03 \x01(\t\x12\x19\n\x11performance_level\x18\x04 \x01(\t\x12\x15\n\rgpu_overdrive\x18\x05 \x01(\t\x12\x1c\n\x14gpu_memory_overdrive\x18\x06 \x01(\t\x12\x11\n\tmax_power\x18\x07 \x01(\t\x12\x0e\n\x06series\x18\x08 \x01(\t\x12\r\n\x05model\x18\t \x01(\t\x12\x0e\n\x06vendor\x18\n \x01(\t\x12\x0b\n\x03sku\x18\x0b \x01(\t\x12\x12\n\nsclk_range\x18\x0c \x01(\t\x12\x12\n\nmclk_range\x18\r \x01(\t\"n\n\x0cTrainiumInfo\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06vendor\x18\x02 \x01(\t\x12\x1b\n\x13neuron_device_count\x18\x03 \x01(\r\x12#\n\x1bneuroncore_per_device_count\x18\x04 \x01(\r\"Q\n\x07TPUInfo\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07hbm_gib\x18\x02 \x01(\r\x12\x18\n\x10\x64\x65vices_per_chip\x18\x03 \x01(\r\x12\r\n\x05\x63ount\x18\x04 \x01(\r\"E\n\rCoreWeaveInfo\x12\x14\n\x0c\x63luster_name\x18\x01 \x01(\t\x12\x0e\n\x06org_id\x18\x02 \x01(\t\x12\x0e\n\x06region\x18\x03 \x01(\t\"\xa8\t\n\x11\x45nvironmentRecord\x12\n\n\x02os\x18\x01 \x01(\t\x12\x0e\n\x06python\x18\x02 \x01(\t\x12\x39\n\nstarted_at\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.TimestampR\tstartedAt\x12\x0e\n\x06\x64ocker\x18\x04 \x01(\t\x12\x0c\n\x04\x61rgs\x18\x05 \x03(\t\x12\x0f\n\x07program\x18\x06 \x01(\t\x12\x1b\n\tcode_path\x18\x07 \x01(\tR\x08\x63odePath\x12&\n\x0f\x63ode_path_local\x18\x08 \x01(\tR\rcodePathLocal\x12*\n\x03git\x18\t \x01(\x0b\x32\x1d.wandb_internal.GitRepoRecord\x12\r\n\x05\x65mail\x18\n \x01(\t\x12\x0c\n\x04root\x18\x0b \x01(\t\x12\x0c\n\x04host\x18\x0c \x01(\t\x12\x10\n\x08username\x18\r \x01(\t\x12\x12\n\nexecutable\x18\x0e \x01(\t\x12\r\n\x05\x63olab\x18\x0f \x01(\t\x12\x1c\n\tcpu_count\x18\x10 \x01(\rR\tcpu_count\x12,\n\x11\x63pu_count_logical\x18\x11 \x01(\rR\x11\x63pu_count_logical\x12\x15\n\x08gpu_type\x18\x12 \x01(\tR\x03gpu\x12\x1c\n\tgpu_count\x18\x13 \x01(\rR\tgpu_count\x12\x39\n\x04\x64isk\x18\x14 \x03(\x0b\x32+.wandb_internal.EnvironmentRecord.DiskEntry\x12*\n\x06memory\x18\x15 \x01(\x0b\x32\x1a.wandb_internal.MemoryInfo\x12$\n\x03\x63pu\x18\x16 \x01(\x0b\x32\x17.wandb_internal.CpuInfo\x12(\n\x05\x61pple\x18\x17 \x01(\x0b\x32\x19.wandb_internal.AppleInfo\x12=\n\ngpu_nvidia\x18\x18 \x03(\x0b\x32\x1d.wandb_internal.GpuNvidiaInfoR\ngpu_nvidia\x12\x14\n\x0c\x63uda_version\x18\x19 \x01(\t\x12\x34\n\x07gpu_amd\x18\x1a \x03(\x0b\x32\x1a.wandb_internal.GpuAmdInfoR\x07gpu_amd\x12;\n\x05slurm\x18\x1b \x03(\x0b\x32,.wandb_internal.EnvironmentRecord.SlurmEntry\x12.\n\x08trainium\x18\x1c \x01(\x0b\x32\x1c.wandb_internal.TrainiumInfo\x12$\n\x03tpu\x18\x1d \x01(\x0b\x32\x17.wandb_internal.TPUInfo\x12\x30\n\tcoreweave\x18\x1e \x01(\x0b\x32\x1d.wandb_internal.CoreWeaveInfo\x12\x12\n\twriter_id\x18\xc7\x01 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\x1a\x45\n\tDiskEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\'\n\x05value\x18\x02 \x01(\x0b\x32\x18.wandb_internal.DiskInfo:\x02\x38\x01\x1a,\n\nSlurmEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x8d\x01\n\x15PythonPackagesRequest\x12\x44\n\x07package\x18\x01 \x03(\x0b\x32\x33.wandb_internal.PythonPackagesRequest.PythonPackage\x1a.\n\rPythonPackage\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07version\x18\x02 \x01(\t\"\x1c\n\x0cJobInputPath\x12\x0c\n\x04path\x18\x01 \x03(\t\"\xd6\x01\n\x0eJobInputSource\x12\x44\n\nrun_config\x18\x01 \x01(\x0b\x32..wandb_internal.JobInputSource.RunConfigSourceH\x00\x12?\n\x04\x66ile\x18\x02 \x01(\x0b\x32/.wandb_internal.JobInputSource.ConfigFileSourceH\x00\x1a\x11\n\x0fRunConfigSource\x1a \n\x10\x43onfigFileSource\x12\x0c\n\x04path\x18\x01 \x01(\tB\x08\n\x06source\"\xc7\x01\n\x0fJobInputRequest\x12\x34\n\x0cinput_source\x18\x01 \x01(\x0b\x32\x1e.wandb_internal.JobInputSource\x12\x33\n\rinclude_paths\x18\x02 \x03(\x0b\x32\x1c.wandb_internal.JobInputPath\x12\x33\n\rexclude_paths\x18\x03 \x03(\x0b\x32\x1c.wandb_internal.JobInputPath\x12\x14\n\x0cinput_schema\x18\x04 \x01(\t\"t\n\x14ServerFeatureRequest\x12.\n\x07\x66\x65\x61ture\x18\x01 \x01(\x0e\x32\x1d.wandb_internal.ServerFeature\x12,\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1c.wandb_internal._RequestInfo\"K\n\x15ServerFeatureResponse\x12\x32\n\x07\x66\x65\x61ture\x18\x01 \x01(\x0b\x32!.wandb_internal.ServerFeatureItem\"2\n\x11ServerFeatureItem\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07\x65nabled\x18\x02 \x01(\x08*\x80\x04\n\rServerFeature\x12\x13\n\x0fLARGE_FILENAMES\x10\x00\x12\x11\n\rARTIFACT_TAGS\x10\x01\x12\x0e\n\nCLIENT_IDS\x10\x02\x12\x1c\n\x18\x41RTIFACT_REGISTRY_SEARCH\x10\x03\x12\x1b\n\x17STRUCTURED_CONSOLE_LOGS\x10\x04\x12(\n$ARTIFACT_COLLECTION_MEMBERSHIP_FILES\x10\x05\x12\x38\n4ARTIFACT_COLLECTION_MEMBERSHIP_FILE_DOWNLOAD_HANDLER\x10\x06\x12\x34\n0USE_ARTIFACT_WITH_ENTITY_AND_PROJECT_INFORMATION\x10\x07\x12\x1f\n\x1b\x45XPAND_DEFINED_METRIC_GLOBS\x10\x08\x12\x1f\n\x1b\x41UTOMATION_EVENT_RUN_METRIC\x10\t\x12&\n\"AUTOMATION_EVENT_RUN_METRIC_CHANGE\x10\n\x12\x1b\n\x17\x41UTOMATION_ACTION_NO_OP\x10\x0b\x12/\n+INCLUDE_ARTIFACT_TYPES_IN_REGISTRY_CREATION\x10\x0c\x12*\n&PROJECT_ARTIFACT_COLLECTION_MEMBERSHIP\x10\rB\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_internal_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + _globals['DESCRIPTOR']._loaded_options = None + _globals['DESCRIPTOR']._serialized_options = b'Z\031core/pkg/service_go_proto' + _globals['_GETSYSTEMMETRICSRESPONSE_SYSTEMMETRICSENTRY']._loaded_options = None + _globals['_GETSYSTEMMETRICSRESPONSE_SYSTEMMETRICSENTRY']._serialized_options = b'8\001' + _globals['_ENVIRONMENTRECORD_DISKENTRY']._loaded_options = None + _globals['_ENVIRONMENTRECORD_DISKENTRY']._serialized_options = b'8\001' + _globals['_ENVIRONMENTRECORD_SLURMENTRY']._loaded_options = None + _globals['_ENVIRONMENTRECORD_SLURMENTRY']._serialized_options = b'8\001' + _globals['_SERVERFEATURE']._serialized_start=22243 + _globals['_SERVERFEATURE']._serialized_end=22755 + _globals['_RECORD']._serialized_start=180 + _globals['_RECORD']._serialized_end=1411 + _globals['_CONTROL']._serialized_start=1414 + _globals['_CONTROL']._serialized_end=1582 + _globals['_RESULT']._serialized_start=1585 + _globals['_RESULT']._serialized_end=2084 + _globals['_FINALRECORD']._serialized_start=2086 + _globals['_FINALRECORD']._serialized_end=2144 + _globals['_VERSIONINFO']._serialized_start=2146 + _globals['_VERSIONINFO']._serialized_end=2244 + _globals['_HEADERRECORD']._serialized_start=2246 + _globals['_HEADERRECORD']._serialized_end=2356 + _globals['_FOOTERRECORD']._serialized_start=2358 + _globals['_FOOTERRECORD']._serialized_end=2417 + _globals['_BRANCHPOINT']._serialized_start=2419 + _globals['_BRANCHPOINT']._serialized_end=2476 + _globals['_RUNRECORD']._serialized_start=2479 + _globals['_RUNRECORD']._serialized_end=3136 + _globals['_GITREPORECORD']._serialized_start=3138 + _globals['_GITREPORECORD']._serialized_end=3197 + _globals['_RUNUPDATERESULT']._serialized_start=3199 + _globals['_RUNUPDATERESULT']._serialized_end=3298 + _globals['_ERRORINFO']._serialized_start=3301 + _globals['_ERRORINFO']._serialized_end=3473 + _globals['_ERRORINFO_ERRORCODE']._serialized_start=3382 + _globals['_ERRORINFO_ERRORCODE']._serialized_end=3473 + _globals['_RUNEXITRECORD']._serialized_start=3475 + _globals['_RUNEXITRECORD']._serialized_end=3571 + _globals['_RUNEXITRESULT']._serialized_start=3573 + _globals['_RUNEXITRESULT']._serialized_end=3588 + _globals['_RUNPREEMPTINGRECORD']._serialized_start=3590 + _globals['_RUNPREEMPTINGRECORD']._serialized_end=3656 + _globals['_RUNPREEMPTINGRESULT']._serialized_start=3658 + _globals['_RUNPREEMPTINGRESULT']._serialized_end=3679 + _globals['_SETTINGSRECORD']._serialized_start=3681 + _globals['_SETTINGSRECORD']._serialized_end=3786 + _globals['_SETTINGSITEM']._serialized_start=3788 + _globals['_SETTINGSITEM']._serialized_end=3835 + _globals['_HISTORYSTEP']._serialized_start=3837 + _globals['_HISTORYSTEP']._serialized_end=3863 + _globals['_HISTORYRECORD']._serialized_start=3866 + _globals['_HISTORYRECORD']._serialized_end=4012 + _globals['_HISTORYITEM']._serialized_start=4014 + _globals['_HISTORYITEM']._serialized_end=4080 + _globals['_HISTORYRESULT']._serialized_start=4082 + _globals['_HISTORYRESULT']._serialized_end=4097 + _globals['_OUTPUTRECORD']._serialized_start=4100 + _globals['_OUTPUTRECORD']._serialized_end=4320 + _globals['_OUTPUTRECORD_OUTPUTTYPE']._serialized_start=4284 + _globals['_OUTPUTRECORD_OUTPUTTYPE']._serialized_end=4320 + _globals['_OUTPUTRESULT']._serialized_start=4322 + _globals['_OUTPUTRESULT']._serialized_end=4336 + _globals['_OUTPUTRAWRECORD']._serialized_start=4339 + _globals['_OUTPUTRAWRECORD']._serialized_end=4565 + _globals['_OUTPUTRAWRECORD_OUTPUTTYPE']._serialized_start=4284 + _globals['_OUTPUTRAWRECORD_OUTPUTTYPE']._serialized_end=4320 + _globals['_OUTPUTRAWRESULT']._serialized_start=4567 + _globals['_OUTPUTRAWRESULT']._serialized_end=4584 + _globals['_METRICRECORD']._serialized_start=4587 + _globals['_METRICRECORD']._serialized_end=5023 + _globals['_METRICRECORD_METRICGOAL']._serialized_start=4957 + _globals['_METRICRECORD_METRICGOAL']._serialized_end=5023 + _globals['_METRICRESULT']._serialized_start=5025 + _globals['_METRICRESULT']._serialized_end=5039 + _globals['_METRICOPTIONS']._serialized_start=5041 + _globals['_METRICOPTIONS']._serialized_end=5108 + _globals['_METRICCONTROL']._serialized_start=5110 + _globals['_METRICCONTROL']._serialized_end=5144 + _globals['_METRICSUMMARY']._serialized_start=5146 + _globals['_METRICSUMMARY']._serialized_end=5272 + _globals['_CONFIGRECORD']._serialized_start=5275 + _globals['_CONFIGRECORD']._serialized_end=5422 + _globals['_CONFIGITEM']._serialized_start=5424 + _globals['_CONFIGITEM']._serialized_end=5489 + _globals['_CONFIGRESULT']._serialized_start=5491 + _globals['_CONFIGRESULT']._serialized_end=5505 + _globals['_SUMMARYRECORD']._serialized_start=5508 + _globals['_SUMMARYRECORD']._serialized_end=5658 + _globals['_SUMMARYITEM']._serialized_start=5660 + _globals['_SUMMARYITEM']._serialized_end=5726 + _globals['_SUMMARYRESULT']._serialized_start=5728 + _globals['_SUMMARYRESULT']._serialized_end=5743 + _globals['_FILESRECORD']._serialized_start=5745 + _globals['_FILESRECORD']._serialized_end=5845 + _globals['_FILESITEM']._serialized_start=5848 + _globals['_FILESITEM']._serialized_end=6084 + _globals['_FILESITEM_POLICYTYPE']._serialized_start=5979 + _globals['_FILESITEM_POLICYTYPE']._serialized_end=6019 + _globals['_FILESITEM_FILETYPE']._serialized_start=6021 + _globals['_FILESITEM_FILETYPE']._serialized_end=6078 + _globals['_FILESRESULT']._serialized_start=6086 + _globals['_FILESRESULT']._serialized_end=6099 + _globals['_STATSRECORD']._serialized_start=6102 + _globals['_STATSRECORD']._serialized_end=6332 + _globals['_STATSRECORD_STATSTYPE']._serialized_start=6309 + _globals['_STATSRECORD_STATSTYPE']._serialized_end=6332 + _globals['_STATSITEM']._serialized_start=6334 + _globals['_STATSITEM']._serialized_end=6378 + _globals['_ARTIFACTRECORD']._serialized_start=6381 + _globals['_ARTIFACTRECORD']._serialized_end=6868 + _globals['_ARTIFACTMANIFEST']._serialized_start=6871 + _globals['_ARTIFACTMANIFEST']._serialized_end=7087 + _globals['_ARTIFACTMANIFESTENTRY']._serialized_start=7090 + _globals['_ARTIFACTMANIFESTENTRY']._serialized_end=7297 + _globals['_EXTRAITEM']._serialized_start=7299 + _globals['_EXTRAITEM']._serialized_end=7343 + _globals['_STORAGEPOLICYCONFIGITEM']._serialized_start=7345 + _globals['_STORAGEPOLICYCONFIGITEM']._serialized_end=7403 + _globals['_ARTIFACTRESULT']._serialized_start=7405 + _globals['_ARTIFACTRESULT']._serialized_end=7421 + _globals['_LINKARTIFACTRESULT']._serialized_start=7423 + _globals['_LINKARTIFACTRESULT']._serialized_end=7443 + _globals['_LINKARTIFACTREQUEST']._serialized_start=7446 + _globals['_LINKARTIFACTREQUEST']._serialized_end=7686 + _globals['_LINKARTIFACTRESPONSE']._serialized_start=7688 + _globals['_LINKARTIFACTRESPONSE']._serialized_end=7779 + _globals['_TBRECORD']._serialized_start=7781 + _globals['_TBRECORD']._serialized_end=7885 + _globals['_TBRESULT']._serialized_start=7887 + _globals['_TBRESULT']._serialized_end=7897 + _globals['_ALERTRECORD']._serialized_start=7899 + _globals['_ALERTRECORD']._serialized_end=8024 + _globals['_ALERTRESULT']._serialized_start=8026 + _globals['_ALERTRESULT']._serialized_end=8039 + _globals['_REQUEST']._serialized_start=8042 + _globals['_REQUEST']._serialized_end=10269 + _globals['_RESPONSE']._serialized_start=10272 + _globals['_RESPONSE']._serialized_end=12091 + _globals['_DEFERREQUEST']._serialized_start=12094 + _globals['_DEFERREQUEST']._serialized_end=12414 + _globals['_DEFERREQUEST_DEFERSTATE']._serialized_start=12167 + _globals['_DEFERREQUEST_DEFERSTATE']._serialized_end=12414 + _globals['_PAUSEREQUEST']._serialized_start=12416 + _globals['_PAUSEREQUEST']._serialized_end=12476 + _globals['_PAUSERESPONSE']._serialized_start=12478 + _globals['_PAUSERESPONSE']._serialized_end=12493 + _globals['_RESUMEREQUEST']._serialized_start=12495 + _globals['_RESUMEREQUEST']._serialized_end=12556 + _globals['_RESUMERESPONSE']._serialized_start=12558 + _globals['_RESUMERESPONSE']._serialized_end=12574 + _globals['_LOGINREQUEST']._serialized_start=12576 + _globals['_LOGINREQUEST']._serialized_end=12653 + _globals['_LOGINRESPONSE']._serialized_start=12655 + _globals['_LOGINRESPONSE']._serialized_end=12693 + _globals['_GETSUMMARYREQUEST']._serialized_start=12695 + _globals['_GETSUMMARYREQUEST']._serialized_end=12760 + _globals['_GETSUMMARYRESPONSE']._serialized_start=12762 + _globals['_GETSUMMARYRESPONSE']._serialized_end=12825 + _globals['_GETSYSTEMMETRICSREQUEST']._serialized_start=12827 + _globals['_GETSYSTEMMETRICSREQUEST']._serialized_end=12898 + _globals['_SYSTEMMETRICSAMPLE']._serialized_start=12900 + _globals['_SYSTEMMETRICSAMPLE']._serialized_end=12982 + _globals['_SYSTEMMETRICSBUFFER']._serialized_start=12984 + _globals['_SYSTEMMETRICSBUFFER']._serialized_end=13057 + _globals['_GETSYSTEMMETRICSRESPONSE']._serialized_start=13060 + _globals['_GETSYSTEMMETRICSRESPONSE']._serialized_end=13262 + _globals['_GETSYSTEMMETRICSRESPONSE_SYSTEMMETRICSENTRY']._serialized_start=13173 + _globals['_GETSYSTEMMETRICSRESPONSE_SYSTEMMETRICSENTRY']._serialized_end=13262 + _globals['_STATUSREQUEST']._serialized_start=13264 + _globals['_STATUSREQUEST']._serialized_end=13325 + _globals['_STATUSRESPONSE']._serialized_start=13327 + _globals['_STATUSRESPONSE']._serialized_end=13368 + _globals['_STOPSTATUSREQUEST']._serialized_start=13370 + _globals['_STOPSTATUSREQUEST']._serialized_end=13435 + _globals['_STOPSTATUSRESPONSE']._serialized_start=13437 + _globals['_STOPSTATUSRESPONSE']._serialized_end=13482 + _globals['_NETWORKSTATUSREQUEST']._serialized_start=13484 + _globals['_NETWORKSTATUSREQUEST']._serialized_end=13552 + _globals['_NETWORKSTATUSRESPONSE']._serialized_start=13554 + _globals['_NETWORKSTATUSRESPONSE']._serialized_end=13634 + _globals['_HTTPRESPONSE']._serialized_start=13636 + _globals['_HTTPRESPONSE']._serialized_end=13704 + _globals['_INTERNALMESSAGESREQUEST']._serialized_start=13706 + _globals['_INTERNALMESSAGESREQUEST']._serialized_end=13777 + _globals['_INTERNALMESSAGESRESPONSE']._serialized_start=13779 + _globals['_INTERNALMESSAGESRESPONSE']._serialized_end=13857 + _globals['_INTERNALMESSAGES']._serialized_start=13859 + _globals['_INTERNALMESSAGES']._serialized_end=13894 + _globals['_POLLEXITREQUEST']._serialized_start=13896 + _globals['_POLLEXITREQUEST']._serialized_end=13959 + _globals['_POLLEXITRESPONSE']._serialized_start=13962 + _globals['_POLLEXITRESPONSE']._serialized_end=14207 + _globals['_OPERATIONSTATSREQUEST']._serialized_start=14209 + _globals['_OPERATIONSTATSREQUEST']._serialized_end=14278 + _globals['_OPERATIONSTATSRESPONSE']._serialized_start=14280 + _globals['_OPERATIONSTATSRESPONSE']._serialized_end=14361 + _globals['_OPERATIONSTATS']._serialized_start=14363 + _globals['_OPERATIONSTATS']._serialized_end=14452 + _globals['_OPERATION']._serialized_start=14455 + _globals['_OPERATION']._serialized_end=14590 + _globals['_SENDERMARKREQUEST']._serialized_start=14592 + _globals['_SENDERMARKREQUEST']._serialized_end=14611 + _globals['_SYNCFINISHREQUEST']._serialized_start=14613 + _globals['_SYNCFINISHREQUEST']._serialized_end=14632 + _globals['_SYNCRESPONSE']._serialized_start=14634 + _globals['_SYNCRESPONSE']._serialized_end=14703 + _globals['_SENDERREADREQUEST']._serialized_start=14705 + _globals['_SENDERREADREQUEST']._serialized_end=14768 + _globals['_STATUSREPORTREQUEST']._serialized_start=14770 + _globals['_STATUSREPORTREQUEST']._serialized_end=14879 + _globals['_SUMMARYRECORDREQUEST']._serialized_start=14881 + _globals['_SUMMARYRECORDREQUEST']._serialized_end=14951 + _globals['_TELEMETRYRECORDREQUEST']._serialized_start=14953 + _globals['_TELEMETRYRECORDREQUEST']._serialized_end=15029 + _globals['_SERVERINFOREQUEST']._serialized_start=15031 + _globals['_SERVERINFOREQUEST']._serialized_end=15096 + _globals['_SERVERINFORESPONSE']._serialized_start=15098 + _globals['_SERVERINFORESPONSE']._serialized_end=15222 + _globals['_SERVERMESSAGES']._serialized_start=15224 + _globals['_SERVERMESSAGES']._serialized_end=15285 + _globals['_SERVERMESSAGE']._serialized_start=15287 + _globals['_SERVERMESSAGE']._serialized_end=15388 + _globals['_FILECOUNTS']._serialized_start=15390 + _globals['_FILECOUNTS']._serialized_end=15489 + _globals['_FILEPUSHERSTATS']._serialized_start=15491 + _globals['_FILEPUSHERSTATS']._serialized_end=15576 + _globals['_FILESUPLOADED']._serialized_start=15578 + _globals['_FILESUPLOADED']._serialized_end=15608 + _globals['_FILETRANSFERINFOREQUEST']._serialized_start=15611 + _globals['_FILETRANSFERINFOREQUEST']._serialized_end=15855 + _globals['_FILETRANSFERINFOREQUEST_TRANSFERTYPE']._serialized_start=15815 + _globals['_FILETRANSFERINFOREQUEST_TRANSFERTYPE']._serialized_end=15855 + _globals['_LOCALINFO']._serialized_start=15857 + _globals['_LOCALINFO']._serialized_end=15906 + _globals['_SHUTDOWNREQUEST']._serialized_start=15908 + _globals['_SHUTDOWNREQUEST']._serialized_end=15971 + _globals['_SHUTDOWNRESPONSE']._serialized_start=15973 + _globals['_SHUTDOWNRESPONSE']._serialized_end=15991 + _globals['_ATTACHREQUEST']._serialized_start=15993 + _globals['_ATTACHREQUEST']._serialized_end=16073 + _globals['_ATTACHRESPONSE']._serialized_start=16075 + _globals['_ATTACHRESPONSE']._serialized_end=16173 + _globals['_TESTINJECTREQUEST']._serialized_start=16176 + _globals['_TESTINJECTREQUEST']._serialized_end=16517 + _globals['_TESTINJECTRESPONSE']._serialized_start=16519 + _globals['_TESTINJECTRESPONSE']._serialized_end=16539 + _globals['_HISTORYACTION']._serialized_start=16541 + _globals['_HISTORYACTION']._serialized_end=16571 + _globals['_PARTIALHISTORYREQUEST']._serialized_start=16574 + _globals['_PARTIALHISTORYREQUEST']._serialized_end=16776 + _globals['_PARTIALHISTORYRESPONSE']._serialized_start=16778 + _globals['_PARTIALHISTORYRESPONSE']._serialized_end=16802 + _globals['_SAMPLEDHISTORYREQUEST']._serialized_start=16804 + _globals['_SAMPLEDHISTORYREQUEST']._serialized_end=16873 + _globals['_SAMPLEDHISTORYITEM']._serialized_start=16875 + _globals['_SAMPLEDHISTORYITEM']._serialized_end=16970 + _globals['_SAMPLEDHISTORYRESPONSE']._serialized_start=16972 + _globals['_SAMPLEDHISTORYRESPONSE']._serialized_end=17046 + _globals['_RUNSTATUSREQUEST']._serialized_start=17048 + _globals['_RUNSTATUSREQUEST']._serialized_end=17112 + _globals['_RUNSTATUSRESPONSE']._serialized_start=17114 + _globals['_RUNSTATUSRESPONSE']._serialized_end=17234 + _globals['_RUNSTARTREQUEST']._serialized_start=17236 + _globals['_RUNSTARTREQUEST']._serialized_end=17339 + _globals['_RUNSTARTRESPONSE']._serialized_start=17341 + _globals['_RUNSTARTRESPONSE']._serialized_end=17359 + _globals['_RUNFINISHWITHOUTEXITREQUEST']._serialized_start=17361 + _globals['_RUNFINISHWITHOUTEXITREQUEST']._serialized_end=17436 + _globals['_RUNFINISHWITHOUTEXITRESPONSE']._serialized_start=17438 + _globals['_RUNFINISHWITHOUTEXITRESPONSE']._serialized_end=17468 + _globals['_CHECKVERSIONREQUEST']._serialized_start=17470 + _globals['_CHECKVERSIONREQUEST']._serialized_end=17562 + _globals['_CHECKVERSIONRESPONSE']._serialized_start=17564 + _globals['_CHECKVERSIONRESPONSE']._serialized_end=17657 + _globals['_JOBINFOREQUEST']._serialized_start=17659 + _globals['_JOBINFOREQUEST']._serialized_end=17721 + _globals['_JOBINFORESPONSE']._serialized_start=17723 + _globals['_JOBINFORESPONSE']._serialized_end=17777 + _globals['_LOGARTIFACTREQUEST']._serialized_start=17780 + _globals['_LOGARTIFACTREQUEST']._serialized_end=17939 + _globals['_LOGARTIFACTRESPONSE']._serialized_start=17941 + _globals['_LOGARTIFACTRESPONSE']._serialized_end=18006 + _globals['_DOWNLOADARTIFACTREQUEST']._serialized_start=18009 + _globals['_DOWNLOADARTIFACTREQUEST']._serialized_end=18199 + _globals['_DOWNLOADARTIFACTRESPONSE']._serialized_start=18201 + _globals['_DOWNLOADARTIFACTRESPONSE']._serialized_end=18250 + _globals['_KEEPALIVEREQUEST']._serialized_start=18252 + _globals['_KEEPALIVEREQUEST']._serialized_end=18316 + _globals['_KEEPALIVERESPONSE']._serialized_start=18318 + _globals['_KEEPALIVERESPONSE']._serialized_end=18337 + _globals['_ARTIFACTINFO']._serialized_start=18339 + _globals['_ARTIFACTINFO']._serialized_end=18452 + _globals['_GITINFO']._serialized_start=18454 + _globals['_GITINFO']._serialized_end=18495 + _globals['_GITSOURCE']._serialized_start=18498 + _globals['_GITSOURCE']._serialized_end=18633 + _globals['_IMAGESOURCE']._serialized_start=18635 + _globals['_IMAGESOURCE']._serialized_end=18663 + _globals['_SOURCE']._serialized_start=18666 + _globals['_SOURCE']._serialized_end=18806 + _globals['_JOBSOURCE']._serialized_start=18808 + _globals['_JOBSOURCE']._serialized_end=18915 + _globals['_PARTIALJOBARTIFACT']._serialized_start=18917 + _globals['_PARTIALJOBARTIFACT']._serialized_end=19003 + _globals['_USEARTIFACTRECORD']._serialized_start=19006 + _globals['_USEARTIFACTRECORD']._serialized_end=19163 + _globals['_USEARTIFACTRESULT']._serialized_start=19165 + _globals['_USEARTIFACTRESULT']._serialized_end=19184 + _globals['_CANCELREQUEST']._serialized_start=19186 + _globals['_CANCELREQUEST']._serialized_end=19268 + _globals['_CANCELRESPONSE']._serialized_start=19270 + _globals['_CANCELRESPONSE']._serialized_end=19286 + _globals['_DISKINFO']._serialized_start=19288 + _globals['_DISKINFO']._serialized_end=19327 + _globals['_MEMORYINFO']._serialized_start=19329 + _globals['_MEMORYINFO']._serialized_end=19356 + _globals['_CPUINFO']._serialized_start=19358 + _globals['_CPUINFO']._serialized_end=19405 + _globals['_APPLEINFO']._serialized_start=19408 + _globals['_APPLEINFO']._serialized_end=19562 + _globals['_GPUNVIDIAINFO']._serialized_start=19564 + _globals['_GPUNVIDIAINFO']._serialized_end=19671 + _globals['_GPUAMDINFO']._serialized_start=19674 + _globals['_GPUAMDINFO']._serialized_end=19939 + _globals['_TRAINIUMINFO']._serialized_start=19941 + _globals['_TRAINIUMINFO']._serialized_end=20051 + _globals['_TPUINFO']._serialized_start=20053 + _globals['_TPUINFO']._serialized_end=20134 + _globals['_COREWEAVEINFO']._serialized_start=20136 + _globals['_COREWEAVEINFO']._serialized_end=20205 + _globals['_ENVIRONMENTRECORD']._serialized_start=20208 + _globals['_ENVIRONMENTRECORD']._serialized_end=21400 + _globals['_ENVIRONMENTRECORD_DISKENTRY']._serialized_start=21285 + _globals['_ENVIRONMENTRECORD_DISKENTRY']._serialized_end=21354 + _globals['_ENVIRONMENTRECORD_SLURMENTRY']._serialized_start=21356 + _globals['_ENVIRONMENTRECORD_SLURMENTRY']._serialized_end=21400 + _globals['_PYTHONPACKAGESREQUEST']._serialized_start=21403 + _globals['_PYTHONPACKAGESREQUEST']._serialized_end=21544 + _globals['_PYTHONPACKAGESREQUEST_PYTHONPACKAGE']._serialized_start=21498 + _globals['_PYTHONPACKAGESREQUEST_PYTHONPACKAGE']._serialized_end=21544 + _globals['_JOBINPUTPATH']._serialized_start=21546 + _globals['_JOBINPUTPATH']._serialized_end=21574 + _globals['_JOBINPUTSOURCE']._serialized_start=21577 + _globals['_JOBINPUTSOURCE']._serialized_end=21791 + _globals['_JOBINPUTSOURCE_RUNCONFIGSOURCE']._serialized_start=21730 + _globals['_JOBINPUTSOURCE_RUNCONFIGSOURCE']._serialized_end=21747 + _globals['_JOBINPUTSOURCE_CONFIGFILESOURCE']._serialized_start=21749 + _globals['_JOBINPUTSOURCE_CONFIGFILESOURCE']._serialized_end=21781 + _globals['_JOBINPUTREQUEST']._serialized_start=21794 + _globals['_JOBINPUTREQUEST']._serialized_end=21993 + _globals['_SERVERFEATUREREQUEST']._serialized_start=21995 + _globals['_SERVERFEATUREREQUEST']._serialized_end=22111 + _globals['_SERVERFEATURERESPONSE']._serialized_start=22113 + _globals['_SERVERFEATURERESPONSE']._serialized_end=22188 + _globals['_SERVERFEATUREITEM']._serialized_start=22190 + _globals['_SERVERFEATUREITEM']._serialized_end=22240 +# @@protoc_insertion_point(module_scope) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v5/wandb_server_pb2.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v5/wandb_server_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..d046eda055b092313965c9f8b1ef7ef94d8f70a6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v5/wandb_server_pb2.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: wandb/proto/wandb_server.proto +# Protobuf Python Version: 5.26.1 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from wandb.proto import wandb_base_pb2 as wandb_dot_proto_dot_wandb__base__pb2 +from wandb.proto import wandb_internal_pb2 as wandb_dot_proto_dot_wandb__internal__pb2 +from wandb.proto import wandb_settings_pb2 as wandb_dot_proto_dot_wandb__settings__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1ewandb/proto/wandb_server.proto\x12\x0ewandb_internal\x1a\x1cwandb/proto/wandb_base.proto\x1a wandb/proto/wandb_internal.proto\x1a wandb/proto/wandb_settings.proto\"k\n\x19ServerAuthenticateRequest\x12\x0f\n\x07\x61pi_key\x18\x01 \x01(\t\x12\x10\n\x08\x62\x61se_url\x18\x02 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"w\n\x1aServerAuthenticateResponse\x12\x16\n\x0e\x64\x65\x66\x61ult_entity\x18\x01 \x01(\t\x12\x14\n\x0c\x65rror_status\x18\x02 \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"D\n\x15ServerShutdownRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x18\n\x16ServerShutdownResponse\"B\n\x13ServerStatusRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x16\n\x14ServerStatusResponse\"r\n\x17ServerInformInitRequest\x12*\n\x08settings\x18\x01 \x01(\x0b\x32\x18.wandb_internal.Settings\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1a\n\x18ServerInformInitResponse\"s\n\x18ServerInformStartRequest\x12*\n\x08settings\x18\x01 \x01(\x0b\x32\x18.wandb_internal.Settings\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1b\n\x19ServerInformStartResponse\"H\n\x19ServerInformFinishRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1c\n\x1aServerInformFinishResponse\"H\n\x19ServerInformAttachRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"u\n\x1aServerInformAttachResponse\x12*\n\x08settings\x18\x01 \x01(\x0b\x32\x18.wandb_internal.Settings\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"H\n\x19ServerInformDetachRequest\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1c\n\x1aServerInformDetachResponse\"]\n\x1bServerInformTeardownRequest\x12\x11\n\texit_code\x18\x01 \x01(\x05\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x1e\n\x1cServerInformTeardownResponse\"\xfb\x04\n\rServerRequest\x12\x12\n\nrequest_id\x18\n \x01(\t\x12\x30\n\x0erecord_publish\x18\x01 \x01(\x0b\x32\x16.wandb_internal.RecordH\x00\x12\x34\n\x12record_communicate\x18\x02 \x01(\x0b\x32\x16.wandb_internal.RecordH\x00\x12>\n\x0binform_init\x18\x03 \x01(\x0b\x32\'.wandb_internal.ServerInformInitRequestH\x00\x12\x42\n\rinform_finish\x18\x04 \x01(\x0b\x32).wandb_internal.ServerInformFinishRequestH\x00\x12\x42\n\rinform_attach\x18\x05 \x01(\x0b\x32).wandb_internal.ServerInformAttachRequestH\x00\x12\x42\n\rinform_detach\x18\x06 \x01(\x0b\x32).wandb_internal.ServerInformDetachRequestH\x00\x12\x46\n\x0finform_teardown\x18\x07 \x01(\x0b\x32+.wandb_internal.ServerInformTeardownRequestH\x00\x12@\n\x0cinform_start\x18\x08 \x01(\x0b\x32(.wandb_internal.ServerInformStartRequestH\x00\x12\x41\n\x0c\x61uthenticate\x18\t \x01(\x0b\x32).wandb_internal.ServerAuthenticateRequestH\x00\x42\x15\n\x13server_request_type\"\x91\x05\n\x0eServerResponse\x12\x12\n\nrequest_id\x18\n \x01(\t\x12\x34\n\x12result_communicate\x18\x02 \x01(\x0b\x32\x16.wandb_internal.ResultH\x00\x12H\n\x14inform_init_response\x18\x03 \x01(\x0b\x32(.wandb_internal.ServerInformInitResponseH\x00\x12L\n\x16inform_finish_response\x18\x04 \x01(\x0b\x32*.wandb_internal.ServerInformFinishResponseH\x00\x12L\n\x16inform_attach_response\x18\x05 \x01(\x0b\x32*.wandb_internal.ServerInformAttachResponseH\x00\x12L\n\x16inform_detach_response\x18\x06 \x01(\x0b\x32*.wandb_internal.ServerInformDetachResponseH\x00\x12P\n\x18inform_teardown_response\x18\x07 \x01(\x0b\x32,.wandb_internal.ServerInformTeardownResponseH\x00\x12J\n\x15inform_start_response\x18\x08 \x01(\x0b\x32).wandb_internal.ServerInformStartResponseH\x00\x12K\n\x15\x61uthenticate_response\x18\t \x01(\x0b\x32*.wandb_internal.ServerAuthenticateResponseH\x00\x42\x16\n\x14server_response_typeB\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_server_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + _globals['DESCRIPTOR']._loaded_options = None + _globals['DESCRIPTOR']._serialized_options = b'Z\031core/pkg/service_go_proto' + _globals['_SERVERAUTHENTICATEREQUEST']._serialized_start=148 + _globals['_SERVERAUTHENTICATEREQUEST']._serialized_end=255 + _globals['_SERVERAUTHENTICATERESPONSE']._serialized_start=257 + _globals['_SERVERAUTHENTICATERESPONSE']._serialized_end=376 + _globals['_SERVERSHUTDOWNREQUEST']._serialized_start=378 + _globals['_SERVERSHUTDOWNREQUEST']._serialized_end=446 + _globals['_SERVERSHUTDOWNRESPONSE']._serialized_start=448 + _globals['_SERVERSHUTDOWNRESPONSE']._serialized_end=472 + _globals['_SERVERSTATUSREQUEST']._serialized_start=474 + _globals['_SERVERSTATUSREQUEST']._serialized_end=540 + _globals['_SERVERSTATUSRESPONSE']._serialized_start=542 + _globals['_SERVERSTATUSRESPONSE']._serialized_end=564 + _globals['_SERVERINFORMINITREQUEST']._serialized_start=566 + _globals['_SERVERINFORMINITREQUEST']._serialized_end=680 + _globals['_SERVERINFORMINITRESPONSE']._serialized_start=682 + _globals['_SERVERINFORMINITRESPONSE']._serialized_end=708 + _globals['_SERVERINFORMSTARTREQUEST']._serialized_start=710 + _globals['_SERVERINFORMSTARTREQUEST']._serialized_end=825 + _globals['_SERVERINFORMSTARTRESPONSE']._serialized_start=827 + _globals['_SERVERINFORMSTARTRESPONSE']._serialized_end=854 + _globals['_SERVERINFORMFINISHREQUEST']._serialized_start=856 + _globals['_SERVERINFORMFINISHREQUEST']._serialized_end=928 + _globals['_SERVERINFORMFINISHRESPONSE']._serialized_start=930 + _globals['_SERVERINFORMFINISHRESPONSE']._serialized_end=958 + _globals['_SERVERINFORMATTACHREQUEST']._serialized_start=960 + _globals['_SERVERINFORMATTACHREQUEST']._serialized_end=1032 + _globals['_SERVERINFORMATTACHRESPONSE']._serialized_start=1034 + _globals['_SERVERINFORMATTACHRESPONSE']._serialized_end=1151 + _globals['_SERVERINFORMDETACHREQUEST']._serialized_start=1153 + _globals['_SERVERINFORMDETACHREQUEST']._serialized_end=1225 + _globals['_SERVERINFORMDETACHRESPONSE']._serialized_start=1227 + _globals['_SERVERINFORMDETACHRESPONSE']._serialized_end=1255 + _globals['_SERVERINFORMTEARDOWNREQUEST']._serialized_start=1257 + _globals['_SERVERINFORMTEARDOWNREQUEST']._serialized_end=1350 + _globals['_SERVERINFORMTEARDOWNRESPONSE']._serialized_start=1352 + _globals['_SERVERINFORMTEARDOWNRESPONSE']._serialized_end=1382 + _globals['_SERVERREQUEST']._serialized_start=1385 + _globals['_SERVERREQUEST']._serialized_end=2020 + _globals['_SERVERRESPONSE']._serialized_start=2023 + _globals['_SERVERRESPONSE']._serialized_end=2680 +# @@protoc_insertion_point(module_scope) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v6/wandb_telemetry_pb2.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v6/wandb_telemetry_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..0d2fde0ea813b529a1f3f93b338dee878a191126 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/v6/wandb_telemetry_pb2.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: wandb/proto/wandb_telemetry.proto +# Protobuf Python Version: 6.30.0 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 6, + 30, + 0, + '', + 'wandb/proto/wandb_telemetry.proto' +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from wandb.proto import wandb_base_pb2 as wandb_dot_proto_dot_wandb__base__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n!wandb/proto/wandb_telemetry.proto\x12\x0ewandb_internal\x1a\x1cwandb/proto/wandb_base.proto\"\xdb\x03\n\x0fTelemetryRecord\x12-\n\x0cimports_init\x18\x01 \x01(\x0b\x32\x17.wandb_internal.Imports\x12/\n\x0eimports_finish\x18\x02 \x01(\x0b\x32\x17.wandb_internal.Imports\x12(\n\x07\x66\x65\x61ture\x18\x03 \x01(\x0b\x32\x17.wandb_internal.Feature\x12\x16\n\x0epython_version\x18\x04 \x01(\t\x12\x13\n\x0b\x63li_version\x18\x05 \x01(\t\x12\x1b\n\x13huggingface_version\x18\x06 \x01(\t\x12 \n\x03\x65nv\x18\x08 \x01(\x0b\x32\x13.wandb_internal.Env\x12%\n\x05label\x18\t \x01(\x0b\x32\x16.wandb_internal.Labels\x12.\n\ndeprecated\x18\n \x01(\x0b\x32\x1a.wandb_internal.Deprecated\x12&\n\x06issues\x18\x0b \x01(\x0b\x32\x16.wandb_internal.Issues\x12\x14\n\x0c\x63ore_version\x18\x0c \x01(\t\x12\x10\n\x08platform\x18\r \x01(\t\x12+\n\x05_info\x18\xc8\x01 \x01(\x0b\x32\x1b.wandb_internal._RecordInfo\"\x11\n\x0fTelemetryResult\"\x9a\x0e\n\x07Imports\x12\r\n\x05torch\x18\x01 \x01(\x08\x12\r\n\x05keras\x18\x02 \x01(\x08\x12\x12\n\ntensorflow\x18\x03 \x01(\x08\x12\x0e\n\x06\x66\x61stai\x18\x04 \x01(\x08\x12\x0f\n\x07sklearn\x18\x05 \x01(\x08\x12\x0f\n\x07xgboost\x18\x06 \x01(\x08\x12\x10\n\x08\x63\x61tboost\x18\x07 \x01(\x08\x12\x10\n\x08lightgbm\x18\x08 \x01(\x08\x12\x19\n\x11pytorch_lightning\x18\t \x01(\x08\x12\x0e\n\x06ignite\x18\n \x01(\x08\x12\x14\n\x0ctransformers\x18\x0b \x01(\x08\x12\x0b\n\x03jax\x18\x0c \x01(\x08\x12\x10\n\x08metaflow\x18\r \x01(\x08\x12\x10\n\x08\x61llennlp\x18\x0e \x01(\x08\x12\x11\n\tautogluon\x18\x0f \x01(\x08\x12\x11\n\tautokeras\x18\x10 \x01(\x08\x12\x10\n\x08\x63\x61talyst\x18\x12 \x01(\x08\x12\x10\n\x08\x64\x65\x65pchem\x18\x15 \x01(\x08\x12\x0f\n\x07\x64\x65\x65pctr\x18\x16 \x01(\x08\x12\x0f\n\x07pycaret\x18\x1c \x01(\x08\x12\x14\n\x0cpytorchvideo\x18\x1d \x01(\x08\x12\x0b\n\x03ray\x18\x1e \x01(\x08\x12\x1a\n\x12simpletransformers\x18\x1f \x01(\x08\x12\x0e\n\x06skorch\x18 \x01(\x08\x12\r\n\x05spacy\x18! \x01(\x08\x12\r\n\x05\x66lash\x18\" \x01(\x08\x12\x0e\n\x06optuna\x18# \x01(\x08\x12\x0f\n\x07recbole\x18$ \x01(\x08\x12\x0c\n\x04mmcv\x18% \x01(\x08\x12\r\n\x05mmdet\x18& \x01(\x08\x12\x11\n\ttorchdrug\x18\' \x01(\x08\x12\x11\n\ttorchtext\x18( \x01(\x08\x12\x13\n\x0btorchvision\x18) \x01(\x08\x12\r\n\x05\x65legy\x18* \x01(\x08\x12\x12\n\ndetectron2\x18+ \x01(\x08\x12\r\n\x05\x66lair\x18, \x01(\x08\x12\x0c\n\x04\x66lax\x18- \x01(\x08\x12\x0c\n\x04syft\x18. \x01(\x08\x12\x0b\n\x03TTS\x18/ \x01(\x08\x12\r\n\x05monai\x18\x30 \x01(\x08\x12\x17\n\x0fhuggingface_hub\x18\x31 \x01(\x08\x12\r\n\x05hydra\x18\x32 \x01(\x08\x12\x10\n\x08\x64\x61tasets\x18\x33 \x01(\x08\x12\x0e\n\x06sacred\x18\x34 \x01(\x08\x12\x0e\n\x06joblib\x18\x35 \x01(\x08\x12\x0c\n\x04\x64\x61sk\x18\x36 \x01(\x08\x12\x11\n\tpaddleocr\x18\x38 \x01(\x08\x12\r\n\x05ppdet\x18\x39 \x01(\x08\x12\x11\n\tpaddleseg\x18: \x01(\x08\x12\x11\n\tpaddlenlp\x18; \x01(\x08\x12\r\n\x05mmseg\x18< \x01(\x08\x12\r\n\x05mmocr\x18= \x01(\x08\x12\r\n\x05mmcls\x18> \x01(\x08\x12\x0c\n\x04timm\x18? \x01(\x08\x12\x0f\n\x07\x66\x61irseq\x18@ \x01(\x08\x12\x12\n\ndeepchecks\x18\x41 \x01(\x08\x12\x10\n\x08\x63omposer\x18\x42 \x01(\x08\x12\x10\n\x08sparseml\x18\x43 \x01(\x08\x12\x10\n\x08\x61nomalib\x18\x44 \x01(\x08\x12\r\n\x05zenml\x18\x45 \x01(\x08\x12\x12\n\ncolossalai\x18\x46 \x01(\x08\x12\x12\n\naccelerate\x18G \x01(\x08\x12\x0e\n\x06merlin\x18H \x01(\x08\x12\x0f\n\x07nanodet\x18I \x01(\x08\x12#\n\x1bsegmentation_models_pytorch\x18J \x01(\x08\x12\x1d\n\x15sentence_transformers\x18K \x01(\x08\x12\x0b\n\x03\x64gl\x18L \x01(\x08\x12\x17\n\x0ftorch_geometric\x18M \x01(\x08\x12\x0c\n\x04jina\x18N \x01(\x08\x12\x0e\n\x06kornia\x18O \x01(\x08\x12\x16\n\x0e\x61lbumentations\x18P \x01(\x08\x12\x10\n\x08keras_cv\x18Q \x01(\x08\x12\x10\n\x08mmengine\x18R \x01(\x08\x12\x11\n\tdiffusers\x18S \x01(\x08\x12\x0b\n\x03trl\x18T \x01(\x08\x12\x0c\n\x04trlx\x18U \x01(\x08\x12\x11\n\tlangchain\x18V \x01(\x08\x12\x13\n\x0bllama_index\x18W \x01(\x08\x12\x15\n\rstability_sdk\x18X \x01(\x08\x12\x0f\n\x07prefect\x18Y \x01(\x08\x12\x13\n\x0bprefect_ray\x18Z \x01(\x08\x12\x10\n\x08pinecone\x18[ \x01(\x08\x12\x10\n\x08\x63hromadb\x18\\ \x01(\x08\x12\x10\n\x08weaviate\x18] \x01(\x08\x12\x13\n\x0bpromptlayer\x18^ \x01(\x08\x12\x0e\n\x06openai\x18_ \x01(\x08\x12\x0e\n\x06\x63ohere\x18` \x01(\x08\x12\x11\n\tanthropic\x18\x61 \x01(\x08\x12\x0c\n\x04peft\x18\x62 \x01(\x08\x12\x0f\n\x07optimum\x18\x63 \x01(\x08\x12\x10\n\x08\x65valuate\x18\x64 \x01(\x08\x12\x10\n\x08langflow\x18\x65 \x01(\x08\x12\x12\n\nkeras_core\x18\x66 \x01(\x08\x12\x18\n\x10lightning_fabric\x18g \x01(\x08\x12\x1c\n\x14\x63urated_transformers\x18h \x01(\x08\x12\x0e\n\x06orjson\x18i \x01(\x08\x12\x11\n\tlightning\x18j \x01(\x08J\x04\x08\x11\x10\x12J\x04\x08\x13\x10\x14J\x04\x08\x14\x10\x15J\x04\x08\x17\x10\x18J\x04\x08\x18\x10\x19J\x04\x08\x19\x10\x1aJ\x04\x08\x1a\x10\x1bJ\x04\x08\x1b\x10\x1cJ\x04\x08\x37\x10\x38\"\x95\r\n\x07\x46\x65\x61ture\x12\r\n\x05watch\x18\x01 \x01(\x08\x12\x0e\n\x06\x66inish\x18\x02 \x01(\x08\x12\x0c\n\x04save\x18\x03 \x01(\x08\x12\x0f\n\x07offline\x18\x04 \x01(\x08\x12\x0f\n\x07resumed\x18\x05 \x01(\x08\x12\x0c\n\x04grpc\x18\x06 \x01(\x08\x12\x0e\n\x06metric\x18\x07 \x01(\x08\x12\r\n\x05keras\x18\x08 \x01(\x08\x12\x11\n\tsagemaker\x18\t \x01(\x08\x12\x1c\n\x14\x61rtifact_incremental\x18\n \x01(\x08\x12\x10\n\x08metaflow\x18\x0b \x01(\x08\x12\x0f\n\x07prodigy\x18\x0c \x01(\x08\x12\x15\n\rset_init_name\x18\r \x01(\x08\x12\x13\n\x0bset_init_id\x18\x0e \x01(\x08\x12\x15\n\rset_init_tags\x18\x0f \x01(\x08\x12\x17\n\x0fset_init_config\x18\x10 \x01(\x08\x12\x14\n\x0cset_run_name\x18\x11 \x01(\x08\x12\x14\n\x0cset_run_tags\x18\x12 \x01(\x08\x12\x17\n\x0fset_config_item\x18\x13 \x01(\x08\x12\x0e\n\x06launch\x18\x14 \x01(\x08\x12\x1c\n\x14torch_profiler_trace\x18\x15 \x01(\x08\x12\x0b\n\x03sb3\x18\x16 \x01(\x08\x12\x17\n\x0finit_return_run\x18\x18 \x01(\x08\x12\x1f\n\x17lightgbm_wandb_callback\x18\x19 \x01(\x08\x12\x1c\n\x14lightgbm_log_summary\x18\x1a \x01(\x08\x12\x1f\n\x17\x63\x61tboost_wandb_callback\x18\x1b \x01(\x08\x12\x1c\n\x14\x63\x61tboost_log_summary\x18\x1c \x01(\x08\x12\x17\n\x0ftensorboard_log\x18\x1d \x01(\x08\x12\x16\n\x0e\x65stimator_hook\x18\x1e \x01(\x08\x12\x1e\n\x16xgboost_wandb_callback\x18\x1f \x01(\x08\x12\"\n\x1axgboost_old_wandb_callback\x18 \x01(\x08\x12\x0e\n\x06\x61ttach\x18! \x01(\x08\x12\x19\n\x11tensorboard_patch\x18\" \x01(\x08\x12\x18\n\x10tensorboard_sync\x18# \x01(\x08\x12\x15\n\rkfp_wandb_log\x18$ \x01(\x08\x12\x1b\n\x13maybe_run_overwrite\x18% \x01(\x08\x12\x1c\n\x14keras_metrics_logger\x18& \x01(\x08\x12\x1e\n\x16keras_model_checkpoint\x18\' \x01(\x08\x12!\n\x19keras_wandb_eval_callback\x18( \x01(\x08\x12\x1d\n\x15\x66low_control_overflow\x18) \x01(\x08\x12\x0c\n\x04sync\x18* \x01(\x08\x12\x1d\n\x15\x66low_control_disabled\x18+ \x01(\x08\x12\x1b\n\x13\x66low_control_custom\x18, \x01(\x08\x12\x14\n\x0copen_metrics\x18. \x01(\x08\x12\x1a\n\x12ultralytics_yolov8\x18/ \x01(\x08\x12\x17\n\x0fimporter_mlflow\x18\x30 \x01(\x08\x12\x15\n\rsync_tfevents\x18\x31 \x01(\x08\x12\x15\n\rasync_uploads\x18\x32 \x01(\x08\x12\x16\n\x0eopenai_autolog\x18\x33 \x01(\x08\x12\x18\n\x10langchain_tracer\x18\x34 \x01(\x08\x12\x16\n\x0e\x63ohere_autolog\x18\x35 \x01(\x08\x12\x1b\n\x13hf_pipeline_autolog\x18\x36 \x01(\x08\x12\r\n\x05lib_c\x18\x38 \x01(\x08\x12\x0f\n\x07lib_cpp\x18\x39 \x01(\x08\x12\x19\n\x11openai_finetuning\x18: \x01(\x08\x12\x19\n\x11\x64iffusers_autolog\x18; \x01(\x08\x12\x1f\n\x17lightning_fabric_logger\x18< \x01(\x08\x12\x14\n\x0cset_step_log\x18= \x01(\x08\x12\x13\n\x0bset_summary\x18> \x01(\x08\x12\x16\n\x0emetric_summary\x18? \x01(\x08\x12\x13\n\x0bmetric_goal\x18@ \x01(\x08\x12\x15\n\rmetric_hidden\x18\x41 \x01(\x08\x12\x18\n\x10metric_step_sync\x18\x42 \x01(\x08\x12\x13\n\x0bshared_mode\x18\x43 \x01(\x08\x12#\n\x1bserver_side_derived_summary\x18\x44 \x01(\x08\x12\x1b\n\x13user_provided_label\x18\x45 \x01(\x08\x12\x1e\n\x16\x64\x63gm_profiling_enabled\x18\x46 \x01(\x08\x12\x11\n\tfork_mode\x18G \x01(\x08\x12\x13\n\x0brewind_mode\x18H \x01(\x08J\x04\x08\x17\x10\x18J\x04\x08-\x10.J\x04\x08\x37\x10\x38\"\xc9\x01\n\x03\x45nv\x12\x0f\n\x07jupyter\x18\x01 \x01(\x08\x12\x0e\n\x06kaggle\x18\x02 \x01(\x08\x12\x0f\n\x07windows\x18\x03 \x01(\x08\x12\x0e\n\x06m1_gpu\x18\x04 \x01(\x08\x12\x10\n\x08trainium\x18\n \x01(\x08\x12\x0b\n\x03pex\x18\x0b \x01(\x08\x12\r\n\x05\x63olab\x18\x0c \x01(\x08\x12\x0f\n\x07ipython\x18\r \x01(\x08\x12\x12\n\naws_lambda\x18\x0e \x01(\x08\x12\x0f\n\x07\x61md_gpu\x18\x0f \x01(\x08J\x04\x08\x05\x10\x06J\x04\x08\x06\x10\x07J\x04\x08\x07\x10\x08J\x04\x08\x08\x10\tJ\x04\x08\t\x10\n\"H\n\x06Labels\x12\x13\n\x0b\x63ode_string\x18\x01 \x01(\t\x12\x13\n\x0brepo_string\x18\x02 \x01(\t\x12\x14\n\x0c\x63ode_version\x18\x03 \x01(\t\"\xc2\x06\n\nDeprecated\x12!\n\x19keras_callback__data_type\x18\x01 \x01(\x08\x12\r\n\x05plots\x18\x05 \x01(\x08\x12!\n\x19init__config_include_keys\x18\x07 \x01(\x08\x12!\n\x19init__config_exclude_keys\x18\x08 \x01(\x08\x12\"\n\x1akeras_callback__save_model\x18\t \x01(\x08\x12\x18\n\x10langchain_tracer\x18\n \x01(\x08\x12\x1a\n\x12\x61rtifact__get_path\x18\x0b \x01(\x08\x12#\n\x1b\x61rtifactmanifestentry__name\x18\x0c \x01(\x08\x12\x1e\n\x16\x61pi__artifact_versions\x18\r \x01(\x08\x12(\n artifact_collection__change_type\x18\x0e \x01(\x08\x12\x1f\n\x17run__define_metric_copy\x18\x0f \x01(\x08\x12\x14\n\x0crun_disabled\x18\x10 \x01(\x08\x12\x16\n\x0ekeras_callback\x18\x11 \x01(\x08\x12$\n\x1crun__define_metric_best_goal\x18\x12 \x01(\x08\x12\x19\n\x11run__finish_quiet\x18\x13 \x01(\x08\x12\x18\n\x10run__reinit_bool\x18\x14 \x01(\x08\x12\x14\n\x0crun__get_url\x18\x15 \x01(\x08\x12\x19\n\x11run__project_name\x18\x16 \x01(\x08\x12\x1c\n\x14run__get_project_url\x18\x17 \x01(\x08\x12\x1a\n\x12run__get_sweep_url\x18\x18 \x01(\x08\x12 \n\x18run__use_artifact_use_as\x18\x19 \x01(\x08\x12\x18\n\x10\x61rtifact__use_as\x18\x1a \x01(\x08\x12\x1d\n\x15\x61rtifact__init_use_as\x18\x1b \x01(\x08\x12\"\n\x1a\x62\x65ta__workflows__log_model\x18\x1c \x01(\x08\x12\"\n\x1a\x62\x65ta__workflows__use_model\x18\x1d \x01(\x08\x12#\n\x1b\x62\x65ta__workflows__link_model\x18\x1e \x01(\x08J\x04\x08\x02\x10\x03J\x04\x08\x03\x10\x04J\x04\x08\x04\x10\x05J\x04\x08\x06\x10\x07\"|\n\x06Issues\x12%\n\x1dsettings__validation_warnings\x18\x01 \x01(\x08\x12!\n\x19settings__unexpected_args\x18\x02 \x01(\x08\x12(\n settings__preprocessing_warnings\x18\x03 \x01(\x08\x42\x1bZ\x19\x63ore/pkg/service_go_protob\x06proto3') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'wandb.proto.wandb_telemetry_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + _globals['DESCRIPTOR']._loaded_options = None + _globals['DESCRIPTOR']._serialized_options = b'Z\031core/pkg/service_go_proto' + _globals['_TELEMETRYRECORD']._serialized_start=84 + _globals['_TELEMETRYRECORD']._serialized_end=559 + _globals['_TELEMETRYRESULT']._serialized_start=561 + _globals['_TELEMETRYRESULT']._serialized_end=578 + _globals['_IMPORTS']._serialized_start=581 + _globals['_IMPORTS']._serialized_end=2399 + _globals['_FEATURE']._serialized_start=2402 + _globals['_FEATURE']._serialized_end=4087 + _globals['_ENV']._serialized_start=4090 + _globals['_ENV']._serialized_end=4291 + _globals['_LABELS']._serialized_start=4293 + _globals['_LABELS']._serialized_end=4365 + _globals['_DEPRECATED']._serialized_start=4368 + _globals['_DEPRECATED']._serialized_end=5202 + _globals['_ISSUES']._serialized_start=5204 + _globals['_ISSUES']._serialized_end=5328 +# @@protoc_insertion_point(module_scope) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/wandb_generate_deprecated.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/wandb_generate_deprecated.py new file mode 100644 index 0000000000000000000000000000000000000000..23240018155a6bdf1f933439382c4aefc9d479a5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/proto/wandb_generate_deprecated.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python + + +def generate_deprecated_class_definition() -> None: + """Generate a class definition listing the deprecated features. + This is to allow static checks to ensure that proper field names are used. + """ + from wandb.proto.wandb_telemetry_pb2 import Deprecated # type: ignore[import] + + deprecated_features = Deprecated.DESCRIPTOR.fields_by_name.keys() + + code: str = ( + "# Generated by wandb/proto/wandb_internal_codegen.py. DO NOT EDIT!\n\n" + "from typing import Literal\n" + "DEPRECATED_FEATURES = Literal[\n" + + ",\n".join(f' "{feature}"' for feature in deprecated_features) + + ",\n" + + "]\n\n" + "class Deprecated:\n" + + "".join( + [ + f' {feature}: DEPRECATED_FEATURES = "{feature}"\n' + for feature in deprecated_features + ] + ) + ) + with open("wandb_deprecated.py", "w") as f: + f.write(code) + +generate_deprecated_class_definition() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/__pycache__/wandb_config.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/__pycache__/wandb_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41ca56be00eea48f3521f88acc71225b894af623 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/__pycache__/wandb_config.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/__pycache__/wandb_helper.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/__pycache__/wandb_helper.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a24cf3eb0eb8ff4c8af8ea80671cac4b3475d35 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/__pycache__/wandb_helper.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/__pycache__/wandb_login.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/__pycache__/wandb_login.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..306bf46566fb9f5b1139a7e37fd7b5d09b52ac03 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/__pycache__/wandb_login.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/__pycache__/wandb_setup.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/__pycache__/wandb_setup.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b383ff842babae86c519f8855da8ecba739e7337 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/__pycache__/wandb_setup.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/__pycache__/_graphql_fragments.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/__pycache__/_graphql_fragments.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9451377c5672d8a2a99de01f73c6f486084382c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/__pycache__/_graphql_fragments.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/__pycache__/_internal_artifact.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/__pycache__/_internal_artifact.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02f87288029dc09033180d499fcaf934ea12f0a7 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/__pycache__/_internal_artifact.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/__pycache__/artifact_instance_cache.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/__pycache__/artifact_instance_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3be693fff2a46aad351ebfd2dc8e840bf2ad21bd Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/__pycache__/artifact_instance_cache.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/__pycache__/artifact_state.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/__pycache__/artifact_state.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5deafe95509b5b9fa8fce4f306fcb983508388f5 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/__pycache__/artifact_state.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/__pycache__/exceptions.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6231b7f0db8439228a129dda60076b535100c8a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/__pycache__/exceptions.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/__pycache__/storage_policy.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/__pycache__/storage_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b877f7c3dc5b9bb2c8cb0171a426b702d28c0386 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/__pycache__/storage_policy.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/_generated/delete_artifact_collection_tag_assignments.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/_generated/delete_artifact_collection_tag_assignments.py new file mode 100644 index 0000000000000000000000000000000000000000..d89d18340cd4a4cb17d09af8edef4e72c278151c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/_generated/delete_artifact_collection_tag_assignments.py @@ -0,0 +1,25 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/artifacts/ + +from __future__ import annotations + +from typing import Optional + +from pydantic import Field + +from wandb._pydantic import GQLBase + + +class DeleteArtifactCollectionTagAssignments(GQLBase): + delete_artifact_collection_tag_assignments: Optional[ + DeleteArtifactCollectionTagAssignmentsDeleteArtifactCollectionTagAssignments + ] = Field(alias="deleteArtifactCollectionTagAssignments") + + +class DeleteArtifactCollectionTagAssignmentsDeleteArtifactCollectionTagAssignments( + GQLBase +): + success: bool + + +DeleteArtifactCollectionTagAssignments.model_rebuild() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/_generated/link_artifact.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/_generated/link_artifact.py new file mode 100644 index 0000000000000000000000000000000000000000..086f8b5a8a57d44d81770de9471a3eef66ca1ac6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/_generated/link_artifact.py @@ -0,0 +1,21 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/artifacts/ + +from __future__ import annotations + +from typing import Optional + +from pydantic import Field + +from wandb._pydantic import GQLBase + + +class LinkArtifact(GQLBase): + link_artifact: Optional[LinkArtifactLinkArtifact] = Field(alias="linkArtifact") + + +class LinkArtifactLinkArtifact(GQLBase): + version_index: Optional[int] = Field(alias="versionIndex") + + +LinkArtifact.model_rebuild() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/_generated/operations.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/_generated/operations.py new file mode 100644 index 0000000000000000000000000000000000000000..ed6d6061b9fa574d7e654fb2d9ab32d17f0408a6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/_generated/operations.py @@ -0,0 +1,620 @@ +# Generated by ariadne-codegen +# Source: tools/graphql_codegen/artifacts/ + +__all__ = [ + "ADD_ALIASES_GQL", + "ARTIFACT_COLLECTION_MEMBERSHIP_FILES_GQL", + "ARTIFACT_VERSION_FILES_GQL", + "CREATE_ARTIFACT_COLLECTION_TAG_ASSIGNMENTS_GQL", + "DELETE_ALIASES_GQL", + "DELETE_ARTIFACT_COLLECTION_TAG_ASSIGNMENTS_GQL", + "DELETE_ARTIFACT_PORTFOLIO_GQL", + "DELETE_ARTIFACT_SEQUENCE_GQL", + "FETCH_LINKED_ARTIFACTS_GQL", + "LINK_ARTIFACT_GQL", + "MOVE_ARTIFACT_COLLECTION_GQL", + "PROJECT_ARTIFACTS_GQL", + "PROJECT_ARTIFACT_COLLECTIONS_GQL", + "PROJECT_ARTIFACT_COLLECTION_GQL", + "PROJECT_ARTIFACT_TYPES_GQL", + "PROJECT_ARTIFACT_TYPE_GQL", + "RUN_INPUT_ARTIFACTS_GQL", + "RUN_OUTPUT_ARTIFACTS_GQL", + "UPDATE_ARTIFACT_GQL", + "UPDATE_ARTIFACT_PORTFOLIO_GQL", + "UPDATE_ARTIFACT_SEQUENCE_GQL", +] + +DELETE_ARTIFACT_SEQUENCE_GQL = """ +mutation DeleteArtifactSequence($id: ID!) { + deleteArtifactSequence(input: {artifactSequenceID: $id}) { + artifactCollection { + __typename + state + } + } +} +""" + +DELETE_ARTIFACT_PORTFOLIO_GQL = """ +mutation DeleteArtifactPortfolio($id: ID!) { + deleteArtifactPortfolio(input: {artifactPortfolioID: $id}) { + artifactCollection { + __typename + state + } + } +} +""" + +UPDATE_ARTIFACT_SEQUENCE_GQL = """ +mutation UpdateArtifactSequence($id: ID!, $name: String, $description: String) { + updateArtifactSequence( + input: {artifactSequenceID: $id, name: $name, description: $description} + ) { + artifactCollection { + __typename + id + name + description + } + } +} +""" + +UPDATE_ARTIFACT_PORTFOLIO_GQL = """ +mutation UpdateArtifactPortfolio($id: ID!, $name: String, $description: String) { + updateArtifactPortfolio( + input: {artifactPortfolioID: $id, name: $name, description: $description} + ) { + artifactCollection { + __typename + id + name + description + } + } +} +""" + +MOVE_ARTIFACT_COLLECTION_GQL = """ +mutation MoveArtifactCollection($artifactSequenceID: ID!, $destinationArtifactTypeName: String!) { + moveArtifactSequence( + input: {artifactSequenceID: $artifactSequenceID, destinationArtifactTypeName: $destinationArtifactTypeName} + ) { + artifactCollection { + __typename + id + name + description + } + } +} +""" + +CREATE_ARTIFACT_COLLECTION_TAG_ASSIGNMENTS_GQL = """ +mutation CreateArtifactCollectionTagAssignments($entityName: String!, $projectName: String!, $artifactCollectionName: String!, $tags: [TagInput!]!) { + createArtifactCollectionTagAssignments( + input: {entityName: $entityName, projectName: $projectName, artifactCollectionName: $artifactCollectionName, tags: $tags} + ) { + tags { + id + name + tagCategoryName + } + } +} +""" + +DELETE_ARTIFACT_COLLECTION_TAG_ASSIGNMENTS_GQL = """ +mutation DeleteArtifactCollectionTagAssignments($entityName: String!, $projectName: String!, $artifactCollectionName: String!, $tags: [TagInput!]!) { + deleteArtifactCollectionTagAssignments( + input: {entityName: $entityName, projectName: $projectName, artifactCollectionName: $artifactCollectionName, tags: $tags} + ) { + success + } +} +""" + +PROJECT_ARTIFACT_COLLECTIONS_GQL = """ +query ProjectArtifactCollections($entityName: String!, $projectName: String!, $artifactTypeName: String!, $cursor: String) { + project(name: $projectName, entityName: $entityName) { + artifactType(name: $artifactTypeName) { + artifactCollections: artifactCollections(after: $cursor) { + ...ArtifactCollectionsFragment + } + } + } +} + +fragment ArtifactCollectionsFragment on ArtifactCollectionConnection { + pageInfo { + endCursor + hasNextPage + } + totalCount + edges { + node { + __typename + id + name + description + createdAt + } + cursor + } +} +""" + +PROJECT_ARTIFACT_COLLECTION_GQL = """ +query ProjectArtifactCollection($entityName: String!, $projectName: String!, $artifactTypeName: String!, $artifactCollectionName: String!, $cursor: String, $perPage: Int = 1000) { + project(name: $projectName, entityName: $entityName) { + artifactType(name: $artifactTypeName) { + artifactCollection: artifactCollection(name: $artifactCollectionName) { + __typename + id + name + description + createdAt + tags { + edges { + node { + id + name + } + } + } + aliases(after: $cursor, first: $perPage) { + edges { + node { + alias + } + cursor + } + pageInfo { + endCursor + hasNextPage + } + } + } + artifactSequence(name: $artifactCollectionName) { + __typename + } + } + } +} +""" + +ARTIFACT_VERSION_FILES_GQL = """ +query ArtifactVersionFiles($entityName: String!, $projectName: String!, $artifactTypeName: String!, $artifactName: String!, $fileNames: [String!], $fileCursor: String, $fileLimit: Int = 50) { + project(name: $projectName, entityName: $entityName) { + artifactType(name: $artifactTypeName) { + artifact(name: $artifactName) { + files(names: $fileNames, after: $fileCursor, first: $fileLimit) { + ...FilesFragment + } + } + } + } +} + +fragment FilesFragment on FileConnection { + edges { + node { + id + name: displayName + url + sizeBytes + storagePath @include(if: true) + mimetype + updatedAt + digest + md5 + directUrl + } + cursor + } + pageInfo { + endCursor + hasNextPage + } +} +""" + +ARTIFACT_COLLECTION_MEMBERSHIP_FILES_GQL = """ +query ArtifactCollectionMembershipFiles($entityName: String!, $projectName: String!, $artifactName: String!, $artifactVersionIndex: String!, $fileNames: [String!], $fileCursor: String, $fileLimit: Int = 50) { + project(name: $projectName, entityName: $entityName) { + artifactCollection(name: $artifactName) { + __typename + artifactMembership(aliasName: $artifactVersionIndex) { + files(names: $fileNames, after: $fileCursor, first: $fileLimit) { + ...FilesFragment + } + } + } + } +} + +fragment FilesFragment on FileConnection { + edges { + node { + id + name: displayName + url + sizeBytes + storagePath @include(if: true) + mimetype + updatedAt + digest + md5 + directUrl + } + cursor + } + pageInfo { + endCursor + hasNextPage + } +} +""" + +PROJECT_ARTIFACT_TYPES_GQL = """ +query ProjectArtifactTypes($entityName: String!, $projectName: String!, $cursor: String) { + project(name: $projectName, entityName: $entityName) { + artifactTypes(after: $cursor) { + ...ArtifactTypesFragment + } + } +} + +fragment ArtifactTypeFragment on ArtifactType { + __typename + id + name + description + createdAt +} + +fragment ArtifactTypesFragment on ArtifactTypeConnection { + edges { + node { + ...ArtifactTypeFragment + } + cursor + } + pageInfo { + endCursor + hasNextPage + } +} +""" + +PROJECT_ARTIFACT_TYPE_GQL = """ +query ProjectArtifactType($entityName: String!, $projectName: String!, $artifactTypeName: String!) { + project(name: $projectName, entityName: $entityName) { + artifactType(name: $artifactTypeName) { + ...ArtifactTypeFragment + } + } +} + +fragment ArtifactTypeFragment on ArtifactType { + __typename + id + name + description + createdAt +} +""" + +PROJECT_ARTIFACTS_GQL = """ +query ProjectArtifacts($project: String!, $entity: String!, $type: String!, $collection: String!, $cursor: String, $perPage: Int = 50, $order: String, $filters: JSONString) { + project(name: $project, entityName: $entity) { + artifactType(name: $type) { + artifactCollection: artifactCollection(name: $collection) { + __typename + name + artifacts(filters: $filters, after: $cursor, first: $perPage, order: $order) { + ...ArtifactsFragment + } + } + } + } +} + +fragment ArtifactFragment on Artifact { + id + artifactSequence { + project { + entityName + name + } + name + } + versionIndex + artifactType { + name + } + description + metadata + ttlDurationSeconds @include(if: true) + ttlIsInherited @include(if: true) + aliases @include(if: true) { + artifactCollection { + __typename + project { + entityName + name + } + name + } + alias + } + tags @include(if: true) { + name + } + historyStep @include(if: true) + state + currentManifest { + file { + directUrl + } + } + commitHash + fileCount + createdAt + updatedAt +} + +fragment ArtifactsFragment on VersionedArtifactConnection { + totalCount + edges { + node { + ...ArtifactFragment + } + version + cursor + } + pageInfo { + endCursor + hasNextPage + } +} +""" + +RUN_OUTPUT_ARTIFACTS_GQL = """ +query RunOutputArtifacts($entity: String!, $project: String!, $runName: String!, $cursor: String, $perPage: Int) { + project(name: $project, entityName: $entity) { + run(name: $runName) { + outputArtifacts(after: $cursor, first: $perPage) { + totalCount + edges { + node { + ...ArtifactFragment + } + cursor + } + pageInfo { + endCursor + hasNextPage + } + } + } + } +} + +fragment ArtifactFragment on Artifact { + id + artifactSequence { + project { + entityName + name + } + name + } + versionIndex + artifactType { + name + } + description + metadata + ttlDurationSeconds @include(if: true) + ttlIsInherited @include(if: true) + aliases @include(if: true) { + artifactCollection { + __typename + project { + entityName + name + } + name + } + alias + } + tags @include(if: true) { + name + } + historyStep @include(if: true) + state + currentManifest { + file { + directUrl + } + } + commitHash + fileCount + createdAt + updatedAt +} +""" + +RUN_INPUT_ARTIFACTS_GQL = """ +query RunInputArtifacts($entity: String!, $project: String!, $runName: String!, $cursor: String, $perPage: Int) { + project(name: $project, entityName: $entity) { + run(name: $runName) { + inputArtifacts(after: $cursor, first: $perPage) { + totalCount + edges { + node { + ...ArtifactFragment + } + cursor + } + pageInfo { + endCursor + hasNextPage + } + } + } + } +} + +fragment ArtifactFragment on Artifact { + id + artifactSequence { + project { + entityName + name + } + name + } + versionIndex + artifactType { + name + } + description + metadata + ttlDurationSeconds @include(if: true) + ttlIsInherited @include(if: true) + aliases @include(if: true) { + artifactCollection { + __typename + project { + entityName + name + } + name + } + alias + } + tags @include(if: true) { + name + } + historyStep @include(if: true) + state + currentManifest { + file { + directUrl + } + } + commitHash + fileCount + createdAt + updatedAt +} +""" + +FETCH_LINKED_ARTIFACTS_GQL = """ +query FetchLinkedArtifacts($artifactID: ID!) { + artifact(id: $artifactID) { + artifactMemberships { + edges { + node { + aliases { + alias + } + versionIndex + artifactCollection { + project { + entityName + name + } + name + __typename + } + } + } + } + } +} +""" + +ADD_ALIASES_GQL = """ +mutation AddAliases($artifactID: ID!, $aliases: [ArtifactCollectionAliasInput!]!) { + addAliases(input: {artifactID: $artifactID, aliases: $aliases}) { + success + } +} +""" + +DELETE_ALIASES_GQL = """ +mutation DeleteAliases($artifactID: ID!, $aliases: [ArtifactCollectionAliasInput!]!) { + deleteAliases(input: {artifactID: $artifactID, aliases: $aliases}) { + success + } +} +""" + +UPDATE_ARTIFACT_GQL = """ +mutation UpdateArtifact($artifactID: ID!, $description: String, $metadata: JSONString, $ttlDurationSeconds: Int64, $tagsToAdd: [TagInput!], $tagsToDelete: [TagInput!], $aliases: [ArtifactAliasInput!]) { + updateArtifact( + input: {artifactID: $artifactID, description: $description, metadata: $metadata, ttlDurationSeconds: $ttlDurationSeconds, tagsToAdd: $tagsToAdd, tagsToDelete: $tagsToDelete, aliases: $aliases} + ) { + artifact { + ...ArtifactFragment + } + } +} + +fragment ArtifactFragment on Artifact { + id + artifactSequence { + project { + entityName + name + } + name + } + versionIndex + artifactType { + name + } + description + metadata + ttlDurationSeconds @include(if: true) + ttlIsInherited @include(if: true) + aliases @include(if: true) { + artifactCollection { + __typename + project { + entityName + name + } + name + } + alias + } + tags @include(if: true) { + name + } + historyStep @include(if: true) + state + currentManifest { + file { + directUrl + } + } + commitHash + fileCount + createdAt + updatedAt +} +""" + +LINK_ARTIFACT_GQL = """ +mutation LinkArtifact($input: LinkArtifactInput!) { + linkArtifact(input: $input) { + versionIndex + } +} +""" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/_internal_artifact.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/_internal_artifact.py new file mode 100644 index 0000000000000000000000000000000000000000..280df6ff0d095bc39924e3f0fe6cd108678647a4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/_internal_artifact.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +import re +from base64 import urlsafe_b64encode +from typing import Any, Final +from zlib import crc32 + +from wandb.sdk.artifacts.artifact import Artifact + +PLACEHOLDER: Final[str] = "PLACEHOLDER" + + +def sanitize_artifact_name(name: str) -> str: + """Sanitize the string to satisfy constraints on artifact names.""" + # If the name is already sanitized, don't change it. + if (sanitized := re.sub(r"[^a-zA-Z0-9_\-.]+", "", name)) == name: + return name + + # Append a short alphanumeric suffix to maintain uniqueness. + # Yes, CRC is meant for checksums and not as a general hash function, but + # a 32-bit CRC hash, encoded as (url-safe) base64, is fairly short while + # providing 4B+ possible values, which should be good enough for the corner + # case names this function is meant to address. + # + # As implemented, the final suffix should be 6 characters. + crc: int = crc32(name.encode("utf-8")) & 0xFFFFFFFF # Ensure it's unsigned + crc_bytes = crc.to_bytes(4, byteorder="big") + suffix = urlsafe_b64encode(crc_bytes).rstrip(b"=").decode("ascii") + + return f"{sanitized}-{suffix}" + + +class InternalArtifact(Artifact): + """InternalArtifact is used to create artifacts that are intended for internal use. + + This includes artifacts of type: `job`, `code`(with `source-` prefix in the collection name), + `run_table` (with `run-` prefix in the collection name), and artifacts that start with `wandb-`. + Users should not use this class directly. + """ + + def __init__( + self, + name: str, + type: str, + description: str | None = None, + metadata: dict[str, Any] | None = None, + incremental: bool = False, + use_as: str | None = None, + ) -> None: + sanitized_name = sanitize_artifact_name(name) + super().__init__( + sanitized_name, PLACEHOLDER, description, metadata, incremental, use_as + ) + self._type = type diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/artifact.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/artifact.py new file mode 100644 index 0000000000000000000000000000000000000000..b93144e1c1af6d394a15ee508c3d5a54e984525e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/artifact.py @@ -0,0 +1,2839 @@ +"""Artifact class.""" + +from __future__ import annotations + +import atexit +import concurrent.futures +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 copy import copy +from dataclasses import dataclass +from datetime import datetime, timedelta +from functools import partial +from itertools import filterfalse +from pathlib import PurePosixPath +from typing import IO, TYPE_CHECKING, Any, Iterator, Literal, Sequence, Type, final +from urllib.parse import quote, urljoin, urlparse + +import requests + +import wandb +from wandb import data_types, env +from wandb._iterutils import one +from wandb.apis.normalize import normalize_exceptions +from wandb.apis.public import ArtifactCollection, ArtifactFiles, Run +from wandb.apis.public.utils import gql_compat +from wandb.data_types import WBValue +from wandb.errors import CommError +from wandb.errors.errors import UnsupportedError +from wandb.errors.term import termerror, termlog, termwarn +from wandb.proto import wandb_internal_pb2 as pb +from wandb.proto.wandb_deprecated import Deprecated +from wandb.sdk import wandb_setup +from wandb.sdk.data_types._dtypes import Type as WBType +from wandb.sdk.data_types._dtypes import TypeRegistry +from wandb.sdk.internal.internal_api import Api as InternalApi +from wandb.sdk.internal.thread_local_settings import _thread_local_api_settings +from wandb.sdk.lib import filesystem, retry, runid, telemetry +from wandb.sdk.lib.deprecate import deprecate +from wandb.sdk.lib.hashutil import B64MD5, b64_to_hex_id, md5_file_b64 +from wandb.sdk.lib.paths import FilePathStr, LogicalPath, StrPath, URIStr +from wandb.sdk.lib.runid import generate_id +from wandb.sdk.mailbox import MailboxHandle +from wandb.util import ( + alias_is_version_index, + artifact_to_json, + fsync_open, + json_dumps_safer, + uri_from_path, + vendor_setup, +) + +from ._generated import ( + ADD_ALIASES_GQL, + DELETE_ALIASES_GQL, + FETCH_LINKED_ARTIFACTS_GQL, + LINK_ARTIFACT_GQL, + UPDATE_ARTIFACT_GQL, + ArtifactAliasInput, + ArtifactCollectionAliasInput, + FetchLinkedArtifacts, + LinkArtifact, + LinkArtifactInput, + TagInput, + UpdateArtifact, +) +from ._graphql_fragments import _gql_artifact_fragment, omit_artifact_fields +from ._validators import ( + LINKED_ARTIFACT_COLLECTION_TYPE, + ArtifactPath, + _LinkArtifactFields, + ensure_logged, + ensure_not_finalized, + is_artifact_registry_project, + remove_registry_prefix, + validate_aliases, + validate_artifact_name, + validate_artifact_type, + validate_metadata, + validate_tags, + validate_ttl_duration_seconds, +) +from .artifact_download_logger import ArtifactDownloadLogger +from .artifact_instance_cache import artifact_instance_cache +from .artifact_manifest import ArtifactManifest +from .artifact_manifest_entry import ArtifactManifestEntry +from .artifact_manifests.artifact_manifest_v1 import ArtifactManifestV1 +from .artifact_state import ArtifactState +from .artifact_ttl import ArtifactTTL +from .exceptions import ( + ArtifactNotLoggedError, + TooFewItemsError, + TooManyItemsError, + WaitTimeoutError, +) +from .staging import get_staging_dir +from .storage_handlers.gcs_handler import _GCSIsADirectoryError +from .storage_layout import StorageLayout +from .storage_policies import WANDB_STORAGE_POLICY +from .storage_policy import StoragePolicy + +reset_path = vendor_setup() + +from wandb_gql import gql # noqa: E402 + +reset_path() + +if TYPE_CHECKING: + from wandb.apis.public import RetryingClient + +logger = logging.getLogger(__name__) + + +@final +@dataclass +class _DeferredArtifactManifest: + """A lightweight wrapper around the manifest URL, used to indicate deferred loading of the actual manifest.""" + + url: str + + +class Artifact: + """Flexible and lightweight building block for dataset and model versioning. + + Construct an empty W&B Artifact. Populate an artifacts contents with methods that + begin with `add`. Once the artifact has all the desired files, you can call + `run.log_artifact()` to log it. + + Args: + name (str): A human-readable name for the artifact. Use the name to identify + a specific artifact in the W&B App UI or programmatically. You can + interactively reference an artifact with the `use_artifact` Public API. + A name can contain letters, numbers, underscores, hyphens, and dots. + The name must be unique across a project. + type (str): The artifact's type. Use the type of an artifact to both organize + and differentiate artifacts. You can use any string that contains letters, + numbers, underscores, hyphens, and dots. Common types include `dataset` or `model`. + Include `model` within your type string if you want to link the artifact + to the W&B Model Registry. Note that some types reserved for internal use + and cannot be set by users. Such types include `job` and types that start with `wandb-`. + description (str | None) = None: A description of the artifact. For Model or Dataset Artifacts, + add documentation for your standardized team model or dataset card. View + an artifact's description programmatically with the `Artifact.description` + attribute or programmatically with the W&B App UI. W&B renders the + description as markdown in the W&B App. + metadata (dict[str, Any] | None) = None: Additional information about an artifact. Specify metadata as a + dictionary of key-value pairs. You can specify no more than 100 total keys. + incremental: Use `Artifact.new_draft()` method instead to modify an + existing artifact. + use_as: Deprecated. + is_link: Boolean indication of if the artifact is a linked artifact(`True`) or source artifact(`False`). + + Returns: + An `Artifact` object. + """ + + _TMP_DIR = tempfile.TemporaryDirectory("wandb-artifacts") + atexit.register(_TMP_DIR.cleanup) + + def __init__( + self, + name: str, + type: str, + description: str | None = None, + metadata: dict[str, Any] | None = None, + incremental: bool = False, + use_as: str | None = None, + ) -> None: + if not re.match(r"^[a-zA-Z0-9_\-.]+$", name): + raise ValueError( + f"Artifact name may only contain alphanumeric characters, dashes, " + f"underscores, and dots. Invalid name: {name}" + ) + + from wandb.sdk.artifacts._internal_artifact import InternalArtifact + + if incremental and not isinstance(self, InternalArtifact): + termwarn("Using experimental arg `incremental`") + + # Internal. + self._client: RetryingClient | None = None + + storage_policy_cls = StoragePolicy.lookup_by_name(WANDB_STORAGE_POLICY) + layout = StorageLayout.V1 if env.get_use_v1_artifacts() else StorageLayout.V2 + policy_config = {"storageLayout": layout} + self._storage_policy = storage_policy_cls.from_config(config=policy_config) + + self._tmp_dir: tempfile.TemporaryDirectory | None = None + self._added_objs: dict[int, tuple[WBValue, ArtifactManifestEntry]] = {} + self._added_local_paths: dict[str, ArtifactManifestEntry] = {} + self._save_handle: MailboxHandle[pb.Result] | None = None + self._download_roots: set[str] = set() + # Set by new_draft(), otherwise the latest artifact will be used as the base. + self._base_id: str | None = None + # Properties. + self._id: str | None = None + self._client_id: str = runid.generate_id(128) + self._sequence_client_id: str = runid.generate_id(128) + self._entity: str | None = None + self._project: str | None = None + self._name: str = validate_artifact_name(name) # includes version after saving + self._version: str | None = None + self._source_entity: str | None = None + self._source_project: str | None = None + self._source_name: str = name # includes version after saving + self._source_version: str | None = None + self._source_artifact: Artifact | None = None + self._is_link: bool = False + self._type: str = validate_artifact_type(type, name) + self._description: str | None = description + self._metadata: dict[str, Any] = validate_metadata(metadata) + self._ttl_duration_seconds: int | None = None + self._ttl_is_inherited: bool = True + self._ttl_changed: bool = False + self._aliases: list[str] = [] + self._saved_aliases: list[str] = [] + self._tags: list[str] = [] + self._saved_tags: list[str] = [] + self._distributed_id: str | None = None + self._incremental: bool = incremental + if use_as is not None: + deprecate( + field_name=Deprecated.artifact__init_use_as, + warning_message=( + "`use_as` argument is deprecated and does not affect the behaviour of `wandb.Artifact()`" + ), + ) + self._use_as: str | None = None + self._state: ArtifactState = ArtifactState.PENDING + self._manifest: ArtifactManifest | _DeferredArtifactManifest | None = ( + ArtifactManifestV1(self._storage_policy) + ) + self._commit_hash: str | None = None + self._file_count: int | None = None + self._created_at: str | None = None + self._updated_at: str | None = None + self._final: bool = False + self._history_step: int | None = None + self._linked_artifacts: list[Artifact] = [] + + # Cache. + artifact_instance_cache[self._client_id] = self + + def __repr__(self) -> str: + return f"" + + @classmethod + def _from_id(cls, artifact_id: str, client: RetryingClient) -> Artifact | None: + if (artifact := artifact_instance_cache.get(artifact_id)) is not None: + return artifact + + query = gql( + """ + query ArtifactByID($id: ID!) { + artifact(id: $id) { + ...ArtifactFragment + } + } + """ + + _gql_artifact_fragment() + ) + response = client.execute( + query, + variable_values={"id": artifact_id}, + ) + attrs = response.get("artifact") + if attrs is None: + return None + + src_collection = attrs["artifactSequence"] + src_project = src_collection["project"] + + entity_name = src_project["entityName"] if src_project else "" + project_name = src_project["name"] if src_project else "" + + name = "{}:v{}".format(src_collection["name"], attrs["versionIndex"]) + return cls._from_attrs(entity_name, project_name, name, attrs, client) + + @classmethod + def _membership_from_name( + cls, + *, + entity: str, + project: str, + name: str, + client: RetryingClient, + ) -> Artifact: + if not InternalApi()._server_supports( + pb.ServerFeature.PROJECT_ARTIFACT_COLLECTION_MEMBERSHIP + ): + raise UnsupportedError( + "querying for the artifact collection membership is not supported " + "by this version of wandb server. Consider updating to the latest version." + ) + + query = gql( + f""" + query ArtifactByName($entityName: String!, $projectName: String!, $name: String!) {{ + project(name: $projectName, entityName: $entityName) {{ + artifactCollectionMembership(name: $name) {{ + id + artifactCollection {{ + id + name + project {{ + id + entityName + name + }} + }} + artifact {{ + ...ArtifactFragment + }} + }} + }} + }} + {_gql_artifact_fragment()} + """ + ) + + query_variable_values: dict[str, Any] = { + "entityName": entity, + "projectName": project, + "name": name, + } + response = client.execute( + query, + variable_values=query_variable_values, + ) + if not (project_attrs := response.get("project")): + raise ValueError(f"project {project!r} not found under entity {entity!r}") + if not (acm_attrs := project_attrs.get("artifactCollectionMembership")): + entity_project = f"{entity}/{project}" + raise ValueError( + f"artifact membership {name!r} not found in {entity_project!r}" + ) + if not (ac_attrs := acm_attrs.get("artifactCollection")): + raise ValueError("artifact collection not found") + if not ( + (ac_name := ac_attrs.get("name")) + and (ac_project_attrs := ac_attrs.get("project")) + ): + raise ValueError("artifact collection project not found") + ac_project = ac_project_attrs.get("name") + ac_entity = ac_project_attrs.get("entityName") + if is_artifact_registry_project(ac_project) and project == "model-registry": + wandb.termwarn( + "This model registry has been migrated and will be discontinued. " + f"Your request was redirected to the corresponding artifact `{ac_name}` in the new registry. " + f"Please update your paths to point to the migrated registry directly, `{ac_project}/{ac_name}`." + ) + entity = ac_entity + project = ac_project + if not (attrs := acm_attrs.get("artifact")): + entity_project = f"{entity}/{project}" + raise ValueError(f"artifact {name!r} not found in {entity_project!r}") + + return cls._from_attrs(entity, project, name, attrs, client) + + @classmethod + def _from_name( + cls, + *, + entity: str, + project: str, + name: str, + client: RetryingClient, + enable_tracking: bool = False, + ) -> Artifact: + if InternalApi()._server_supports( + pb.ServerFeature.PROJECT_ARTIFACT_COLLECTION_MEMBERSHIP + ): + return cls._membership_from_name( + entity=entity, + project=project, + name=name, + client=client, + ) + + query_variable_values: dict[str, Any] = { + "entityName": entity, + "projectName": project, + "name": name, + } + query_vars = ["$entityName: String!", "$projectName: String!", "$name: String!"] + query_args = ["name: $name"] + + server_supports_enabling_artifact_usage_tracking = ( + InternalApi().server_project_type_introspection() + ) + if server_supports_enabling_artifact_usage_tracking: + query_vars.append("$enableTracking: Boolean") + query_args.append("enableTracking: $enableTracking") + query_variable_values["enableTracking"] = enable_tracking + + vars_str = ", ".join(query_vars) + args_str = ", ".join(query_args) + + query = gql( + f""" + query ArtifactByName({vars_str}) {{ + project(name: $projectName, entityName: $entityName) {{ + artifact({args_str}) {{ + ...ArtifactFragment + }} + }} + }} + {_gql_artifact_fragment()} + """ + ) + response = client.execute( + query, + variable_values=query_variable_values, + ) + project_attrs = response.get("project") + if not project_attrs: + raise ValueError(f"project '{project}' not found under entity '{entity}'") + attrs = project_attrs.get("artifact") + if not attrs: + raise ValueError(f"artifact '{name}' not found in '{entity}/{project}'") + + return cls._from_attrs(entity, project, name, attrs, client) + + @classmethod + def _from_attrs( + cls, + entity: str, + project: str, + name: str, + attrs: dict[str, Any], + client: RetryingClient, + aliases: list[str] | None = None, + ) -> Artifact: + # Placeholder is required to skip validation. + artifact = cls("placeholder", type="placeholder") + artifact._client = client + artifact._entity = entity + artifact._project = project + artifact._name = name + artifact._assign_attrs(attrs, aliases) + + artifact.finalize() + + # Cache. + assert artifact.id is not None + artifact_instance_cache[artifact.id] = artifact + return artifact + + # TODO: Eventually factor out is_link. Have to currently use it since some forms of fetching the artifact + # doesn't make it clear if the artifact is a link or not and have to manually set it. + def _assign_attrs( + self, + attrs: dict[str, Any], + aliases: list[str] | None = None, + is_link: bool | None = None, + ) -> None: + """Update this Artifact's attributes using the server response.""" + self._id = attrs["id"] + + src_version = f"v{attrs['versionIndex']}" + src_collection = attrs["artifactSequence"] + src_project = src_collection["project"] + + self._source_entity = src_project["entityName"] if src_project else "" + self._source_project = src_project["name"] if src_project else "" + self._source_name = f"{src_collection['name']}:{src_version}" + self._source_version = src_version + + if self._entity is None: + self._entity = self._source_entity + if self._project is None: + self._project = self._source_project + + if self._name is None: + self._name = 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 != self._source_name + ) + else: + self._is_link = is_link + + self._type = attrs["artifactType"]["name"] + self._description = attrs["description"] + + entity = self._entity + project = self._project + collection, *_ = self._name.split(":") + + processed_aliases = [] + # The future of aliases is to move all alias fetches to the membership level + # so we don't have to do the collection fetches below + if aliases: + processed_aliases = aliases + else: + processed_aliases = [ + obj["alias"] + for obj in attrs["aliases"] + if obj["artifactCollection"] + and obj["artifactCollection"]["project"] + and obj["artifactCollection"]["project"]["entityName"] == entity + and obj["artifactCollection"]["project"]["name"] == project + and obj["artifactCollection"]["name"] == collection + ] + + version_aliases = list(filter(alias_is_version_index, processed_aliases)) + other_aliases = list(filterfalse(alias_is_version_index, processed_aliases)) + + try: + version = one( + version_aliases, too_short=TooFewItemsError, too_long=TooManyItemsError + ) + except TooFewItemsError: + version = src_version # default to the source version + except TooManyItemsError: + msg = f"Expected at most one version alias, got {len(version_aliases)}: {version_aliases!r}" + raise ValueError(msg) from None + + self._version = version + + if ":" not in self._name: + self._name = f"{self._name}:{version}" + + self._aliases = other_aliases + self._saved_aliases = copy(other_aliases) + + tags = [obj["name"] for obj in (attrs.get("tags") or [])] + self._tags = tags + self._saved_tags = copy(tags) + + metadata_str = attrs["metadata"] + self._metadata = validate_metadata( + json.loads(metadata_str) if metadata_str else {} + ) + + self._ttl_duration_seconds = validate_ttl_duration_seconds( + attrs.get("ttlDurationSeconds") + ) + self._ttl_is_inherited = ( + True if (attrs.get("ttlIsInherited") is None) else attrs["ttlIsInherited"] + ) + + self._state = ArtifactState(attrs["state"]) + + try: + manifest_url = attrs["currentManifest"]["file"]["directUrl"] + except (LookupError, TypeError): + self._manifest = None + else: + self._manifest = _DeferredArtifactManifest(manifest_url) + + self._commit_hash = attrs["commitHash"] + self._file_count = attrs["fileCount"] + self._created_at = attrs["createdAt"] + self._updated_at = attrs["updatedAt"] + self._history_step = attrs.get("historyStep", None) + + @ensure_logged + def new_draft(self) -> Artifact: + """Create a new draft artifact with the same content as this committed artifact. + + Modifying an existing artifact creates a new artifact version known + as an "incremental artifact". The artifact returned can be extended or + modified and logged as a new version. + + Returns: + An `Artifact` object. + + Raises: + ArtifactNotLoggedError: If the artifact is not logged. + """ + # Name, _entity and _project are set to the *source* name/entity/project: + # if this artifact is saved it must be saved to the source sequence. + artifact = Artifact(self.source_name.split(":")[0], self.type) + artifact._entity = self._source_entity + artifact._project = self._source_project + artifact._source_entity = self._source_entity + artifact._source_project = self._source_project + + # This artifact's parent is the one we are making a draft from. + artifact._base_id = self.id + + # We can reuse the client, and copy over all the attributes that aren't + # version-dependent and don't depend on having been logged. + artifact._client = self._client + artifact._description = self.description + artifact._metadata = self.metadata + artifact._manifest = ArtifactManifest.from_manifest_json( + self.manifest.to_manifest_json() + ) + return artifact + + # Properties (Python Class managed attributes). + + @property + def id(self) -> str | None: + """The artifact's ID.""" + if self.is_draft(): + return None + assert self._id is not None + return self._id + + @property + @ensure_logged + def entity(self) -> str: + """The name of the entity that the artifact collection belongs to. + + If the artifact is a link, the entity will be the entity of the linked artifact. + """ + assert self._entity is not None + return self._entity + + @property + @ensure_logged + def project(self) -> str: + """The name of the project that the artifact collection belongs to. + + If the artifact is a link, the project will be the project of the linked artifact. + """ + assert self._project is not None + return self._project + + @property + def name(self) -> str: + """The artifact name and version of the artifact. + + A string with the format `{collection}:{alias}`. If fetched before an artifact is logged/saved, the name won't contain the alias. + If the artifact is a link, the name will be the name of the linked artifact. + """ + return self._name + + @property + def qualified_name(self) -> str: + """The entity/project/name of the artifact. + + If the artifact is a link, the qualified name will be the qualified name of the linked artifact path. + """ + return f"{self.entity}/{self.project}/{self.name}" + + @property + @ensure_logged + def version(self) -> str: + """The artifact's version. + + A string with the format `v{number}`. + If the artifact is a link artifact, the version will be from the linked collection. + """ + assert self._version is not None + return self._version + + @property + @ensure_logged + def collection(self) -> ArtifactCollection: + """The collection this artifact was retrieved from. + + A collection is an ordered group of artifact versions. + If this artifact was retrieved from a portfolio / linked collection, that + collection will be returned rather than the collection + that an artifact version originated from. The collection + that an artifact originates from is known as the source sequence. + """ + base_name = self.name.split(":")[0] + return ArtifactCollection( + self._client, self.entity, self.project, base_name, self.type + ) + + @property + @ensure_logged + def source_entity(self) -> str: + """The name of the entity of the source artifact.""" + assert self._source_entity is not None + return self._source_entity + + @property + @ensure_logged + def source_project(self) -> str: + """The name of the project of the source artifact.""" + assert self._source_project is not None + return self._source_project + + @property + def source_name(self) -> str: + """The artifact name and version of the source artifact. + + A string with the format `{source_collection}:{alias}`. Before the artifact is saved, + contains only the name since the version is not yet known. + """ + return self._source_name + + @property + def source_qualified_name(self) -> str: + """The source_entity/source_project/source_name of the source artifact.""" + return f"{self.source_entity}/{self.source_project}/{self.source_name}" + + @property + @ensure_logged + def source_version(self) -> str: + """The source artifact's version. + + A string with the format `v{number}`. + """ + assert self._source_version is not None + return self._source_version + + @property + @ensure_logged + def source_collection(self) -> ArtifactCollection: + """The artifact's source collection. + + The source collection is the collection that the artifact was logged from. + """ + base_name = self.source_name.split(":")[0] + return ArtifactCollection( + self._client, self.source_entity, self.source_project, base_name, self.type + ) + + @property + def is_link(self) -> bool: + """Boolean flag indicating if the artifact is a link artifact. + + True: The artifact is a link artifact to a source artifact. + False: The artifact is a source artifact. + """ + return self._is_link + + @property + @ensure_logged + def linked_artifacts(self) -> list[Artifact]: + """Returns a list of all the linked artifacts of a source artifact. + + If the artifact is a link artifact (`artifact.is_link == True`), it will return an empty list. + Limited to 500 results.""" + if not self.is_link: + self._linked_artifacts = self._fetch_linked_artifacts() + return self._linked_artifacts + + @property + @ensure_logged + def source_artifact(self) -> Artifact: + """Returns the source artifact. The source artifact is the original logged artifact. + + If the artifact itself is a source artifact (`artifact.is_link == False`), it will return itself.""" + if not self.is_link: + return self + if self._source_artifact is None: + if self._client is None: + raise ValueError("Client is not initialized") + + try: + artifact = self._from_name( + entity=self.source_entity, + project=self.source_project, + name=self.source_name, + client=self._client, + ) + self._source_artifact = artifact + except Exception as e: + raise ValueError( + f"Unable to fetch source artifact for linked artifact {self.name}" + ) from e + return self._source_artifact + + @property + def type(self) -> str: + """The artifact's type. Common types include `dataset` or `model`.""" + return self._type + + @property + @ensure_logged + def url(self) -> str: + """ + Constructs the URL of the artifact. + + Returns: + str: The URL of the artifact. + """ + try: + base_url = self._client.app_url # type: ignore[union-attr] + except AttributeError: + return "" + + if not self.is_link: + return self._construct_standard_url(base_url) + if is_artifact_registry_project(self.project): + return self._construct_registry_url(base_url) + if self._type == "model" or self.project == "model-registry": + return self._construct_model_registry_url(base_url) + return self._construct_standard_url(base_url) + + def _construct_standard_url(self, base_url: str) -> str: + if not all( + [ + base_url, + self.entity, + self.project, + self._type, + self.collection.name, + self._version, + ] + ): + return "" + return urljoin( + base_url, + f"{self.entity}/{self.project}/artifacts/{quote(self._type)}/{quote(self.collection.name)}/{self._version}", + ) + + def _construct_registry_url(self, base_url: str) -> str: + if not all( + [ + base_url, + self.entity, + self.project, + self.collection.name, + self._version, + ] + ): + return "" + + try: + org, *_ = InternalApi()._fetch_orgs_and_org_entities_from_entity( + self.entity + ) + except ValueError: + return "" + + selection_path = quote( + f"{self.entity}/{self.project}/{self.collection.name}", safe="" + ) + return urljoin( + base_url, + f"orgs/{org.display_name}/registry/{remove_registry_prefix(self.project)}?selectionPath={selection_path}&view=membership&version={self.version}", + ) + + def _construct_model_registry_url(self, base_url: str) -> str: + if not all( + [ + base_url, + self.entity, + self.project, + self.collection.name, + self._version, + ] + ): + return "" + selection_path = quote( + f"{self.entity}/{self.project}/{self.collection.name}", safe="" + ) + return urljoin( + base_url, + f"{self.entity}/registry/model?selectionPath={selection_path}&view=membership&version={self._version}", + ) + + @property + def description(self) -> str | None: + """A description of the artifact.""" + return self._description + + @description.setter + def description(self, description: str | None) -> None: + """Set the description of the artifact. + + For model or dataset Artifacts, add documentation for your + standardized team model or dataset card. In the W&B UI the + description is rendered as markdown. + + Editing the description will apply the changes to the source artifact and all linked artifacts associated with it. + + Args: + description: Free text that offers a description of the artifact. + """ + if self.is_link: + wandb.termwarn( + "Editing the description of this linked artifact will edit the description for the source artifact and it's linked artifacts as well." + ) + self._description = description + + @property + def metadata(self) -> dict: + """User-defined artifact metadata. + + Structured data associated with the artifact. + """ + return self._metadata + + @metadata.setter + def metadata(self, metadata: dict) -> None: + """User-defined artifact metadata. + + Metadata set this way will eventually be queryable and plottable in the UI; e.g. + the class distribution of a dataset. + + Note: There is currently a limit of 100 total keys. + Editing the metadata will apply the changes to the source artifact and all linked artifacts associated with it. + + Args: + metadata: Structured data associated with the artifact. + """ + if self.is_link: + wandb.termwarn( + "Editing the metadata of this linked artifact will edit the metadata for the source artifact and it's linked artifacts as well." + ) + self._metadata = validate_metadata(metadata) + + @property + def ttl(self) -> timedelta | None: + """The time-to-live (TTL) policy of an artifact. + + Artifacts are deleted shortly after a TTL policy's duration passes. + If set to `None`, the artifact deactivates TTL policies and will be not + scheduled for deletion, even if there is a team default TTL. + An artifact inherits a TTL policy from + the team default if the team administrator defines a default + TTL and there is no custom policy set on an artifact. + + Raises: + ArtifactNotLoggedError: Unable to fetch inherited TTL if the + artifact has not been logged or saved. + """ + if self._ttl_is_inherited and (self.is_draft() or self._ttl_changed): + raise ArtifactNotLoggedError(f"{type(self).__name__}.ttl", self) + if self._ttl_duration_seconds is None: + return None + return timedelta(seconds=self._ttl_duration_seconds) + + @ttl.setter + def ttl(self, ttl: timedelta | ArtifactTTL | None) -> None: + """The time-to-live (TTL) policy of an artifact. + + Artifacts are deleted shortly after a TTL policy's duration passes. + If set to `None`, the artifact has no TTL policy set and it is not + scheduled for deletion. An artifact inherits a TTL policy from + the team default if the team administrator defines a default + TTL and there is no custom policy set on an artifact. + + Args: + ttl: The duration as a positive Python `datetime.timedelta` Type + that represents how long the artifact will remain active from its creation. + + """ + if self.type == "wandb-history": + raise ValueError("Cannot set artifact TTL for type wandb-history") + + if self.is_link: + raise ValueError( + "Cannot set TTL for link artifact. " + "Unlink the artifact first then set the TTL for the source artifact" + ) + + self._ttl_changed = True + if isinstance(ttl, ArtifactTTL): + if ttl == ArtifactTTL.INHERIT: + self._ttl_is_inherited = True + else: + raise ValueError(f"Unhandled ArtifactTTL enum {ttl}") + else: + self._ttl_is_inherited = False + if ttl is None: + self._ttl_duration_seconds = None + else: + if ttl.total_seconds() <= 0: + raise ValueError( + f"Artifact TTL Duration has to be positive. ttl: {ttl.total_seconds()}" + ) + self._ttl_duration_seconds = int(ttl.total_seconds()) + + @property + @ensure_logged + def aliases(self) -> list[str]: + """List of one or more semantically-friendly references or + + identifying "nicknames" assigned to an artifact version. + + Aliases are mutable references that you can programmatically reference. + Change an artifact's alias with the W&B App UI or programmatically. + See [Create new artifact versions](https://docs.wandb.ai/guides/artifacts/create-a-new-artifact-version) + for more information. + """ + return self._aliases + + @aliases.setter + @ensure_logged + def aliases(self, aliases: list[str]) -> None: + """Set the aliases associated with this artifact.""" + self._aliases = validate_aliases(aliases) + + @property + @ensure_logged + def tags(self) -> list[str]: + """List of one or more tags assigned to this artifact version.""" + return self._tags + + @tags.setter + @ensure_logged + def tags(self, tags: list[str]) -> None: + """Set the tags associated with this artifact. + + Editing tags will apply the changes to the source artifact and all linked artifacts associated with it. + """ + if self.is_link: + wandb.termwarn( + "Editing tags will apply the changes to the source artifact and all linked artifacts associated with it." + ) + self._tags = validate_tags(tags) + + @property + def distributed_id(self) -> str | None: + """The distributed ID of the artifact. + + + """ + return self._distributed_id + + @distributed_id.setter + def distributed_id(self, distributed_id: str | None) -> None: + self._distributed_id = distributed_id + + @property + def incremental(self) -> bool: + """Boolean flag indicating if the artifact is an incremental artifact. + + + """ + return self._incremental + + @property + def use_as(self) -> str | None: + """Deprecated.""" + deprecate( + field_name=Deprecated.artifact__use_as, + warning_message=("The use_as property of Artifact is deprecated."), + ) + return self._use_as + + @property + def state(self) -> str: + """The status of the artifact. One of: "PENDING", "COMMITTED", or "DELETED".""" + return self._state.value + + @property + def manifest(self) -> ArtifactManifest: + """The artifact's manifest. + + The manifest lists all of its contents, and can't be changed once the artifact + has been logged. + """ + if isinstance(self._manifest, _DeferredArtifactManifest): + # A deferred manifest URL flags a deferred download request, + # so fetch the manifest to override the placeholder object + self._manifest = self._load_manifest(self._manifest.url) + return self._manifest + + if self._manifest is None: + query = gql( + """ + query ArtifactManifest( + $entityName: String!, + $projectName: String!, + $name: String! + ) { + project(entityName: $entityName, name: $projectName) { + artifact(name: $name) { + currentManifest { + file { + directUrl + } + } + } + } + } + """ + ) + assert self._client is not None + response = self._client.execute( + query, + variable_values={ + "entityName": self._entity, + "projectName": self._project, + "name": self._name, + }, + ) + attrs = response["project"]["artifact"] + manifest_url = attrs["currentManifest"]["file"]["directUrl"] + self._manifest = self._load_manifest(manifest_url) + + return self._manifest + + @property + def digest(self) -> str: + """The logical digest of the artifact. + + The digest is the checksum of the artifact's contents. If an artifact has the + same digest as the current `latest` version, then `log_artifact` is a no-op. + """ + return self.manifest.digest() + + @property + def size(self) -> int: + """The total size of the artifact in bytes. + + Includes any references tracked by this artifact. + """ + total_size: int = 0 + for entry in self.manifest.entries.values(): + if entry.size is not None: + total_size += entry.size + return total_size + + @property + @ensure_logged + def commit_hash(self) -> str: + """The hash returned when this artifact was committed.""" + assert self._commit_hash is not None + return self._commit_hash + + @property + @ensure_logged + def file_count(self) -> int: + """The number of files (including references).""" + assert self._file_count is not None + return self._file_count + + @property + @ensure_logged + def created_at(self) -> str: + """Timestamp when the artifact was created.""" + assert self._created_at is not None + return self._created_at + + @property + @ensure_logged + def updated_at(self) -> str: + """The time when the artifact was last updated.""" + assert self._created_at is not None + return self._updated_at or self._created_at + + @property + @ensure_logged + def history_step(self) -> int | None: + """The nearest step at which history metrics were logged for the source run of the artifact. + + Examples: + ```python + run = artifact.logged_by() + if run and (artifact.history_step is not None): + history = run.sample_history( + min_step=artifact.history_step, + max_step=artifact.history_step + 1, + keys=["my_metric"], + ) + ``` + """ + if self._history_step is None: + return None + return max(0, self._history_step - 1) + + # State management. + + def finalize(self) -> None: + """Finalize the artifact version. + + You cannot modify an artifact version once it is finalized because the artifact + is logged as a specific artifact version. Create a new artifact version + to log more data to an artifact. An artifact is automatically finalized + when you log the artifact with `log_artifact`. + """ + self._final = True + + def is_draft(self) -> bool: + """Check if artifact is not saved. + + Returns: + Boolean. `False` if artifact is saved. `True` if artifact is not saved. + """ + return self._state == 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 != 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(type(self).wait.__qualname__, 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: + query_template = """ + query ArtifactByIDShort($id: ID!) { + artifact(id: $id) { + ...ArtifactFragment + } + } + """ + _gql_artifact_fragment() + + query = gql(query_template) + + assert self._client is not None + response = self._client.execute( + query, + variable_values={"id": artifact_id}, + ) + + try: + attrs = response["artifact"] + except LookupError: + raise ValueError(f"Unable to fetch artifact with id: {artifact_id!r}") + else: + # _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(attrs, is_link=False) + + @normalize_exceptions + def _update(self) -> None: + """Persists artifact changes to the wandb backend.""" + if self._client is None: + raise RuntimeError("Client not initialized for artifact mutations") + + entity = self.entity + project = self.project + collection = self.name.split(":")[0] + + aliases = None + introspect_query = gql( + """ + query ProbeServerAddAliasesInput { + AddAliasesInputInfoType: __type(name: "AddAliasesInput") { + name + inputFields { + name + } + } + } + """ + ) + + data = self._client.execute(introspect_query) + if data.get("AddAliasesInputInfoType"): # wandb backend version >= 0.13.0 + alias_props = { + "entity_name": entity, + "project_name": project, + "artifact_collection_name": collection, + } + if aliases_to_add := (set(self.aliases) - set(self._saved_aliases)): + add_mutation = gql(ADD_ALIASES_GQL) + add_alias_inputs = [ + ArtifactCollectionAliasInput(**alias_props, alias=alias) + for alias in aliases_to_add + ] + try: + self._client.execute( + add_mutation, + variable_values={ + "artifactID": self.id, + "aliases": [a.model_dump() for a in add_alias_inputs], + }, + ) + except CommError as e: + raise CommError( + "You do not have permission to add" + f" {'at least one of the following aliases' if len(aliases_to_add) > 1 else 'the following alias'}" + f" to this artifact: {aliases_to_add}" + ) from e + + if aliases_to_delete := (set(self._saved_aliases) - set(self.aliases)): + delete_mutation = gql(DELETE_ALIASES_GQL) + delete_alias_inputs = [ + ArtifactCollectionAliasInput(**alias_props, alias=alias) + for alias in aliases_to_delete + ] + try: + self._client.execute( + delete_mutation, + variable_values={ + "artifactID": self.id, + "aliases": [a.model_dump() for a in delete_alias_inputs], + }, + ) + except CommError as e: + raise CommError( + f"You do not have permission to delete" + f" {'at least one of the following aliases' if len(aliases_to_delete) > 1 else 'the following alias'}" + f" from this artifact: {aliases_to_delete}" + ) from e + + self._saved_aliases = copy(self.aliases) + + else: # wandb backend version < 0.13.0 + aliases = [ + ArtifactAliasInput( + artifact_collection_name=collection, alias=alias + ).model_dump() + for alias in self.aliases + ] + + omit_fields = omit_artifact_fields(api=InternalApi()) + omit_variables = set() + + if {"ttlIsInherited", "ttlDurationSeconds"} & omit_fields: + if self._ttl_changed: + termwarn( + "Server not compatible with setting Artifact TTLs, please upgrade the server to use Artifact TTL" + ) + + omit_variables |= {"ttlDurationSeconds"} + + tags_to_add = validate_tags(set(self.tags) - set(self._saved_tags)) + tags_to_del = validate_tags(set(self._saved_tags) - set(self.tags)) + + if {"tags"} & omit_fields: + if tags_to_add or tags_to_del: + termwarn( + "Server not compatible with Artifact tags. " + "To use Artifact tags, please upgrade the server to v0.85 or higher." + ) + + omit_variables |= {"tagsToAdd", "tagsToDelete"} + + mutation = gql_compat( + UPDATE_ARTIFACT_GQL, omit_variables=omit_variables, omit_fields=omit_fields + ) + + gql_vars = { + "artifactID": self.id, + "description": self.description, + "metadata": json_dumps_safer(self.metadata), + "ttlDurationSeconds": self._ttl_duration_seconds_to_gql(), + "aliases": aliases, + "tagsToAdd": [TagInput(tag_name=t).model_dump() for t in tags_to_add], + "tagsToDelete": [TagInput(tag_name=t).model_dump() for t in tags_to_del], + } + + data = self._client.execute(mutation, variable_values=gql_vars) + + result = UpdateArtifact.model_validate(data).update_artifact + if not (result and (artifact := result.artifact)): + raise ValueError("Unable to parse updateArtifact response") + self._assign_attrs(artifact.model_dump()) + + self._ttl_changed = False # Reset after updating artifact + + # Adding, removing, getting entries. + + def __getitem__(self, name: str) -> WBValue | None: + """Get the WBValue object located at the artifact relative `name`. + + Args: + name: The artifact relative name to get. + + Returns: + W&B object that can be logged with `run.log()` and visualized in the W&B UI. + + Raises: + ArtifactNotLoggedError: If the artifact isn't logged or the run is offline. + """ + return self.get(name) + + def __setitem__(self, name: str, item: WBValue) -> ArtifactManifestEntry: + """Add `item` to the artifact at path `name`. + + Args: + name: The path within the artifact to add the object. + item: The object to add. + + Returns: + The added manifest entry + + Raises: + ArtifactFinalizedError: You cannot make changes to the current + artifact version because it is finalized. Log a new artifact + version instead. + """ + return self.add(item, name) + + @contextlib.contextmanager + @ensure_not_finalized + def new_file( + self, name: str, mode: str = "x", encoding: str | None = None + ) -> Iterator[IO]: + """Open a new temporary file and add it to the artifact. + + Args: + name: The name of the new file to add to the artifact. + mode: The file access mode to use to open the new file. + encoding: The encoding used to open the new file. + + Returns: + A new file object that can be written to. Upon closing, the file + is automatically added to the artifact. + + Raises: + ArtifactFinalizedError: You cannot make changes to the current + artifact version because it is finalized. Log a new artifact + version instead. + """ + overwrite: bool = "x" not in mode + + if self._tmp_dir is None: + self._tmp_dir = tempfile.TemporaryDirectory() + path = os.path.join(self._tmp_dir.name, name.lstrip("/")) + + filesystem.mkdir_exists_ok(os.path.dirname(path)) + 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 ({type(e).__name__}: {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}") + + termlog( + "Adding directory to artifact ({})... ".format( + os.path.join(".", os.path.normpath(local_path)) + ), + newline=False, + ) + start_time = time.time() + + 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) + if name is not None: + logical_path = os.path.join(name, logical_path) + paths.append((logical_path, physical_path)) + + def add_manifest_file(log_phy_path: tuple[str, str]) -> None: + logical_path, physical_path = log_phy_path + self._add_local_file( + name=logical_path, + path=physical_path, + skip_cache=skip_cache, + policy=policy, + overwrite=merge, + ) + + num_threads = 8 + pool = multiprocessing.dummy.Pool(num_threads) + pool.map(add_manifest_file, paths) + pool.close() + pool.join() + + termlog("Done. %.1fs" % (time.time() - start_time), prefix=False) + + @ensure_not_finalized + def add_reference( + self, + uri: ArtifactManifestEntry | str, + name: StrPath | None = None, + checksum: bool = True, + max_objects: int | None = None, + ) -> Sequence[ArtifactManifestEntry]: + """Add a reference denoted by a URI to the artifact. + + Unlike files or directories that you add to an artifact, references are not + uploaded to W&B. For more information, + see [Track external files](https://docs.wandb.ai/guides/artifacts/track-external-files). + + By default, the following schemes are supported: + + - http(s): The size and digest of the file will be inferred by the + `Content-Length` and the `ETag` response headers returned by the server. + - s3: The checksum and size are pulled from the object metadata. + If bucket versioning is enabled, then the version ID is also tracked. + - gs: The checksum and size are pulled from the object metadata. If bucket + versioning is enabled, then the version ID is also tracked. + - https, domain matching `*.blob.core.windows.net` + - Azure: The checksum and size are be pulled from the blob metadata. + If storage account versioning is enabled, then the version ID is + also tracked. + - file: The checksum and size are pulled from the file system. This scheme + is useful if you have an NFS share or other externally mounted volume + containing files you wish to track but not necessarily upload. + + For any other scheme, the digest is just a hash of the URI and the size is left + blank. + + Args: + uri: The URI path of the reference to add. The URI path can be an object + returned from `Artifact.get_entry` to store a reference to another + artifact's entry. + name: The path within the artifact to place the contents of this reference. + checksum: Whether or not to checksum the resource(s) located at the + reference URI. Checksumming is strongly recommended as it enables + automatic integrity validation. Disabling checksumming will speed up + artifact creation but reference directories will not iterated through so the + objects in the directory will not be saved to the artifact. We recommend + setting `checksum=False` when adding reference objects, in which case + a new version will only be created if the reference URI changes. + max_objects: The maximum number of objects to consider when adding a + reference that points to directory or bucket store prefix. + By default, the maximum number of objects allowed for Amazon S3, + GCS, Azure, and local files is 10,000,000. Other URI schemas + do not have a maximum. + + Returns: + The added manifest entries. + + Raises: + ArtifactFinalizedError: You cannot make changes to the current + artifact version because it is finalized. Log a new artifact + version instead. + """ + if name is not None: + name = LogicalPath(name) + + # This is a bit of a hack, we want to check if the uri is a of the type + # ArtifactManifestEntry. If so, then recover the reference URL. + if isinstance(uri, ArtifactManifestEntry): + uri_str = uri.ref_url() + elif isinstance(uri, str): + uri_str = uri + url = urlparse(str(uri_str)) + if not url.scheme: + raise ValueError( + "References must be URIs. To reference a local file, use file://" + ) + + manifest_entries = self._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)) + entry = self.manifest.get_entry_by_path(path) + if entry: + self.manifest.remove_entry(entry) + return + + entries = self.manifest.get_entries_in_directory(path) + if not entries: + raise FileNotFoundError(f"No such file or directory: {path}") + for entry in entries: + self.manifest.remove_entry(entry) + + def get_path(self, name: StrPath) -> ArtifactManifestEntry: + """Deprecated. Use `get_entry(name)`.""" + deprecate( + field_name=Deprecated.artifact__get_path, + warning_message="Artifact.get_path(name) is deprecated, use Artifact.get_entry(name) instead.", + ) + return self.get_entry(name) + + @ensure_logged + def get_entry(self, name: StrPath) -> ArtifactManifestEntry: + """Get the entry with the given name. + + Args: + name: The artifact relative name to get + + Returns: + A `W&B` object. + + Raises: + ArtifactNotLoggedError: if the artifact isn't logged or the run is offline. + KeyError: if the artifact doesn't contain an entry with the given name. + """ + name = LogicalPath(name) + entry = self.manifest.entries.get(name) or self._get_obj_entry(name)[0] + if entry is None: + raise KeyError(f"Path not contained in artifact: {name}") + entry._parent_artifact = self + return entry + + @ensure_logged + def get(self, name: str) -> WBValue | None: + """Get the WBValue object located at the artifact relative `name`. + + Args: + name: The artifact relative name to retrieve. + + Returns: + W&B object that can be logged with `run.log()` and + visualized in the W&B UI. + + Raises: + ArtifactNotLoggedError: if the artifact isn't logged or the + run is offline. + """ + entry, wb_class = self._get_obj_entry(name) + if entry is None or wb_class is None: + return None + + # If the entry is a reference from another artifact, then get it directly from + # that artifact. + referenced_id = entry._referenced_artifact_id() + if referenced_id: + assert self._client is not None + artifact = self._from_id(referenced_id, client=self._client) + assert artifact is not None + return artifact.get(uri_from_path(entry.ref)) + + # Special case for wandb.Table. This is intended to be a short term + # optimization. Since tables are likely to download many other assets in + # artifact(s), we eagerly download the artifact using the parallelized + # `artifact.download`. In the future, we should refactor the deserialization + # pattern such that this special case is not needed. + if wb_class == wandb.Table: + self.download() + + # Get the ArtifactManifestEntry + item = self.get_entry(entry.path) + item_path = item.download() + + # Load the object from the JSON blob + result = None + json_obj = {} + 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. + """ + entry = self._added_local_paths.get(local_path, None) + if entry is None: + return None + return entry.path + + 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) + entry = self.manifest.entries.get(wandb_file_name) + if entry is not None: + return entry, wb_class + return None, None + + # Downloading. + + @ensure_logged + def download( + self, + root: StrPath | None = None, + allow_missing_references: bool = False, + skip_cache: bool | None = None, + path_prefix: StrPath | None = None, + multipart: bool | None = None, + ) -> FilePathStr: + """Download the contents of the artifact to the specified root directory. + + Existing files located within `root` are not modified. Explicitly delete `root` + before you call `download` if you want the contents of `root` to exactly match + the artifact. + + Args: + root: The directory W&B stores the artifact's files. + allow_missing_references: If set to `True`, any invalid reference paths + will be ignored while downloading referenced files. + skip_cache: If set to `True`, the artifact cache will be skipped when + downloading and W&B will download each file into the default root or + specified download directory. + path_prefix: If specified, only files with a path that starts with the given + prefix will be downloaded. Uses unix format (forward slashes). + multipart: If set to `None` (default), the artifact will be downloaded + in parallel using multipart download if individual file size is greater than + 2GB. If set to `True` or `False`, the artifact will be downloaded in + parallel or serially regardless of the file size. + + Returns: + The path to the downloaded contents. + + Raises: + ArtifactNotLoggedError: If the artifact is not logged. + """ + root = FilePathStr(str(root or self._default_root())) + self._add_download_root(root) + + # TODO: download artifacts using core when implemented + # if is_require_core(): + # return self._download_using_core( + # root=root, + # allow_missing_references=allow_missing_references, + # skip_cache=bool(skip_cache), + # path_prefix=path_prefix, + # ) + return self._download( + root=root, + allow_missing_references=allow_missing_references, + skip_cache=skip_cache, + path_prefix=path_prefix, + multipart=multipart, + ) + + def _download_using_core( + self, + root: str, + allow_missing_references: bool = False, + skip_cache: bool = False, + path_prefix: StrPath | None = None, + ) -> FilePathStr: + import pathlib + + from wandb.sdk.backend.backend import Backend + + # TODO: Create a special stream instead of relying on an existing run. + if wandb.run is None: + wl = wandb_setup.singleton() + + stream_id = generate_id() + + settings = wl.settings.to_proto() + # TODO: remove this + tmp_dir = pathlib.Path(tempfile.mkdtemp()) + + settings.sync_dir.value = str(tmp_dir) + settings.sync_file.value = str(tmp_dir / f"{stream_id}.wandb") + settings.files_dir.value = str(tmp_dir / "files") + settings.run_id.value = stream_id + + service = wl.ensure_service() + service.inform_init(settings=settings, run_id=stream_id) + + backend = Backend(settings=wl.settings, service=service) + backend.ensure_launched() + + assert backend.interface + backend.interface._stream_id = stream_id # type: ignore + else: + assert wandb.run._backend + backend = wandb.run._backend + + assert backend.interface + handle = backend.interface.deliver_download_artifact( + self.id, # type: ignore + root, + allow_missing_references, + skip_cache, + path_prefix, # type: ignore + ) + # TODO: Start the download process in the user process too, to handle reference downloads + self._download( + root=root, + allow_missing_references=allow_missing_references, + skip_cache=skip_cache, + path_prefix=path_prefix, + ) + result = handle.wait_or(timeout=None) + + response = result.response.download_artifact_response + if response.error_message: + raise ValueError(f"Error downloading artifact: {response.error_message}") + + return FilePathStr(root) + + def _download( + self, + root: str, + allow_missing_references: bool = False, + skip_cache: bool | None = None, + path_prefix: StrPath | None = None, + multipart: bool | None = None, + ) -> FilePathStr: + nfiles = len(self.manifest.entries) + size = sum(e.size or 0 for e in self.manifest.entries.values()) + log = False + if nfiles > 5000 or size > 50 * 1024 * 1024: + log = True + termlog( + f"Downloading large artifact {self.name}, {size / (1024 * 1024):.2f}MB. {nfiles} files... ", + ) + start_time = datetime.now() + download_logger = ArtifactDownloadLogger(nfiles=nfiles) + + def _download_entry( + entry: ArtifactManifestEntry, + executor: concurrent.futures.Executor, + api_key: str | None, + cookies: dict | None, + headers: dict | None, + ) -> None: + _thread_local_api_settings.api_key = api_key + _thread_local_api_settings.cookies = cookies + _thread_local_api_settings.headers = headers + + try: + entry.download( + root, + skip_cache=skip_cache, + executor=executor, + multipart=multipart, + ) + except FileNotFoundError as e: + if allow_missing_references: + wandb.termwarn(str(e)) + return + raise + except _GCSIsADirectoryError as e: + logger.debug(str(e)) + return + download_logger.notify_downloaded() + + with concurrent.futures.ThreadPoolExecutor(64) as executor: + download_entry = partial( + _download_entry, + executor=executor, + api_key=_thread_local_api_settings.api_key, + cookies=_thread_local_api_settings.cookies, + headers=_thread_local_api_settings.headers, + ) + active_futures = set() + has_next_page = True + cursor = None + while has_next_page: + fetch_url_batch_size = env.get_artifact_fetch_file_url_batch_size() + attrs = self._fetch_file_urls(cursor, fetch_url_batch_size) + has_next_page = attrs["pageInfo"]["hasNextPage"] + cursor = attrs["pageInfo"]["endCursor"] + for edge in attrs["edges"]: + entry = self.get_entry(edge["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 = edge["node"]["directUrl"] + if (not path_prefix) or entry.path.startswith(str(path_prefix)): + active_futures.add(executor.submit(download_entry, entry)) + # Wait for download threads to catch up. + max_backlog = fetch_url_batch_size + if len(active_futures) > max_backlog: + for future in concurrent.futures.as_completed(active_futures): + future.result() # check for errors + active_futures.remove(future) + if len(active_futures) <= max_backlog: + break + # Check for errors. + for future in concurrent.futures.as_completed(active_futures): + future.result() + + if log: + now = datetime.now() + delta = abs((now - start_time).total_seconds()) + hours = int(delta // 3600) + minutes = int((delta - hours * 3600) // 60) + seconds = delta - hours * 3600 - minutes * 60 + speed = size / 1024 / 1024 / delta + termlog( + f"Done. {hours}:{minutes}:{seconds:.1f} ({speed:.1f}MB/s)", + prefix=False, + ) + return FilePathStr(root) + + @retry.retriable( + retry_timedelta=timedelta(minutes=3), + retryable_exceptions=(requests.RequestException), + ) + def _fetch_file_urls(self, cursor: str | None, per_page: int | None = 5000) -> Any: + if InternalApi()._server_supports( + pb.ServerFeature.ARTIFACT_COLLECTION_MEMBERSHIP_FILES + ): + query = gql( + """ + query ArtifactCollectionMembershipFileURLs($entityName: String!, $projectName: String!, \ + $artifactName: String!, $artifactVersionIndex: String!, $cursor: String, $perPage: Int) { + project(name: $projectName, entityName: $entityName) { + artifactCollection(name: $artifactName) { + artifactMembership(aliasName: $artifactVersionIndex) { + files(after: $cursor, first: $perPage) { + pageInfo { + hasNextPage + endCursor + } + edges { + node { + name + directUrl + } + } + } + } + } + } + } + """ + ) + assert self._client is not None + response = self._client.execute( + query, + variable_values={ + "entityName": self.entity, + "projectName": self.project, + "artifactName": self.name.split(":")[0], + "artifactVersionIndex": self.version, + "cursor": cursor, + "perPage": per_page, + }, + timeout=60, + ) + return response["project"]["artifactCollection"]["artifactMembership"][ + "files" + ] + else: + query = gql( + """ + query ArtifactFileURLs($id: ID!, $cursor: String, $perPage: Int) { + artifact(id: $id) { + files(after: $cursor, first: $perPage) { + pageInfo { + hasNextPage + endCursor + } + edges { + node { + name + directUrl + } + } + } + } + } + """ + ) + assert self._client is not None + response = self._client.execute( + query, + variable_values={"id": self.id, "cursor": cursor, "perPage": per_page}, + timeout=60, + ) + return response["artifact"]["files"] + + @ensure_logged + def checkout(self, root: str | None = None) -> str: + """Replace the specified root directory with the contents of the artifact. + + WARNING: This will delete all files in `root` that are not included in the + artifact. + + Args: + root: The directory to replace with this artifact's files. + + Returns: + The path of the checked out contents. + + Raises: + ArtifactNotLoggedError: If the artifact is not logged. + """ + root = root or self._default_root(include_version=False) + + for dirpath, _, files in os.walk(root): + for file in files: + full_path = os.path.join(dirpath, file) + artifact_path = os.path.relpath(full_path, start=root) + try: + self.get_entry(artifact_path) + except KeyError: + # File is not part of the artifact, remove it. + os.remove(full_path) + + return self.download(root=root) + + @ensure_logged + def verify(self, root: str | None = None) -> None: + """Verify that the contents of an artifact match the manifest. + + All files in the directory are checksummed and the checksums are then + cross-referenced against the artifact's manifest. References are not verified. + + Args: + root: The directory to verify. If None artifact will be downloaded to + './artifacts/self.name/'. + + Raises: + ArtifactNotLoggedError: If the artifact is not logged. + ValueError: If the verification fails. + """ + root = root or self._default_root() + + for dirpath, _, files in os.walk(root): + for file in files: + full_path = os.path.join(dirpath, file) + artifact_path = os.path.relpath(full_path, start=root) + try: + self.get_entry(artifact_path) + except KeyError: + raise ValueError( + f"Found file {full_path} which is not a member of artifact {self.name}" + ) + + ref_count = 0 + for entry in self.manifest.entries.values(): + if entry.ref is None: + if md5_file_b64(os.path.join(root, entry.path)) != entry.digest: + raise ValueError(f"Digest mismatch for file: {entry.path}") + else: + ref_count += 1 + if ref_count > 0: + termwarn(f"skipped verification of {ref_count} refs") + + @ensure_logged + def file(self, root: str | None = None) -> StrPath: + """Download a single file artifact to the directory you specify with `root`. + + Args: + root: The root directory to store the file. Defaults to + `./artifacts/self.name/`. + + Returns: + The full path of the downloaded file. + + Raises: + ArtifactNotLoggedError: If the artifact is not logged. + ValueError: If the artifact contains more than one file. + """ + if root is None: + root = os.path.join(".", "artifacts", self.name) + + if len(self.manifest.entries) > 1: + raise ValueError( + "This artifact contains more than one file, call `.download()` to get " + 'all files or call .get_entry("filename").download()' + ) + + return self.get_entry(list(self.manifest.entries)[0]).download(root) + + @ensure_logged + def files( + self, names: list[str] | None = None, per_page: int = 50 + ) -> ArtifactFiles: + """Iterate over all files stored in this artifact. + + Args: + names: The filename paths relative to the root of the artifact you wish to + list. + per_page: The number of files to return per request. + + Returns: + An iterator containing `File` objects. + + Raises: + ArtifactNotLoggedError: If the artifact is not logged. + """ + return ArtifactFiles(self._client, self, names, per_page) + + def _default_root(self, include_version: bool = True) -> FilePathStr: + name = self.source_name if include_version else self.source_name.split(":")[0] + root = os.path.join(env.get_artifact_dir(), name) + # In case we're on a system where the artifact dir has a name corresponding to + # an unexpected filesystem, we'll check for alternate roots. If one exists we'll + # use that, otherwise we'll fall back to the system-preferred path. + path = filesystem.check_exists(root) or filesystem.system_preferred_path(root) + return FilePathStr(str(path)) + + def _add_download_root(self, dir_path: str) -> None: + self._download_roots.add(os.path.abspath(dir_path)) + + def _local_path_to_name(self, file_path: str) -> str | None: + """Convert a local file path to a path entry in the artifact.""" + abs_file_path = os.path.abspath(file_path) + abs_file_parts = abs_file_path.split(os.sep) + for i in range(len(abs_file_parts) + 1): + if os.path.join(os.sep, *abs_file_parts[:i]) in self._download_roots: + return os.path.join(*abs_file_parts[i:]) + return None + + # Others. + + @ensure_logged + def delete(self, delete_aliases: bool = False) -> None: + """Delete an artifact and its files. + + If called on a linked artifact, only the link is deleted, and the + source artifact is unaffected. + + Use `artifact.unlink()` instead of `artifact.delete()` to remove a link between a source artifact and a linked artifact. + + Args: + delete_aliases: If set to `True`, deletes all aliases associated + with the artifact. Otherwise, this raises an exception if + the artifact has existing aliases. This parameter is ignored + if the artifact is linked (a member of a portfolio collection). + + Raises: + ArtifactNotLoggedError: If the artifact is not logged. + """ + if self.is_link: + wandb.termwarn( + "Deleting a link artifact will only unlink the artifact from the source artifact and not delete the source artifact and the data of the source artifact." + ) + self._unlink() + else: + self._delete(delete_aliases) + + @normalize_exceptions + def _delete(self, delete_aliases: bool = False) -> None: + mutation = gql( + """ + mutation DeleteArtifact($artifactID: ID!, $deleteAliases: Boolean) { + deleteArtifact(input: { + artifactID: $artifactID + deleteAliases: $deleteAliases + }) { + artifact { + id + } + } + } + """ + ) + assert self._client is not None + self._client.execute( + mutation, + variable_values={ + "artifactID": self.id, + "deleteAliases": delete_aliases, + }, + ) + + @normalize_exceptions + def link( + self, target_path: str, aliases: list[str] | None = None + ) -> Artifact | None: + """Link this artifact to a portfolio (a promoted collection of artifacts). + + Args: + target_path: The path to the portfolio inside a project. + The target path must adhere to one of the following + schemas `{portfolio}`, `{project}/{portfolio}` or + `{entity}/{project}/{portfolio}`. + To link the artifact to the Model Registry, rather than to a generic + portfolio inside a project, set `target_path` to the following + schema `{"model-registry"}/{Registered Model Name}` or + `{entity}/{"model-registry"}/{Registered Model Name}`. + aliases: A list of strings that uniquely identifies the artifact + inside the specified portfolio. + + Raises: + ArtifactNotLoggedError: If the artifact is not logged. + + Returns: + The linked artifact if linking was successful, otherwise None. + """ + from wandb import Api + + if self.is_link: + wandb.termwarn( + "Linking to a link artifact will result in directly linking to the source artifact of that link artifact." + ) + + if self._client is None: + raise ValueError("Client not initialized for artifact mutations") + + # Save the artifact first if necessary + if self.is_draft(): + if not self._is_draft_save_started(): + self.save(project=self.source_project) + + # Wait until the artifact is committed before trying to link it. + self.wait() + + api = Api(overrides={"entity": self.source_entity}) + + target = ArtifactPath.from_str(target_path).with_defaults( + project=api.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.project and is_artifact_registry_project(target.project): + # 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 + organization = target.prefix or api.settings.get("organization") or "" + + target.prefix = InternalApi()._resolve_org_entity_name( + self.source_entity, organization + ) + else: + target = target.with_defaults(prefix=self.source_entity) + + # Prepare the validated GQL input, send it + alias_inputs = [ + ArtifactAliasInput(artifact_collection_name=target.name, alias=a) + for a in (aliases or []) + ] + gql_input = LinkArtifactInput( + artifact_id=self.id, + artifact_portfolio_name=target.name, + entity_name=target.prefix, + project_name=target.project, + aliases=alias_inputs, + ) + gql_vars = {"input": gql_input.model_dump(exclude_none=True)} + gql_op = gql(LINK_ARTIFACT_GQL) + data = self._client.execute(gql_op, variable_values=gql_vars) + + result = LinkArtifact.model_validate(data).link_artifact + if not (result and (version_idx := result.version_index) is not None): + raise ValueError("Unable to parse linked artifact version from response") + + # Fetch the linked artifact to return it + linked_path = f"{target.to_str()}:v{version_idx}" + + try: + return api._artifact(linked_path) + except Exception as e: + wandb.termerror(f"Error fetching link artifact after linking: {e}") + return None + + @ensure_logged + def unlink(self) -> None: + """Unlink this artifact if it is currently a member of a promoted collection of artifacts. + + Raises: + ArtifactNotLoggedError: If the artifact is not logged. + ValueError: If the artifact is not linked, in other words, + it is not a member of a portfolio collection. + """ + # Fail early if this isn't a linked artifact to begin with + if not self.is_link: + raise ValueError( + f"Artifact {self.qualified_name!r} is not a linked artifact and cannot be unlinked. " + f"To delete it, use {self.delete.__qualname__!r} instead." + ) + + self._unlink() + + @normalize_exceptions + def _unlink(self) -> None: + mutation = gql( + """ + mutation UnlinkArtifact($artifactID: ID!, $artifactPortfolioID: ID!) { + unlinkArtifact( + input: { artifactID: $artifactID, artifactPortfolioID: $artifactPortfolioID } + ) { + artifactID + success + clientMutationId + } + } + """ + ) + assert self._client is not None + try: + self._client.execute( + mutation, + variable_values={ + "artifactID": self.id, + "artifactPortfolioID": self.collection.id, + }, + ) + except CommError as e: + raise CommError( + f"You do not have permission to unlink the artifact {self.qualified_name}" + ) from e + + @ensure_logged + def used_by(self) -> list[Run]: + """Get a list of the runs that have used this artifact and its linked artifacts. + + Returns: + A list of `Run` objects. + + Raises: + ArtifactNotLoggedError: If the artifact is not logged. + """ + query = gql( + """ + query ArtifactUsedBy( + $id: ID!, + ) { + artifact(id: $id) { + usedBy { + edges { + node { + name + project { + name + entityName + } + } + } + } + } + } + """ + ) + assert self._client is not None + response = self._client.execute( + query, + variable_values={"id": self.id}, + ) + return [ + Run( + self._client, + edge["node"]["project"]["entityName"], + edge["node"]["project"]["name"], + edge["node"]["name"], + ) + for edge in response.get("artifact", {}).get("usedBy", {}).get("edges", []) + ] + + @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. + """ + query = gql( + """ + query ArtifactCreatedBy( + $id: ID! + ) { + artifact(id: $id) { + createdBy { + ... on Run { + name + project { + name + entityName + } + } + } + } + } + """ + ) + assert self._client is not None + response = self._client.execute( + query, + variable_values={"id": self.id}, + ) + creator = response.get("artifact", {}).get("createdBy", {}) + if creator.get("name") is None: + return None + return Run( + self._client, + creator["project"]["entityName"], + creator["project"]["name"], + creator["name"], + ) + + @ensure_logged + def json_encode(self) -> dict[str, Any]: + """Returns the artifact encoded to the JSON format. + + Returns: + A `dict` with `string` keys representing attributes of the artifact. + """ + return artifact_to_json(self) + + @staticmethod + def _expected_type( + entity_name: str, project_name: str, name: str, client: RetryingClient + ) -> str | None: + """Returns the expected type for a given artifact name and project.""" + query = gql( + """ + query ArtifactType( + $entityName: String, + $projectName: String, + $name: String! + ) { + project(name: $projectName, entityName: $entityName) { + artifact(name: $name) { + artifactType { + name + } + } + } + } + """ + ) + if ":" not in name: + name += ":latest" + response = client.execute( + query, + variable_values={ + "entityName": entity_name, + "projectName": project_name, + "name": name, + }, + ) + return ( + ((response.get("project") or {}).get("artifact") or {}).get("artifactType") + or {} + ).get("name") + + def _load_manifest(self, url: str) -> ArtifactManifest: + with requests.get(url) as response: + response.raise_for_status() + return ArtifactManifest.from_manifest_json(response.json()) + + def _ttl_duration_seconds_to_gql(self) -> int | None: + # Set artifact ttl value to ttl_duration_seconds if the user set a value + # otherwise use ttl_status to indicate the backend INHERIT(-1) or DISABLED(-2) when the TTL is None + # When ttl_change = None its a no op since nothing changed + INHERIT = -1 # noqa: N806 + DISABLED = -2 # noqa: N806 + + if not self._ttl_changed: + return None + if self._ttl_is_inherited: + return INHERIT + return self._ttl_duration_seconds or DISABLED + + def _fetch_linked_artifacts(self) -> list[Artifact]: + """Fetches all linked artifacts from the server.""" + if self.id is None: + raise ValueError( + "Unable to find any artifact memberships for artifact without an ID" + ) + if self._client is None: + raise ValueError("Client is not initialized") + response = self._client.execute( + gql_compat(FETCH_LINKED_ARTIFACTS_GQL), + variable_values={"artifactID": self.id}, + ) + result = FetchLinkedArtifacts.model_validate(response) + + if not ( + (artifact := result.artifact) + and (memberships := artifact.artifact_memberships) + and (membership_edges := memberships.edges) + ): + raise ValueError("Unable to find any artifact memberships for artifact") + + linked_artifacts: deque[Artifact] = deque() + linked_nodes = ( + node + for edge in membership_edges + if ( + (node := edge.node) + and (col := node.artifact_collection) + and (col.typename__ == LINKED_ARTIFACT_COLLECTION_TYPE) + ) + ) + for node in linked_nodes: + # Trick for O(1) membership check that maintains order + alias_names = dict.fromkeys(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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/artifact_instance_cache.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/artifact_instance_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..e6fd6e9676d048a0a7fc0715bb7ae107ae01e7cc --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/artifact_instance_cache.py @@ -0,0 +1,17 @@ +"""Recent Artifact storage. + +Artifacts are registered in the cache to ensure they won't be immediately garbage +collected and can be retrieved by their ID. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from wandb.sdk.lib.capped_dict import CappedDict + +if TYPE_CHECKING: + from wandb.sdk.artifacts.artifact import Artifact + +# There is nothing special about the artifact cache, it's just a global capped dict. +artifact_instance_cache: dict[str, Artifact] = CappedDict(100) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/artifact_manifest_entry.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/artifact_manifest_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..c4163d61f6f67e90237c2039f37dd5ca2a3bec21 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/artifact_manifest_entry.py @@ -0,0 +1,259 @@ +"""Artifact manifest entry.""" + +from __future__ import annotations + +import concurrent.futures +import json +import logging +import os +from pathlib import Path +from typing import TYPE_CHECKING +from urllib.parse import urlparse + +from wandb.proto.wandb_deprecated import Deprecated +from wandb.sdk.lib import filesystem +from wandb.sdk.lib.deprecate import deprecate +from wandb.sdk.lib.hashutil import ( + B64MD5, + ETag, + b64_to_hex_id, + hex_to_b64_id, + md5_file_b64, +) +from wandb.sdk.lib.paths import FilePathStr, LogicalPath, StrPath, URIStr + +logger = logging.getLogger(__name__) + +if TYPE_CHECKING: + from typing_extensions import TypedDict + + from wandb.sdk.artifacts.artifact import Artifact + + class ArtifactManifestEntryDict(TypedDict, total=False): + path: str + digest: str + skip_cache: bool + ref: str + birthArtifactID: str + size: int + extra: dict + local_path: str + + +class ArtifactManifestEntry: + """A single entry in an artifact manifest.""" + + path: LogicalPath + digest: B64MD5 | URIStr | FilePathStr | ETag + skip_cache: bool + ref: FilePathStr | URIStr | None + birth_artifact_id: str | None + size: int | None + extra: dict + local_path: str | None + + _parent_artifact: Artifact | None = None + _download_url: str | None = None + + def __init__( + self, + path: StrPath, + digest: B64MD5 | URIStr | FilePathStr | ETag, + skip_cache: bool | None = False, + ref: FilePathStr | URIStr | None = None, + birth_artifact_id: str | None = None, + size: int | None = None, + extra: dict | None = None, + local_path: StrPath | None = None, + ) -> None: + self.path = LogicalPath(path) + self.digest = digest + self.ref = ref + self.birth_artifact_id = birth_artifact_id + self.size = size + self.extra = extra or {} + self.local_path = str(local_path) if local_path else None + if self.local_path and self.size is None: + self.size = Path(self.local_path).stat().st_size + self.skip_cache = skip_cache or False + + def __repr__(self) -> str: + cls = self.__class__.__name__ + ref = f", ref={self.ref!r}" if self.ref is not None else "" + birth_artifact_id = ( + f", birth_artifact_id={self.birth_artifact_id!r}" + if self.birth_artifact_id is not None + else "" + ) + size = f", size={self.size}" if self.size is not None else "" + extra = f", extra={json.dumps(self.extra)}" if self.extra else "" + local_path = f", local_path={self.local_path!r}" if self.local_path else "" + skip_cache = f", skip_cache={self.skip_cache}" + others = ref + birth_artifact_id + size + extra + local_path + skip_cache + return f"{cls}(path={self.path!r}, digest={self.digest!r}{others})" + + def __eq__(self, other: object) -> bool: + """Strict equality, comparing all public fields. + + ArtifactManifestEntries for the same file may not compare equal if they were + added in different ways or created for different parent artifacts. + """ + if not isinstance(other, ArtifactManifestEntry): + return False + return ( + self.path == other.path + and self.digest == other.digest + and self.ref == other.ref + and self.birth_artifact_id == other.birth_artifact_id + and self.size == other.size + and self.extra == other.extra + and self.local_path == other.local_path + and self.skip_cache == other.skip_cache + ) + + @property + def name(self) -> LogicalPath: + """Deprecated; use `path` instead.""" + deprecate( + field_name=Deprecated.artifactmanifestentry__name, + warning_message="ArtifactManifestEntry.name is deprecated, use .path instead.", + ) + return self.path + + def parent_artifact(self) -> Artifact: + """Get the artifact to which this artifact entry belongs. + + Returns: + (PublicArtifact): The parent artifact + """ + if self._parent_artifact is None: + raise NotImplementedError + return self._parent_artifact + + def download( + self, + root: str | None = None, + skip_cache: bool | None = None, + executor: concurrent.futures.Executor | None = None, + multipart: bool | 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. + """ + if self._parent_artifact is None: + raise NotImplementedError + + root = root or self._parent_artifact._default_root() + self._parent_artifact._add_download_root(root) + path = str(Path(self.path)) + dest_path = os.path.join(root, path) + + if skip_cache: + override_cache_path = dest_path + else: + override_cache_path = None + + # Skip checking the cache (and possibly downloading) if the file already exists + # and has the digest we're expecting. + try: + md5_hash = md5_file_b64(dest_path) + except (FileNotFoundError, IsADirectoryError): + logger.debug(f"unable to find {dest_path}, skip searching for file") + else: + if self.digest == md5_hash: + return FilePathStr(dest_path) + + if self.ref is not None: + cache_path = self._parent_artifact.manifest.storage_policy.load_reference( + self, local=True, dest_path=override_cache_path + ) + else: + cache_path = self._parent_artifact.manifest.storage_policy.load_file( + self._parent_artifact, + self, + dest_path=override_cache_path, + executor=executor, + multipart=multipart, + ) + + if skip_cache: + return FilePathStr(dest_path) + else: + return FilePathStr( + str(filesystem.copy_or_overwrite_changed(cache_path, dest_path)) + ) + + def ref_target(self) -> FilePathStr | URIStr: + """Get the reference URL that is targeted by this artifact entry. + + Returns: + (str): The reference URL of this artifact entry. + + Raises: + ValueError: If this artifact entry was not a reference. + """ + if self.ref is None: + raise ValueError("Only reference entries support ref_target().") + if self._parent_artifact is None: + return self.ref + return self._parent_artifact.manifest.storage_policy.load_reference( + self._parent_artifact.manifest.entries[self.path], local=False + ) + + def ref_url(self) -> str: + """Get a URL to this artifact entry. + + These URLs can be referenced by another artifact. + + Returns: + (str): A URL representing this artifact entry. + + Examples: + Basic usage + ``` + ref_url = source_artifact.get_entry("file.txt").ref_url() + derived_artifact.add_reference(ref_url) + ``` + """ + if self._parent_artifact is None: + raise NotImplementedError + assert self._parent_artifact.id is not None + return ( + "wandb-artifact://" + + b64_to_hex_id(B64MD5(self._parent_artifact.id)) + + "/" + + self.path + ) + + def to_json(self) -> ArtifactManifestEntryDict: + contents: ArtifactManifestEntryDict = { + "path": self.path, + "digest": self.digest, + } + if self.size is not None: + contents["size"] = self.size + if self.ref: + contents["ref"] = self.ref + if self.birth_artifact_id: + contents["birthArtifactID"] = self.birth_artifact_id + if self.local_path: + contents["local_path"] = self.local_path + if self.skip_cache: + contents["skip_cache"] = self.skip_cache + if self.extra: + contents["extra"] = self.extra + return contents + + def _is_artifact_reference(self) -> bool: + return self.ref is not None and urlparse(self.ref).scheme == "wandb-artifact" + + 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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/artifact_saver.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/artifact_saver.py new file mode 100644 index 0000000000000000000000000000000000000000..e163f150060f553cf22ce5dd9916dcc3868d4830 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/artifact_saver.py @@ -0,0 +1,277 @@ +"""Artifact saver.""" + +from __future__ import annotations + +import concurrent.futures +import json +import os +import tempfile +from typing import TYPE_CHECKING, Awaitable, Sequence + +import wandb +import wandb.filesync.step_prepare +from wandb import util +from wandb.sdk.artifacts.artifact_manifest import ArtifactManifest +from wandb.sdk.lib.hashutil import B64MD5, b64_to_hex_id, md5_file_b64 +from wandb.sdk.lib.paths import URIStr + +if TYPE_CHECKING: + from typing import Protocol + + from wandb.sdk.artifacts.artifact_manifest_entry import ArtifactManifestEntry + from wandb.sdk.internal.file_pusher import FilePusher + from wandb.sdk.internal.internal_api import Api as InternalApi + from wandb.sdk.internal.progress import ProgressFn + + class SaveFn(Protocol): + def __call__( + self, entry: ArtifactManifestEntry, progress_callback: ProgressFn + ) -> bool: + pass + + class SaveFnAsync(Protocol): + def __call__( + self, entry: ArtifactManifestEntry, progress_callback: ProgressFn + ) -> Awaitable[bool]: + pass + + +class ArtifactSaver: + _server_artifact: dict | None # TODO better define this dict + + def __init__( + self, + api: InternalApi, + digest: str, + manifest_json: dict, + file_pusher: FilePusher, + is_user_created: bool = False, + ) -> None: + self._api = api + self._file_pusher = file_pusher + self._digest = digest + self._manifest = ArtifactManifest.from_manifest_json( + manifest_json, + api=self._api, + ) + self._is_user_created = is_user_created + self._server_artifact = None + + def save( + self, + entity: str, + project: str, + type: str, + name: str, + client_id: str, + sequence_client_id: str, + distributed_id: str | None = None, + finalize: bool = True, + metadata: dict | None = None, + ttl_duration_seconds: int | None = None, + description: str | None = None, + aliases: Sequence[str] | None = None, + tags: Sequence[str] | None = None, + use_after_commit: bool = False, + incremental: bool = False, + history_step: int | None = None, + base_id: str | None = None, + ) -> dict | None: + return self._save_internal( + entity, + project, + type, + name, + client_id, + sequence_client_id, + distributed_id, + finalize, + metadata, + ttl_duration_seconds, + description, + aliases, + tags, + use_after_commit, + incremental, + history_step, + base_id, + ) + + def _save_internal( + self, + entity: str, + project: str, + type: str, + name: str, + client_id: str, + sequence_client_id: str, + distributed_id: str | None = None, + finalize: bool = True, + metadata: dict | None = None, + ttl_duration_seconds: int | None = None, + description: str | None = None, + aliases: Sequence[str] | None = None, + tags: Sequence[str] | None = None, + use_after_commit: bool = False, + incremental: bool = False, + history_step: int | None = None, + base_id: str | None = None, + ) -> dict | None: + alias_specs = [] + for alias in aliases or []: + alias_specs.append({"artifactCollectionName": name, "alias": alias}) + + tag_specs = [{"tagName": tag} for tag in tags or []] + + """Returns the server artifact.""" + self._server_artifact, latest = self._api.create_artifact( + type, + name, + self._digest, + metadata=metadata, + ttl_duration_seconds=ttl_duration_seconds, + aliases=alias_specs, + tags=tag_specs, + description=description, + is_user_created=self._is_user_created, + distributed_id=distributed_id, + client_id=client_id, + sequence_client_id=sequence_client_id, + history_step=history_step, + ) + + assert self._server_artifact is not None # mypy optionality unwrapper + artifact_id = self._server_artifact["id"] + if base_id is None and latest: + base_id = latest["id"] + if self._server_artifact["state"] == "COMMITTED": + if use_after_commit: + self._api.use_artifact( + artifact_id, + artifact_entity_name=entity, + artifact_project_name=project, + ) + return self._server_artifact + if ( + self._server_artifact["state"] != "PENDING" + # For old servers, see https://github.com/wandb/wandb/pull/6190 + and self._server_artifact["state"] != "DELETED" + ): + raise Exception( + 'Unknown artifact state "{}"'.format(self._server_artifact["state"]) + ) + + manifest_type = "FULL" + manifest_filename = "wandb_manifest.json" + if incremental: + manifest_type = "INCREMENTAL" + manifest_filename = "wandb_manifest.incremental.json" + elif distributed_id: + manifest_type = "PATCH" + manifest_filename = "wandb_manifest.patch.json" + artifact_manifest_id, _ = self._api.create_artifact_manifest( + manifest_filename, + "", + artifact_id, + base_artifact_id=base_id, + include_upload=False, + type=manifest_type, + ) + + step_prepare = wandb.filesync.step_prepare.StepPrepare( + self._api, 0.1, 0.01, 1000 + ) # TODO: params + step_prepare.start() + + # Upload Artifact "L1" files, the actual artifact contents + self._file_pusher.store_manifest_files( + self._manifest, + artifact_id, + lambda entry, progress_callback: self._manifest.storage_policy.store_file( + artifact_id, + artifact_manifest_id, + entry, + step_prepare, + progress_callback=progress_callback, + ), + ) + + def before_commit() -> None: + self._resolve_client_id_manifest_references() + with tempfile.NamedTemporaryFile("w+", suffix=".json", delete=False) as fp: + path = os.path.abspath(fp.name) + json.dump(self._manifest.to_manifest_json(), fp, indent=4) + digest = md5_file_b64(path) + if distributed_id or incremental: + # If we're in the distributed flow, we want to update the + # patch manifest we created with our finalized digest. + _, resp = self._api.update_artifact_manifest( + artifact_manifest_id, + digest=digest, + ) + else: + # In the regular flow, we can recreate the full manifest with the + # updated digest. + # + # NOTE: We do this for backwards compatibility with older backends + # that don't support the 'updateArtifactManifest' API. + _, resp = self._api.create_artifact_manifest( + manifest_filename, + digest, + artifact_id, + base_artifact_id=base_id, + ) + + # We're duplicating the file upload logic a little, which isn't great. + upload_url = resp["uploadUrl"] + upload_headers = resp["uploadHeaders"] + extra_headers = {} + for upload_header in upload_headers: + key, val = upload_header.split(":", 1) + extra_headers[key] = val + with open(path, "rb") as fp2: + self._api.upload_file_retry( + upload_url, + fp2, + extra_headers=extra_headers, + ) + + commit_result: concurrent.futures.Future[None] = concurrent.futures.Future() + + # This will queue the commit. It will only happen after all the file uploads are done + self._file_pusher.commit_artifact( + artifact_id, + finalize=finalize, + before_commit=before_commit, + result_future=commit_result, + ) + + # Block until all artifact files are uploaded and the + # artifact is committed. + try: + commit_result.result() + finally: + step_prepare.shutdown() + + if finalize and use_after_commit: + self._api.use_artifact( + artifact_id, + artifact_entity_name=entity, + artifact_project_name=project, + ) + + return self._server_artifact + + def _resolve_client_id_manifest_references(self) -> None: + for entry_path in self._manifest.entries: + entry = self._manifest.entries[entry_path] + if entry.ref is not None: + if entry.ref.startswith("wandb-client-artifact:"): + client_id = util.host_from_path(entry.ref) + artifact_file_path = util.uri_from_path(entry.ref) + artifact_id = self._api._resolve_client_id(client_id) + if artifact_id is None: + raise RuntimeError(f"Could not resolve client id {client_id}") + entry.ref = URIStr( + f"wandb-artifact://{b64_to_hex_id(B64MD5(artifact_id))}/{artifact_file_path}" + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/artifact_ttl.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/artifact_ttl.py new file mode 100644 index 0000000000000000000000000000000000000000..e63c69031923aa36a2214526443861497f3575d6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/exceptions.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..541d9c7d47b813edf899d7cac9b7d001cabc631f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/exceptions.py @@ -0,0 +1,71 @@ +"""Artifact exceptions.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, TypeVar + +from wandb import errors + +if TYPE_CHECKING: + from wandb.sdk.artifacts.artifact import Artifact + + ArtifactT = TypeVar("ArtifactT", bound=Artifact) + + +class ArtifactStatusError(AttributeError): + """Raised when an artifact is in an invalid state for the requested operation.""" + + def __init__( + self, + msg: str = "Artifact is in an invalid state for the requested operation.", + name: str | None = None, + obj: ArtifactT | None = None, + ): + # Follow the same pattern as AttributeError in python 3.10+ by `name/obj` attributes + # See: https://docs.python.org/3/library/exceptions.html#AttributeError + try: + super().__init__(msg, name=name, obj=obj) + except TypeError: + # The `name`/`obj` keyword args and attributes were only added in python >= 3.10 + super().__init__(msg) + self.name = name or "" + self.obj = obj + + +class ArtifactNotLoggedError(ArtifactStatusError): + """Raised for Artifact methods or attributes only available after logging.""" + + def __init__(self, fullname: str, obj: ArtifactT): + *_, name = fullname.split(".") + msg = ( + f"{fullname!r} used prior to logging artifact or while in offline mode. " + f"Call {type(obj).wait.__qualname__}() 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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/staging.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/staging.py new file mode 100644 index 0000000000000000000000000000000000000000..24a6313ca0507d1f4ee110570c80062644c08cb9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/storage_handler.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/storage_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..0f3abd02c93dd87497fbbfc413dbc9695a259e06 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/storage_handler.py @@ -0,0 +1,62 @@ +"""Storage handler.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Sequence + +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 = 10**7 + + +class StorageHandler: + 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 + + 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 + + def store_path( + self, + artifact: Artifact, + path: URIStr | FilePathStr, + name: str | None = None, + checksum: bool = True, + max_objects: int | None = None, + ) -> Sequence[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 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/storage_policy.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/storage_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..b33beabd42b98184ee39d350458dd1f3efb77973 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/artifacts/storage_policy.py @@ -0,0 +1,75 @@ +"""Storage policy.""" + +from __future__ import annotations + +import concurrent.futures +from typing import TYPE_CHECKING, Sequence + +from wandb.sdk.internal.internal_api import Api as InternalApi +from wandb.sdk.lib.paths import FilePathStr, URIStr + +if TYPE_CHECKING: + from wandb.filesync.step_prepare import StepPrepare + from wandb.sdk.artifacts.artifact import Artifact + from wandb.sdk.artifacts.artifact_manifest_entry import ArtifactManifestEntry + from wandb.sdk.internal.progress import ProgressFn + + +class StoragePolicy: + @classmethod + def lookup_by_name(cls, name: str) -> type[StoragePolicy]: + import wandb.sdk.artifacts.storage_policies # noqa: F401 + + for sub in cls.__subclasses__(): + if sub.name() == name: + return sub + raise NotImplementedError(f"Failed to find storage policy '{name}'") + + @classmethod + def name(cls) -> str: + raise NotImplementedError + + @classmethod + def from_config(cls, config: dict, api: InternalApi | None = None) -> StoragePolicy: + raise NotImplementedError + + def config(self) -> dict: + raise NotImplementedError + + def load_file( + self, + artifact: Artifact, + manifest_entry: ArtifactManifestEntry, + dest_path: str | None = None, + executor: concurrent.futures.Executor | None = None, + multipart: bool | None = None, + ) -> FilePathStr: + raise NotImplementedError + + def store_file( + self, + artifact_id: str, + artifact_manifest_id: str, + entry: ArtifactManifestEntry, + preparer: StepPrepare, + progress_callback: ProgressFn | None = None, + ) -> bool: + raise NotImplementedError + + def store_reference( + self, + artifact: Artifact, + path: URIStr | FilePathStr, + name: str | None = None, + checksum: bool = True, + max_objects: int | None = None, + ) -> Sequence[ArtifactManifestEntry]: + raise NotImplementedError + + def load_reference( + self, + manifest_entry: ArtifactManifestEntry, + local: bool = False, + dest_path: str | None = None, + ) -> FilePathStr | URIStr: + raise NotImplementedError diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/_dtypes.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/_dtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..015b6af0501266264dcf710ce6f883a3c0f7dad9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/_dtypes.py @@ -0,0 +1,914 @@ +import datetime +import math +import typing as t + +from wandb.util import ( + _is_artifact_string, + _is_artifact_version_weave_dict, + get_module, + is_numpy_array, +) + +np = get_module("numpy") # intentionally not required + +if t.TYPE_CHECKING: + from wandb.sdk.artifacts.artifact import Artifact + +ConvertibleToType = t.Union["Type", t.Type["Type"], type, t.Any] + + +class TypeRegistry: + """A resolver for python objects that can deserialize JSON dicts. + + Additional types can be registered via the .add call. + """ + + _types_by_name = None + _types_by_class = None + + @staticmethod + def types_by_name(): + if TypeRegistry._types_by_name is None: + TypeRegistry._types_by_name = {} + return TypeRegistry._types_by_name + + @staticmethod + def types_by_class(): + if TypeRegistry._types_by_class is None: + TypeRegistry._types_by_class = {} + return TypeRegistry._types_by_class + + @staticmethod + def add(wb_type: t.Type["Type"]) -> None: + assert issubclass(wb_type, Type) + TypeRegistry.types_by_name().update({wb_type.name: wb_type}) + for name in wb_type.legacy_names: + TypeRegistry.types_by_name().update({name: wb_type}) + TypeRegistry.types_by_class().update( + {_type: wb_type for _type in wb_type.types} + ) + + @staticmethod + def type_of(py_obj: t.Optional[t.Any]) -> "Type": + # Special case handler for common case of np.nans. np.nan + # is of type 'float', but should be treated as a None. This is + # because np.nan can co-exist with other types in dataframes, + # but will be ultimately treated as a None. Ignoring type since + # mypy does not trust that py_obj is a float by the time it is + # passed to isnan. + if py_obj.__class__ is float and math.isnan(py_obj): # type: ignore + return NoneType() + + # TODO: generalize this to handle other config input types + if _is_artifact_string(py_obj) or _is_artifact_version_weave_dict(py_obj): + return TypeRegistry.types_by_name().get("artifactVersion")() + + class_handler = TypeRegistry.types_by_class().get(py_obj.__class__) + _type = None + if class_handler: + _type = class_handler.from_obj(py_obj) + else: + _type = PythonObjectType.from_obj(py_obj) + return _type + + @staticmethod + def type_from_dict( + json_dict: t.Dict[str, t.Any], artifact: t.Optional["Artifact"] = None + ) -> "Type": + wb_type = json_dict.get("wb_type") + if wb_type is None: + TypeError("json_dict must contain `wb_type` key") + _type = TypeRegistry.types_by_name().get(wb_type) + if _type is None: + TypeError(f"missing type handler for {wb_type}") + return _type.from_json(json_dict, artifact) + + @staticmethod + def type_from_dtype(dtype: ConvertibleToType) -> "Type": + # The dtype is already an instance of Type + if isinstance(dtype, Type): + wbtype: Type = dtype + + # The dtype is a subclass of Type + elif isinstance(dtype, type) and issubclass(dtype, Type): + wbtype = dtype() + + # The dtype is a subclass of generic python type + elif isinstance(dtype, type): + handler = TypeRegistry.types_by_class().get(dtype) + + # and we have a registered handler + if handler: + wbtype = handler() + + # else, fallback to object type + else: + wbtype = PythonObjectType.from_obj(dtype) + + # The dtype is a list, then we resolve the list notation + elif isinstance(dtype, list): + if len(dtype) == 0: + wbtype = ListType() + elif len(dtype) == 1: + wbtype = ListType(TypeRegistry.type_from_dtype(dtype[0])) + + # lists of more than 1 are treated as unions + else: + wbtype = UnionType([TypeRegistry.type_from_dtype(dt) for dt in dtype]) + + # The dtype is a dict, then we resolve the dict notation + elif isinstance(dtype, dict): + wbtype = TypedDictType( + {key: TypeRegistry.type_from_dtype(dtype[key]) for key in dtype} + ) + + # The dtype is a concrete instance, which we will treat as a constant + else: + wbtype = ConstType(dtype) + + return wbtype + + +def _params_obj_to_json_obj( + params_obj: t.Any, + artifact: t.Optional["Artifact"] = None, +) -> t.Any: + """Helper method.""" + if params_obj.__class__ is dict: + return { + key: _params_obj_to_json_obj(params_obj[key], artifact) + for key in params_obj + } + elif params_obj.__class__ in [list, set, tuple, frozenset]: + return [_params_obj_to_json_obj(item, artifact) for item in list(params_obj)] + elif isinstance(params_obj, Type): + return params_obj.to_json(artifact) + else: + return params_obj + + +def _json_obj_to_params_obj( + json_obj: t.Any, artifact: t.Optional["Artifact"] = None +) -> t.Any: + """Helper method.""" + if json_obj.__class__ is dict: + if "wb_type" in json_obj: + return TypeRegistry.type_from_dict(json_obj, artifact) + else: + return { + key: _json_obj_to_params_obj(json_obj[key], artifact) + for key in json_obj + } + elif json_obj.__class__ is list: + return [_json_obj_to_params_obj(item, artifact) for item in json_obj] + else: + return json_obj + + +class Type: + """The most generic type that all types subclass. + + It provides simple serialization and deserialization as well as equality checks. + A name class-level property must be uniquely set by subclasses. + """ + + # Subclasses must override with a unique name. This is used to identify the + # class during serializations and deserializations + name: t.ClassVar[str] = "" + + # List of names by which this class can deserialize + legacy_names: t.ClassVar[t.List[str]] = [] + + # Subclasses may override with a list of `types` which this Type is capable + # of being initialized. This is used by the Type Registry when calling `TypeRegistry.type_of`. + # Some types will have an empty list - for example `Union`. There is no raw python type which + # inherently maps to a Union and therefore the list should be empty. + types: t.ClassVar[t.List[type]] = [] + + # Contains the further specification of the Type + _params: t.Dict[str, t.Any] + + def __init__(*args, **kwargs): + pass + + @property + def params(self): + if not hasattr(self, "_params") or self._params is None: + self._params = {} + return self._params + + def assign(self, py_obj: t.Optional[t.Any] = None) -> "Type": + """Assign a python object to the type. + + May to be overridden by subclasses + + Args: + py_obj (any, optional): Any python object which the user wishes to assign to + this type + + Returns: + Type: a new type representing the result of the assignment. + """ + return self.assign_type(TypeRegistry.type_of(py_obj)) + + def assign_type(self, wb_type: "Type") -> "Type": + # Default - should be overridden + if isinstance(wb_type, self.__class__) and self.params == wb_type.params: + return self + else: + return InvalidType() + + def to_json(self, artifact: t.Optional["Artifact"] = None) -> t.Dict[str, t.Any]: + """Generate a jsonable dictionary serialization the type. + + If overridden by subclass, ensure that `from_json` is equivalently overridden. + + Args: + artifact (wandb.Artifact, optional): If the serialization is being performed + for a particular artifact, pass that artifact. Defaults to None. + + Returns: + dict: Representation of the type + """ + res = { + "wb_type": self.name, + "params": _params_obj_to_json_obj(self.params, artifact), + } + if res["params"] is None or res["params"] == {}: + del res["params"] + + return res + + @classmethod + def from_json( + cls, + json_dict: t.Dict[str, t.Any], + artifact: t.Optional["Artifact"] = None, + ) -> "Type": + """Construct a new instance of the type using a JSON dictionary. + + The mirror function of `to_json`. If overridden by subclass, ensure that + `to_json` is equivalently overridden. + + Returns: + _Type: an instance of a subclass of the _Type class. + """ + return cls(**_json_obj_to_params_obj(json_dict.get("params", {}), artifact)) + + @classmethod + def from_obj(cls, py_obj: t.Optional[t.Any] = None) -> "Type": + return cls() + + def explain(self, other: t.Any, depth=0) -> str: + """Explain why an item is not assignable to a type. + + Assumes that the caller has already validated that the assignment fails. + + Args: + other (any): Any object depth (int, optional): depth of the type checking. + Defaults to 0. + + Returns: + str: human-readable explanation + """ + wbtype = TypeRegistry.type_of(other) + gap = "".join(["\t"] * depth) + if depth > 0: + return f"{gap}{wbtype} not assignable to {self}" + else: + return f"{gap}{other} of type {wbtype} is not assignable to {self}" + + def __repr__(self): + rep = self.name.capitalize() + if len(self.params.keys()) > 0: + rep += "(" + for ndx, key in enumerate(self.params.keys()): + if ndx > 0: + rep += ", " + rep += key + ":" + str(self.params[key]) + rep += ")" + return rep + + def __eq__(self, other): + return self is other or ( + isinstance(self, Type) + and isinstance(other, Type) + and self.name == other.name + and self.params.keys() == other.params.keys() + and all([self.params[k] == other.params[k] for k in self.params]) + ) + + +class InvalidType(Type): + """A disallowed type. + + Assignments to a InvalidType result in a Never Type. InvalidType is basically the + invalid case. + """ + + name = "invalid" + types: t.ClassVar[t.List[type]] = [] + + def assign_type(self, wb_type: "Type") -> "InvalidType": + return self + + +class AnyType(Type): + """An object that can be any type. + + Assignments to an AnyType result in the AnyType except None which results in an + InvalidType. + """ + + name = "any" + types: t.ClassVar[t.List[type]] = [] + + def assign_type(self, wb_type: "Type") -> t.Union["AnyType", InvalidType]: + return ( + self + if not (isinstance(wb_type, NoneType) or isinstance(wb_type, InvalidType)) + else InvalidType() + ) + + +class UnknownType(Type): + """An object with an unknown type. + + All assignments to an UnknownType result in the type of the assigned object except + `None` which results in a InvalidType. + """ + + name = "unknown" + types: t.ClassVar[t.List[type]] = [] + + def assign_type(self, wb_type: "Type") -> "Type": + return wb_type if not isinstance(wb_type, NoneType) else InvalidType() + + +class NoneType(Type): + name = "none" + types: t.ClassVar[t.List[type]] = [None.__class__] + + +class StringType(Type): + name = "string" + types: t.ClassVar[t.List[type]] = [str] + + +class NumberType(Type): + name = "number" + types: t.ClassVar[t.List[type]] = [int, float] + + +if np: + NumberType.types.append(np.byte) + NumberType.types.append(np.short) + NumberType.types.append(np.ushort) + NumberType.types.append(np.intc) + NumberType.types.append(np.uintc) + NumberType.types.append(np.int_) + NumberType.types.append(np.uint) + NumberType.types.append(np.longlong) + NumberType.types.append(np.ulonglong) + NumberType.types.append(np.half) + NumberType.types.append(np.float16) + NumberType.types.append(np.single) + NumberType.types.append(np.double) + NumberType.types.append(np.longdouble) + NumberType.types.append(np.csingle) + NumberType.types.append(np.cdouble) + NumberType.types.append(np.clongdouble) + NumberType.types.append(np.int8) + NumberType.types.append(np.int16) + NumberType.types.append(np.int32) + NumberType.types.append(np.int64) + NumberType.types.append(np.uint8) + NumberType.types.append(np.uint16) + NumberType.types.append(np.uint32) + NumberType.types.append(np.uint64) + NumberType.types.append(np.intp) + NumberType.types.append(np.uintp) + NumberType.types.append(np.float32) + NumberType.types.append(np.float64) + NumberType.types.append(np.complex64) + NumberType.types.append(np.complex128) + + numpy_major_version = np.__version__.split(".")[0] + if int(numpy_major_version) < 2: + NumberType.types.append(np.float_) + NumberType.types.append(np.complex_) + + +class TimestampType(Type): + name = "timestamp" + types: t.ClassVar[t.List[type]] = [datetime.datetime, datetime.date] + + +if np: + TimestampType.types.append(np.datetime64) + + +class BooleanType(Type): + name = "boolean" + types: t.ClassVar[t.List[type]] = [bool] + + +if np: + BooleanType.types.append(np.bool_) + + +class PythonObjectType(Type): + """A backup type that keeps track of the python object name.""" + + name = "pythonObject" + legacy_names = ["object"] + types: t.ClassVar[t.List[type]] = [] + + def __init__(self, class_name: str): + self.params.update({"class_name": class_name}) + + @classmethod + def from_obj(cls, py_obj: t.Optional[t.Any] = None) -> "PythonObjectType": + return cls(py_obj.__class__.__name__) + + +class ConstType(Type): + """A constant value (currently only primitives supported).""" + + name = "const" + types: t.ClassVar[t.List[type]] = [] + + def __init__(self, val: t.Optional[t.Any] = None, is_set: t.Optional[bool] = False): + if val.__class__ not in [str, int, float, bool, set, list, None.__class__]: + TypeError( + f"ConstType only supports str, int, float, bool, set, list, and None types. Found {val}" + ) + if is_set or isinstance(val, set): + is_set = True + assert isinstance(val, set) or isinstance(val, list) + val = set(val) + + self.params.update({"val": val, "is_set": is_set}) + + def assign(self, py_obj: t.Optional[t.Any] = None) -> "Type": + return self.assign_type(ConstType(py_obj)) + + @classmethod + def from_obj(cls, py_obj: t.Optional[t.Any] = None) -> "ConstType": + return cls(py_obj) + + def __repr__(self): + return str(self.params["val"]) + + +def _flatten_union_types(wb_types: t.List[Type]) -> t.List[Type]: + final_types = [] + for allowed_type in wb_types: + if isinstance(allowed_type, UnionType): + internal_types = _flatten_union_types(allowed_type.params["allowed_types"]) + for internal_type in internal_types: + final_types.append(internal_type) + else: + final_types.append(allowed_type) + return final_types + + +def _union_assigner( + allowed_types: t.List[Type], + obj_or_type: t.Union[Type, t.Optional[t.Any]], + type_mode=False, +) -> t.Union[t.List[Type], InvalidType]: + resolved_types = [] + valid = False + unknown_count = 0 + + for allowed_type in allowed_types: + if valid: + resolved_types.append(allowed_type) + else: + if isinstance(allowed_type, UnknownType): + unknown_count += 1 + else: + if type_mode: + assert isinstance(obj_or_type, Type) + assigned_type = allowed_type.assign_type(obj_or_type) + else: + assigned_type = allowed_type.assign(obj_or_type) + if isinstance(assigned_type, InvalidType): + resolved_types.append(allowed_type) + else: + resolved_types.append(assigned_type) + valid = True + + if not valid: + if unknown_count == 0: + return InvalidType() + else: + if type_mode: + assert isinstance(obj_or_type, Type) + new_type = obj_or_type + else: + new_type = UnknownType().assign(obj_or_type) + if isinstance(new_type, InvalidType): + return InvalidType() + else: + resolved_types.append(new_type) + unknown_count -= 1 + + for _ in range(unknown_count): + resolved_types.append(UnknownType()) + + resolved_types = _flatten_union_types(resolved_types) + resolved_types.sort(key=str) + return resolved_types + + +class UnionType(Type): + """An "or" of types.""" + + name = "union" + types: t.ClassVar[t.List[type]] = [] + + def __init__( + self, + allowed_types: t.Optional[t.Sequence[ConvertibleToType]] = None, + ): + assert allowed_types is None or (allowed_types.__class__ is list) + if allowed_types is None: + wb_types = [] + else: + wb_types = [TypeRegistry.type_from_dtype(dt) for dt in allowed_types] + + wb_types = _flatten_union_types(wb_types) + wb_types.sort(key=str) + self.params.update({"allowed_types": wb_types}) + + def assign( + self, py_obj: t.Optional[t.Any] = None + ) -> t.Union["UnionType", InvalidType]: + resolved_types = _union_assigner( + self.params["allowed_types"], py_obj, type_mode=False + ) + if isinstance(resolved_types, InvalidType): + return InvalidType() + return self.__class__(resolved_types) + + def assign_type(self, wb_type: "Type") -> t.Union["UnionType", InvalidType]: + if isinstance(wb_type, UnionType): + assignees = wb_type.params["allowed_types"] + else: + assignees = [wb_type] + + resolved_types = self.params["allowed_types"] + for assignee in assignees: + resolved_types = _union_assigner(resolved_types, assignee, type_mode=True) + if isinstance(resolved_types, InvalidType): + return InvalidType() + + return self.__class__(resolved_types) + + def explain(self, other: t.Any, depth=0) -> str: + exp = super().explain(other, depth) + for ndx, subtype in enumerate(self.params["allowed_types"]): + if ndx > 0: + exp += "\n{}and".format("".join(["\t"] * depth)) + exp += "\n" + subtype.explain(other, depth=depth + 1) + return exp + + def __repr__(self): + return "{}".format(" or ".join([str(t) for t in self.params["allowed_types"]])) + + +def OptionalType(dtype: ConvertibleToType) -> UnionType: # noqa: N802 + """Function that mimics the Type class API for constructing an "Optional Type". + + This is just a Union[wb_type, NoneType]. + + Args: + dtype (Type): type to be optional + + Returns: + Type: Optional version of the type. + """ + return UnionType([TypeRegistry.type_from_dtype(dtype), NoneType()]) + + +class ListType(Type): + """A list of homogeneous types.""" + + name = "list" + types: t.ClassVar[t.List[type]] = [list, tuple, set, frozenset] + + def __init__( + self, + element_type: t.Optional[ConvertibleToType] = None, + length: t.Optional[int] = None, + ): + if element_type is None: + wb_type: Type = UnknownType() + else: + wb_type = TypeRegistry.type_from_dtype(element_type) + + self.params.update({"element_type": wb_type, "length": length}) + + @classmethod + def from_obj(cls, py_obj: t.Optional[t.Any] = None) -> "ListType": + if py_obj is None or not hasattr(py_obj, "__iter__"): + raise TypeError("ListType.from_obj expects py_obj to by list-like") + else: + if hasattr(py_obj, "tolist"): + py_list = py_obj.tolist() + else: + py_list = list(py_obj) + + elm_type: Type + if None not in py_list: + elm_type = UnknownType() + else: + elm_type = OptionalType(UnknownType()) + + for item in py_list: + _elm_type = elm_type.assign(item) + # Commenting this out since we don't want to crash user code at this point, but rather + # retain an invalid internal list type. + # if isinstance(_elm_type, InvalidType): + # raise TypeError( + # "List contained incompatible types. Item at index {}: \n{}".format( + # ndx, elm_type.explain(item, 1) + # ) + # ) + + elm_type = _elm_type + + return cls(elm_type, len(py_list)) + + def assign_type(self, wb_type: "Type") -> t.Union["ListType", InvalidType]: + if isinstance(wb_type, ListType): + assigned_type = self.params["element_type"].assign_type( + wb_type.params["element_type"] + ) + if not isinstance(assigned_type, InvalidType): + return ListType( + assigned_type, + None + if self.params["length"] != wb_type.params["length"] + else self.params["length"], + ) + + return InvalidType() + + def assign( + self, py_obj: t.Optional[t.Any] = None + ) -> t.Union["ListType", InvalidType]: + if hasattr(py_obj, "__iter__"): + new_element_type = self.params["element_type"] + # The following ignore is needed since the above hasattr(py_obj, "__iter__") enforces iteration + # error: Argument 1 to "list" has incompatible type "Optional[Any]"; expected "Iterable[Any]" + py_list = list(py_obj) # type: ignore + for obj in py_list: + new_element_type = new_element_type.assign(obj) + if isinstance(new_element_type, InvalidType): + return InvalidType() + return ListType(new_element_type, len(py_list)) + + return InvalidType() + + def explain(self, other: t.Any, depth=0) -> str: + exp = super().explain(other, depth) + gap = "".join(["\t"] * depth) + if ( # yes, this is a bit verbose, but the mypy typechecker likes it this way + isinstance(other, list) + or isinstance(other, tuple) + or isinstance(other, set) + or isinstance(other, frozenset) + ): + new_element_type = self.params["element_type"] + for ndx, obj in enumerate(list(other)): + _new_element_type = new_element_type.assign(obj) + if isinstance(_new_element_type, InvalidType): + exp += f"\n{gap}Index {ndx}:\n{new_element_type.explain(obj, depth + 1)}" + break + new_element_type = _new_element_type + return exp + + def __repr__(self): + return "{}[]".format(self.params["element_type"]) + + +class NDArrayType(Type): + """Represents a list of homogeneous types.""" + + name = "ndarray" + types: t.ClassVar[t.List[type]] = [] # will manually add type if np is available + _serialization_path: t.Optional[t.Dict[str, str]] + + def __init__( + self, + shape: t.Sequence[int], + serialization_path: t.Optional[t.Dict[str, str]] = None, + ): + self.params.update({"shape": list(shape)}) + self._serialization_path = serialization_path + + @classmethod + def from_obj(cls, py_obj: t.Optional[t.Any] = None) -> "NDArrayType": + if is_numpy_array(py_obj): + return cls(py_obj.shape) # type: ignore + elif isinstance(py_obj, list): + shape = [] + target = py_obj + while isinstance(target, list): + dim = len(target) + shape.append(dim) + if dim > 0: + target = target[0] + return cls(shape) + else: + raise TypeError( + f"NDArrayType.from_obj expects py_obj to be ndarray or list, found {py_obj.__class__}" + ) + + def assign_type(self, wb_type: "Type") -> t.Union["NDArrayType", InvalidType]: + if ( + isinstance(wb_type, NDArrayType) + and self.params["shape"] == wb_type.params["shape"] + ): + return self + elif isinstance(wb_type, ListType): + # Should we return error here? + return self + + return InvalidType() + + def assign( + self, py_obj: t.Optional[t.Any] = None + ) -> t.Union["NDArrayType", InvalidType]: + if is_numpy_array(py_obj) or isinstance(py_obj, list): + py_type = self.from_obj(py_obj) + return self.assign_type(py_type) + + return InvalidType() + + def to_json(self, artifact: t.Optional["Artifact"] = None) -> t.Dict[str, t.Any]: + # custom override to support serialization path outside of params internal dict + res = { + "wb_type": self.name, + "params": { + "shape": self.params["shape"], + "serialization_path": self._serialization_path, + }, + } + + return res + + def _get_serialization_path(self) -> t.Optional[t.Dict[str, str]]: + return self._serialization_path + + def _set_serialization_path(self, path: str, key: str) -> None: + self._serialization_path = {"path": path, "key": key} + + def _clear_serialization_path(self) -> None: + self._serialization_path = None + + +if np: + NDArrayType.types.append(np.ndarray) + +# class KeyPolicy: +# EXACT = "E" # require exact key match +# SUBSET = "S" # all known keys are optional and unknown keys are disallowed +# UNRESTRICTED = "U" # all known keys are optional and unknown keys are Unknown + + +class TypedDictType(Type): + """Represents a dictionary object where each key can have a type.""" + + name = "typedDict" + legacy_names = ["dictionary"] + types: t.ClassVar[t.List[type]] = [dict] + + def __init__( + self, + type_map: t.Optional[t.Dict[str, ConvertibleToType]] = None, + ): + if type_map is None: + type_map = {} + self.params.update( + { + "type_map": { + key: TypeRegistry.type_from_dtype(type_map[key]) for key in type_map + } + } + ) + + @classmethod + def from_obj(cls, py_obj: t.Optional[t.Any] = None) -> "TypedDictType": + if not isinstance(py_obj, dict): + TypeError("TypedDictType.from_obj expects a dictionary") + + assert isinstance(py_obj, dict) # helps mypy type checker + return cls({key: TypeRegistry.type_of(py_obj[key]) for key in py_obj}) + + def assign_type(self, wb_type: "Type") -> t.Union["TypedDictType", InvalidType]: + if ( + isinstance(wb_type, TypedDictType) + and len( + set(wb_type.params["type_map"].keys()) + - set(self.params["type_map"].keys()) + ) + == 0 + ): + type_map = {} + for key in self.params["type_map"]: + type_map[key] = self.params["type_map"][key].assign_type( + wb_type.params["type_map"].get(key, UnknownType()) + ) + if isinstance(type_map[key], InvalidType): + return InvalidType() + return TypedDictType(type_map) + + return InvalidType() + + def assign( + self, py_obj: t.Optional[t.Any] = None + ) -> t.Union["TypedDictType", InvalidType]: + if ( + isinstance(py_obj, dict) + and len(set(py_obj.keys()) - set(self.params["type_map"].keys())) == 0 + ): + type_map = {} + for key in self.params["type_map"]: + type_map[key] = self.params["type_map"][key].assign( + py_obj.get(key, None) + ) + if isinstance(type_map[key], InvalidType): + return InvalidType() + return TypedDictType(type_map) + + return InvalidType() + + def explain(self, other: t.Any, depth=0) -> str: + exp = super().explain(other, depth) + gap = "".join(["\t"] * depth) + if isinstance(other, dict): + extra_keys = set(other.keys()) - set(self.params["type_map"].keys()) + if len(extra_keys) > 0: + exp += "\n{}Found extra keys: {}".format( + gap, ",".join(list(extra_keys)) + ) + + for key in self.params["type_map"]: + val = other.get(key, None) + if isinstance(self.params["type_map"][key].assign(val), InvalidType): + exp += "\n{}Key '{}':\n{}".format( + gap, + key, + self.params["type_map"][key].explain(val, depth=depth + 1), + ) + return exp + + def __repr__(self): + return "{}".format(self.params["type_map"]) + + +# Special Types +TypeRegistry.add(InvalidType) +TypeRegistry.add(AnyType) +TypeRegistry.add(UnknownType) + +# Types with default type mappings +TypeRegistry.add(NoneType) +TypeRegistry.add(StringType) +TypeRegistry.add(TimestampType) +TypeRegistry.add(NumberType) +TypeRegistry.add(BooleanType) +TypeRegistry.add(ListType) +TypeRegistry.add(TypedDictType) + +# Types without default type mappings +TypeRegistry.add(UnionType) +TypeRegistry.add(PythonObjectType) +TypeRegistry.add(ConstType) + +# Common Industry Types +TypeRegistry.add(NDArrayType) + +__all__ = [ + "TypeRegistry", + "InvalidType", + "UnknownType", + "AnyType", + "NoneType", + "StringType", + "NumberType", + "TimestampType", + "BooleanType", + "ListType", + "TypedDictType", + "UnionType", + "PythonObjectType", + "ConstType", + "OptionalType", + "Type", + "NDArrayType", +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/_private.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/_private.py new file mode 100644 index 0000000000000000000000000000000000000000..887bc8a231014d06dbe65590663064ec792eeb84 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/bokeh.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/bokeh.py new file mode 100644 index 0000000000000000000000000000000000000000..dfaf6307e1107e3a07a866076731da2edfd94a63 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/bokeh.py @@ -0,0 +1,87 @@ +import codecs +import json +import os +import pathlib +from typing import TYPE_CHECKING, Union + +from wandb import util +from wandb.sdk.lib import runid + +from . import _dtypes +from ._private import MEDIA_TMP +from .base_types.media import Media + +if TYPE_CHECKING: + from bokeh import document, model + + +class Bokeh(Media): + """Wandb class for Bokeh plots. + + Args: + val: Bokeh plot + """ + + _log_type = "bokeh-file" + + def __init__( + self, + data_or_path: Union[ + str, + pathlib.Path, + "document.Document", + "model.Model", + ], + ): + super().__init__() + bokeh = util.get_module("bokeh", required=True) + if isinstance(data_or_path, (str, pathlib.Path)) and os.path.exists( + data_or_path + ): + data_or_path = str(data_or_path) + + with open(data_or_path) as file: + b_json = json.load(file) + self.b_obj = bokeh.document.Document.from_json(b_json) + self._set_file(data_or_path, is_tmp=False, extension=".bokeh.json") + elif isinstance(data_or_path, bokeh.model.Model): + _data = bokeh.document.Document() + _data.add_root(data_or_path) + # serialize/deserialize pairing followed by sorting attributes ensures + # that the file's sha's are equivalent in subsequent calls + self.b_obj = bokeh.document.Document.from_json(_data.to_json()) + b_json = self.b_obj.to_json() + if "references" in b_json["roots"]: + b_json["roots"]["references"].sort(key=lambda x: x["id"]) + + tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ".bokeh.json") + with codecs.open(tmp_path, "w", encoding="utf-8") as fp: + util.json_dump_safer(b_json, fp) + self._set_file(tmp_path, is_tmp=True, extension=".bokeh.json") + elif not isinstance(data_or_path, bokeh.document.Document): + raise TypeError( + "Bokeh constructor accepts Bokeh document/model or path to Bokeh json file" + ) + + def get_media_subdir(self): + return os.path.join("media", "bokeh") + + def to_json(self, run): + # TODO: (tss) this is getting redundant for all the media objects. We can probably + # pull this into Media#to_json and remove this type override for all the media types. + # There are only a few cases where the type is different between artifacts and runs. + json_dict = super().to_json(run) + json_dict["_type"] = self._log_type + return json_dict + + @classmethod + def from_json(cls, json_obj, source_artifact): + return cls(source_artifact.get_entry(json_obj["path"]).download()) + + +class _BokehFileType(_dtypes.Type): + name = "bokeh-file" + types = [Bokeh] + + +_dtypes.TypeRegistry.add(_BokehFileType) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/graph.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/graph.py new file mode 100644 index 0000000000000000000000000000000000000000..bc59f31f51b48406cc4dd80ad8f2f5c71f438fbb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/html.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/html.py new file mode 100644 index 0000000000000000000000000000000000000000..8eb79416ebe08e1e150f152e8baef112cf56a9cc --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/html.py @@ -0,0 +1,165 @@ +import os +import pathlib +from typing import TYPE_CHECKING, Sequence, Type, Union + +from wandb.sdk.lib import filesystem, runid + +from . import _dtypes +from ._private import MEDIA_TMP +from .base_types.media import BatchableMedia + +if TYPE_CHECKING: # pragma: no cover + from typing import TextIO + + from wandb.sdk.artifacts.artifact import Artifact + + from ..wandb_run import Run as LocalRun + + +class Html(BatchableMedia): + """W&B class for logging HTML content to W&B.""" + + _log_type = "html-file" + + def __init__( + self, + data: Union[str, pathlib.Path, "TextIO"], + inject: bool = True, + data_is_not_path: bool = False, + ) -> None: + """Creates a W&B HTML object. + + Args: + data: + A string that is a path to a file with the extension ".html", + or a string or IO object containing literal HTML. + inject: Add a stylesheet to the HTML object. If set + to False the HTML will pass through unchanged. + data_is_not_path: If set to False, the data will be + treated as a path to a file. + + Examples: + It can be initialized by providing a path to a file: + + ```python + with wandb.init() as run: + run.log({"html": wandb.Html("./index.html")}) + ``` + + Alternatively, it can be initialized by providing literal HTML, + in either a string or IO object: + + ```python + with wandb.init() as run: + run.log({"html": wandb.Html("

Hello, world!

")}) + ``` + """ + super().__init__() + data_is_path = ( + isinstance(data, (str, pathlib.Path)) + and os.path.isfile(data) + and os.path.splitext(data)[1] == ".html" + ) and not data_is_not_path + data_path = "" + if data_is_path: + data_path = str(data) + with open(data_path, encoding="utf-8") as file: + self.html = file.read() + elif isinstance(data, str): + self.html = data + elif hasattr(data, "read"): + if hasattr(data, "seek"): + data.seek(0) + self.html = data.read() + else: + raise ValueError("data must be a string or an io object") + + if inject: + self.inject_head() + + if inject or not data_is_path: + tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ".html") + with open(tmp_path, "w", encoding="utf-8") as out: + out.write(self.html) + + self._set_file(tmp_path, is_tmp=True) + else: + self._set_file(data_path, is_tmp=False) + + def inject_head(self) -> None: + """Inject a tag into the HTML. + + + """ + join = "" + if "" in self.html: + parts = self.html.split("", 1) + parts[0] = parts[0] + "" + elif "" in self.html: + parts = self.html.split("", 1) + parts[0] = parts[0] + "" + parts[1] = "" + parts[1] + else: + parts = ["", self.html] + parts.insert( + 1, + '', + ) + self.html = join.join(parts).strip() + + @classmethod + def get_media_subdir(cls: Type["Html"]) -> str: + """Get media subdirectory. + + " + """ + return os.path.join("media", "html") + + def to_json(self, run_or_artifact: Union["LocalRun", "Artifact"]) -> dict: + """Returns the JSON representation expected by the backend. + + + """ + json_dict = super().to_json(run_or_artifact) + json_dict["_type"] = self._log_type + return json_dict + + @classmethod + def from_json( + cls: Type["Html"], json_obj: dict, source_artifact: "Artifact" + ) -> "Html": + """Deserialize a JSON object into it's class representation. + + " + """ + return cls(source_artifact.get_entry(json_obj["path"]).download(), inject=False) + + @classmethod + def seq_to_json( + cls: Type["Html"], + seq: Sequence["BatchableMedia"], + run: "LocalRun", + key: str, + step: Union[int, str], + ) -> dict: + """Convert a sequence of HTML objects to a JSON representation. + + " + """ + base_path = os.path.join(run.dir, cls.get_media_subdir()) + filesystem.mkdir_exists_ok(base_path) + + meta = { + "_type": "html", + "count": len(seq), + "html": [h.to_json(run) for h in seq], + } + return meta + + +class _HtmlFileType(_dtypes.Type): + name = "html-file" + types = [Html] + + +_dtypes.TypeRegistry.add(_HtmlFileType) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/image.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/image.py new file mode 100644 index 0000000000000000000000000000000000000000..52aeb7a09e629c12ba1ad58651ed79b57819ccdc --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/image.py @@ -0,0 +1,974 @@ +import hashlib +import logging +import os +import pathlib +from io import BytesIO +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Type, Union, cast +from urllib import parse + +from packaging.version import parse as parse_version + +import wandb +from wandb import util +from wandb.sdk.lib import hashutil, runid +from wandb.sdk.lib.paths import LogicalPath + +from . import _dtypes +from ._private import MEDIA_TMP +from .base_types.media import BatchableMedia, Media +from .helper_types.bounding_boxes_2d import BoundingBoxes2D +from .helper_types.classes import Classes +from .helper_types.image_mask import ImageMask + +if TYPE_CHECKING: # pragma: no cover + import matplotlib # type: ignore + import numpy as np + import torch # type: ignore + from PIL.Image import Image as PILImage + + from wandb.sdk.artifacts.artifact import Artifact + + ImageDataType = Union[ + "matplotlib.artist.Artist", "PILImage", "TorchTensorType", "np.ndarray" + ] + ImageDataOrPathType = Union[str, pathlib.Path, "Image", ImageDataType] + TorchTensorType = Union["torch.Tensor", "torch.Variable"] + + +def _warn_on_invalid_data_range( + data: "np.ndarray", + normalize: bool = True, +) -> None: + if not normalize: + return + + np = util.get_module( + "numpy", + required="wandb.Image requires numpy if not supplying PIL Images: pip install numpy", + ) + + if np.min(data) < 0 or np.max(data) > 255: + wandb.termwarn( + "Data passed to `wandb.Image` should consist of values in the range [0, 255], " + "image data will be normalized to this range, " + "but behavior will be removed in a future version of wandb.", + repeat=False, + ) + + +def _guess_and_rescale_to_0_255(data: "np.ndarray") -> "np.ndarray": + """Guess the image's format and rescale its values to the range [0, 255]. + + This is an unfortunate design flaw carried forward for backward + compatibility. A better design would have been to document the expected + data format and not mangle the data provided by the user. + + If given data in the range [0, 1], we multiply all values by 255 + and round down to get integers. + + If given data in the range [-1, 1], we rescale it by mapping -1 to 0 and + 1 to 255, then round down to get integers. + + We clip and round all other data. + """ + try: + import numpy as np + except ImportError: + raise wandb.Error( + "wandb.Image requires numpy if not supplying PIL images: pip install numpy" + ) from None + + data_min: float = data.min() + data_max: float = data.max() + + if 0 <= data_min and data_max <= 1: + return (data * 255).astype(np.uint8) + + elif -1 <= data_min and data_max <= 1: + return (255 * 0.5 * (data + 1)).astype(np.uint8) + + else: + return data.clip(0, 255).astype(np.uint8) + + +def _convert_to_uint8(data: "np.ndarray") -> "np.ndarray": + np = util.get_module( + "numpy", + required="wandb.Image requires numpy if not supplying PIL Images: pip install numpy", + ) + return data.astype(np.uint8) + + +def _server_accepts_image_filenames(run: "wandb.Run") -> bool: + if run.offline: + return True + + # Newer versions of wandb accept large image filenames arrays + # but older versions would have issues with this. + max_cli_version = util._get_max_cli_version() + if max_cli_version is None: + return False + + accepts_image_filenames: bool = parse_version(max_cli_version) >= parse_version( + "0.12.10" + ) + return accepts_image_filenames + + +def _server_accepts_artifact_path(run: "wandb.Run") -> bool: + if run.offline: + return False + + max_cli_version = util._get_max_cli_version() + if max_cli_version is None: + return False + + return parse_version(max_cli_version) >= parse_version("0.12.14") + + +class Image(BatchableMedia): + """A class for logging images to W&B.""" + + MAX_ITEMS = 108 + + # PIL limit + MAX_DIMENSION = 65500 + + _log_type = "image-file" + + format: Optional[str] + _grouping: Optional[int] + _caption: Optional[str] + _width: Optional[int] + _height: Optional[int] + _image: Optional["PILImage"] + _classes: Optional["Classes"] + _boxes: Optional[Dict[str, "BoundingBoxes2D"]] + _masks: Optional[Dict[str, "ImageMask"]] + _file_type: Optional[str] + + def __init__( + self, + data_or_path: "ImageDataOrPathType", + mode: Optional[str] = None, + caption: Optional[str] = None, + grouping: Optional[int] = None, + classes: Optional[Union["Classes", Sequence[dict]]] = None, + boxes: Optional[Union[Dict[str, "BoundingBoxes2D"], Dict[str, dict]]] = None, + masks: Optional[Union[Dict[str, "ImageMask"], Dict[str, dict]]] = None, + file_type: Optional[str] = None, + normalize: bool = True, + ) -> None: + """Initialize a `wandb.Image` object. + + Args: + data_or_path: Accepts NumPy array/pytorch tensor of image data, + a PIL image object, or a path to an image file. If a NumPy + array or pytorch tensor is provided, + the image data will be saved to the given file type. + If the values are not in the range [0, 255] or all values are in the range [0, 1], + the image pixel values will be normalized to the range [0, 255] + unless `normalize` is set to False. + - pytorch tensor should be in the format (channel, height, width) + - NumPy array should be in the format (height, width, channel) + mode: The PIL mode for an image. Most common are "L", "RGB", + "RGBA". Full explanation at https://pillow.readthedocs.io/en/stable/handbook/concepts.html#modes + caption: Label for display of image. + grouping: The grouping number for the image. + classes: A list of class information for the image, + used for labeling bounding boxes, and image masks. + boxes: A dictionary containing bounding box information for the image. + see: https://docs.wandb.ai/ref/python/data-types/boundingboxes2d/ + masks: A dictionary containing mask information for the image. + see: https://docs.wandb.ai/ref/python/data-types/imagemask/ + file_type: The file type to save the image as. + This parameter has no effect if data_or_path is a path to an image file. + normalize: If True, normalize the image pixel values to fall within the range of [0, 255]. + Normalize is only applied if data_or_path is a numpy array or pytorch tensor. + + Examples: + Create a wandb.Image from a numpy array + + ```python + import numpy as np + import wandb + + with wandb.init() as run: + examples = [] + for i in range(3): + pixels = np.random.randint(low=0, high=256, size=(100, 100, 3)) + image = wandb.Image(pixels, caption=f"random field {i}") + examples.append(image) + run.log({"examples": examples}) + ``` + + Create a wandb.Image from a PILImage + + ```python + import numpy as np + from PIL import Image as PILImage + import wandb + + with wandb.init() as run: + examples = [] + for i in range(3): + pixels = np.random.randint( + low=0, high=256, size=(100, 100, 3), dtype=np.uint8 + ) + pil_image = PILImage.fromarray(pixels, mode="RGB") + image = wandb.Image(pil_image, caption=f"random field {i}") + examples.append(image) + run.log({"examples": examples}) + ``` + + Log .jpg rather than .png (default) + + ```python + import numpy as np + import wandb + + with wandb.init() as run: + examples = [] + for i in range(3): + pixels = np.random.randint(low=0, high=256, size=(100, 100, 3)) + image = wandb.Image( + pixels, caption=f"random field {i}", file_type="jpg" + ) + examples.append(image) + run.log({"examples": examples}) + ``` + """ + super().__init__(caption=caption) + # TODO: We should remove grouping, it's a terrible name and I don't + # think anyone uses it. + + self._grouping = None + self._width = None + self._height = None + self._image = None + self._classes = None + self._boxes = None + self._masks = None + self._file_type = None + + # Allows the user to pass an Image object as the first parameter and have a perfect copy, + # only overriding additional metadata passed in. If this pattern is compelling, we can generalize. + if isinstance(data_or_path, Image): + self._initialize_from_wbimage(data_or_path) + elif isinstance(data_or_path, (str, pathlib.Path)): + data_or_path = str(data_or_path) + + if self.path_is_reference(data_or_path): + self._initialize_from_reference(data_or_path) + else: + self._initialize_from_path(data_or_path) + else: + self._initialize_from_data(data_or_path, mode, file_type, normalize) + self._set_initialization_meta( + grouping, caption, classes, boxes, masks, file_type + ) + + def _set_initialization_meta( + self, + grouping: Optional[int] = None, + caption: Optional[str] = None, + classes: Optional[Union["Classes", Sequence[dict]]] = None, + boxes: Optional[Union[Dict[str, "BoundingBoxes2D"], Dict[str, dict]]] = None, + masks: Optional[Union[Dict[str, "ImageMask"], Dict[str, dict]]] = None, + file_type: Optional[str] = None, + ) -> None: + if grouping is not None: + self._grouping = grouping + + total_classes = {} + + if boxes: + if not isinstance(boxes, dict): + raise ValueError('Images "boxes" argument must be a dictionary') + boxes_final: Dict[str, BoundingBoxes2D] = {} + for key in boxes: + box_item = boxes[key] + if isinstance(box_item, BoundingBoxes2D): + boxes_final[key] = box_item + elif isinstance(box_item, dict): + # TODO: Consider injecting top-level classes if user-provided is empty + boxes_final[key] = BoundingBoxes2D(box_item, key) + total_classes.update(boxes_final[key]._class_labels) + self._boxes = boxes_final + + if masks: + if not isinstance(masks, dict): + raise ValueError('Images "masks" argument must be a dictionary') + masks_final: Dict[str, ImageMask] = {} + for key in masks: + mask_item = masks[key] + if isinstance(mask_item, ImageMask): + masks_final[key] = mask_item + elif isinstance(mask_item, dict): + # TODO: Consider injecting top-level classes if user-provided is empty + masks_final[key] = ImageMask(mask_item, key) + if hasattr(masks_final[key], "_val"): + total_classes.update(masks_final[key]._val["class_labels"]) + self._masks = masks_final + + if classes is not None: + if isinstance(classes, Classes): + total_classes.update( + {val["id"]: val["name"] for val in classes._class_set} + ) + else: + total_classes.update({val["id"]: val["name"] for val in classes}) + + if len(total_classes.keys()) > 0: + self._classes = Classes( + [ + {"id": key, "name": total_classes[key]} + for key in total_classes.keys() + ] + ) + if self.image is not None: + self._width, self._height = self.image.size + self._free_ram() + + def _initialize_from_wbimage(self, wbimage: "Image") -> None: + self._grouping = wbimage._grouping + self._caption = wbimage._caption + self._width = wbimage._width + self._height = wbimage._height + self._image = wbimage._image + self._classes = wbimage._classes + self._path = wbimage._path + self._is_tmp = wbimage._is_tmp + self._extension = wbimage._extension + self._sha256 = wbimage._sha256 + self._size = wbimage._size + self.format = wbimage.format + self._file_type = wbimage._file_type + self._artifact_source = wbimage._artifact_source + self._artifact_target = wbimage._artifact_target + + # We do not want to implicitly copy boxes or masks, just the image-related data. + # self._boxes = wbimage._boxes + # self._masks = wbimage._masks + + def _initialize_from_path(self, path: str) -> None: + pil_image = util.get_module( + "PIL.Image", + required='wandb.Image needs the PIL package. To get it, run "pip install pillow".', + ) + self._set_file(path, is_tmp=False) + self._image = pil_image.open(path) + assert self._image is not None + self._image.load() + ext = os.path.splitext(path)[1][1:] + self.format = ext + + def _initialize_from_reference(self, path: str) -> None: + self._path = path + self._is_tmp = False + self._sha256 = hashlib.sha256(path.encode("utf-8")).hexdigest() + path = parse.urlparse(path).path + ext = path.split("/")[-1].split(".")[-1] + self.format = ext + + def _initialize_from_data( + self, + data: "ImageDataType", + mode: Optional[str] = None, + file_type: Optional[str] = None, + normalize: bool = True, + ) -> None: + pil_image = util.get_module( + "PIL.Image", + required='wandb.Image needs the PIL package. To get it, run "pip install pillow".', + ) + + accepted_formats = ["png", "jpg", "jpeg", "bmp"] + self.format = file_type or "png" + + if self.format not in accepted_formats: + raise ValueError(f"file_type must be one of {accepted_formats}") + + tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + "." + self.format) + + if util.is_matplotlib_typename(util.get_full_typename(data)): + buf = BytesIO() + util.ensure_matplotlib_figure(data).savefig(buf, format=self.format) + self._image = pil_image.open(buf) + elif isinstance(data, pil_image.Image): + self._image = data + elif util.is_pytorch_tensor_typename(util.get_full_typename(data)): + if hasattr(data, "requires_grad") and data.requires_grad: + data = data.detach() # type: ignore + if hasattr(data, "dtype") and str(data.dtype) == "torch.uint8": + data = data.to(float) # type: ignore [union-attr] + mode = mode or self.guess_mode(data, file_type) + data = data.permute(1, 2, 0).cpu().numpy() # type: ignore [union-attr] + + _warn_on_invalid_data_range(data, normalize) + + data = _guess_and_rescale_to_0_255(data) if normalize else data # type: ignore [arg-type] + data = _convert_to_uint8(data) + + if data.ndim > 2: + data = data.squeeze() + + self._image = pil_image.fromarray( + data, + mode=mode, + ) + else: + if hasattr(data, "numpy"): # TF data eager tensors + data = data.numpy() + if data.ndim > 2: # type: ignore [union-attr] + # get rid of trivial dimensions as a convenience + data = data.squeeze() # type: ignore [union-attr] + + _warn_on_invalid_data_range(data, normalize) # type: ignore [arg-type] + + mode = mode or self.guess_mode(data, file_type) + data = _guess_and_rescale_to_0_255(data) if normalize else data # type: ignore [arg-type] + data = _convert_to_uint8(data) # type: ignore [arg-type] + self._image = pil_image.fromarray( + data, + mode=mode, + ) + + assert self._image is not None + self._image.save(tmp_path, transparency=None) + self._set_file(tmp_path, is_tmp=True) + + @classmethod + def from_json( + cls: Type["Image"], json_obj: dict, source_artifact: "Artifact" + ) -> "Image": + """Factory method to create an Audio object from a JSON object. + + " + """ + classes: Optional[Classes] = None + if json_obj.get("classes") is not None: + value = source_artifact.get(json_obj["classes"]["path"]) + assert isinstance(value, (type(None), Classes)) + classes = value + + masks = json_obj.get("masks") + _masks: Optional[Dict[str, ImageMask]] = None + if masks: + _masks = {} + for key in masks: + _masks[key] = ImageMask.from_json(masks[key], source_artifact) + _masks[key]._set_artifact_source(source_artifact) + _masks[key]._key = key + + boxes = json_obj.get("boxes") + _boxes: Optional[Dict[str, BoundingBoxes2D]] = None + if boxes: + _boxes = {} + for key in boxes: + _boxes[key] = BoundingBoxes2D.from_json(boxes[key], source_artifact) + _boxes[key]._key = key + + return cls( + source_artifact.get_entry(json_obj["path"]).download(), + caption=json_obj.get("caption"), + grouping=json_obj.get("grouping"), + classes=classes, + boxes=_boxes, + masks=_masks, + ) + + @classmethod + def get_media_subdir(cls: Type["Image"]) -> str: + """Get media subdirectory. + + " + """ + return os.path.join("media", "images") + + def bind_to_run( + self, + run: "wandb.Run", + key: Union[int, str], + step: Union[int, str], + id_: Optional[Union[int, str]] = None, + ignore_copy_err: Optional[bool] = None, + ) -> None: + """Bind this object to a run. + + + """ + # For Images, we are going to avoid copying the image file to the run. + # We should make this common functionality for all media types, but that + # requires a broader UI refactor. This model can easily be moved to the + # higher level Media class, but that will require every UI surface area + # that depends on the `path` to be able to instead consume + # `artifact_path`. I (Tim) think the media panel makes up most of this + # space, but there are also custom charts, and maybe others. Let's + # commit to getting all that fixed up before moving this to the top + # level Media class. + if self.path_is_reference(self._path): + raise ValueError( + "Image media created by a reference to external storage cannot currently be added to a run" + ) + + if ( + not _server_accepts_artifact_path(run) + or self._get_artifact_entry_ref_url() is None + ): + super().bind_to_run(run, key, step, id_, ignore_copy_err=ignore_copy_err) + if self._boxes is not None: + for i, k in enumerate(self._boxes): + id_ = f"{id_}{i}" if id_ is not None else None + self._boxes[k].bind_to_run( + run, key, step, id_, ignore_copy_err=ignore_copy_err + ) + + if self._masks is not None: + for i, k in enumerate(self._masks): + id_ = f"{id_}{i}" if id_ is not None else None + self._masks[k].bind_to_run( + run, key, step, id_, ignore_copy_err=ignore_copy_err + ) + + def to_json(self, run_or_artifact: Union["wandb.Run", "Artifact"]) -> dict: + """Returns the JSON representation expected by the backend. + + + """ + json_dict = super().to_json(run_or_artifact) + json_dict["_type"] = Image._log_type + json_dict["format"] = self.format + + if self._width is not None: + json_dict["width"] = self._width + if self._height is not None: + json_dict["height"] = self._height + if self._grouping: + json_dict["grouping"] = self._grouping + + if isinstance(run_or_artifact, wandb.Artifact): + artifact = run_or_artifact + if ( + self._masks is not None or self._boxes is not None + ) and self._classes is None: + raise ValueError( + "classes must be passed to wandb.Image which have masks or bounding boxes when adding to artifacts" + ) + + if self._classes is not None: + class_id = hashutil._md5( + str(self._classes._class_set).encode("utf-8") + ).hexdigest() + class_name = os.path.join( + "media", + "classes", + class_id + "_cls", + ) + classes_entry = artifact.add(self._classes, class_name) + json_dict["classes"] = { + "type": "classes-file", + "path": classes_entry.path, + "digest": classes_entry.digest, + } + + elif not isinstance(run_or_artifact, wandb.Run): + raise TypeError("to_json accepts wandb.Run or wandb_artifact.Artifact") + + if self._boxes: + json_dict["boxes"] = { + k: box.to_json(run_or_artifact) for (k, box) in self._boxes.items() + } + if self._masks: + json_dict["masks"] = { + k: mask.to_json(run_or_artifact) for (k, mask) in self._masks.items() + } + return json_dict + + def guess_mode( + self, + data: Union["np.ndarray", "torch.Tensor"], + file_type: Optional[str] = None, + ) -> str: + """Guess what type of image the np.array is representing. + + + """ + # TODO: do we want to support dimensions being at the beginning of the array? + ndims = data.ndim + if util.is_pytorch_tensor_typename(util.get_full_typename(data)): + # Torch tenors typically have the channels dimension first + num_channels = data.shape[0] + else: + num_channels = data.shape[-1] + + if ndims == 2 or num_channels == 1: + return "L" + elif num_channels == 3: + return "RGB" + elif num_channels == 4: + if file_type in ["jpg", "jpeg"]: + wandb.termwarn( + "JPEG format does not support transparency. " + "Ignoring alpha channel.", + repeat=False, + ) + return "RGB" + else: + return "RGBA" + else: + raise ValueError( + f"Un-supported shape for image conversion {list(data.shape)}" + ) + + @classmethod + def seq_to_json( + cls: Type["Image"], + seq: Sequence["BatchableMedia"], + run: "wandb.Run", + key: str, + step: Union[int, str], + ) -> dict: + """Convert a sequence of Image objects to a JSON representation. + + " + """ + if TYPE_CHECKING: + seq = cast(Sequence["Image"], seq) + + jsons = [obj.to_json(run) for obj in seq] + + media_dir = cls.get_media_subdir() + + for obj in jsons: + expected = LogicalPath(media_dir) + if "path" in obj and not obj["path"].startswith(expected): + raise ValueError( + "Files in an array of Image's must be in the {} directory, not {}".format( + cls.get_media_subdir(), obj["path"] + ) + ) + + num_images_to_log = len(seq) + width, height = seq[0].image.size # type: ignore + format = jsons[0]["format"] + + def size_equals_image(image: "Image") -> bool: + img_width, img_height = image.image.size # type: ignore + return img_width == width and img_height == height + + sizes_match = all(size_equals_image(img) for img in seq) + if not sizes_match: + logging.warning( + "Images sizes do not match. This will causes images to be display incorrectly in the UI." + ) + + meta = { + "_type": "images/separated", + "width": width, + "height": height, + "format": format, + "count": num_images_to_log, + } + if _server_accepts_image_filenames(run): + meta["filenames"] = [ + obj.get("path", obj.get("artifact_path")) for obj in jsons + ] + else: + wandb.termwarn( + "Unable to log image array filenames. In some cases, this can prevent images from being " + "viewed in the UI. Please upgrade your wandb server", + repeat=False, + ) + + captions = Image.all_captions(seq) + + if captions: + meta["captions"] = captions + + all_masks = Image.all_masks(seq, run, key, step) + + if all_masks: + meta["all_masks"] = all_masks + + all_boxes = Image.all_boxes(seq, run, key, step) + + if all_boxes: + meta["all_boxes"] = all_boxes + + return meta + + @classmethod + def all_masks( + cls: Type["Image"], + images: Sequence["Image"], + run: "wandb.Run", + run_key: str, + step: Union[int, str], + ) -> Union[List[Optional[dict]], bool]: + """Collect all masks from a list of images. + + " + """ + all_mask_groups: List[Optional[dict]] = [] + for image in images: + if image._masks: + mask_group = {} + for k in image._masks: + mask = image._masks[k] + mask_group[k] = mask.to_json(run) + all_mask_groups.append(mask_group) + else: + all_mask_groups.append(None) + if all_mask_groups and not all(x is None for x in all_mask_groups): + return all_mask_groups + else: + return False + + @classmethod + def all_boxes( + cls: Type["Image"], + images: Sequence["Image"], + run: "wandb.Run", + run_key: str, + step: Union[int, str], + ) -> Union[List[Optional[dict]], bool]: + """Collect all boxes from a list of images. + + " + """ + all_box_groups: List[Optional[dict]] = [] + for image in images: + if image._boxes: + box_group = {} + for k in image._boxes: + box = image._boxes[k] + box_group[k] = box.to_json(run) + all_box_groups.append(box_group) + else: + all_box_groups.append(None) + if all_box_groups and not all(x is None for x in all_box_groups): + return all_box_groups + else: + return False + + @classmethod + def all_captions( + cls: Type["Image"], images: Sequence["Media"] + ) -> Union[bool, Sequence[Optional[str]]]: + """Get captions from a list of images. + + " + """ + return cls.captions(images) + + def __ne__(self, other: object) -> bool: + return not self.__eq__(other) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Image): + return False + else: + if self.path_is_reference(self._path) and self.path_is_reference( + other._path + ): + return self._path == other._path + self_image = self.image + other_image = other.image + if self_image is not None: + self_image = list(self_image.getdata()) # type: ignore + if other_image is not None: + other_image = list(other_image.getdata()) # type: ignore + + return ( + self._grouping == other._grouping + and self._caption == other._caption + and self._width == other._width + and self._height == other._height + and self_image == other_image + and self._classes == other._classes + ) + + def to_data_array(self) -> List[Any]: + """Convert to data array. + + + """ + res = [] + if self.image is not None: + data = list(self.image.getdata()) + for i in range(self.image.height): + res.append(data[i * self.image.width : (i + 1) * self.image.width]) + self._free_ram() + return res + + def _free_ram(self) -> None: + if self._path is not None: + self._image = None + + @property + def image(self) -> Optional["PILImage"]: + if self._image is None: + if self._path is not None and not self.path_is_reference(self._path): + pil_image = util.get_module( + "PIL.Image", + required='wandb.Image needs the PIL package. To get it, run "pip install pillow".', + ) + self._image = pil_image.open(self._path) + self._image.load() + return self._image + + +# Custom dtypes for typing system +class _ImageFileType(_dtypes.Type): + name = "image-file" + legacy_names = ["wandb.Image"] + types = [Image] + + def __init__( + self, + box_layers=None, + box_score_keys=None, + mask_layers=None, + class_map=None, + **kwargs, + ): + box_layers = box_layers or {} + box_score_keys = box_score_keys or [] + mask_layers = mask_layers or {} + class_map = class_map or {} + + if isinstance(box_layers, _dtypes.ConstType): + box_layers = box_layers._params["val"] + if not isinstance(box_layers, dict): + raise TypeError("box_layers must be a dict") + else: + box_layers = _dtypes.ConstType( + {layer_key: set(box_layers[layer_key]) for layer_key in box_layers} + ) + + if isinstance(mask_layers, _dtypes.ConstType): + mask_layers = mask_layers._params["val"] + if not isinstance(mask_layers, dict): + raise TypeError("mask_layers must be a dict") + else: + mask_layers = _dtypes.ConstType( + {layer_key: set(mask_layers[layer_key]) for layer_key in mask_layers} + ) + + if isinstance(box_score_keys, _dtypes.ConstType): + box_score_keys = box_score_keys._params["val"] + if not isinstance(box_score_keys, list) and not isinstance(box_score_keys, set): + raise TypeError("box_score_keys must be a list or a set") + else: + box_score_keys = _dtypes.ConstType(set(box_score_keys)) + + if isinstance(class_map, _dtypes.ConstType): + class_map = class_map._params["val"] + if not isinstance(class_map, dict): + raise TypeError("class_map must be a dict") + else: + class_map = _dtypes.ConstType(class_map) + + self.params.update( + { + "box_layers": box_layers, + "box_score_keys": box_score_keys, + "mask_layers": mask_layers, + "class_map": class_map, + } + ) + + def assign_type(self, wb_type=None): + if isinstance(wb_type, _ImageFileType): + box_layers_self = self.params["box_layers"].params["val"] or {} + box_score_keys_self = self.params["box_score_keys"].params["val"] or [] + mask_layers_self = self.params["mask_layers"].params["val"] or {} + class_map_self = self.params["class_map"].params["val"] or {} + + box_layers_other = wb_type.params["box_layers"].params["val"] or {} + box_score_keys_other = wb_type.params["box_score_keys"].params["val"] or [] + mask_layers_other = wb_type.params["mask_layers"].params["val"] or {} + class_map_other = wb_type.params["class_map"].params["val"] or {} + + # Merge the class_ids from each set of box_layers + box_layers = { + str(key): set( + list(box_layers_self.get(key, [])) + + list(box_layers_other.get(key, [])) + ) + for key in set( + list(box_layers_self.keys()) + list(box_layers_other.keys()) + ) + } + + # Merge the class_ids from each set of mask_layers + mask_layers = { + str(key): set( + list(mask_layers_self.get(key, [])) + + list(mask_layers_other.get(key, [])) + ) + for key in set( + list(mask_layers_self.keys()) + list(mask_layers_other.keys()) + ) + } + + # Merge the box score keys + box_score_keys = set(list(box_score_keys_self) + list(box_score_keys_other)) + + # Merge the class_map + class_map = { + str(key): class_map_self.get(key, class_map_other.get(key, None)) + for key in set( + list(class_map_self.keys()) + list(class_map_other.keys()) + ) + } + + return _ImageFileType(box_layers, box_score_keys, mask_layers, class_map) + + return _dtypes.InvalidType() + + @classmethod + def from_obj(cls, py_obj): + if not isinstance(py_obj, Image): + raise TypeError("py_obj must be a wandb.Image") + else: + if hasattr(py_obj, "_boxes") and py_obj._boxes: + box_layers = { + str(key): set(py_obj._boxes[key]._class_labels.keys()) + for key in py_obj._boxes.keys() + } + box_score_keys = { + key + for val in py_obj._boxes.values() + for box in val._val + for key in box.get("scores", {}).keys() + } + + else: + box_layers = {} + box_score_keys = set() + + if hasattr(py_obj, "_masks") and py_obj._masks: + mask_layers = { + str(key): set( + py_obj._masks[key]._val["class_labels"].keys() + if hasattr(py_obj._masks[key], "_val") + else [] + ) + for key in py_obj._masks.keys() + } + else: + mask_layers = {} + + if hasattr(py_obj, "_classes") and py_obj._classes: + class_set = { + str(item["id"]): item["name"] for item in py_obj._classes._class_set + } + else: + class_set = {} + + return cls(box_layers, box_score_keys, mask_layers, class_set) + + +_dtypes.TypeRegistry.add(_ImageFileType) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/molecule.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/molecule.py new file mode 100644 index 0000000000000000000000000000000000000000..e2129d4b64e0e34138d58de081e15850e3e66a16 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/molecule.py @@ -0,0 +1,250 @@ +import io +import os +import pathlib +from typing import TYPE_CHECKING, Optional, Sequence, Type, Union + +from wandb import util +from wandb.sdk.lib import runid +from wandb.sdk.lib.paths import LogicalPath + +from ._private import MEDIA_TMP +from .base_types.media import BatchableMedia, Media + +if TYPE_CHECKING: # pragma: no cover + from typing import TextIO + + import rdkit.Chem # type: ignore + + from wandb.sdk.artifacts.artifact import Artifact + + from ..wandb_run import Run as LocalRun + + RDKitDataType = Union[str, "rdkit.Chem.rdchem.Mol"] + + +class Molecule(BatchableMedia): + """W&B class for 3D Molecular data.""" + + SUPPORTED_TYPES = { + "pdb", + "pqr", + "mmcif", + "mcif", + "cif", + "sdf", + "sd", + "gro", + "mol2", + "mmtf", + } + SUPPORTED_RDKIT_TYPES = {"mol", "sdf"} + _log_type = "molecule-file" + + def __init__( + self, + data_or_path: Union[str, pathlib.Path, "TextIO"], + caption: Optional[str] = None, + **kwargs: str, + ) -> None: + """Initialize a Molecule object. + + Args: + data_or_path: Molecule can be initialized from a file name or an io object. + caption: Caption associated with the molecule for display. + """ + super().__init__(caption=caption) + + if hasattr(data_or_path, "name"): + # if the file has a path, we just detect the type and copy it from there + data_or_path = data_or_path.name + + if hasattr(data_or_path, "read"): + if hasattr(data_or_path, "seek"): + data_or_path.seek(0) + molecule = data_or_path.read() + + extension = kwargs.pop("file_type", None) + if extension is None: + raise ValueError( + "Must pass file_type keyword argument when using io objects." + ) + if extension not in Molecule.SUPPORTED_TYPES: + raise ValueError( + "Molecule 3D only supports files of the type: " + + ", ".join(Molecule.SUPPORTED_TYPES) + ) + + tmp_path = os.path.join( + MEDIA_TMP.name, runid.generate_id() + "." + extension + ) + with open(tmp_path, "w") as f: + f.write(molecule) + + self._set_file(tmp_path, is_tmp=True) + elif isinstance(data_or_path, (str, pathlib.Path)): + data_or_path = str(data_or_path) + + extension = os.path.splitext(data_or_path)[1][1:] + if extension not in Molecule.SUPPORTED_TYPES: + raise ValueError( + "Molecule only supports files of the type: " + + ", ".join(Molecule.SUPPORTED_TYPES) + ) + + self._set_file(data_or_path, is_tmp=False) + else: + raise ValueError("Data must be file name or a file object") + + @classmethod + def from_rdkit( + cls, + data_or_path: "RDKitDataType", + caption: Optional[str] = None, + convert_to_3d_and_optimize: bool = True, + mmff_optimize_molecule_max_iterations: int = 200, + ) -> "Molecule": + """Convert RDKit-supported file/object types to wandb.Molecule. + + Args: + data_or_path: (string, rdkit.Chem.rdchem.Mol) + Molecule can be initialized from a file name or an rdkit.Chem.rdchem.Mol object. + caption: (string) + Caption associated with the molecule for display. + convert_to_3d_and_optimize: (bool) + Convert to rdkit.Chem.rdchem.Mol with 3D coordinates. + This is an expensive operation that may take a long time for complicated molecules. + mmff_optimize_molecule_max_iterations: (int) + Number of iterations to use in rdkit.Chem.AllChem.MMFFOptimizeMolecule + + + """ + rdkit_chem = util.get_module( + "rdkit.Chem", + required='wandb.Molecule needs the rdkit-pypi package. To get it, run "pip install rdkit-pypi".', + ) + rdkit_chem_all_chem = util.get_module( + "rdkit.Chem.AllChem", + required='wandb.Molecule needs the rdkit-pypi package. To get it, run "pip install rdkit-pypi".', + ) + + if isinstance(data_or_path, str): + # path to a file? + path = pathlib.Path(data_or_path) + extension = path.suffix.split(".")[-1] + if extension not in Molecule.SUPPORTED_RDKIT_TYPES: + raise ValueError( + "Molecule.from_rdkit only supports files of the type: " + + ", ".join(Molecule.SUPPORTED_RDKIT_TYPES) + ) + # use the appropriate method + if extension == "sdf": + with rdkit_chem.SDMolSupplier(data_or_path) as supplier: + molecule = next(supplier) # get only the first molecule + else: + molecule = getattr(rdkit_chem, f"MolFrom{extension.capitalize()}File")( + data_or_path + ) + elif isinstance(data_or_path, rdkit_chem.rdchem.Mol): + molecule = data_or_path + else: + raise TypeError("Data must be file name or an rdkit.Chem.rdchem.Mol object") + + if convert_to_3d_and_optimize: + molecule = rdkit_chem.AddHs(molecule) + rdkit_chem_all_chem.EmbedMolecule(molecule) + rdkit_chem_all_chem.MMFFOptimizeMolecule( + molecule, + maxIters=mmff_optimize_molecule_max_iterations, + ) + # convert to the pdb format supported by Molecule + pdb_block = rdkit_chem.rdmolfiles.MolToPDBBlock(molecule) + + return cls(io.StringIO(pdb_block), caption=caption, file_type="pdb") + + @classmethod + def from_smiles( + cls, + data: str, + caption: Optional[str] = None, + sanitize: bool = True, + convert_to_3d_and_optimize: bool = True, + mmff_optimize_molecule_max_iterations: int = 200, + ) -> "Molecule": + """Convert SMILES string to wandb.Molecule. + + Args: + data: SMILES string. + caption: Caption associated with the molecule for display. + sanitize: Check if the molecule is chemically reasonable by + the RDKit's definition. + convert_to_3d_and_optimize: Convert to rdkit.Chem.rdchem.Mol + with 3D coordinates. This is a computationally intensive + operation that may take a long time for complicated molecules. + mmff_optimize_molecule_max_iterations: Number of iterations to + use in rdkit.Chem.AllChem.MMFFOptimizeMolecule. + + + """ + rdkit_chem = util.get_module( + "rdkit.Chem", + required='wandb.Molecule needs the rdkit-pypi package. To get it, run "pip install rdkit-pypi".', + ) + molecule = rdkit_chem.MolFromSmiles(data, sanitize=sanitize) + if molecule is None: + raise ValueError("Unable to parse the SMILES string.") + + return cls.from_rdkit( + data_or_path=molecule, + caption=caption, + convert_to_3d_and_optimize=convert_to_3d_and_optimize, + mmff_optimize_molecule_max_iterations=mmff_optimize_molecule_max_iterations, + ) + + @classmethod + def get_media_subdir(cls: Type["Molecule"]) -> str: + """Get media subdirectory. + + + """ + return os.path.join("media", "molecule") + + def to_json(self, run_or_artifact: Union["LocalRun", "Artifact"]) -> dict: + """Returns the JSON representation expected by the backend. + + + """ + json_dict = super().to_json(run_or_artifact) + json_dict["_type"] = self._log_type + return json_dict + + @classmethod + def seq_to_json( + cls: Type["Molecule"], + seq: Sequence["BatchableMedia"], + run: "LocalRun", + key: str, + step: Union[int, str], + ) -> dict: + """Convert a sequence of Molecule objects to a JSON representation. + + + """ + seq = list(seq) + + jsons = [obj.to_json(run) for obj in seq] + + for obj in jsons: + expected = LogicalPath(cls.get_media_subdir()) + if not obj["path"].startswith(expected): + raise ValueError( + "Files in an array of Molecule's must be in the {} directory, not {}".format( + cls.get_media_subdir(), obj["path"] + ) + ) + + return { + "_type": "molecule", + "filenames": [obj["path"] for obj in jsons], + "count": len(jsons), + "captions": Media.captions(seq), + } diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/table.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/table.py new file mode 100644 index 0000000000000000000000000000000000000000..d2d39e49e667d3f8db4c92d3691d67fc260dc2f1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/table.py @@ -0,0 +1,1468 @@ +import base64 +import binascii +import codecs +import datetime +import json +import logging +import os +from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Set, Tuple + +import wandb +from wandb import util +from wandb.sdk.lib import runid + +from . import _dtypes +from ._private import MEDIA_TMP +from .base_types.media import Media, _numpy_arrays_to_lists +from .base_types.wb_value import WBValue +from .table_decorators import ( + allow_incremental_logging_after_append, + allow_relogging_after_mutation, + ensure_not_incremental, +) +from .utils import _json_helper + +if TYPE_CHECKING: + from wandb.sdk.artifacts import artifact + + from ...wandb_run import Run as LocalRun + + +class _TableLinkMixin: + def set_table(self, table): + self._table = table + + +class _TableKey(str, _TableLinkMixin): + def set_table(self, table, col_name): + assert col_name in table.columns + self._table = table + self._col_name = col_name + + +class _TableIndex(int, _TableLinkMixin): + def get_row(self): + row = {} + if self._table: + row = { + c: self._table.data[self][i] for i, c in enumerate(self._table.columns) + } + + return row + + +class _PrimaryKeyType(_dtypes.Type): + name = "primaryKey" + legacy_names = ["wandb.TablePrimaryKey"] + + def assign_type(self, wb_type=None): + if isinstance(wb_type, _dtypes.StringType) or isinstance( + wb_type, _PrimaryKeyType + ): + return self + return _dtypes.InvalidType() + + @classmethod + def from_obj(cls, py_obj): + if not isinstance(py_obj, _TableKey): + raise TypeError("py_obj must be a wandb.Table") + else: + return cls() + + +class _ForeignKeyType(_dtypes.Type): + name = "foreignKey" + legacy_names = ["wandb.TableForeignKey"] + types = [_TableKey] + + def __init__(self, table, col_name): + assert isinstance(table, Table) + assert isinstance(col_name, str) + assert col_name in table.columns + self.params.update({"table": table, "col_name": col_name}) + + def assign_type(self, wb_type=None): + if isinstance(wb_type, _dtypes.StringType): + return self + elif ( + isinstance(wb_type, _ForeignKeyType) + and id(self.params["table"]) == id(wb_type.params["table"]) + and self.params["col_name"] == wb_type.params["col_name"] + ): + return self + + return _dtypes.InvalidType() + + @classmethod + def from_obj(cls, py_obj): + if not isinstance(py_obj, _TableKey): + raise TypeError("py_obj must be a _TableKey") + else: + return cls(py_obj._table, py_obj._col_name) + + def to_json(self, artifact=None): + res = super().to_json(artifact) + if artifact is not None: + table_name = f"media/tables/t_{runid.generate_id()}" + entry = artifact.add(self.params["table"], table_name) + res["params"]["table"] = entry.path + else: + raise AssertionError( + "_ForeignKeyType does not support serialization without an artifact" + ) + return res + + @classmethod + def from_json( + cls, + json_dict, + artifact, + ): + table = None + col_name = None + if artifact is None: + raise AssertionError( + "_ForeignKeyType does not support deserialization without an artifact" + ) + else: + table = artifact.get(json_dict["params"]["table"]) + col_name = json_dict["params"]["col_name"] + + if table is None: + raise AssertionError("Unable to deserialize referenced table") + + return cls(table, col_name) + + +class _ForeignIndexType(_dtypes.Type): + name = "foreignIndex" + legacy_names = ["wandb.TableForeignIndex"] + types = [_TableIndex] + + def __init__(self, table): + assert isinstance(table, Table) + self.params.update({"table": table}) + + def assign_type(self, wb_type=None): + if isinstance(wb_type, _dtypes.NumberType): + return self + elif isinstance(wb_type, _ForeignIndexType) and id(self.params["table"]) == id( + wb_type.params["table"] + ): + return self + + return _dtypes.InvalidType() + + @classmethod + def from_obj(cls, py_obj): + if not isinstance(py_obj, _TableIndex): + raise TypeError("py_obj must be a _TableIndex") + else: + return cls(py_obj._table) + + def to_json(self, artifact=None): + res = super().to_json(artifact) + if artifact is not None: + table_name = f"media/tables/t_{runid.generate_id()}" + entry = artifact.add(self.params["table"], table_name) + res["params"]["table"] = entry.path + else: + raise AssertionError( + "_ForeignIndexType does not support serialization without an artifact" + ) + return res + + @classmethod + def from_json( + cls, + json_dict, + artifact, + ): + table = None + if artifact is None: + raise AssertionError( + "_ForeignIndexType does not support deserialization without an artifact" + ) + else: + table = artifact.get(json_dict["params"]["table"]) + + if table is None: + raise AssertionError("Unable to deserialize referenced table") + + return cls(table) + + +_SUPPORTED_LOGGING_MODES = ["IMMUTABLE", "MUTABLE", "INCREMENTAL"] + + +class Table(Media): + """The Table class used to display and analyze tabular data. + + Unlike traditional spreadsheets, Tables support numerous types of data: + scalar values, strings, numpy arrays, and most subclasses of `wandb.data_types.Media`. + This means you can embed `Images`, `Video`, `Audio`, and other sorts of rich, annotated media + directly in Tables, alongside other traditional scalar values. + + This class is the primary class used to generate W&B Tables + https://docs.wandb.ai/guides/models/tables/. + """ + + MAX_ROWS = 10000 + MAX_ARTIFACT_ROWS = 200000 + _MAX_EMBEDDING_DIMENSIONS = 150 + _log_type = "table" + + def __init__( + self, + columns=None, + data=None, + rows=None, + dataframe=None, + dtype=None, + optional=True, + allow_mixed_types=False, + log_mode: Optional[ + Literal["IMMUTABLE", "MUTABLE", "INCREMENTAL"] + ] = "IMMUTABLE", + ): + """Initializes a Table object. + + The rows is available for legacy reasons and should not be used. + The Table class uses data to mimic the Pandas API. + + Args: + columns: (List[str]) Names of the columns in the table. + Defaults to ["Input", "Output", "Expected"]. + data: (List[List[any]]) 2D row-oriented array of values. + dataframe: (pandas.DataFrame) DataFrame object used to create the table. + When set, `data` and `columns` arguments are ignored. + rows: (List[List[any]]) 2D row-oriented array of values. + optional: (Union[bool,List[bool]]) Determines if `None` values are allowed. Default to True + - If a singular bool value, then the optionality is enforced for all + columns specified at construction time + - If a list of bool values, then the optionality is applied to each + column - should be the same length as `columns` + applies to all columns. A list of bool values applies to each respective column. + allow_mixed_types: (bool) Determines if columns are allowed to have mixed types + (disables type validation). Defaults to False + log_mode: Optional[str] Controls how the Table is logged when mutations occur. + Options: + - "IMMUTABLE" (default): Table can only be logged once; subsequent + logging attempts after the table has been mutated will be no-ops. + - "MUTABLE": Table can be re-logged after mutations, creating + a new artifact version each time it's logged. + - "INCREMENTAL": Table data is logged incrementally, with each log creating + a new artifact entry containing the new data since the last log. + """ + super().__init__() + self._validate_log_mode(log_mode) + self.log_mode = log_mode + if self.log_mode == "INCREMENTAL": + self._increment_num: int | None = None + self._last_logged_idx: int | None = None + self._previous_increments_paths: list[str] | None = None + self._run_target_for_increments: LocalRun | None = None + self._pk_col = None + self._fk_cols: set[str] = set() + if allow_mixed_types: + dtype = _dtypes.AnyType + + # This is kept for legacy reasons (tss: personally, I think we should remove this) + if columns is None: + columns = ["Input", "Output", "Expected"] + + # Explicit dataframe option + if dataframe is not None: + self._init_from_dataframe(dataframe, columns, optional, dtype) + else: + # Expected pattern + if data is not None: + if util.is_numpy_array(data): + self._init_from_ndarray(data, columns, optional, dtype) + elif util.is_pandas_data_frame(data): + self._init_from_dataframe(data, columns, optional, dtype) + else: + self._init_from_list(data, columns, optional, dtype) + + # legacy + elif rows is not None: + self._init_from_list(rows, columns, optional, dtype) + + # Default empty case + else: + self._init_from_list([], columns, optional, dtype) + + def _validate_log_mode(self, log_mode): + assert log_mode in _SUPPORTED_LOGGING_MODES, ( + f"Invalid log_mode: {log_mode}. Must be one of {_SUPPORTED_LOGGING_MODES}" + ) + + @staticmethod + def _assert_valid_columns(columns): + valid_col_types = [str, int] + assert isinstance(columns, list), "columns argument expects a `list` object" + assert len(columns) == 0 or all( + [type(col) in valid_col_types for col in columns] + ), "columns argument expects list of strings or ints" + + def _init_from_list(self, data, columns, optional=True, dtype=None): + assert isinstance(data, list), "data argument expects a `list` object" + self.data = [] + self._assert_valid_columns(columns) + self.columns = columns + self._make_column_types(dtype, optional) + for row in data: + self.add_data(*row) + + def _init_from_ndarray(self, ndarray, columns, optional=True, dtype=None): + assert util.is_numpy_array(ndarray), ( + "ndarray argument expects a `numpy.ndarray` object" + ) + self.data = [] + self._assert_valid_columns(columns) + self.columns = columns + self._make_column_types(dtype, optional) + for row in ndarray: + self.add_data(*row) + + def _init_from_dataframe(self, dataframe, columns, optional=True, dtype=None): + assert util.is_pandas_data_frame(dataframe), ( + "dataframe argument expects a `pandas.core.frame.DataFrame` object" + ) + self.data = [] + columns = list(dataframe.columns) + self._assert_valid_columns(columns) + self.columns = columns + self._make_column_types(dtype, optional) + for row in range(len(dataframe)): + self.add_data(*tuple(dataframe[col].values[row] for col in self.columns)) + + def _make_column_types(self, dtype=None, optional=True): + if dtype is None: + dtype = _dtypes.UnknownType() + + if optional.__class__ is not list: + optional = [optional for _ in range(len(self.columns))] + + if dtype.__class__ is not list: + dtype = [dtype for _ in range(len(self.columns))] + + self._column_types = _dtypes.TypedDictType({}) + for col_name, opt, dt in zip(self.columns, optional, dtype): + self.cast(col_name, dt, opt) + + def _load_incremental_table_state_from_resumed_run(self, run: "LocalRun", key: str): + """Handle updating incremental table state for resumed runs. + + This method is called when a run is resumed and there are previous + increments of this table that need to be preserved. It updates the + table's internal state to track previous increments and the current + increment number. + """ + if ( + self._previous_increments_paths is not None + or self._increment_num is not None + ): + raise AssertionError( + "The table has been initialized for a resumed run already" + ) + + self._set_incremental_table_run_target(run) + + summary_from_key = run.summary.get(key) + + if ( + summary_from_key is None + or not isinstance(summary_from_key, dict) + or summary_from_key.get("_type") != "incremental-table-file" + ): + # The key was never logged to the run or its last logged + # value was not an incrementally logged table. + return + + previous_increments_paths = summary_from_key.get( + "previous_increments_paths", [] + ) + + # add the artifact path of the last logged increment + last_artifact_path = summary_from_key.get("artifact_path") + + if last_artifact_path: + previous_increments_paths.append(last_artifact_path) + + # add 1 because a new increment is being logged + last_increment_num = summary_from_key.get("increment_num", 0) + + self._increment_num = last_increment_num + 1 + self._previous_increments_paths = previous_increments_paths + + def _set_incremental_table_run_target(self, run: "LocalRun") -> None: + """Associate a Run object with this incremental Table. + + A Table object in incremental mode can only be logged to a single Run. + Raises an error if the table is already associated to a different run. + """ + if self._run_target_for_increments is None: + self._run_target_for_increments = run + elif self._run_target_for_increments is not run: + raise AssertionError("An incremental Table can only be logged to one Run.") + + @allow_relogging_after_mutation + def cast(self, col_name, dtype, optional=False): + """Casts a column to a specific data type. + + This can be one of the normal python classes, an internal W&B type, + or an example object, like an instance of wandb.Image or + wandb.Classes. + + Args: + col_name (str): The name of the column to cast. + dtype (class, wandb.wandb_sdk.interface._dtypes.Type, any): The + target dtype. + optional (bool): If the column should allow Nones. + """ + assert col_name in self.columns + + wbtype = _dtypes.TypeRegistry.type_from_dtype(dtype) + + if optional: + wbtype = _dtypes.OptionalType(wbtype) + + # Cast each value in the row, raising an error if there are invalid entries. + col_ndx = self.columns.index(col_name) + for row in self.data: + result_type = wbtype.assign(row[col_ndx]) + if isinstance(result_type, _dtypes.InvalidType): + raise TypeError( + f"Existing data {row[col_ndx]}, of type {_dtypes.TypeRegistry.type_of(row[col_ndx])} cannot be cast to {wbtype}" + ) + wbtype = result_type + + # Assert valid options + is_pk = isinstance(wbtype, _PrimaryKeyType) + is_fk = isinstance(wbtype, _ForeignKeyType) + is_fi = isinstance(wbtype, _ForeignIndexType) + if is_pk or is_fk or is_fi: + assert not optional, ( + "Primary keys, foreign keys, and foreign indexes cannot be optional." + ) + + if (is_fk or is_fk) and id(wbtype.params["table"]) == id(self): + raise AssertionError("Cannot set a foreign table reference to same table.") + + if is_pk: + assert self._pk_col is None, ( + f"Cannot have multiple primary keys - {self._pk_col} is already set as the primary key." + ) + + # Update the column type + self._column_types.params["type_map"][col_name] = wbtype + + # Wrap the data if needed + self._update_keys() + return wbtype + + def __ne__(self, other): + return not self.__eq__(other) + + def _eq_debug(self, other, should_assert=False): + eq = isinstance(other, Table) + assert not should_assert or eq, ( + f"Found type {other.__class__}, expected {Table}" + ) + eq = eq and len(self.data) == len(other.data) + assert not should_assert or eq, ( + f"Found {len(other.data)} rows, expected {len(self.data)}" + ) + eq = eq and self.columns == other.columns + assert not should_assert or eq, ( + f"Found columns {other.columns}, expected {self.columns}" + ) + eq = eq and self._column_types == other._column_types + assert not should_assert or eq, ( + f"Found column type {other._column_types}, expected column type {self._column_types}" + ) + if eq: + for row_ndx in range(len(self.data)): + for col_ndx in range(len(self.data[row_ndx])): + _eq = self.data[row_ndx][col_ndx] == other.data[row_ndx][col_ndx] + # equal if all are equal + if util.is_numpy_array(_eq): + _eq = ((_eq * -1) + 1).sum() == 0 + eq = eq and _eq + assert not should_assert or eq, ( + f"Unequal data at row_ndx {row_ndx} col_ndx {col_ndx}: found {other.data[row_ndx][col_ndx]}, expected {self.data[row_ndx][col_ndx]}" + ) + if not eq: + return eq + return eq + + def __eq__(self, other): + return self._eq_debug(other) + + @allow_relogging_after_mutation + def add_row(self, *row): + """Deprecated. Use `Table.add_data` method instead.""" + logging.warning("add_row is deprecated, use add_data") + self.add_data(*row) + + @allow_relogging_after_mutation + @allow_incremental_logging_after_append + def add_data(self, *data): + """Adds a new row of data to the table. + + The maximum amount ofrows in a table is determined by + `wandb.Table.MAX_ARTIFACT_ROWS`. + + The length of the data should match the length of the table column. + """ + if len(data) != len(self.columns): + raise ValueError( + f"This table expects {len(self.columns)} columns: {self.columns}, found {len(data)}" + ) + + # Special case to pre-emptively cast a column as a key. + # Needed as String.assign(Key) is invalid + for ndx, item in enumerate(data): + if isinstance(item, _TableLinkMixin): + self.cast( + self.columns[ndx], + _dtypes.TypeRegistry.type_of(item), + optional=False, + ) + + # Update the table's column types + result_type = self._get_updated_result_type(data) + self._column_types = result_type + + # rows need to be mutable + if isinstance(data, tuple): + data = list(data) + # Add the new data + self.data.append(data) + + # Update the wrapper values if needed + self._update_keys(force_last=True) + + def _get_updated_result_type(self, row): + """Returns the updated result type based on the inputted row. + + Raises: + TypeError: if the assignment is invalid. + """ + incoming_row_dict = { + col_key: row[ndx] for ndx, col_key in enumerate(self.columns) + } + current_type = self._column_types + result_type = current_type.assign(incoming_row_dict) + if isinstance(result_type, _dtypes.InvalidType): + raise TypeError( + f"Data row contained incompatible types:\n{current_type.explain(incoming_row_dict)}" + ) + return result_type + + def _to_table_json(self, max_rows=None, warn=True): + # separate this method for easier testing + if max_rows is None: + max_rows = Table.MAX_ROWS + n_rows = len(self.data) + if n_rows > max_rows and warn: + # NOTE: Never raises for reinit="create_new" runs. + # Since this is called by bind_to_run(), this can be fixed by + # propagating the run. It cannot be fixed for to_json() calls + # that are given an artifact, other than by deferring to singleton + # settings. + if wandb.run and ( + wandb.run.settings.table_raise_on_max_row_limit_exceeded + or wandb.run.settings.strict + ): + raise ValueError( + f"Table row limit exceeded: table has {n_rows} rows, limit is {max_rows}. " + f"To increase the maximum number of allowed rows in a wandb.Table, override " + f"the limit with `wandb.Table.MAX_ARTIFACT_ROWS = X` and try again. Note: " + f"this may cause slower queries in the W&B UI." + ) + logging.warning(f"Truncating wandb.Table object to {max_rows} rows.") + + if self.log_mode == "INCREMENTAL" and self._last_logged_idx is not None: + return { + "columns": self.columns, + "data": self.data[ + self._last_logged_idx + 1 : self._last_logged_idx + 1 + max_rows + ], + } + else: + return {"columns": self.columns, "data": self.data[:max_rows]} + + def bind_to_run(self, *args, **kwargs): + """Bind this object to a run. + + + """ + # We set `warn=False` since Tables will now always be logged to both + # files and artifacts. The file limit will never practically matter and + # this code path will be ultimately removed. The 10k limit warning confuses + # users given that we publicly say 200k is the limit. + data = self._to_table_json(warn=False) + tmp_path = os.path.join(MEDIA_TMP.name, runid.generate_id() + ".table.json") + data = _numpy_arrays_to_lists(data) + with codecs.open(tmp_path, "w", encoding="utf-8") as fp: + util.json_dump_safer(data, fp) + self._set_file(tmp_path, is_tmp=True, extension=".table.json") + super().bind_to_run(*args, **kwargs) + + @classmethod + def get_media_subdir(cls): + """Get media subdirectory. + + + """ + return os.path.join("media", "table") + + @classmethod + def from_json(cls, json_obj, source_artifact: "artifact.Artifact"): + """Deserialize JSON object into it's class representation. + + + """ + data = [] + column_types = None + np_deserialized_columns = {} + timestamp_column_indices = set() + log_mode = json_obj.get("log_mode", "IMMUTABLE") + if json_obj.get("column_types") is not None: + column_types = _dtypes.TypeRegistry.type_from_dict( + json_obj["column_types"], source_artifact + ) + for col_name in column_types.params["type_map"]: + col_type = column_types.params["type_map"][col_name] + ndarray_type = None + if isinstance(col_type, _dtypes.NDArrayType): + ndarray_type = col_type + elif isinstance(col_type, _dtypes.UnionType): + for t in col_type.params["allowed_types"]: + if isinstance(t, _dtypes.NDArrayType): + ndarray_type = t + elif isinstance(t, _dtypes.TimestampType): + timestamp_column_indices.add( + json_obj["columns"].index(col_name) + ) + + elif isinstance(col_type, _dtypes.TimestampType): + timestamp_column_indices.add(json_obj["columns"].index(col_name)) + + if ( + ndarray_type is not None + and ndarray_type._get_serialization_path() is not None + ): + serialization_path = ndarray_type._get_serialization_path() + + if serialization_path is None: + continue + + np = util.get_module( + "numpy", + required="Deserializing NumPy columns requires NumPy to be installed.", + ) + deserialized = np.load( + source_artifact.get_entry(serialization_path["path"]).download() + ) + np_deserialized_columns[json_obj["columns"].index(col_name)] = ( + deserialized[serialization_path["key"]] + ) + ndarray_type._clear_serialization_path() + + if log_mode == "INCREMENTAL": + unprocessed_table_data = _get_data_from_increments( + json_obj, source_artifact + ) + else: + unprocessed_table_data = json_obj["data"] + + for r_ndx, row in enumerate(unprocessed_table_data): + data.append( + _process_table_row( + row, + timestamp_column_indices, + np_deserialized_columns, + source_artifact, + r_ndx, + ) + ) + + # construct Table with dtypes for each column if type information exists + dtypes = None + if column_types is not None: + dtypes = [ + column_types.params["type_map"][str(col)] for col in json_obj["columns"] + ] + + new_obj = cls( + columns=json_obj["columns"], data=data, dtype=dtypes, log_mode=log_mode + ) + + if column_types is not None: + new_obj._column_types = column_types + + new_obj._update_keys() + return new_obj + + def to_json(self, run_or_artifact): + """Returns the JSON representation expected by the backend. + + + """ + json_dict = super().to_json(run_or_artifact) + + if self.log_mode == "INCREMENTAL": + if self._previous_increments_paths is None: + self._previous_increments_paths = [] + if self._increment_num is None: + self._increment_num = 0 + + json_dict.update( + { + "increment_num": self._increment_num, + "previous_increments_paths": self._previous_increments_paths, + } + ) + + if isinstance(run_or_artifact, wandb.Run): + if self.log_mode == "INCREMENTAL": + wbvalue_type = "incremental-table-file" + else: + wbvalue_type = "table-file" + + json_dict.update( + { + "_type": wbvalue_type, + "ncols": len(self.columns), + "nrows": len(self.data), + "log_mode": self.log_mode, + } + ) + + elif isinstance(run_or_artifact, wandb.Artifact): + artifact = run_or_artifact + mapped_data = [] + data = self._to_table_json(Table.MAX_ARTIFACT_ROWS)["data"] + + ndarray_col_ndxs = set() + for col_ndx, col_name in enumerate(self.columns): + col_type = self._column_types.params["type_map"][col_name] + ndarray_type = None + if isinstance(col_type, _dtypes.NDArrayType): + ndarray_type = col_type + elif isinstance(col_type, _dtypes.UnionType): + for t in col_type.params["allowed_types"]: + if isinstance(t, _dtypes.NDArrayType): + ndarray_type = t + + # Do not serialize 1d arrays - these are likely embeddings and + # will not have the same cost as higher dimensional arrays + is_1d_array = ( + ndarray_type is not None + and "shape" in ndarray_type._params + and isinstance(ndarray_type._params["shape"], list) + and len(ndarray_type._params["shape"]) == 1 + and ndarray_type._params["shape"][0] + <= self._MAX_EMBEDDING_DIMENSIONS + ) + if is_1d_array: + self._column_types.params["type_map"][col_name] = _dtypes.ListType( + _dtypes.NumberType, ndarray_type._params["shape"][0] + ) + elif ndarray_type is not None: + np = util.get_module( + "numpy", + required="Serializing NumPy requires NumPy to be installed.", + ) + file_name = f"{str(col_name)}_{runid.generate_id()}.npz" + npz_file_name = os.path.join(MEDIA_TMP.name, file_name) + np.savez_compressed( + npz_file_name, + **{ + str(col_name): self.get_column(col_name, convert_to="numpy") + }, + ) + entry = artifact.add_file( + npz_file_name, "media/serialized_data/" + file_name, is_tmp=True + ) + ndarray_type._set_serialization_path(entry.path, str(col_name)) + ndarray_col_ndxs.add(col_ndx) + + for row in data: + mapped_row = [] + for ndx, v in enumerate(row): + if ndx in ndarray_col_ndxs: + mapped_row.append(None) + else: + mapped_row.append(_json_helper(v, artifact)) + mapped_data.append(mapped_row) + + json_dict.update( + { + "_type": Table._log_type, + "columns": self.columns, + "data": mapped_data, + "ncols": len(self.columns), + "nrows": len(mapped_data), + "column_types": self._column_types.to_json(artifact), + "log_mode": self.log_mode, + } + ) + else: + raise TypeError("to_json accepts wandb_run.Run or wandb_artifact.Artifact") + + return json_dict + + def iterrows(self): + """Returns the table data by row, showing the index of the row and the relevant data. + + Yields: + ------ + index: The index of the row. Using this value in other W&B tables + will automatically build a relationship between the tables + row: The data of the row. + + + """ + for ndx in range(len(self.data)): + index = _TableIndex(ndx) + index.set_table(self) + yield index, self.data[ndx] + + @allow_relogging_after_mutation + def set_pk(self, col_name): + """Set primary key type for Table object. + + + """ + # TODO: Docs + assert col_name in self.columns + self.cast(col_name, _PrimaryKeyType()) + + @allow_relogging_after_mutation + def set_fk(self, col_name, table, table_col): + """Set foreign key type for Table object. + + + """ + # TODO: Docs + assert col_name in self.columns + assert col_name != self._pk_col + self.cast(col_name, _ForeignKeyType(table, table_col)) + + def _update_keys(self, force_last=False): + """Updates the known key-like columns based on current column types. + + If the state has been updated since the last update, wraps the data + appropriately in the Key classes. + + Args: + force_last: (bool) Wraps the last column of data even if there + are no key updates. + """ + _pk_col = None + _fk_cols = set() + + # Buildup the known keys from column types + c_types = self._column_types.params["type_map"] + for t in c_types: + if isinstance(c_types[t], _PrimaryKeyType): + _pk_col = t + elif isinstance(c_types[t], _ForeignKeyType) or isinstance( + c_types[t], _ForeignIndexType + ): + _fk_cols.add(t) + + # If there are updates to perform, safely update them + has_update = _pk_col != self._pk_col or _fk_cols != self._fk_cols + if has_update: + # If we removed the PK + if _pk_col is None and self._pk_col is not None: + raise AssertionError( + f"Cannot unset primary key (column {self._pk_col})" + ) + # If there is a removed FK + if len(self._fk_cols - _fk_cols) > 0: + raise AssertionError( + f"Cannot unset foreign key. Attempted to unset ({self._fk_cols - _fk_cols})" + ) + + self._pk_col = _pk_col + self._fk_cols = _fk_cols + + # Apply updates to data only if there are update or the caller + # requested the final row to be updated + if has_update or force_last: + self._apply_key_updates(not has_update) + + def _apply_key_updates(self, only_last=False): + """Appropriately wraps the underlying data in special Key classes. + + Args: + only_last: only apply the updates to the last row (used for performance when + the caller knows that the only new data is the last row and no updates were + applied to the column types) + """ + c_types = self._column_types.params["type_map"] + + # Define a helper function which will wrap the data of a single row + # in the appropriate class wrapper. + def update_row(row_ndx): + for fk_col in self._fk_cols: + col_ndx = self.columns.index(fk_col) + + # Wrap the Foreign Keys + if isinstance(c_types[fk_col], _ForeignKeyType) and not isinstance( + self.data[row_ndx][col_ndx], _TableKey + ): + self.data[row_ndx][col_ndx] = _TableKey(self.data[row_ndx][col_ndx]) + self.data[row_ndx][col_ndx].set_table( + c_types[fk_col].params["table"], + c_types[fk_col].params["col_name"], + ) + + # Wrap the Foreign Indexes + elif isinstance(c_types[fk_col], _ForeignIndexType) and not isinstance( + self.data[row_ndx][col_ndx], _TableIndex + ): + self.data[row_ndx][col_ndx] = _TableIndex( + self.data[row_ndx][col_ndx] + ) + self.data[row_ndx][col_ndx].set_table( + c_types[fk_col].params["table"] + ) + + # Wrap the Primary Key + if self._pk_col is not None: + col_ndx = self.columns.index(self._pk_col) + self.data[row_ndx][col_ndx] = _TableKey(self.data[row_ndx][col_ndx]) + self.data[row_ndx][col_ndx].set_table(self, self._pk_col) + + if only_last: + update_row(len(self.data) - 1) + else: + for row_ndx in range(len(self.data)): + update_row(row_ndx) + + @ensure_not_incremental + @allow_relogging_after_mutation + def add_column(self, name, data, optional=False): + """Adds a column of data to the table. + + Args: + name: (str) - the unique name of the column + data: (list | np.array) - a column of homogeneous data + optional: (bool) - if null-like values are permitted + """ + assert isinstance(name, str) and name not in self.columns + is_np = util.is_numpy_array(data) + assert isinstance(data, list) or is_np + assert isinstance(optional, bool) + is_first_col = len(self.columns) == 0 + assert is_first_col or len(data) == len(self.data), ( + f"Expected length {len(self.data)}, found {len(data)}" + ) + + # Add the new data + for ndx in range(max(len(data), len(self.data))): + if is_first_col: + self.data.append([]) + if is_np: + self.data[ndx].append(data[ndx]) + else: + self.data[ndx].append(data[ndx]) + # add the column + self.columns.append(name) + + try: + self.cast(name, _dtypes.UnknownType(), optional=optional) + except TypeError: + # Undo the changes + if is_first_col: + self.data = [] + self.columns = [] + else: + for ndx in range(len(self.data)): + self.data[ndx] = self.data[ndx][:-1] + self.columns = self.columns[:-1] + raise + + def get_column(self, name, convert_to=None): + """Retrieves a column from the table and optionally converts it to a NumPy object. + + Args: + name: (str) - the name of the column + convert_to: (str, optional) + - "numpy": will convert the underlying data to numpy object + """ + assert name in self.columns + assert convert_to is None or convert_to == "numpy" + if convert_to == "numpy": + np = util.get_module( + "numpy", required="Converting to NumPy requires installing NumPy" + ) + col = [] + col_ndx = self.columns.index(name) + for row in self.data: + item = row[col_ndx] + if convert_to is not None and isinstance(item, WBValue): + item = item.to_data_array() + col.append(item) + if convert_to == "numpy": + col = np.array(col) + return col + + def get_index(self): + """Returns an array of row indexes for use in other tables to create links.""" + ndxs = [] + for ndx in range(len(self.data)): + index = _TableIndex(ndx) + index.set_table(self) + ndxs.append(index) + return ndxs + + def get_dataframe(self): + """Returns a `pandas.DataFrame` of the table.""" + pd = util.get_module( + "pandas", + required="Converting to pandas.DataFrame requires installing pandas", + ) + return pd.DataFrame.from_records(self.data, columns=self.columns) + + def index_ref(self, index): + """Gets a reference of the index of a row in the table. + + + """ + assert index < len(self.data) + _index = _TableIndex(index) + _index.set_table(self) + return _index + + @ensure_not_incremental + @allow_relogging_after_mutation + def add_computed_columns(self, fn): + """Adds one or more computed columns based on existing data. + + Args: + fn: A function which accepts one or two parameters, ndx (int) and + row (dict), which is expected to return a dict representing + new columns for that row, keyed by the new column names. + - `ndx` is an integer representing the index of the row. Only included if `include_ndx` + is set to `True`. + - `row` is a dictionary keyed by existing columns + """ + new_columns = {} + for ndx, row in self.iterrows(): + row_dict = {self.columns[i]: row[i] for i in range(len(self.columns))} + new_row_dict = fn(ndx, row_dict) + assert isinstance(new_row_dict, dict) + for key in new_row_dict: + new_columns[key] = new_columns.get(key, []) + new_columns[key].append(new_row_dict[key]) + for new_col_name in new_columns: + self.add_column(new_col_name, new_columns[new_col_name]) + + +class _PartitionTablePartEntry: + """Helper class for PartitionTable to track its parts.""" + + def __init__(self, entry, source_artifact): + self.entry = entry + self.source_artifact = source_artifact + self._part = None + + def get_part(self): + if self._part is None: + self._part = self.source_artifact.get(self.entry.path) + return self._part + + def free(self): + self._part = None + + +class PartitionedTable(Media): + """A table which is composed of multiple sub-tables. + + Currently, PartitionedTable is designed to point to a directory within an + artifact. + """ + + _log_type = "partitioned-table" + + def __init__(self, parts_path): + """Initialize a PartitionedTable. + + Args: + parts_path (str): path to a directory of tables in the artifact. + """ + super().__init__() + self.parts_path = parts_path + self._loaded_part_entries = {} + + def to_json(self, artifact_or_run): + json_obj = { + "_type": PartitionedTable._log_type, + } + if isinstance(artifact_or_run, wandb.Run): + artifact_entry_url = self._get_artifact_entry_ref_url() + if artifact_entry_url is None: + raise ValueError( + "PartitionedTables must first be added to an Artifact before logging to a Run" + ) + json_obj["artifact_path"] = artifact_entry_url + else: + json_obj["parts_path"] = self.parts_path + return json_obj + + @classmethod + def from_json(cls, json_obj, source_artifact): + instance = cls(json_obj["parts_path"]) + entries = source_artifact.manifest.get_entries_in_directory( + json_obj["parts_path"] + ) + for entry in entries: + instance._add_part_entry(entry, source_artifact) + return instance + + def iterrows(self): + """Iterate over rows as (ndx, row). + + Args: + index (int): The index of the row. + row (List[any]): The data of the row. + """ + columns = None + ndx = 0 + for entry_path in self._loaded_part_entries: + part = self._loaded_part_entries[entry_path].get_part() + if columns is None: + columns = part.columns + elif columns != part.columns: + raise ValueError( + f"Table parts have non-matching columns. {columns} != {part.columns}" + ) + for _, row in part.iterrows(): + yield ndx, row + ndx += 1 + + self._loaded_part_entries[entry_path].free() + + def _add_part_entry(self, entry, source_artifact): + self._loaded_part_entries[entry.path] = _PartitionTablePartEntry( + entry, source_artifact + ) + + def __ne__(self, other): + return not self.__eq__(other) + + def __eq__(self, other): + return isinstance(other, self.__class__) and self.parts_path == other.parts_path + + def bind_to_run(self, *args, **kwargs): + raise ValueError("PartitionedTables cannot be bound to runs") + + +class JoinedTable(Media): + """Join two tables for visualization in the Artifact UI. + + Args: + table1 (str, wandb.Table, ArtifactManifestEntry): + the path to a wandb.Table in an artifact, the table object, or ArtifactManifestEntry + table2 (str, wandb.Table): + the path to a wandb.Table in an artifact, the table object, or ArtifactManifestEntry + join_key (str, [str, str]): + key or keys to perform the join + """ + + _log_type = "joined-table" + + def __init__(self, table1, table2, join_key): + super().__init__() + + if not isinstance(join_key, str) and ( + not isinstance(join_key, list) or len(join_key) != 2 + ): + raise ValueError( + "JoinedTable join_key should be a string or a list of two strings" + ) + + if not self._validate_table_input(table1): + raise ValueError( + "JoinedTable table1 should be an artifact path to a table or wandb.Table object" + ) + + if not self._validate_table_input(table2): + raise ValueError( + "JoinedTable table2 should be an artifact path to a table or wandb.Table object" + ) + + self._table1 = table1 + self._table2 = table2 + self._join_key = join_key + + @classmethod + def from_json(cls, json_obj, source_artifact): + t1 = source_artifact.get(json_obj["table1"]) + if t1 is None: + t1 = json_obj["table1"] + + t2 = source_artifact.get(json_obj["table2"]) + if t2 is None: + t2 = json_obj["table2"] + + return cls( + t1, + t2, + json_obj["join_key"], + ) + + @staticmethod + def _validate_table_input(table): + """Helper method to validate that the table input is one of the 3 supported types.""" + return ( + (isinstance(table, str) and table.endswith(".table.json")) + or isinstance(table, Table) + or isinstance(table, PartitionedTable) + or (hasattr(table, "ref_url") and table.ref_url().endswith(".table.json")) + ) + + def _ensure_table_in_artifact(self, table, artifact, table_ndx): + """Helper method to add the table to the incoming artifact. Returns the path.""" + if isinstance(table, Table) or isinstance(table, PartitionedTable): + table_name = f"t{table_ndx}_{str(id(self))}" + if ( + table._artifact_source is not None + and table._artifact_source.name is not None + ): + table_name = os.path.basename(table._artifact_source.name) + entry = artifact.add(table, table_name) + table = entry.path + # Check if this is an ArtifactManifestEntry + elif hasattr(table, "ref_url"): + # Give the new object a unique, yet deterministic name + name = binascii.hexlify(base64.standard_b64decode(table.digest)).decode( + "ascii" + )[:20] + entry = artifact.add_reference( + table.ref_url(), "{}.{}.json".format(name, table.name.split(".")[-2]) + )[0] + table = entry.path + + err_str = "JoinedTable table:{} not found in artifact. Add a table to the artifact using Artifact#add(, {}) before adding this JoinedTable" + if table not in artifact._manifest.entries: + raise ValueError(err_str.format(table, table)) + + return table + + def to_json(self, artifact_or_run): + json_obj = { + "_type": JoinedTable._log_type, + } + if isinstance(artifact_or_run, wandb.Run): + artifact_entry_url = self._get_artifact_entry_ref_url() + if artifact_entry_url is None: + raise ValueError( + "JoinedTables must first be added to an Artifact before logging to a Run" + ) + json_obj["artifact_path"] = artifact_entry_url + else: + table1 = self._ensure_table_in_artifact(self._table1, artifact_or_run, 1) + table2 = self._ensure_table_in_artifact(self._table2, artifact_or_run, 2) + json_obj.update( + { + "table1": table1, + "table2": table2, + "join_key": self._join_key, + } + ) + return json_obj + + def __ne__(self, other): + return not self.__eq__(other) + + def _eq_debug(self, other, should_assert=False): + eq = isinstance(other, JoinedTable) + assert not should_assert or eq, ( + f"Found type {other.__class__}, expected {JoinedTable}" + ) + eq = eq and self._join_key == other._join_key + assert not should_assert or eq, ( + f"Found {other._join_key} join key, expected {self._join_key}" + ) + eq = eq and self._table1._eq_debug(other._table1, should_assert) + eq = eq and self._table2._eq_debug(other._table2, should_assert) + return eq + + def __eq__(self, other): + return self._eq_debug(other, False) + + def bind_to_run(self, *args, **kwargs): + raise ValueError("JoinedTables cannot be bound to runs") + + +class _TableType(_dtypes.Type): + name = "table" + legacy_names = ["wandb.Table"] + types = [Table] + + def __init__(self, column_types=None): + if column_types is None: + column_types = _dtypes.UnknownType() + if isinstance(column_types, dict): + column_types = _dtypes.TypedDictType(column_types) + elif not ( + isinstance(column_types, _dtypes.TypedDictType) + or isinstance(column_types, _dtypes.UnknownType) + ): + raise TypeError("column_types must be a dict or TypedDictType") + + self.params.update({"column_types": column_types}) + + def assign_type(self, wb_type=None): + if isinstance(wb_type, _TableType): + column_types = self.params["column_types"].assign_type( + wb_type.params["column_types"] + ) + if not isinstance(column_types, _dtypes.InvalidType): + return _TableType(column_types) + + return _dtypes.InvalidType() + + @classmethod + def from_obj(cls, py_obj): + if not isinstance(py_obj, Table): + raise TypeError("py_obj must be a wandb.Table") + else: + return cls(py_obj._column_types) + + +class _JoinedTableType(_dtypes.Type): + name = "joined-table" + types = [JoinedTable] + + +class _PartitionedTableType(_dtypes.Type): + name = "partitioned-table" + types = [PartitionedTable] + + +_dtypes.TypeRegistry.add(_TableType) +_dtypes.TypeRegistry.add(_JoinedTableType) +_dtypes.TypeRegistry.add(_PartitionedTableType) +_dtypes.TypeRegistry.add(_ForeignKeyType) +_dtypes.TypeRegistry.add(_PrimaryKeyType) +_dtypes.TypeRegistry.add(_ForeignIndexType) + + +def _get_data_from_increments( + json_obj: Dict[str, Any], source_artifact: "artifact.Artifact" +) -> List[Any]: + """Get data from incremental table artifacts. + + Args: + json_obj: The JSON object containing table metadata. + source_artifact: The source artifact containing the table data. + + Returns: + List of table rows from all increments. + """ + if "latest" not in source_artifact.aliases: + wandb.termwarn( + ( + "It is recommended to use the latest version of the " + "incremental table artifact for ordering guarantees." + ), + repeat=False, + ) + data: List[Any] = [] + increment_num = json_obj.get("increment_num", None) + if increment_num is None: + return data + + # Sort by increment number first, then by timestamp if present + # Format of name is: "{incr_num}-{timestamp_ms}.{key}.table.json" + def get_sort_key(key: str) -> Tuple[int, int]: + try: + parts = key.split(".") + increment_parts = parts[0].split("-") + increment_num = int(increment_parts[0]) + # If there's a timestamp part, use it for secondary sorting + timestamp = int(increment_parts[1]) if len(increment_parts) > 1 else 0 + except (ValueError, IndexError): + wandb.termwarn( + ( + f"Could not parse artifact entry for increment {key}." + " The entry name does not follow the naming convention" + " -..table.json" + " The data in the table will be out of order." + ), + repeat=False, + ) + return (0, 0) + + return (increment_num, timestamp) + + sorted_increment_keys = [] + for entry_key in source_artifact.manifest.entries: + if entry_key.endswith(".table.json"): + sorted_increment_keys.append(entry_key) + + sorted_increment_keys.sort(key=get_sort_key) + + for entry_key in sorted_increment_keys: + try: + with open(source_artifact.manifest.entries[entry_key].download()) as f: + table_data = json.load(f) + data.extend(table_data["data"]) + except (json.JSONDecodeError, KeyError) as e: + raise wandb.Error(f"Invalid table file {entry_key}") from e + return data + + +def _process_table_row( + row: List[Any], + timestamp_column_indices: Set[_dtypes.TimestampType], + np_deserialized_columns: Dict[int, Any], + source_artifact: "artifact.Artifact", + row_idx: int, +) -> List[Any]: + """Convert special columns in a table row to Python types. + + Processes a single row of table data by converting timestamp values to + datetime objects, replacing np typed cells with numpy array data, + and initializing media objects from their json value. + + + Args: + row: The row data to process. + timestamp_column_indices: Set of column indices containing timestamps. + np_deserialized_columns: Dictionary mapping column indices to numpy arrays. + source_artifact: The source artifact containing the table data. + row_idx: The index of the current row. + + Returns: + Processed row data. + """ + row_data = [] + for c_ndx, item in enumerate(row): + cell: Any + if c_ndx in timestamp_column_indices and isinstance(item, (int, float)): + cell = datetime.datetime.fromtimestamp( + item / 1000, tz=datetime.timezone.utc + ) + elif c_ndx in np_deserialized_columns: + cell = np_deserialized_columns[c_ndx][row_idx] + elif ( + isinstance(item, dict) + and "_type" in item + and (obj := WBValue.init_from_json(item, source_artifact)) + ): + cell = obj + else: + cell = item + row_data.append(cell) + return row_data diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/table_decorators.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/table_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..5c4ead3462d8745ef21c319321c9773667a2ee4d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/table_decorators.py @@ -0,0 +1,108 @@ +"""Decorators for W&B Table operations.""" + +from __future__ import annotations + +from functools import wraps +from typing import Any, Callable, TypeVar + +from typing_extensions import Concatenate, ParamSpec + +import wandb + +_P = ParamSpec("_P") +_T = TypeVar("_T") + + +def allow_relogging_after_mutation( + method: Callable[Concatenate[wandb.Table, _P], _T], +) -> Callable[Concatenate[wandb.Table, _P], _T]: + """Decorator that handles table state after mutations based on log_mode. + + For MUTABLE tables, resets the run and artifact target to allow re-logging. + For IMMUTABLE tables, warns if attempting to mutate after logging. + """ + + @wraps(method) + def wrapper(self: wandb.Table, *args: Any, **kwargs: Any) -> _T: + has_been_logged = self._run is not None or self._artifact_target is not None + + if self.log_mode == "MUTABLE": + self._run = None + self._artifact_target = None + self._path = None + self._sha256 = None + elif self.log_mode == "IMMUTABLE" and has_been_logged: + wandb.termwarn( + "You are mutating a Table with log_mode='IMMUTABLE' that has been " + "logged already. Subsequent log() calls will have no effect. " + "Set log_mode='MUTABLE' to enable re-logging after mutations", + repeat=False, + ) + + return method(self, *args, **kwargs) + + return wrapper + + +def allow_incremental_logging_after_append( + method: Callable[Concatenate[wandb.Table, _P], _T], +) -> Callable[Concatenate[wandb.Table, _P], _T]: + """Decorator that handles incremental logging state after append operations. + + For INCREMENTAL tables, manages artifact references and increments counters + to support partial data logging. + """ + + @wraps(method) + def wrapper(self: wandb.Table, *args: Any, **kwargs: Any) -> _T: + res = method(self, *args, **kwargs) + + if self.log_mode != "INCREMENTAL" or self._artifact_target is None: + return res + + art_entry_url = self._get_artifact_entry_ref_url() + if art_entry_url is not None: + if self._previous_increments_paths is None: + raise ValueError( + "_previous_increments_paths must be set if incremental" + " table has been logged already" + ) + self._previous_increments_paths.append(art_entry_url) + self._run = None + self._artifact_target = None + self._path = None + self._sha256 = None + + if self._increment_num is None: + raise ValueError( + "_increment_num must be set if incremental table has been" + " logged already" + ) + + self._increment_num += 1 + if self._increment_num > 99: + wandb.termwarn( + "You have exceeded 100 increments for this table. " + "Only the latest 100 increments will be visualized in the run workspace.", + repeat=False, + ) + return res + + return wrapper + + +def ensure_not_incremental( + method: Callable[Concatenate[wandb.Table, _P], _T], +) -> Callable[Concatenate[wandb.Table, _P], _T]: + """Decorator that checks if log mode is incremental to disallow methods from being called.""" + + @wraps(method) + def wrapper(self: wandb.Table, *args: Any, **kwargs: Any) -> _T: + if self.log_mode == "INCREMENTAL": + raise wandb.Error( + f"Operation '{method.__name__}' is not supported for tables with " + "log_mode='INCREMENTAL'. Use a different log mode like 'MUTABLE' or 'IMMUTABLE'." + ) + return method(self, *args, **kwargs) + + return wrapper diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/trace_tree.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/trace_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..d42d407c8a4ad9397306be9e3ea5a37383496a6e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/trace_tree.py @@ -0,0 +1,440 @@ +"""This module contains the `WBTraceTree` media type, and the supporting dataclasses. + +A `WBTraceTree` is a media object containing a root span and an +arbitrary model dump as a serializable dictionary. Logging such media type will +result in a W&B Trace Debugger panel being created in the workspace UI. +""" + +import dataclasses +import hashlib +import json +import typing +from dataclasses import dataclass, field +from enum import Enum +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union + +import wandb +from wandb.sdk.data_types import _dtypes +from wandb.sdk.data_types.base_types.media import Media +from wandb.sdk.data_types.utils import _json_helper + +if TYPE_CHECKING: # pragma: no cover + from wandb.sdk.artifacts.artifact import Artifact + + from ..wandb_run import Run as LocalRun + + +class StatusCode(str, Enum): + SUCCESS = "SUCCESS" + ERROR = "ERROR" + + def __str__(self) -> str: + return str(self.value) + + +class SpanKind(str, Enum): + LLM = "LLM" + CHAIN = "CHAIN" + AGENT = "AGENT" + TOOL = "TOOL" + + def __str__(self) -> str: + return str(self.value) + + +@dataclass() +class Result: + inputs: Optional[Dict[str, Any]] = field(default=None) + outputs: Optional[Dict[str, Any]] = field(default=None) + + +@dataclass() +class Span: + span_id: Optional[str] = field(default=None) + name: Optional[str] = field(default=None) + start_time_ms: Optional[int] = field(default=None) + end_time_ms: Optional[int] = field(default=None) + status_code: Optional[StatusCode] = field(default=None) + status_message: Optional[str] = field(default=None) + attributes: Optional[Dict[str, Any]] = field(default=None) + results: Optional[List[Result]] = field(default=None) + child_spans: Optional[List["Span"]] = field(default=None) + span_kind: Optional[SpanKind] = field(default=None) + + def add_attribute(self, key: str, value: Any) -> None: + if self.attributes is None: + self.attributes = {} + self.attributes[key] = value + + def add_named_result(self, inputs: Dict[str, Any], outputs: Dict[str, Any]) -> None: + if self.results is None: + self.results = [] + self.results.append(Result(inputs, outputs)) + + def add_child_span(self, span: "Span") -> None: + if self.child_spans is None: + self.child_spans = [] + self.child_spans.append(span) + + +class WBTraceTree(Media): + """Media object for trace tree data. + + Args: + root_span (Span): The root span of the trace tree. + model_dict (dict, optional): A dictionary containing the model dump. + NOTE: model_dict is a completely-user-defined dict. The UI will render + a JSON viewer for this dict, giving special treatment to dictionaries + with a `_kind` key. This is because model vendors have such different + serialization formats that we need to be flexible here. + """ + + _log_type = "wb_trace_tree" + + def __init__( + self, + root_span: Span, + model_dict: typing.Optional[dict] = None, + ): + super().__init__() + self._root_span = root_span + self._model_dict = model_dict + + @classmethod + def get_media_subdir(cls) -> str: + return "media/wb_trace_tree" + + def to_json(self, run: Optional[Union["LocalRun", "Artifact"]]) -> dict: + res = {"_type": self._log_type} + # Here we use `dumps` to put things into string format. This is because + # the complex data structures create problems for gorilla history to parquet. + if self._model_dict is not None: + model_dump_str = _safe_serialize(self._model_dict) + res["model_hash"] = _hash_id(model_dump_str) + res["model_dict_dumps"] = model_dump_str + res["root_span_dumps"] = _safe_serialize(dataclasses.asdict(self._root_span)) + return res + + def is_bound(self) -> bool: + return True + + +class _WBTraceTreeFileType(_dtypes.Type): + name = "wb_trace_tree" + types = [WBTraceTree] + + +_dtypes.TypeRegistry.add(_WBTraceTreeFileType) + + +# generate a deterministic 16 character id based on input string +def _hash_id(s: str) -> str: + return hashlib.md5(s.encode("utf-8")).hexdigest()[:16] + + +def _fallback_serialize(obj: Any) -> str: + try: + return f"<>" + except Exception: + return "<>" + + +def _safe_serialize(obj: dict) -> str: + try: + return json.dumps( + _json_helper(obj, None), + skipkeys=True, + default=_fallback_serialize, + ) + except Exception: + return "{}" + + +class TraceAttribute: + """Descriptor for accessing and setting attributes of the `Trace` class.""" + + def __set_name__(self, owner: type, name: str) -> None: + self.name = name + + def __get__(self, instance: "Trace", owner: type) -> Any: + return getattr(instance._span, self.name) + + def __set__(self, instance: "Trace", value: Any) -> None: + setattr(instance._span, self.name, value) + + +class Trace: + """A simplification of WBTraceTree and Span to manage a trace - a collection of spans, their metadata and hierarchy. + + Args: + name: (str) The name of the root span. + kind: (str, optional) The kind of the root span. + status_code: (str, optional) The status of the root span, either "error" or "success". + status_message: (str, optional) Any status message associated with the root span. + metadata: (dict, optional) Any additional metadata for the root span. + start_time_ms: (int, optional) The start time of the root span in milliseconds. + end_time_ms: (int, optional) The end time of the root span in milliseconds. + inputs: (dict, optional) The named inputs of the root span. + outputs: (dict, optional) The named outputs of the root span. + model_dict: (dict, optional) A json serializable dictionary containing the model architecture details. + + Example: + .. code-block:: python + ``` + trace = Trace( + name="My awesome Model", + kind="LLM", + status_code= "SUCCESS", + metadata={"attr_1": 1, "attr_2": 2,}, + start_time_ms=int(round(time.time() * 1000)), + end_time_ms=int(round(time.time() * 1000))+1000, + inputs={"user": "How old is google?"}, + outputs={"assistant": "25 years old"}, + model_dict={"_kind": "openai", "api_type": "azure"} + ) + run = wandb.init(project=,) + trace.log("my_trace") + wandb.finish() + ``` + """ + + name = TraceAttribute() + status_code = TraceAttribute() + status_message = TraceAttribute() + start_time_ms = TraceAttribute() + end_time_ms = TraceAttribute() + + def __init__( + self, + name: str, + kind: Optional[str] = None, + status_code: Optional[str] = None, + status_message: Optional[str] = None, + metadata: Optional[dict] = None, + start_time_ms: Optional[int] = None, + end_time_ms: Optional[int] = None, + inputs: Optional[dict] = None, + outputs: Optional[dict] = None, + model_dict: Optional[dict] = None, + ): + self._span = self._assert_and_create_span( + name=name, + kind=kind, + status_code=status_code, + status_message=status_message, + metadata=metadata, + start_time_ms=start_time_ms, + end_time_ms=end_time_ms, + inputs=inputs, + outputs=outputs, + ) + if model_dict is not None: + assert isinstance(model_dict, dict), "Model dict must be a dictionary" + self._model_dict = model_dict + + def _assert_and_create_span( + self, + name: str, + kind: Optional[str] = None, + status_code: Optional[str] = None, + status_message: Optional[str] = None, + metadata: Optional[dict] = None, + start_time_ms: Optional[int] = None, + end_time_ms: Optional[int] = None, + inputs: Optional[dict] = None, + outputs: Optional[dict] = None, + ) -> Span: + """Utility to assert the validity of the span parameters and create a span object. + + Args: + name: The name of the span. + kind: The kind of the span. + status_code: The status code of the span. + status_message: The status message of the span. + metadata: Dictionary of metadata to be logged with the span. + start_time_ms: Start time of the span in milliseconds. + end_time_ms: End time of the span in milliseconds. + inputs: Dictionary of inputs to be logged with the span. + outputs: Dictionary of outputs to be logged with the span. + + Returns: + A Span object. + """ + if kind is not None: + assert kind.upper() in SpanKind.__members__, ( + "Invalid span kind, can be one of 'LLM', 'AGENT', 'CHAIN', 'TOOL'" + ) + kind = SpanKind(kind.upper()) + if status_code is not None: + assert status_code.upper() in StatusCode.__members__, ( + "Invalid status code, can be one of 'SUCCESS' or 'ERROR'" + ) + status_code = StatusCode(status_code.upper()) + if inputs is not None: + assert isinstance(inputs, dict), "Inputs must be a dictionary" + if outputs is not None: + assert isinstance(outputs, dict), "Outputs must be a dictionary" + if inputs or outputs: + result = Result(inputs=inputs, outputs=outputs) + else: + result = None + + if metadata is not None: + assert isinstance(metadata, dict), "Metadata must be a dictionary" + + return Span( + name=name, + span_kind=kind, + status_code=status_code, + status_message=status_message, + attributes=metadata, + start_time_ms=start_time_ms, + end_time_ms=end_time_ms, + results=[result] if result else None, + ) + + def add_child( + self, + child: "Trace", + ) -> "Trace": + """Utility to add a child span to the current span of the trace. + + Args: + child: The child span to be added to the current span of the trace. + + Returns: + The current trace object with the child span added to it. + """ + self._span.add_child_span(child._span) + if self._model_dict is not None and child._model_dict is not None: + self._model_dict.update({child._span.name: child._model_dict}) + return self + + def add_inputs_and_outputs(self, inputs: dict, outputs: dict) -> "Trace": + """Add a result to the span of the current trace. + + Args: + inputs: Dictionary of inputs to be logged with the span. + outputs: Dictionary of outputs to be logged with the span. + + Returns: + The current trace object with the result added to it. + """ + if self._span.results is None: + result = Result(inputs=inputs, outputs=outputs) + self._span.results = [result] + else: + result = Result(inputs=inputs, outputs=outputs) + self._span.results.append(result) + return self + + def add_metadata(self, metadata: dict) -> "Trace": + """Add metadata to the span of the current trace.""" + if self._span.attributes is None: + self._span.attributes = metadata + else: + self._span.attributes.update(metadata) + return self + + @property + def metadata(self) -> Optional[Dict[str, str]]: + """Get the metadata of the trace. + + Returns: + Dictionary of metadata. + """ + return self._span.attributes + + @metadata.setter + def metadata(self, value: Dict[str, str]) -> None: + """Set the metadata of the trace. + + Args: + value: Dictionary of metadata to be set. + """ + if self._span.attributes is None: + self._span.attributes = value + else: + self._span.attributes.update(value) + + @property + def inputs(self) -> Optional[Dict[str, str]]: + """Get the inputs of the trace. + + Returns: + Dictionary of inputs. + """ + return self._span.results[-1].inputs if self._span.results else None + + @inputs.setter + def inputs(self, value: Dict[str, str]) -> None: + """Set the inputs of the trace. + + Args: + value: Dictionary of inputs to be set. + """ + if self._span.results is None: + result = Result(inputs=value, outputs={}) + self._span.results = [result] + else: + result = Result(inputs=value, outputs=self._span.results[-1].outputs) + self._span.results.append(result) + + @property + def outputs(self) -> Optional[Dict[str, str]]: + """Get the outputs of the trace. + + Returns: + Dictionary of outputs. + """ + return self._span.results[-1].outputs if self._span.results else None + + @outputs.setter + def outputs(self, value: Dict[str, str]) -> None: + """Set the outputs of the trace. + + Args: + value: Dictionary of outputs to be set. + """ + if self._span.results is None: + result = Result(inputs={}, outputs=value) + self._span.results = [result] + else: + result = Result(inputs=self._span.results[-1].inputs, outputs=value) + self._span.results.append(result) + + @property + def kind(self) -> Optional[str]: + """Get the kind of the trace. + + Returns: + The kind of the trace. + """ + return self._span.span_kind.value if self._span.span_kind else None + + @kind.setter + def kind(self, value: str) -> None: + """Set the kind of the trace. + + Args: + value: The kind of the trace to be set. + """ + assert value.upper() in SpanKind.__members__, ( + "Invalid span kind, can be one of 'LLM', 'AGENT', 'CHAIN', 'TOOL'" + ) + self._span.span_kind = SpanKind(value.upper()) + + def log(self, name: str) -> None: + """Log the trace to a wandb run. + + Args: + name: The name of the trace to be logged + """ + trace_tree = WBTraceTree(self._span, self._model_dict) + # NOTE: Does not work for reinit="create_new" runs. + # This method should be deprecated and users should call run.log(). + assert wandb.run is not None, ( + "You must call wandb.init() before logging a trace" + ) + assert len(name.strip()) > 0, "You must provide a valid name to log the trace" + wandb.run.log({name: trace_tree}) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0a7515446782ddce590f814f9546aea8e2887c4e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/data_types/utils.py @@ -0,0 +1,260 @@ +import datetime +import logging +import os +from decimal import Decimal +from typing import TYPE_CHECKING, Optional, Sequence, Union, cast + +import wandb +from wandb import util + +from ..internal import incremental_table_util +from .base_types.media import BatchableMedia, Media +from .base_types.wb_value import WBValue +from .image import _server_accepts_image_filenames +from .plotly import Plotly + +if TYPE_CHECKING: # pragma: no cover + import matplotlib # type: ignore + import pandas as pd + import plotly # type: ignore + + from ..wandb_run import Run as LocalRun + + ValToJsonType = Union[ + dict, + "WBValue", + Sequence["WBValue"], + "plotly.Figure", + "matplotlib.artist.Artist", + "pd.DataFrame", + object, + ] + + +def history_dict_to_json( + run: Optional["LocalRun"], + payload: dict, + step: Optional[int] = None, + ignore_copy_err: Optional[bool] = None, +) -> dict: + # Converts a History row dict's elements so they're friendly for JSON serialization. + + if step is None: + # We should be at the top level of the History row; assume this key is set. + step = payload["_step"] + + # We use list here because we were still seeing cases of RuntimeError dict changed size + for key in list(payload): + val = payload[key] + if isinstance(val, dict): + payload[key] = history_dict_to_json( + run, val, step=step, ignore_copy_err=ignore_copy_err + ) + else: + payload[key] = val_to_json( + run, key, val, namespace=step, ignore_copy_err=ignore_copy_err + ) + + return payload + + +# TODO: refine this +def val_to_json( + run: Optional["LocalRun"], + key: str, + val: "ValToJsonType", + namespace: Optional[Union[str, int]] = None, + ignore_copy_err: Optional[bool] = None, +) -> Union[Sequence, dict]: + # Converts a wandb datatype to its JSON representation. + if namespace is None: + raise ValueError( + "val_to_json must be called with a namespace(a step number, or 'summary') argument" + ) + + converted = val + + if isinstance(val, (int, float, str, bool)): + # These are already JSON-serializable, + # no need to do the expensive checks below. + return converted # type: ignore[return-value] + + typename = util.get_full_typename(val) + + if util.is_pandas_data_frame(val): + val = wandb.Table(dataframe=val) + + elif util.is_matplotlib_typename(typename) or util.is_plotly_typename(typename): + val = Plotly.make_plot_media(val) + elif isinstance(val, (list, tuple, range)) and all( + isinstance(v, WBValue) for v in val + ): + assert run + # This check will break down if Image/Audio/... have child classes. + if ( + len(val) + and isinstance(val[0], BatchableMedia) + and all(isinstance(v, type(val[0])) for v in val) + ): + if TYPE_CHECKING: + val = cast(Sequence["BatchableMedia"], val) + + items = _prune_max_seq(val) + + if _server_accepts_image_filenames(run): + for item in items: + item.bind_to_run( + run=run, + key=key, + step=namespace, + ignore_copy_err=ignore_copy_err, + ) + else: + for i, item in enumerate(items): + item.bind_to_run( + run=run, + key=key, + step=namespace, + id_=i, + ignore_copy_err=ignore_copy_err, + ) + if run._attach_id and run._init_pid != os.getpid(): + wandb.termwarn( + f"Attempting to log a sequence of {items[0].__class__.__name__} objects from multiple processes might result in data loss. Please upgrade your wandb server", + repeat=False, + ) + + return items[0].seq_to_json(items, run, key, namespace) + else: + # TODO(adrian): Good idea to pass on the same key here? Maybe include + # the array index? + # There is a bug here: if this array contains two arrays of the same type of + # anonymous media objects, their eventual names will collide. + # This used to happen. The frontend doesn't handle heterogeneous arrays + # raise ValueError( + # "Mixed media types in the same list aren't supported") + return [ + val_to_json( + run, key, v, namespace=namespace, ignore_copy_err=ignore_copy_err + ) + for v in val + ] + + if isinstance(val, WBValue): + assert run + if isinstance(val, Media) and not val.is_bound(): + if hasattr(val, "_log_type") and val._log_type in [ + "table", + "partitioned-table", + "joined-table", + ]: + _log_table_artifact(val, key, run) + + # Partitioned tables and joined tables do not support being bound to runs. + if not ( + hasattr(val, "_log_type") + and val._log_type in ["partitioned-table", "joined-table"] + ): + val.bind_to_run(run, key, namespace) + + res = val.to_json(run) + + if isinstance(val, wandb.Table) and val.log_mode == "INCREMENTAL": + # Set the _last_logged_idx AFTER the Table has been logged and + # bound to the run. + val._last_logged_idx = len(val.data) - 1 + return res + + return converted # type: ignore + + +def _log_table_artifact(val: "Media", key: str, run: "LocalRun") -> None: + """Log a table to the run based on the table type and logging mode. + + Creates and logs a `run_table` type for Table, PartitionedTable, and + JoinedTable values. For tables with log_mode="INCREMENTAL", creates and + logs an incremental artifact of type `wandb-run-incremental-table.` + + Args: + val: A wbvalue with log_type "table", "partitioned-table", + or "joined-table." + key: The key used to log val. + run: The LocalRun used to log val. + """ + from wandb.sdk.artifacts._internal_artifact import InternalArtifact + + if isinstance(val, wandb.Table) and val.log_mode == "INCREMENTAL": + if ( + run.resumed + and val._previous_increments_paths is None + and val._increment_num is None + ): + val._load_incremental_table_state_from_resumed_run(run, key) + else: + val._set_incremental_table_run_target(run) + art = incremental_table_util.init_artifact(run, key) + entry_name = incremental_table_util.get_entry_name(val, key) + else: + art = InternalArtifact(f"run-{run.id}-{key}", "run_table") + entry_name = key + + art.add(val, entry_name) + run.log_artifact(art) + + +def _prune_max_seq(seq: Sequence["BatchableMedia"]) -> Sequence["BatchableMedia"]: + # If media type has a max respect it + items = seq + if hasattr(seq[0], "MAX_ITEMS") and seq[0].MAX_ITEMS < len(seq): + logging.warning( + f"Only {seq[0].MAX_ITEMS} {seq[0].__class__.__name__} will be uploaded." + ) + items = seq[: seq[0].MAX_ITEMS] + return items + + +def _json_helper(val, artifact): + if isinstance(val, WBValue): + return val.to_json(artifact) + elif val.__class__ is dict: + res = {} + for key in val: + res[key] = _json_helper(val[key], artifact) + return res + + if hasattr(val, "tolist"): + py_val = val.tolist() + if val.__class__.__name__ == "datetime64" and isinstance(py_val, int): + # when numpy datetime64 .tolist() returns an int, it is nanoseconds. + # need to convert to milliseconds + return _json_helper(py_val / int(1e6), artifact) + return _json_helper(py_val, artifact) + elif hasattr(val, "item"): + return _json_helper(val.item(), artifact) + + if isinstance(val, datetime.datetime): + if val.tzinfo is None: + val = datetime.datetime( + val.year, + val.month, + val.day, + val.hour, + val.minute, + val.second, + val.microsecond, + tzinfo=datetime.timezone.utc, + ) + return int(val.timestamp() * 1000) + elif isinstance(val, datetime.date): + return int( + datetime.datetime( + val.year, val.month, val.day, tzinfo=datetime.timezone.utc + ).timestamp() + * 1000 + ) + elif isinstance(val, (list, tuple)): + return [_json_helper(i, artifact) for i in val] + elif isinstance(val, Decimal): + return float(val) + else: + return util.json_friendly(val)[0] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/integration_utils/auto_logging.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/integration_utils/auto_logging.py new file mode 100644 index 0000000000000000000000000000000000000000..5c3d36b9ce29299fdf2cc3d72b8878ab2e4db9ba --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/integration_utils/auto_logging.py @@ -0,0 +1,232 @@ +import asyncio +import functools +import inspect +import logging +from typing import Any, Dict, Optional, Protocol, Sequence, TypeVar + +import wandb.sdk +import wandb.util +from wandb.sdk.lib import telemetry as wb_telemetry +from wandb.sdk.lib.timer import Timer + +logger = logging.getLogger(__name__) + + +AutologInitArgs = Optional[Dict[str, Any]] + + +K = TypeVar("K", bound=str) +V = TypeVar("V") + + +class Response(Protocol[K, V]): + def __getitem__(self, key: K) -> V: ... # pragma: no cover + + def get( + self, key: K, default: Optional[V] = None + ) -> Optional[V]: ... # pragma: no cover + + +class ArgumentResponseResolver(Protocol): + def __call__( + self, + args: Sequence[Any], + kwargs: Dict[str, Any], + response: Response, + start_time: float, + time_elapsed: float, + ) -> Optional[Dict[str, Any]]: ... # pragma: no cover + + +class PatchAPI: + def __init__( + self, + name: str, + symbols: Sequence[str], + resolver: ArgumentResponseResolver, + ) -> None: + """Patches the API to log wandb Media or metrics.""" + # name of the LLM provider, e.g. "Cohere" or "OpenAI" or package name like "Transformers" + self.name = name + # api library name, e.g. "cohere" or "openai" or "transformers" + self._api = None + # dictionary of original methods + self.original_methods: Dict[str, Any] = {} + # list of symbols to patch, e.g. ["Client.generate", "Edit.create"] or ["Pipeline.__call__"] + self.symbols = symbols + # resolver callable to convert args/response into a dictionary of wandb media objects or metrics + self.resolver = resolver + + @property + def set_api(self) -> Any: + """Returns the API module.""" + lib_name = self.name.lower() + if self._api is None: + self._api = wandb.util.get_module( + name=lib_name, + required=f"To use the W&B {self.name} Autolog, " + f"you need to have the `{lib_name}` python " + f"package installed. Please install it with `pip install {lib_name}`.", + lazy=False, + ) + return self._api + + def patch(self, run: "wandb.Run") -> None: + """Patches the API to log media or metrics to W&B.""" + for symbol in self.symbols: + # split on dots, e.g. "Client.generate" -> ["Client", "generate"] + symbol_parts = symbol.split(".") + # and get the attribute from the module + original = functools.reduce(getattr, symbol_parts, self.set_api) + + def method_factory(original_method: Any): + async def async_method(*args, **kwargs): + future = asyncio.Future() + + async def callback(coro): + try: + result = await coro + loggable_dict = self.resolver( + args, kwargs, result, timer.start_time, timer.elapsed + ) + if loggable_dict is not None: + run.log(loggable_dict) + future.set_result(result) + except Exception as e: + logger.warning(e) + + with Timer() as timer: + coro = original_method(*args, **kwargs) + asyncio.ensure_future(callback(coro)) + + return await future + + def sync_method(*args, **kwargs): + with Timer() as timer: + result = original_method(*args, **kwargs) + try: + loggable_dict = self.resolver( + args, kwargs, result, timer.start_time, timer.elapsed + ) + if loggable_dict is not None: + run.log(loggable_dict) + except Exception as e: + logger.warning(e) + return result + + if inspect.iscoroutinefunction(original_method): + return functools.wraps(original_method)(async_method) + else: + return functools.wraps(original_method)(sync_method) + + # save original method + self.original_methods[symbol] = original + # monkey patch the method + if len(symbol_parts) == 1: + setattr(self.set_api, symbol_parts[0], method_factory(original)) + else: + setattr( + functools.reduce(getattr, symbol_parts[:-1], self.set_api), + symbol_parts[-1], + method_factory(original), + ) + + def unpatch(self) -> None: + """Unpatches the API.""" + for symbol, original in self.original_methods.items(): + # split on dots, e.g. "Client.generate" -> ["Client", "generate"] + symbol_parts = symbol.split(".") + # unpatch the method + if len(symbol_parts) == 1: + setattr(self.set_api, symbol_parts[0], original) + else: + setattr( + functools.reduce(getattr, symbol_parts[:-1], self.set_api), + symbol_parts[-1], + original, + ) + + +class AutologAPI: + def __init__( + self, + name: str, + symbols: Sequence[str], + resolver: ArgumentResponseResolver, + telemetry_feature: Optional[str] = None, + ) -> None: + """Autolog API calls to W&B.""" + self._telemetry_feature = telemetry_feature + self._patch_api = PatchAPI( + name=name, + symbols=symbols, + resolver=resolver, + ) + self._name = self._patch_api.name + self._run: Optional[wandb.Run] = None + self.__run_created_by_autolog: bool = False + + @property + def _is_enabled(self) -> bool: + """Returns whether autologging is enabled.""" + return self._run is not None + + def __call__(self, init: AutologInitArgs = None) -> None: + """Enable autologging.""" + self.enable(init=init) + + def _run_init(self, init: AutologInitArgs = None) -> None: + """Handle wandb run initialization.""" + # - autolog(init: dict = {...}) calls wandb.init(**{...}) + # regardless of whether there is a wandb.run or not, + # we only track if the run was created by autolog + # - todo: autolog(init: dict | run = run) would use the user-provided run + # - autolog() uses the wandb.run if there is one, otherwise it calls wandb.init() + if init: + _wandb_run = wandb.run + # we delegate dealing with the init dict to wandb.init() + self._run = wandb.init(**init) + if _wandb_run != self._run: + self.__run_created_by_autolog = True + elif wandb.run is None: + self._run = wandb.init() + self.__run_created_by_autolog = True + else: + self._run = wandb.run + + def enable(self, init: AutologInitArgs = None) -> None: + """Enable autologging. + + Args: + init: Optional dictionary of arguments to pass to wandb.init(). + + """ + if self._is_enabled: + logger.info( + f"{self._name} autologging is already enabled, disabling and re-enabling." + ) + self.disable() + + logger.info(f"Enabling {self._name} autologging.") + self._run_init(init=init) + + self._patch_api.patch(self._run) + + if self._telemetry_feature: + with wb_telemetry.context(self._run) as tel: + setattr(tel.feature, self._telemetry_feature, True) + + def disable(self) -> None: + """Disable autologging.""" + if self._run is None: + return + + logger.info(f"Disabling {self._name} autologging.") + + if self.__run_created_by_autolog: + self._run.finish() + self.__run_created_by_autolog = False + + self._run = None + + self._patch_api.unpatch() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/integration_utils/data_logging.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/integration_utils/data_logging.py new file mode 100644 index 0000000000000000000000000000000000000000..b0b971cc17211228132698f4279b7b7db1a81bed --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/integration_utils/data_logging.py @@ -0,0 +1,475 @@ +# wandb.integrations.data_logging.py +# +# Contains common utility functions that enable +# logging datasets and predictions to wandb. +import sys +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union + +import wandb + +if TYPE_CHECKING: + from wandb.data_types import _TableIndex + +CAN_INFER_IMAGE_AND_VIDEO = sys.version_info.major == 3 and sys.version_info.minor >= 5 + + +class ValidationDataLogger: + """Logs validation data as a wandb.Table. + + ValidationDataLogger is intended to be used inside of library integrations + in order to facilitate the process of optionally building a validation dataset + and logging periodic predictions against such validation data using WandB best + practices. + """ + + validation_inputs: Union[Sequence, Dict[str, Sequence]] + validation_targets: Optional[Union[Sequence, Dict[str, Sequence]]] + validation_indexes: List["_TableIndex"] + prediction_row_processor: Optional[Callable] + class_labels_table: Optional["wandb.Table"] + infer_missing_processors: bool + + def __init__( + self, + inputs: Union[Sequence, Dict[str, Sequence]], + targets: Optional[Union[Sequence, Dict[str, Sequence]]] = None, + indexes: Optional[List["_TableIndex"]] = None, + validation_row_processor: Optional[Callable] = None, + prediction_row_processor: Optional[Callable] = None, + input_col_name: str = "input", + target_col_name: str = "target", + table_name: str = "wb_validation_data", + artifact_type: str = "validation_dataset", + class_labels: Optional[List[str]] = None, + infer_missing_processors: bool = True, + ) -> None: + """Initialize a new ValidationDataLogger. + + Args: + inputs: A list of input vectors or dictionary of lists of input vectors + (used if the model has multiple named inputs) + targets: A list of target vectors or dictionary of lists of target vectors + (used if the model has multiple named targets/putputs). Defaults to `None`. + `targets` and `indexes` cannot both be `None`. + indexes: An ordered list of `wandb.data_types._TableIndex` mapping the + input items to their source table. This is most commonly retrieved by using + `indexes = my_data_table.get_index()`. Defaults to `None`. `targets` + and `indexes` cannot both be `None`. + validation_row_processor: A function to apply to the validation data, + commonly used to visualize the data. The function will receive an `ndx` (`int`) + and a `row` (`dict`). If `inputs` is a list, then `row["input"]` will be the input + data for the row. Else, it will be keyed based on the name of the input slot + (corresponding to `inputs`). If `targets` is a list, then + `row["target"]` will be the target data for the row. Else, it will + be keyed based on `targets`. For example, if your input data is a + single ndarray, but you wish to visualize the data as an image, + then you can provide `lambda ndx, row: {"img": wandb.Image(row["input"])}` + as the processor. If `None`, we will try to guess the appropriate processor. + Ignored if `log_evaluation` is `False` or `val_keys` are present. Defaults to `None`. + prediction_row_processor: Same as validation_row_processor, but applied to the + model's output. `row["output"]` will contain the results of the model output. + Defaults to `None`. + input_col_name: The name to use for the input column. + Defaults to `"input"`. + target_col_name: The name to use for the target column. + Defaults to `"target"`. + table_name: The name to use for the validation table. + Defaults to `"wb_validation_data"`. + artifact_type: The artifact type to use for the validation data. + Defaults to `"validation_dataset"`. + class_labels: Optional list of labels to use in the inferred + processors. If the model's `target` or `output` is inferred to be a class, + we will attempt to map the class to these labels. Defaults to `None`. + infer_missing_processors: Determines if processors are inferred if + they are missing. Defaults to True. + """ + class_labels_table: Optional[wandb.Table] + if isinstance(class_labels, list) and len(class_labels) > 0: + class_labels_table = wandb.Table( + columns=["label"], data=[[label] for label in class_labels] + ) + else: + class_labels_table = None + + if indexes is None: + assert targets is not None + local_validation_table = wandb.Table(columns=[], data=[]) + + if isinstance(targets, dict): + for col_name in targets: + local_validation_table.add_column(col_name, targets[col_name]) + else: + local_validation_table.add_column(target_col_name, targets) + + if isinstance(inputs, dict): + for col_name in inputs: + local_validation_table.add_column(col_name, inputs[col_name]) + else: + local_validation_table.add_column(input_col_name, inputs) + + if validation_row_processor is None and infer_missing_processors: + example_input = _make_example(inputs) + example_target = _make_example(targets) + if example_input is not None and example_target is not None: + validation_row_processor = _infer_validation_row_processor( + example_input, + example_target, + class_labels_table, + input_col_name, + target_col_name, + ) + + if validation_row_processor is not None: + local_validation_table.add_computed_columns(validation_row_processor) + + local_validation_artifact = wandb.Artifact(table_name, artifact_type) + local_validation_artifact.add(local_validation_table, "validation_data") + if wandb.run: + wandb.run.use_artifact(local_validation_artifact) + indexes = local_validation_table.get_index() + else: + local_validation_artifact = None + + self.class_labels_table = class_labels_table + self.validation_inputs = inputs + self.validation_targets = targets + self.validation_indexes = indexes + self.prediction_row_processor = prediction_row_processor + self.infer_missing_processors = infer_missing_processors + self.local_validation_artifact = local_validation_artifact + self.input_col_name = input_col_name + + def make_predictions( + self, predict_fn: Callable + ) -> Union[Sequence, Dict[str, Sequence]]: + """Produce predictions by passing `validation_inputs` to `predict_fn`. + + Args: + predict_fn (Callable): Any function which can accept `validation_inputs` and produce + a list of vectors or dictionary of lists of vectors + + Returns: + (Sequence | Dict[str, Sequence]): The returned value of predict_fn + """ + return predict_fn(self.validation_inputs) + + def log_predictions( + self, + predictions: Union[Sequence, Dict[str, Sequence]], + prediction_col_name: str = "output", + val_ndx_col_name: str = "val_row", + table_name: str = "validation_predictions", + commit: bool = True, + ) -> wandb.data_types.Table: + """Log a set of predictions. + + Intended usage: + + vl.log_predictions(vl.make_predictions(self.model.predict)) + + Args: + predictions (Sequence | Dict[str, Sequence]): A list of prediction vectors or dictionary + of lists of prediction vectors + prediction_col_name (str, optional): the name of the prediction column. Defaults to "output". + val_ndx_col_name (str, optional): The name of the column linking prediction table + to the validation ata table. Defaults to "val_row". + table_name (str, optional): name of the prediction table. Defaults to "validation_predictions". + commit (bool, optional): determines if commit should be called on the logged data. Defaults to False. + """ + pred_table = wandb.Table(columns=[], data=[]) + if isinstance(predictions, dict): + for col_name in predictions: + pred_table.add_column(col_name, predictions[col_name]) + else: + pred_table.add_column(prediction_col_name, predictions) + pred_table.add_column(val_ndx_col_name, self.validation_indexes) + + if self.prediction_row_processor is None and self.infer_missing_processors: + example_prediction = _make_example(predictions) + example_input = _make_example(self.validation_inputs) + if example_prediction is not None and example_input is not None: + self.prediction_row_processor = _infer_prediction_row_processor( + example_prediction, + example_input, + self.class_labels_table, + self.input_col_name, + prediction_col_name, + ) + + if self.prediction_row_processor is not None: + pred_table.add_computed_columns(self.prediction_row_processor) + + wandb.log({table_name: pred_table}, commit=commit) + return pred_table + + +def _make_example(data: Any) -> Optional[Union[Dict, Sequence, Any]]: + """Used to make an example input, target, or output.""" + example: Optional[Union[Dict, Sequence, Any]] + + if isinstance(data, dict): + example = {} + for key in data: + example[key] = data[key][0] + elif hasattr(data, "__len__"): + example = data[0] + else: + example = None + + return example + + +def _get_example_shape(example: Union[Sequence, Any]): + """Get the shape of an object if applicable.""" + shape = [] + if not isinstance(example, str) and hasattr(example, "__len__"): + length = len(example) + shape = [length] + if length > 0: + shape += _get_example_shape(example[0]) + return shape + + +def _bind(lambda_fn: Callable, **closure_kwargs: Any) -> Callable: + """Create a closure around a lambda function by binding `closure_kwargs` to the function.""" + + def closure(*args: Any, **kwargs: Any) -> Any: + _k = {} + _k.update(kwargs) + _k.update(closure_kwargs) + return lambda_fn(*args, **_k) + + return closure + + +def _infer_single_example_keyed_processor( + example: Union[Sequence, Any], + class_labels_table: Optional["wandb.Table"] = None, + possible_base_example: Optional[Union[Sequence, Any]] = None, +) -> Dict[str, Callable]: + """Infers a processor from a single example. + + Infers a processor from a single example with optional class_labels_table + and base_example. Base example is useful for cases such as segmentation masks + """ + shape = _get_example_shape(example) + processors: Dict[str, Callable] = {} + if ( + class_labels_table is not None + and len(shape) == 1 + and shape[0] == len(class_labels_table.data) + ): + np = wandb.util.get_module( + "numpy", + required="Inferring processors require numpy", + ) + # Assume these are logits + class_names = class_labels_table.get_column("label") + + processors["max_class"] = lambda n, d, p: class_labels_table.index_ref( # type: ignore + np.argmax(d) + ) + # TODO: Consider adding back if users ask + # processors["min_class"] = lambda n, d, p: class_labels_table.index_ref( # type: ignore + # np.argmin(d) + # ) + + values = np.unique(example) + is_one_hot = len(values) == 2 and set(values) == {0, 1} + if not is_one_hot: + processors["score"] = lambda n, d, p: { + class_names[i]: d[i] for i in range(shape[0]) + } + elif ( + len(shape) == 1 + and shape[0] == 1 + and ( + isinstance(example[0], int) + or (hasattr(example, "tolist") and isinstance(example.tolist()[0], int)) # type: ignore + ) + ): + # assume this is a class + if class_labels_table is not None: + processors["class"] = ( + lambda n, d, p: class_labels_table.index_ref(d[0]) + if d[0] < len(class_labels_table.data) + else d[0] + ) # type: ignore + else: + processors["val"] = lambda n, d, p: d[0] + elif len(shape) == 1: + np = wandb.util.get_module( + "numpy", + required="Inferring processors require numpy", + ) + # This could be anything + if shape[0] <= 10: + # if less than 10, fan out the results + # processors["node"] = lambda n, d, p: {i: d[i] for i in range(shape[0])} + processors["node"] = lambda n, d, p: [ + d[i].tolist() if hasattr(d[i], "tolist") else d[i] + for i in range(shape[0]) + ] + # just report the argmax and argmin + processors["argmax"] = lambda n, d, p: np.argmax(d) + + values = np.unique(example) + is_one_hot = len(values) == 2 and set(values) == {0, 1} + if not is_one_hot: + processors["argmin"] = lambda n, d, p: np.argmin(d) + elif len(shape) == 2 and CAN_INFER_IMAGE_AND_VIDEO: + if ( + class_labels_table is not None + and possible_base_example is not None + and shape == _get_example_shape(possible_base_example) + ): + # consider this a segmentation mask + processors["image"] = lambda n, d, p: wandb.Image( + p, + masks={ + "masks": { + "mask_data": d, + "class_labels": class_labels_table.get_column("label"), # type: ignore + } + }, + ) + else: + # consider this a 2d image + processors["image"] = lambda n, d, p: wandb.Image(d) + elif len(shape) == 3 and CAN_INFER_IMAGE_AND_VIDEO: + # consider this an image + processors["image"] = lambda n, d, p: wandb.Image(d) + elif len(shape) == 4 and CAN_INFER_IMAGE_AND_VIDEO: + # consider this a video + processors["video"] = lambda n, d, p: wandb.Video(d) + + return processors + + +def _infer_validation_row_processor( + example_input: Union[Dict, Sequence], + example_target: Union[Dict, Sequence, Any], + class_labels_table: Optional["wandb.Table"] = None, + input_col_name: str = "input", + target_col_name: str = "target", +) -> Callable: + """Infers the composite processor for the validation data.""" + single_processors = {} + if isinstance(example_input, dict): + for key in example_input: + key_processors = _infer_single_example_keyed_processor(example_input[key]) + for p_key in key_processors: + single_processors[f"{key}:{p_key}"] = _bind( + lambda ndx, row, key_processor, key: key_processor( + ndx, + row[key], + None, + ), + key_processor=key_processors[p_key], + key=key, + ) + else: + key = input_col_name + key_processors = _infer_single_example_keyed_processor(example_input) + for p_key in key_processors: + single_processors[f"{key}:{p_key}"] = _bind( + lambda ndx, row, key_processor, key: key_processor( + ndx, + row[key], + None, + ), + key_processor=key_processors[p_key], + key=key, + ) + + if isinstance(example_target, dict): + for key in example_target: + key_processors = _infer_single_example_keyed_processor( + example_target[key], class_labels_table + ) + for p_key in key_processors: + single_processors[f"{key}:{p_key}"] = _bind( + lambda ndx, row, key_processor, key: key_processor( + ndx, + row[key], + None, + ), + key_processor=key_processors[p_key], + key=key, + ) + else: + key = target_col_name + key_processors = _infer_single_example_keyed_processor( + example_target, + class_labels_table, + example_input if not isinstance(example_input, dict) else None, + ) + for p_key in key_processors: + single_processors[f"{key}:{p_key}"] = _bind( + lambda ndx, row, key_processor, key: key_processor( + ndx, + row[key], + row[input_col_name] + if not isinstance(example_input, dict) + else None, + ), + key_processor=key_processors[p_key], + key=key, + ) + + def processor(ndx, row): + return {key: single_processors[key](ndx, row) for key in single_processors} + + return processor + + +def _infer_prediction_row_processor( + example_prediction: Union[Dict, Sequence], + example_input: Union[Dict, Sequence], + class_labels_table: Optional["wandb.Table"] = None, + input_col_name: str = "input", + output_col_name: str = "output", +) -> Callable: + """Infers the composite processor for the prediction output data.""" + single_processors = {} + + if isinstance(example_prediction, dict): + for key in example_prediction: + key_processors = _infer_single_example_keyed_processor( + example_prediction[key], class_labels_table + ) + for p_key in key_processors: + single_processors[f"{key}:{p_key}"] = _bind( + lambda ndx, row, key_processor, key: key_processor( + ndx, + row[key], + None, + ), + key_processor=key_processors[p_key], + key=key, + ) + else: + key = output_col_name + key_processors = _infer_single_example_keyed_processor( + example_prediction, + class_labels_table, + example_input if not isinstance(example_input, dict) else None, + ) + for p_key in key_processors: + single_processors[f"{key}:{p_key}"] = _bind( + lambda ndx, row, key_processor, key: key_processor( + ndx, + row[key], + ndx.get_row().get("val_row").get_row().get(input_col_name) + if not isinstance(example_input, dict) + else None, + ), + key_processor=key_processors[p_key], + key=key, + ) + + def processor(ndx, row): + return {key: single_processors[key](ndx, row) for key in single_processors} + + return processor diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/interface/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/interface/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/interface/constants.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/interface/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..09fe1e26f0ce72e23df8b627ff15e332f6ebc4e6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/interface/constants.py @@ -0,0 +1,4 @@ +# +NOTIFY_PROCESS = 1 +NOTIFY_SHUTDOWN = 2 +NOTIFY_REQUEST = 3 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/interface/interface.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/interface/interface.py new file mode 100644 index 0000000000000000000000000000000000000000..89b4a3fee510fd58f4b383097ae6f2d53d5f177a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/interface/interface.py @@ -0,0 +1,1056 @@ +"""Interface base class - Used to send messages to the internal process. + +InterfaceBase: The abstract class +InterfaceShared: Common routines for socket and queue based implementations +InterfaceQueue: Use multiprocessing queues to send and receive messages +InterfaceSock: Use socket to send and receive messages +""" + +import gzip +import logging +import time +from abc import abstractmethod +from pathlib import Path +from secrets import token_hex +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Iterable, + List, + Literal, + NewType, + Optional, + Tuple, + TypedDict, + Union, +) + +from wandb import termwarn +from wandb.proto import wandb_internal_pb2 as pb +from wandb.proto import wandb_telemetry_pb2 as tpb +from wandb.sdk.artifacts.artifact import Artifact +from wandb.sdk.artifacts.artifact_manifest import ArtifactManifest +from wandb.sdk.artifacts.staging import get_staging_dir +from wandb.sdk.lib import json_util as json +from wandb.sdk.mailbox import HandleAbandonedError, MailboxHandle +from wandb.util import ( + WandBJSONEncoderOld, + get_h5_typename, + json_dumps_safer, + json_dumps_safer_history, + json_friendly, + json_friendly_val, + maybe_compress_summary, +) + +from ..data_types.utils import history_dict_to_json, val_to_json +from . import summary_record as sr + +MANIFEST_FILE_SIZE_THRESHOLD = 100_000 + +GlobStr = NewType("GlobStr", str) + + +PolicyName = Literal["now", "live", "end"] + + +class FilesDict(TypedDict): + files: Iterable[Tuple[GlobStr, PolicyName]] + + +if TYPE_CHECKING: + from ..wandb_run import Run + + +logger = logging.getLogger("wandb") + + +def file_policy_to_enum(policy: "PolicyName") -> "pb.FilesItem.PolicyType.V": + if policy == "now": + enum = pb.FilesItem.PolicyType.NOW + elif policy == "end": + enum = pb.FilesItem.PolicyType.END + elif policy == "live": + enum = pb.FilesItem.PolicyType.LIVE + return enum + + +def file_enum_to_policy(enum: "pb.FilesItem.PolicyType.V") -> "PolicyName": + if enum == pb.FilesItem.PolicyType.NOW: + policy: PolicyName = "now" + elif enum == pb.FilesItem.PolicyType.END: + policy = "end" + elif enum == pb.FilesItem.PolicyType.LIVE: + policy = "live" + return policy + + +class InterfaceBase: + _drop: bool + + def __init__(self) -> None: + self._drop = False + + def publish_header(self) -> None: + header = pb.HeaderRecord() + self._publish_header(header) + + @abstractmethod + def _publish_header(self, header: pb.HeaderRecord) -> None: + raise NotImplementedError + + def deliver_status(self) -> MailboxHandle[pb.Result]: + return self._deliver_status(pb.StatusRequest()) + + @abstractmethod + def _deliver_status( + self, + status: pb.StatusRequest, + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + def _make_config( + self, + data: Optional[dict] = None, + key: Optional[Union[Tuple[str, ...], str]] = None, + val: Optional[Any] = None, + obj: Optional[pb.ConfigRecord] = None, + ) -> pb.ConfigRecord: + config = obj or pb.ConfigRecord() + if data: + for k, v in data.items(): + update = config.update.add() + update.key = k + update.value_json = json_dumps_safer(json_friendly(v)[0]) + if key: + update = config.update.add() + if isinstance(key, tuple): + for k in key: + update.nested_key.append(k) + else: + update.key = key + update.value_json = json_dumps_safer(json_friendly(val)[0]) + return config + + def _make_run(self, run: "Run") -> pb.RunRecord: # noqa: C901 + proto_run = pb.RunRecord() + if run._settings.entity is not None: + proto_run.entity = run._settings.entity + if run._settings.project is not None: + proto_run.project = run._settings.project + if run._settings.run_group is not None: + proto_run.run_group = run._settings.run_group + if run._settings.run_job_type is not None: + proto_run.job_type = run._settings.run_job_type + if run._settings.run_id is not None: + proto_run.run_id = run._settings.run_id + if run._settings.run_name is not None: + proto_run.display_name = run._settings.run_name + if run._settings.run_notes is not None: + proto_run.notes = run._settings.run_notes + if run._settings.run_tags is not None: + proto_run.tags.extend(run._settings.run_tags) + if run._start_time is not None: + proto_run.start_time.FromMicroseconds(int(run._start_time * 1e6)) + if run._starting_step is not None: + proto_run.starting_step = run._starting_step + if run._settings.git_remote_url is not None: + proto_run.git.remote_url = run._settings.git_remote_url + if run._settings.git_commit is not None: + proto_run.git.commit = run._settings.git_commit + if run._settings.sweep_id is not None: + proto_run.sweep_id = run._settings.sweep_id + if run._settings.host: + proto_run.host = run._settings.host + if run._settings.resumed: + proto_run.resumed = run._settings.resumed + if run._settings.fork_from: + run_moment = run._settings.fork_from + proto_run.branch_point.run = run_moment.run + proto_run.branch_point.metric = run_moment.metric + proto_run.branch_point.value = run_moment.value + if run._settings.resume_from: + run_moment = run._settings.resume_from + proto_run.branch_point.run = run_moment.run + proto_run.branch_point.metric = run_moment.metric + proto_run.branch_point.value = run_moment.value + if run._forked: + proto_run.forked = run._forked + if run._config is not None: + config_dict = run._config._as_dict() # type: ignore + self._make_config(data=config_dict, obj=proto_run.config) + if run._telemetry_obj: + proto_run.telemetry.MergeFrom(run._telemetry_obj) + if run._start_runtime: + proto_run.runtime = run._start_runtime + return proto_run + + def publish_run(self, run: "Run") -> None: + run_record = self._make_run(run) + self._publish_run(run_record) + + @abstractmethod + def _publish_run(self, run: pb.RunRecord) -> None: + raise NotImplementedError + + def publish_cancel(self, cancel_slot: str) -> None: + cancel = pb.CancelRequest(cancel_slot=cancel_slot) + self._publish_cancel(cancel) + + @abstractmethod + def _publish_cancel(self, cancel: pb.CancelRequest) -> None: + raise NotImplementedError + + def publish_config( + self, + data: Optional[dict] = None, + key: Optional[Union[Tuple[str, ...], str]] = None, + val: Optional[Any] = None, + ) -> None: + cfg = self._make_config(data=data, key=key, val=val) + + self._publish_config(cfg) + + @abstractmethod + def _publish_config(self, cfg: pb.ConfigRecord) -> None: + raise NotImplementedError + + @abstractmethod + def _publish_metric(self, metric: pb.MetricRecord) -> None: + raise NotImplementedError + + def _make_summary_from_dict(self, summary_dict: dict) -> pb.SummaryRecord: + summary = pb.SummaryRecord() + for k, v in summary_dict.items(): + update = summary.update.add() + update.key = k + update.value_json = json.dumps(v) + return summary + + def _summary_encode( + self, + value: Any, + path_from_root: str, + run: "Run", + ) -> dict: + """Normalize, compress, and encode sub-objects for backend storage. + + value: Object to encode. + path_from_root: `str` dot separated string from the top-level summary to the + current `value`. + + Returns: + A new tree of dict's with large objects replaced with dictionaries + with "_type" entries that say which type the original data was. + """ + # Constructs a new `dict` tree in `json_value` that discards and/or + # encodes objects that aren't JSON serializable. + + if isinstance(value, dict): + json_value = {} + for key, value in value.items(): # noqa: B020 + json_value[key] = self._summary_encode( + value, + path_from_root + "." + key, + run=run, + ) + return json_value + else: + friendly_value, converted = json_friendly( + val_to_json(run, path_from_root, value, namespace="summary") + ) + json_value, compressed = maybe_compress_summary( + friendly_value, get_h5_typename(value) + ) + if compressed: + # TODO(jhr): impleement me + pass + # self.write_h5(path_from_root, friendly_value) + + return json_value + + def _make_summary( + self, + summary_record: sr.SummaryRecord, + run: "Run", + ) -> pb.SummaryRecord: + pb_summary_record = pb.SummaryRecord() + + for item in summary_record.update: + pb_summary_item = pb_summary_record.update.add() + key_length = len(item.key) + + assert key_length > 0 + + if key_length > 1: + pb_summary_item.nested_key.extend(item.key) + else: + pb_summary_item.key = item.key[0] + + path_from_root = ".".join(item.key) + json_value = self._summary_encode( + item.value, + path_from_root, + run=run, + ) + json_value, _ = json_friendly(json_value) # type: ignore + + pb_summary_item.value_json = json.dumps( + json_value, + cls=WandBJSONEncoderOld, + ) + + for item in summary_record.remove: + pb_summary_item = pb_summary_record.remove.add() + key_length = len(item.key) + + assert key_length > 0 + + if key_length > 1: + pb_summary_item.nested_key.extend(item.key) + else: + pb_summary_item.key = item.key[0] + + return pb_summary_record + + def publish_summary( + self, + run: "Run", + summary_record: sr.SummaryRecord, + ) -> None: + pb_summary_record = self._make_summary(summary_record, run=run) + self._publish_summary(pb_summary_record) + + @abstractmethod + def _publish_summary(self, summary: pb.SummaryRecord) -> None: + raise NotImplementedError + + def _make_files(self, files_dict: "FilesDict") -> pb.FilesRecord: + files = pb.FilesRecord() + for path, policy in files_dict["files"]: + f = files.files.add() + f.path = path + f.policy = file_policy_to_enum(policy) + return files + + def publish_files(self, files_dict: "FilesDict") -> None: + files = self._make_files(files_dict) + self._publish_files(files) + + @abstractmethod + def _publish_files(self, files: pb.FilesRecord) -> None: + raise NotImplementedError + + def publish_python_packages(self, working_set) -> None: + python_packages = pb.PythonPackagesRequest() + for pkg in working_set: + python_packages.package.add(name=pkg.key, version=pkg.version) + self._publish_python_packages(python_packages) + + @abstractmethod + def _publish_python_packages( + self, python_packages: pb.PythonPackagesRequest + ) -> None: + raise NotImplementedError + + def _make_artifact(self, artifact: "Artifact") -> pb.ArtifactRecord: + proto_artifact = pb.ArtifactRecord() + proto_artifact.type = artifact.type + proto_artifact.name = artifact.name + proto_artifact.client_id = artifact._client_id + proto_artifact.sequence_client_id = artifact._sequence_client_id + proto_artifact.digest = artifact.digest + if artifact.distributed_id: + proto_artifact.distributed_id = artifact.distributed_id + if artifact.description: + proto_artifact.description = artifact.description + if artifact.metadata: + proto_artifact.metadata = json.dumps(json_friendly_val(artifact.metadata)) + if artifact._base_id: + proto_artifact.base_id = artifact._base_id + + ttl_duration_input = artifact._ttl_duration_seconds_to_gql() + if ttl_duration_input: + proto_artifact.ttl_duration_seconds = ttl_duration_input + proto_artifact.incremental_beta1 = artifact.incremental + self._make_artifact_manifest(artifact.manifest, obj=proto_artifact.manifest) + return proto_artifact + + def _make_artifact_manifest( + self, + artifact_manifest: ArtifactManifest, + obj: Optional[pb.ArtifactManifest] = None, + ) -> pb.ArtifactManifest: + proto_manifest = obj or pb.ArtifactManifest() + proto_manifest.version = artifact_manifest.version() + proto_manifest.storage_policy = artifact_manifest.storage_policy.name() + + # Very large manifests need to be written to file to avoid protobuf size limits. + if len(artifact_manifest) > MANIFEST_FILE_SIZE_THRESHOLD: + path = self._write_artifact_manifest_file(artifact_manifest) + proto_manifest.manifest_file_path = path + return proto_manifest + + for k, v in artifact_manifest.storage_policy.config().items() or {}.items(): + cfg = proto_manifest.storage_policy_config.add() + cfg.key = k + cfg.value_json = json.dumps(v) + + for entry in sorted(artifact_manifest.entries.values(), key=lambda k: k.path): + proto_entry = proto_manifest.contents.add() + proto_entry.path = entry.path + proto_entry.digest = entry.digest + if entry.size: + proto_entry.size = entry.size + if entry.birth_artifact_id: + proto_entry.birth_artifact_id = entry.birth_artifact_id + if entry.ref: + proto_entry.ref = entry.ref + if entry.local_path: + proto_entry.local_path = entry.local_path + proto_entry.skip_cache = entry.skip_cache + for k, v in entry.extra.items(): + proto_extra = proto_entry.extra.add() + proto_extra.key = k + proto_extra.value_json = json.dumps(v) + return proto_manifest + + def _write_artifact_manifest_file(self, manifest: ArtifactManifest) -> str: + manifest_dir = Path(get_staging_dir()) / "artifact_manifests" + manifest_dir.mkdir(parents=True, exist_ok=True) + # It would be simpler to use `manifest.to_json()`, but that gets very slow for + # large manifests since it encodes the whole thing as a single JSON object. + filename = f"{time.time()}_{token_hex(8)}.manifest_contents.jl.gz" + manifest_file_path = manifest_dir / filename + with gzip.open(manifest_file_path, mode="wt", compresslevel=1) as f: + for entry in manifest.entries.values(): + f.write(f"{json.dumps(entry.to_json())}\n") + return str(manifest_file_path) + + def deliver_link_artifact( + self, + artifact: "Artifact", + portfolio_name: str, + aliases: Iterable[str], + entity: Optional[str] = None, + project: Optional[str] = None, + organization: Optional[str] = None, + ) -> MailboxHandle[pb.Result]: + link_artifact = pb.LinkArtifactRequest() + if artifact.is_draft(): + link_artifact.client_id = artifact._client_id + else: + link_artifact.server_id = artifact.id if artifact.id else "" + link_artifact.portfolio_name = portfolio_name + link_artifact.portfolio_entity = entity or "" + link_artifact.portfolio_organization = organization or "" + link_artifact.portfolio_project = project or "" + link_artifact.portfolio_aliases.extend(aliases) + + return self._deliver_link_artifact(link_artifact) + + @abstractmethod + def _deliver_link_artifact( + self, link_artifact: pb.LinkArtifactRequest + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + @staticmethod + def _make_partial_source_str( + source: Any, job_info: Dict[str, Any], metadata: Dict[str, Any] + ) -> str: + """Construct use_artifact.partial.source_info.source as str.""" + source_type = job_info.get("source_type", "").strip() + if source_type == "artifact": + info_source = job_info.get("source", {}) + source.artifact.artifact = info_source.get("artifact", "") + source.artifact.entrypoint.extend(info_source.get("entrypoint", [])) + source.artifact.notebook = info_source.get("notebook", False) + build_context = info_source.get("build_context") + if build_context: + source.artifact.build_context = build_context + dockerfile = info_source.get("dockerfile") + if dockerfile: + source.artifact.dockerfile = dockerfile + elif source_type == "repo": + source.git.git_info.remote = metadata.get("git", {}).get("remote", "") + source.git.git_info.commit = metadata.get("git", {}).get("commit", "") + source.git.entrypoint.extend(metadata.get("entrypoint", [])) + source.git.notebook = metadata.get("notebook", False) + build_context = metadata.get("build_context") + if build_context: + source.git.build_context = build_context + dockerfile = metadata.get("dockerfile") + if dockerfile: + source.git.dockerfile = dockerfile + elif source_type == "image": + source.image.image = metadata.get("docker", "") + else: + raise ValueError("Invalid source type") + + source_str: str = source.SerializeToString() + return source_str + + def _make_proto_use_artifact( + self, + use_artifact: pb.UseArtifactRecord, + job_name: str, + job_info: Dict[str, Any], + metadata: Dict[str, Any], + ) -> pb.UseArtifactRecord: + use_artifact.partial.job_name = job_name + use_artifact.partial.source_info._version = job_info.get("_version", "") + use_artifact.partial.source_info.source_type = job_info.get("source_type", "") + use_artifact.partial.source_info.runtime = job_info.get("runtime", "") + + src_str = self._make_partial_source_str( + source=use_artifact.partial.source_info.source, + job_info=job_info, + metadata=metadata, + ) + use_artifact.partial.source_info.source.ParseFromString(src_str) # type: ignore[arg-type] + + return use_artifact + + def publish_use_artifact( + self, + artifact: "Artifact", + ) -> None: + assert artifact.id is not None, "Artifact must have an id" + + use_artifact = pb.UseArtifactRecord( + id=artifact.id, + type=artifact.type, + name=artifact.name, + ) + + # TODO(gst): move to internal process + if "_partial" in artifact.metadata: + # Download source info from logged partial job artifact + job_info = {} + try: + path = artifact.get_entry("wandb-job.json").download() + with open(path) as f: + job_info = json.load(f) + + except Exception as e: + logger.warning( + f"Failed to download partial job info from artifact {artifact}, : {e}" + ) + termwarn( + f"Failed to download partial job info from artifact {artifact}, : {e}" + ) + return + + try: + use_artifact = self._make_proto_use_artifact( + use_artifact=use_artifact, + job_name=artifact.name, + job_info=job_info, + metadata=artifact.metadata, + ) + except Exception as e: + logger.warning(f"Failed to construct use artifact proto: {e}") + termwarn(f"Failed to construct use artifact proto: {e}") + return + + self._publish_use_artifact(use_artifact) + + @abstractmethod + def _publish_use_artifact(self, proto_artifact: pb.UseArtifactRecord) -> None: + raise NotImplementedError + + def deliver_artifact( + self, + run: "Run", + artifact: "Artifact", + aliases: Iterable[str], + tags: Optional[Iterable[str]] = None, + history_step: Optional[int] = None, + is_user_created: bool = False, + use_after_commit: bool = False, + finalize: bool = True, + ) -> MailboxHandle[pb.Result]: + proto_run = self._make_run(run) + proto_artifact = self._make_artifact(artifact) + proto_artifact.run_id = proto_run.run_id + proto_artifact.project = proto_run.project + proto_artifact.entity = proto_run.entity + proto_artifact.user_created = is_user_created + proto_artifact.use_after_commit = use_after_commit + proto_artifact.finalize = finalize + + proto_artifact.aliases.extend(aliases or []) + proto_artifact.tags.extend(tags or []) + + log_artifact = pb.LogArtifactRequest() + log_artifact.artifact.CopyFrom(proto_artifact) + if history_step is not None: + log_artifact.history_step = history_step + log_artifact.staging_dir = get_staging_dir() + resp = self._deliver_artifact(log_artifact) + return resp + + @abstractmethod + def _deliver_artifact( + self, + log_artifact: pb.LogArtifactRequest, + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + def deliver_download_artifact( + self, + artifact_id: str, + download_root: str, + allow_missing_references: bool, + skip_cache: bool, + path_prefix: Optional[str], + ) -> MailboxHandle[pb.Result]: + download_artifact = pb.DownloadArtifactRequest() + download_artifact.artifact_id = artifact_id + download_artifact.download_root = download_root + download_artifact.allow_missing_references = allow_missing_references + download_artifact.skip_cache = skip_cache + download_artifact.path_prefix = path_prefix or "" + resp = self._deliver_download_artifact(download_artifact) + return resp + + @abstractmethod + def _deliver_download_artifact( + self, download_artifact: pb.DownloadArtifactRequest + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + def publish_artifact( + self, + run: "Run", + artifact: "Artifact", + aliases: Iterable[str], + tags: Optional[Iterable[str]] = None, + is_user_created: bool = False, + use_after_commit: bool = False, + finalize: bool = True, + ) -> None: + proto_run = self._make_run(run) + proto_artifact = self._make_artifact(artifact) + proto_artifact.run_id = proto_run.run_id + proto_artifact.project = proto_run.project + proto_artifact.entity = proto_run.entity + proto_artifact.user_created = is_user_created + proto_artifact.use_after_commit = use_after_commit + proto_artifact.finalize = finalize + proto_artifact.aliases.extend(aliases or []) + proto_artifact.tags.extend(tags or []) + self._publish_artifact(proto_artifact) + + @abstractmethod + def _publish_artifact(self, proto_artifact: pb.ArtifactRecord) -> None: + raise NotImplementedError + + def publish_tbdata(self, log_dir: str, save: bool, root_logdir: str = "") -> None: + tbrecord = pb.TBRecord() + tbrecord.log_dir = log_dir + tbrecord.save = save + tbrecord.root_dir = root_logdir + self._publish_tbdata(tbrecord) + + @abstractmethod + def _publish_tbdata(self, tbrecord: pb.TBRecord) -> None: + raise NotImplementedError + + @abstractmethod + def _publish_telemetry(self, telem: tpb.TelemetryRecord) -> None: + raise NotImplementedError + + def publish_environment(self, environment: pb.EnvironmentRecord) -> None: + self._publish_environment(environment) + + @abstractmethod + def _publish_environment(self, environment: pb.EnvironmentRecord) -> None: + raise NotImplementedError + + def publish_partial_history( + self, + run: "Run", + data: dict, + user_step: int, + step: Optional[int] = None, + flush: Optional[bool] = None, + publish_step: bool = True, + ) -> None: + data = history_dict_to_json(run, data, step=user_step, ignore_copy_err=True) + data.pop("_step", None) + + # add timestamp to the history request, if not already present + # the timestamp might come from the tensorboard log logic + if "_timestamp" not in data: + data["_timestamp"] = time.time() + + partial_history = pb.PartialHistoryRequest() + for k, v in data.items(): + item = partial_history.item.add() + item.key = k + item.value_json = json_dumps_safer_history(v) + + if publish_step and step is not None: + partial_history.step.num = step + if flush is not None: + partial_history.action.flush = flush + self._publish_partial_history(partial_history) + + @abstractmethod + def _publish_partial_history(self, history: pb.PartialHistoryRequest) -> None: + raise NotImplementedError + + def publish_history( + self, + run: "Run", + data: dict, + step: Optional[int] = None, + publish_step: bool = True, + ) -> None: + data = history_dict_to_json(run, data, step=step) + history = pb.HistoryRecord() + if publish_step: + assert step is not None + history.step.num = step + data.pop("_step", None) + for k, v in data.items(): + item = history.item.add() + item.key = k + item.value_json = json_dumps_safer_history(v) + self._publish_history(history) + + @abstractmethod + def _publish_history(self, history: pb.HistoryRecord) -> None: + raise NotImplementedError + + def publish_preempting(self) -> None: + preempt_rec = pb.RunPreemptingRecord() + self._publish_preempting(preempt_rec) + + @abstractmethod + def _publish_preempting(self, preempt_rec: pb.RunPreemptingRecord) -> None: + raise NotImplementedError + + def publish_output(self, name: str, data: str) -> None: + # from vendor.protobuf import google3.protobuf.timestamp + # ts = timestamp.Timestamp() + # ts.GetCurrentTime() + # now = datetime.now() + if name == "stdout": + otype = pb.OutputRecord.OutputType.STDOUT + elif name == "stderr": + otype = pb.OutputRecord.OutputType.STDERR + else: + # TODO(jhr): throw error? + termwarn("unknown type") + o = pb.OutputRecord(output_type=otype, line=data) + o.timestamp.GetCurrentTime() + self._publish_output(o) + + @abstractmethod + def _publish_output(self, outdata: pb.OutputRecord) -> None: + raise NotImplementedError + + def publish_output_raw(self, name: str, data: str) -> None: + # from vendor.protobuf import google3.protobuf.timestamp + # ts = timestamp.Timestamp() + # ts.GetCurrentTime() + # now = datetime.now() + if name == "stdout": + otype = pb.OutputRawRecord.OutputType.STDOUT + elif name == "stderr": + otype = pb.OutputRawRecord.OutputType.STDERR + else: + # TODO(jhr): throw error? + termwarn("unknown type") + o = pb.OutputRawRecord(output_type=otype, line=data) + o.timestamp.GetCurrentTime() + self._publish_output_raw(o) + + @abstractmethod + def _publish_output_raw(self, outdata: pb.OutputRawRecord) -> None: + raise NotImplementedError + + def publish_pause(self) -> None: + pause = pb.PauseRequest() + self._publish_pause(pause) + + @abstractmethod + def _publish_pause(self, pause: pb.PauseRequest) -> None: + raise NotImplementedError + + def publish_resume(self) -> None: + resume = pb.ResumeRequest() + self._publish_resume(resume) + + @abstractmethod + def _publish_resume(self, resume: pb.ResumeRequest) -> None: + raise NotImplementedError + + def publish_alert( + self, title: str, text: str, level: str, wait_duration: int + ) -> None: + proto_alert = pb.AlertRecord() + proto_alert.title = title + proto_alert.text = text + proto_alert.level = level + proto_alert.wait_duration = wait_duration + self._publish_alert(proto_alert) + + @abstractmethod + def _publish_alert(self, alert: pb.AlertRecord) -> None: + raise NotImplementedError + + def _make_exit(self, exit_code: Optional[int]) -> pb.RunExitRecord: + exit = pb.RunExitRecord() + if exit_code is not None: + exit.exit_code = exit_code + return exit + + def publish_exit(self, exit_code: Optional[int]) -> None: + exit_data = self._make_exit(exit_code) + self._publish_exit(exit_data) + + @abstractmethod + def _publish_exit(self, exit_data: pb.RunExitRecord) -> None: + raise NotImplementedError + + def publish_keepalive(self) -> None: + keepalive = pb.KeepaliveRequest() + self._publish_keepalive(keepalive) + + @abstractmethod + def _publish_keepalive(self, keepalive: pb.KeepaliveRequest) -> None: + raise NotImplementedError + + def publish_job_input( + self, + include_paths: List[List[str]], + exclude_paths: List[List[str]], + input_schema: Optional[dict], + run_config: bool = False, + file_path: str = "", + ): + """Publishes a request to add inputs to the job. + + If run_config is True, the wandb.config will be added as a job input. + If file_path is provided, the file at file_path will be added as a job + input. + + The paths provided as arguments are sequences of dictionary keys that + specify a path within the wandb.config. If a path is included, the + corresponding field will be treated as a job input. If a path is + excluded, the corresponding field will not be treated as a job input. + + Args: + include_paths: paths within config to include as job inputs. + exclude_paths: paths within config to exclude as job inputs. + input_schema: A JSON Schema describing which attributes will be + editable from the Launch drawer. + run_config: bool indicating whether wandb.config is the input source. + file_path: path to file to include as a job input. + """ + if run_config and file_path: + raise ValueError( + "run_config and file_path are mutually exclusive arguments." + ) + request = pb.JobInputRequest() + include_records = [pb.JobInputPath(path=path) for path in include_paths] + exclude_records = [pb.JobInputPath(path=path) for path in exclude_paths] + request.include_paths.extend(include_records) + request.exclude_paths.extend(exclude_records) + source = pb.JobInputSource( + run_config=pb.JobInputSource.RunConfigSource(), + ) + if run_config: + source.run_config.CopyFrom(pb.JobInputSource.RunConfigSource()) + else: + source.file.CopyFrom( + pb.JobInputSource.ConfigFileSource(path=file_path), + ) + request.input_source.CopyFrom(source) + if input_schema: + request.input_schema = json_dumps_safer(input_schema) + + return self._publish_job_input(request) + + @abstractmethod + def _publish_job_input( + self, request: pb.JobInputRequest + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + def join(self) -> None: + # Drop indicates that the internal process has already been shutdown + if self._drop: + return + + handle = self._deliver_shutdown() + + try: + handle.wait_or(timeout=30) + except TimeoutError: + # This can happen if the server fails to respond due to a bug + # or due to being very busy. + logger.warning("timed out communicating shutdown") + except HandleAbandonedError: + # This can happen if the connection to the server is closed + # before a response is read. + logger.warning("handle abandoned while communicating shutdown") + + @abstractmethod + def _deliver_shutdown(self) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + def deliver_run(self, run: "Run") -> MailboxHandle[pb.Result]: + run_record = self._make_run(run) + return self._deliver_run(run_record) + + def deliver_finish_sync( + self, + ) -> MailboxHandle[pb.Result]: + sync = pb.SyncFinishRequest() + return self._deliver_finish_sync(sync) + + @abstractmethod + def _deliver_finish_sync( + self, sync: pb.SyncFinishRequest + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + @abstractmethod + def _deliver_run(self, run: pb.RunRecord) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + def deliver_run_start(self, run: "Run") -> MailboxHandle[pb.Result]: + run_start = pb.RunStartRequest(run=self._make_run(run)) + return self._deliver_run_start(run_start) + + @abstractmethod + def _deliver_run_start( + self, run_start: pb.RunStartRequest + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + def deliver_attach(self, attach_id: str) -> MailboxHandle[pb.Result]: + attach = pb.AttachRequest(attach_id=attach_id) + return self._deliver_attach(attach) + + @abstractmethod + def _deliver_attach( + self, + status: pb.AttachRequest, + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + def deliver_stop_status(self) -> MailboxHandle[pb.Result]: + status = pb.StopStatusRequest() + return self._deliver_stop_status(status) + + @abstractmethod + def _deliver_stop_status( + self, + status: pb.StopStatusRequest, + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + def deliver_network_status(self) -> MailboxHandle[pb.Result]: + status = pb.NetworkStatusRequest() + return self._deliver_network_status(status) + + @abstractmethod + def _deliver_network_status( + self, + status: pb.NetworkStatusRequest, + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + def deliver_internal_messages(self) -> MailboxHandle[pb.Result]: + internal_message = pb.InternalMessagesRequest() + return self._deliver_internal_messages(internal_message) + + @abstractmethod + def _deliver_internal_messages( + self, internal_message: pb.InternalMessagesRequest + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + def deliver_get_summary(self) -> MailboxHandle[pb.Result]: + get_summary = pb.GetSummaryRequest() + return self._deliver_get_summary(get_summary) + + @abstractmethod + def _deliver_get_summary( + self, + get_summary: pb.GetSummaryRequest, + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + def deliver_get_system_metrics(self) -> MailboxHandle[pb.Result]: + get_system_metrics = pb.GetSystemMetricsRequest() + return self._deliver_get_system_metrics(get_system_metrics) + + @abstractmethod + def _deliver_get_system_metrics( + self, get_summary: pb.GetSystemMetricsRequest + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + def deliver_exit(self, exit_code: Optional[int]) -> MailboxHandle[pb.Result]: + exit_data = self._make_exit(exit_code) + return self._deliver_exit(exit_data) + + @abstractmethod + def _deliver_exit( + self, + exit_data: pb.RunExitRecord, + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + @abstractmethod + def deliver_operation_stats(self) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + def deliver_poll_exit(self) -> MailboxHandle[pb.Result]: + poll_exit = pb.PollExitRequest() + return self._deliver_poll_exit(poll_exit) + + @abstractmethod + def _deliver_poll_exit( + self, + poll_exit: pb.PollExitRequest, + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + def deliver_finish_without_exit(self) -> MailboxHandle[pb.Result]: + run_finish_without_exit = pb.RunFinishWithoutExitRequest() + return self._deliver_finish_without_exit(run_finish_without_exit) + + @abstractmethod + def _deliver_finish_without_exit( + self, run_finish_without_exit: pb.RunFinishWithoutExitRequest + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + def deliver_request_sampled_history(self) -> MailboxHandle[pb.Result]: + sampled_history = pb.SampledHistoryRequest() + return self._deliver_request_sampled_history(sampled_history) + + @abstractmethod + def _deliver_request_sampled_history( + self, sampled_history: pb.SampledHistoryRequest + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError + + def deliver_request_run_status(self) -> MailboxHandle[pb.Result]: + run_status = pb.RunStatusRequest() + return self._deliver_request_run_status(run_status) + + @abstractmethod + def _deliver_request_run_status( + self, run_status: pb.RunStatusRequest + ) -> MailboxHandle[pb.Result]: + raise NotImplementedError diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/interface/interface_relay.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/interface/interface_relay.py new file mode 100644 index 0000000000000000000000000000000000000000..ded7989ddba3d7d6842f54ea3ebcfaccdb28aacb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/interface/interface_relay.py @@ -0,0 +1,38 @@ +"""InterfaceRelay - Derived from InterfaceQueue using RelayRouter to preserve uuid req/resp. + +See interface.py for how interface classes relate to each other. +""" + +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING + +from wandb.proto import wandb_internal_pb2 as pb +from wandb.sdk.mailbox import Mailbox + +from .interface_queue import InterfaceQueue + +if TYPE_CHECKING: + from queue import Queue + + +logger = logging.getLogger("wandb") + + +class InterfaceRelay(InterfaceQueue): + _mailbox: Mailbox + + def __init__( + self, + mailbox: Mailbox, + record_q: Queue[pb.Record], + result_q: Queue[pb.Result], + relay_q: Queue[pb.Result], + ) -> None: + self.relay_q = relay_q + super().__init__( + record_q=record_q, + result_q=result_q, + mailbox=mailbox, + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/interface/router_relay.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/interface/router_relay.py new file mode 100644 index 0000000000000000000000000000000000000000..f115668399147c17ffdcfbf4f54a7a3f2aa8a802 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/interface/router_relay.py @@ -0,0 +1,50 @@ +"""Router - handle message router (relay). + +Router to manage responses from a queue with relay. + +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from wandb.proto import wandb_internal_pb2 as pb +from wandb.proto import wandb_server_pb2 as spb +from wandb.sdk.mailbox import Mailbox + +from .router_queue import MessageQueueRouter + +if TYPE_CHECKING: + from queue import Queue + + +class MessageRelayRouter(MessageQueueRouter): + _relay_queue: Queue[pb.Result] + + def __init__( + self, + request_queue: Queue[pb.Record], + response_queue: Queue[pb.Result], + relay_queue: Queue[pb.Result], + mailbox: Mailbox, + ) -> None: + self._relay_queue = relay_queue + super().__init__( + request_queue=request_queue, + response_queue=response_queue, + mailbox=mailbox, + ) + + def _handle_msg_rcv(self, msg: pb.Result | spb.ServerResponse) -> None: + if isinstance(msg, pb.Result): + relay_msg = msg + else: + relay_msg = msg.result_communicate + + # This is legacy-service logic for returning responses to the client. + # A different thread reads the "relay queue" and writes responses on + # the socket. + if relay_msg.control.relay_id: + self._relay_queue.put(relay_msg) + else: + super()._handle_msg_rcv(msg) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/interface/router_sock.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/interface/router_sock.py new file mode 100644 index 0000000000000000000000000000000000000000..649cc2ff4a7c26bd25031af297dcbbd1f75f3ea4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/interface/router_sock.py @@ -0,0 +1,32 @@ +"""Router - handle message router (sock). + +Router to manage responses from a socket client. + +""" + +from __future__ import annotations + +from wandb.proto import wandb_internal_pb2 as pb +from wandb.proto import wandb_server_pb2 as spb +from wandb.sdk.lib.sock_client import SockClient, SockClientClosedError +from wandb.sdk.mailbox import Mailbox + +from .router import MessageRouter, MessageRouterClosedError + + +class MessageSockRouter(MessageRouter): + _sock_client: SockClient + _mailbox: Mailbox + + def __init__(self, sock_client: SockClient, mailbox: Mailbox) -> None: + self._sock_client = sock_client + super().__init__(mailbox=mailbox) + + def _read_message(self) -> spb.ServerResponse | None: + try: + return self._sock_client.read_server_response(timeout=1) + except SockClientClosedError as e: + raise MessageRouterClosedError from e + + def _send_message(self, record: pb.Record) -> None: + self._sock_client.send_record_communicate(record) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/interface/summary_record.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/interface/summary_record.py new file mode 100644 index 0000000000000000000000000000000000000000..2050a39080759ef12c54364aaf76b1dee6ab7e1d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/interface/summary_record.py @@ -0,0 +1,67 @@ +"""Summary Record. + +This module implements a summary record as an intermediate format before being converted +to a protocol buffer. +""" + +import typing as t + + +class SummaryRecord: + """Encodes a diff -- analogous to the SummaryRecord protobuf message.""" + + update: t.List["SummaryItem"] + remove: t.List["SummaryItem"] + + def __init__(self): + self.update = [] + self.remove = [] + + def __str__(self): + s = "SummaryRecord:\n Update:\n " + s += "\n ".join([str(item) for item in self.update]) + s += "\n Remove:\n " + s += "\n ".join([str(item) for item in self.remove]) + s += "\n" + return s + + __repr__ = __str__ + + def _add_next_parent(self, parent_key): + with_next_parent = SummaryRecord() + with_next_parent.update = [ + item._add_next_parent(parent_key) for item in self.update + ] + with_next_parent.remove = [ + item._add_next_parent(parent_key) for item in self.remove + ] + + return with_next_parent + + +class SummaryItem: + """Analogous to the SummaryItem protobuf message.""" + + key: t.Tuple[str] + value: t.Any + + def __init__(self): + self.key = tuple() + self.value = None + + def __str__(self): + return "SummaryItem: key: " + str(self.key) + " value: " + str(self.value) + + __repr__ = __str__ + + def _add_next_parent(self, parent_key): + with_next_parent = SummaryItem() + + key = self.key + if not isinstance(key, tuple): + key = (key,) + + with_next_parent.key = (parent_key,) + self.key + with_next_parent.value = self.value + + return with_next_parent diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/context.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/context.py new file mode 100644 index 0000000000000000000000000000000000000000..1ad49ee15a1e15b76c1cfacdbc2158fe8cfa9ad7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/context.py @@ -0,0 +1,89 @@ +"""Context Keeper.""" + +import logging +import threading +from typing import Dict, Optional + +from wandb.proto.wandb_internal_pb2 import Record, Result + +logger = logging.getLogger(__name__) + + +class Context: + _cancel_event: threading.Event + # TODO(debug_context) add debug setting to enable this + # _debug_record: Optional[Record] + + def __init__(self) -> None: + self._cancel_event = threading.Event() + # TODO(debug_context) see above + # self._debug_record = None + + def cancel(self) -> None: + self._cancel_event.set() + + @property + def cancel_event(self) -> threading.Event: + return self._cancel_event + + +def context_id_from_record(record: Record) -> str: + context_id = record.control.mailbox_slot + return context_id + + +def context_id_from_result(result: Result) -> str: + context_id = result.control.mailbox_slot + return context_id + + +class ContextKeeper: + _active_items: Dict[str, Context] + + def __init__(self) -> None: + self._active_items = {} + + def add_from_record(self, record: Record) -> Optional[Context]: + context_id = context_id_from_record(record) + if not context_id: + return None + context_obj = self.add(context_id) + + # TODO(debug_context) see above + # context_obj._debug_record = record + + return context_obj + + def add(self, context_id: str) -> Context: + assert context_id + context_obj = Context() + self._active_items[context_id] = context_obj + return context_obj + + def get(self, context_id: str) -> Optional[Context]: + item = self._active_items.get(context_id) + return item + + def release(self, context_id: str) -> None: + if not context_id: + return + _ = self._active_items.pop(context_id, None) + + def cancel(self, context_id: str) -> bool: + item = self.get(context_id) + if item: + item.cancel() + return True + return False + + # TODO(debug_context) see above + # def _debug_print_orphans(self, print_to_stdout: bool) -> None: + # for context_id, context in self._active_items.items(): + # record = context._debug_record + # record_type = record.WhichOneof("record_type") if record else "unknown" + # message = ( + # f"Context: {context_id} {context.cancel_event.is_set()} {record_type}" + # ) + # logger.warning(message) + # if print_to_stdout: + # print(message) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/datastore.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/datastore.py new file mode 100644 index 0000000000000000000000000000000000000000..76376f9b1535473d698d56db85a3af316f76ec16 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/datastore.py @@ -0,0 +1,293 @@ +"""leveldb log datastore. + +Format is described at: + https://github.com/google/leveldb/blob/master/doc/log_format.md + +block := record* trailer? +record := + checksum: uint32 // crc32c of type and data[] ; little-endian + length: uint16 // little-endian + type: uint8 // One of FULL, FIRST, MIDDLE, LAST + data: uint8[length] + +header := + ident: char[4] + magic: uint16 + version: uint8 +""" + +# TODO: possibly restructure code by porting the C++ or go implementation + +import logging +import os +import struct +import zlib +from typing import TYPE_CHECKING, Optional, Tuple + +import wandb + +if TYPE_CHECKING: + from typing import IO, Any + + from wandb.proto.wandb_internal_pb2 import Record + +logger = logging.getLogger(__name__) + +LEVELDBLOG_HEADER_LEN = 7 +LEVELDBLOG_BLOCK_LEN = 32768 +LEVELDBLOG_DATA_LEN = LEVELDBLOG_BLOCK_LEN - LEVELDBLOG_HEADER_LEN + +LEVELDBLOG_FULL = 1 +LEVELDBLOG_FIRST = 2 +LEVELDBLOG_MIDDLE = 3 +LEVELDBLOG_LAST = 4 + +LEVELDBLOG_HEADER_IDENT = ":W&B" +LEVELDBLOG_HEADER_MAGIC = ( + 0xBEE1 # zlib.crc32(bytes("Weights & Biases", 'iso8859-1')) & 0xffff +) +LEVELDBLOG_HEADER_VERSION = 0 + +try: + bytes("", "ascii") + + def strtobytes(x): + """Strtobytes.""" + return bytes(x, "iso8859-1") + + # def bytestostr(x): + # return str(x, 'iso8859-1') + +except Exception: + strtobytes = str + # bytestostr = str + + +class DataStore: + _index: int + _flush_offset: int + + def __init__(self) -> None: + self._opened_for_scan = False + self._fp: Optional[IO[Any]] = None + self._index = 0 + self._flush_offset = 0 + self._size_bytes = 0 + + self._crc = [0] * (LEVELDBLOG_LAST + 1) + for x in range(1, LEVELDBLOG_LAST + 1): + self._crc[x] = zlib.crc32(strtobytes(chr(x))) & 0xFFFFFFFF + + assert ( + wandb._assert_is_internal_process # type: ignore + ), "DataStore can only be used in the internal process" + + def open_for_write(self, fname: str) -> None: + self._fname = fname + logger.info("open: %s", fname) + open_flags = "xb" + self._fp = open(fname, open_flags) + self._write_header() + + def open_for_append(self, fname): + # TODO: implement + self._fname = fname + logger.info("open: %s", fname) + self._fp = open(fname, "wb") + # do something with _index + + def open_for_scan(self, fname): + self._fname = fname + logger.info("open for scan: %s", fname) + self._fp = open(fname, "r+b") + self._index = 0 + self._size_bytes = os.stat(fname).st_size + self._opened_for_scan = True + self._read_header() + + def seek(self, offset: int) -> None: + self._fp.seek(offset) # type: ignore + self._index = offset + + def get_offset(self) -> int: + offset = self._fp.tell() # type: ignore + return offset + + def in_last_block(self): + """Determine if we're in the last block to handle in-progress writes.""" + return self._index > self._size_bytes - LEVELDBLOG_DATA_LEN + + def scan_record(self): + assert self._opened_for_scan, "file not open for scanning" + # TODO(jhr): handle some assertions as file corruption issues + # assume we have enough room to read header, checked by caller? + header = self._fp.read(LEVELDBLOG_HEADER_LEN) + if len(header) == 0: + return None + assert len(header) == LEVELDBLOG_HEADER_LEN, ( + f"record header is {len(header)} bytes instead of the expected {LEVELDBLOG_HEADER_LEN}" + ) + fields = struct.unpack(" LEVELDBLOG_DATA_LEN: + self._write_record( + s[data_used : data_used + LEVELDBLOG_DATA_LEN], + LEVELDBLOG_MIDDLE, + ) + data_used += LEVELDBLOG_DATA_LEN + data_left -= LEVELDBLOG_DATA_LEN + + # write last and flush the entire block to disk + self._write_record(s[data_used:], LEVELDBLOG_LAST) + self._fp.flush() + os.fsync(self._fp.fileno()) + self._flush_offset = self._index + + return start_offset, self._index, self._flush_offset + + def ensure_flushed(self, off: int) -> None: + self._fp.flush() # type: ignore + + def write(self, obj: "Record") -> Tuple[int, int, int]: + """Write a protocol buffer. + + Args: + obj: Protocol buffer to write. + + Returns: + (start_offset, end_offset, flush_offset) if successful, + None otherwise + + """ + raw_size = obj.ByteSize() + s = obj.SerializeToString() + assert len(s) == raw_size, "invalid serialization" + ret = self._write_data(s) + return ret + + def close(self) -> None: + if self._fp is not None: + logger.info("close: %s", self._fname) + self._fp.close() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/file_pusher.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/file_pusher.py new file mode 100644 index 0000000000000000000000000000000000000000..72b5b2d8ca41af9d44ccb284c78d600289570f6c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/file_pusher.py @@ -0,0 +1,177 @@ +import concurrent.futures +import logging +import os +import queue +import tempfile +import threading +import time +from typing import TYPE_CHECKING, Optional, Tuple + +import wandb +import wandb.util +from wandb.filesync import stats, step_checksum, step_upload +from wandb.sdk.lib.paths import LogicalPath + +if TYPE_CHECKING: + from wandb.sdk.artifacts.artifact_manifest import ArtifactManifest + from wandb.sdk.artifacts.artifact_saver import SaveFn + from wandb.sdk.internal import file_stream, internal_api + from wandb.sdk.internal.settings_static import SettingsStatic + + +logger = logging.getLogger(__name__) + + +class FilePusher: + """Parallel file upload class. + + This manages uploading multiple files in parallel. It will restart a given file's + upload job if it receives a notification that that file has been modified. The + finish() method will block until all events have been processed and all uploads are + complete. + """ + + MAX_UPLOAD_JOBS = 64 + + def __init__( + self, + api: "internal_api.Api", + file_stream: "file_stream.FileStreamApi", + settings: Optional["SettingsStatic"] = None, + ) -> None: + self._api = api + + # Temporary directory for copies we make of some file types to + # reduce the probability that the file gets changed while we're + # uploading it. + self._tempdir = tempfile.TemporaryDirectory("wandb") + + self._stats = stats.Stats() + + self._incoming_queue: queue.Queue[step_checksum.Event] = queue.Queue() + self._event_queue: queue.Queue[step_upload.Event] = queue.Queue() + + self._step_checksum = step_checksum.StepChecksum( + self._api, + self._tempdir, + self._incoming_queue, + self._event_queue, + self._stats, + ) + self._step_checksum.start() + + self._step_upload = step_upload.StepUpload( + self._api, + self._stats, + self._event_queue, + self.MAX_UPLOAD_JOBS, + file_stream=file_stream, + settings=settings, + ) + self._step_upload.start() + + self._stats_thread_stop = threading.Event() + if os.environ.get("WANDB_DEBUG"): + # debug thread to monitor and report file pusher stats + self._stats_thread = threading.Thread( + target=self._file_pusher_stats, + daemon=True, + name="FPStatsThread", + ) + self._stats_thread.start() + + def _file_pusher_stats(self) -> None: + while not self._stats_thread_stop.is_set(): + logger.info(f"FilePusher stats: {self._stats._stats}") + time.sleep(1) + + def get_status(self) -> Tuple[bool, stats.Summary]: + running = self.is_alive() + summary = self._stats.summary() + return running, summary + + def print_status(self, prefix: bool = True) -> None: + step = 0 + spinner_states = ["-", "\\", "|", "/"] + stop = False + while True: + if not self.is_alive(): + stop = True + summary = self._stats.summary() + line = f" {summary.uploaded_bytes / 1048576.0:.2f}MB of {summary.total_bytes / 1048576.0:.2f}MB uploaded ({summary.deduped_bytes / 1048576.0:.2f}MB deduped)\r" + line = spinner_states[step % 4] + line + step += 1 + wandb.termlog(line, newline=False, prefix=prefix) + if stop: + break + time.sleep(0.25) + dedupe_fraction = ( + summary.deduped_bytes / float(summary.total_bytes) + if summary.total_bytes > 0 + else 0 + ) + if dedupe_fraction > 0.01: + wandb.termlog( + "W&B sync reduced upload amount by %.1f%% " + % (dedupe_fraction * 100), + prefix=prefix, + ) + # clear progress line. + wandb.termlog(" " * 79, prefix=prefix) + + def file_counts_by_category(self) -> stats.FileCountsByCategory: + return self._stats.file_counts_by_category() + + def file_changed(self, save_name: LogicalPath, path: str, copy: bool = True): + """Tell the file pusher that a file's changed and should be uploaded. + + Args: + save_name: string logical location of the file relative to the run + directory. + path: actual string path of the file to upload on the filesystem. + """ + # Tests in linux were failing because wandb-events.jsonl didn't exist + if not os.path.exists(path) or not os.path.isfile(path): + return + if os.path.getsize(path) == 0: + return + + event = step_checksum.RequestUpload(path, save_name, copy) + self._incoming_queue.put(event) + + def store_manifest_files( + self, + manifest: "ArtifactManifest", + artifact_id: str, + save_fn: "SaveFn", + ) -> None: + event = step_checksum.RequestStoreManifestFiles(manifest, artifact_id, save_fn) + self._incoming_queue.put(event) + + def commit_artifact( + self, + artifact_id: str, + *, + finalize: bool = True, + before_commit: step_upload.PreCommitFn, + result_future: "concurrent.futures.Future[None]", + ): + event = step_checksum.RequestCommitArtifact( + artifact_id, finalize, before_commit, result_future + ) + self._incoming_queue.put(event) + + def finish(self, callback: Optional[step_upload.OnRequestFinishFn] = None): + logger.info("shutting down file pusher") + self._incoming_queue.put(step_checksum.RequestFinish(callback)) + self._stats_thread_stop.set() + + def join(self) -> None: + # NOTE: must have called finish before join + logger.info("waiting for file pusher") + while self.is_alive(): + time.sleep(0.5) + self._tempdir.cleanup() + + def is_alive(self) -> bool: + return self._step_checksum.is_alive() or self._step_upload.is_alive() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/file_stream.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/file_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..644659c65281bcfd155d77c537ffaaf6f874d204 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/file_stream.py @@ -0,0 +1,686 @@ +import functools +import itertools +import json +import logging +import os +import queue +import random +import sys +import threading +import time +from types import TracebackType +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + List, + NamedTuple, + Optional, + Set, + Tuple, + Type, + Union, +) + +if TYPE_CHECKING: + from typing import TypedDict + + class ProcessedChunk(TypedDict): + offset: int + content: List[str] + + class ProcessedBinaryChunk(TypedDict): + offset: int + content: str + encoding: str + + +import requests + +import wandb +from wandb import util +from wandb.sdk.internal import internal_api + +from ..lib import file_stream_utils + +logger = logging.getLogger(__name__) + + +class Chunk(NamedTuple): + filename: str + data: str + + +class DefaultFilePolicy: + def __init__(self, start_chunk_id: int = 0) -> None: + self._chunk_id = start_chunk_id + self.has_debug_log = False + + def process_chunks( + self, chunks: List[Chunk] + ) -> Union[bool, "ProcessedChunk", "ProcessedBinaryChunk", List["ProcessedChunk"]]: + chunk_id = self._chunk_id + self._chunk_id += len(chunks) + return {"offset": chunk_id, "content": [c.data for c in chunks]} + + # TODO: this is very inefficient, this is meant for temporary debugging and will be removed in future releases + def _debug_log(self, data: Any): + if self.has_debug_log or not os.environ.get("WANDB_DEBUG_FILESTREAM_LOG"): + return + + loaded = json.loads(data) + if not isinstance(loaded, dict): + return + + # get key size and convert to MB + key_sizes = [(k, len(json.dumps(v))) for k, v in loaded.items()] + key_msg = [f"{k}: {v / 1048576:.5f} MB" for k, v in key_sizes] + wandb.termerror(f"Step: {loaded['_step']} | {key_msg}", repeat=False) + self.has_debug_log = True + + +class JsonlFilePolicy(DefaultFilePolicy): + def process_chunks(self, chunks: List[Chunk]) -> "ProcessedChunk": + chunk_id = self._chunk_id + # TODO: chunk_id is getting reset on each request... + self._chunk_id += len(chunks) + chunk_data = [] + for chunk in chunks: + if len(chunk.data) > util.MAX_LINE_BYTES: + msg = f"Metric data exceeds maximum size of {util.to_human_size(util.MAX_LINE_BYTES)} ({util.to_human_size(len(chunk.data))})" + wandb.termerror(msg, repeat=False) + wandb._sentry.message(msg, repeat=False) + self._debug_log(chunk.data) + else: + chunk_data.append(chunk.data) + + return { + "offset": chunk_id, + "content": chunk_data, + } + + +class SummaryFilePolicy(DefaultFilePolicy): + def process_chunks(self, chunks: List[Chunk]) -> Union[bool, "ProcessedChunk"]: + data = chunks[-1].data + if len(data) > util.MAX_LINE_BYTES: + msg = f"Summary data exceeds maximum size of {util.to_human_size(util.MAX_LINE_BYTES)}. Dropping it." + wandb.termerror(msg, repeat=False) + wandb._sentry.message(msg, repeat=False) + self._debug_log(data) + return False + return {"offset": 0, "content": [data]} + + +class StreamCRState: + r"""Stream state that tracks carriage returns. + + There are two streams: stdout and stderr. We create two instances for each stream. + An instance holds state about: + found_cr: if a carriage return has been found in this stream. + cr: most recent offset (line number) where we found \r. + We update this offset with every progress bar update. + last_normal: most recent offset without a \r in this stream. + i.e. the most recent "normal" line. + """ + + found_cr: bool + cr: Optional[int] + last_normal: Optional[int] + + def __init__(self) -> None: + self.found_cr = False + self.cr = None + self.last_normal = None + + +class CRDedupeFilePolicy(DefaultFilePolicy): + r"""File stream policy for removing carriage-return erased characters. + + This is what a terminal does. We use it for console output to reduce the amount of + data we need to send over the network (eg. for progress bars), while preserving the + output's appearance in the web app. + + CR stands for "carriage return", for the character \r. It tells the terminal to move + the cursor back to the start of the current line. Progress bars (like tqdm) use \r + repeatedly to overwrite a line with newer updates. This gives the illusion of the + progress bar filling up in real-time. + """ + + def __init__(self, start_chunk_id: int = 0) -> None: + super().__init__(start_chunk_id=start_chunk_id) + self._prev_chunk = None + + self.global_offset = 0 + # cr refers to carriage return \r + self.stderr = StreamCRState() + self.stdout = StreamCRState() + + @staticmethod + def get_consecutive_offsets(console: Dict[int, str]) -> List[List[int]]: + """Compress consecutive line numbers into an interval. + + Args: + console: Dict[int, str] which maps offsets (line numbers) to lines of text. + It represents a mini version of our console dashboard on the UI. + + Returns: + A list of intervals (we compress consecutive line numbers into an interval). + + Example: + >>> console = {2: "", 3: "", 4: "", 5: "", 10: "", 11: "", 20: ""} + >>> get_consecutive_offsets(console) + [(2, 5), (10, 11), (20, 20)] + """ + offsets = sorted(list(console.keys())) + intervals: List = [] + for i, num in enumerate(offsets): + if i == 0: + intervals.append([num, num]) + continue + largest = intervals[-1][1] + if num == largest + 1: + intervals[-1][1] = num + else: + intervals.append([num, num]) + return intervals + + @staticmethod + def split_chunk(chunk: Chunk) -> Tuple[str, str]: + r"""Split chunks. + + Args: + chunk: object with two fields: filename (str) & data (str) + `chunk.data` is a str containing the lines we want. It usually contains \n or \r or both. + `chunk.data` has two possible formats (for the two streams - stdout and stderr): + - "2020-08-25T20:38:36.895321 this is my line of text\nsecond line\n" + - "ERROR 2020-08-25T20:38:36.895321 this is my line of text\nsecond line\nthird\n". + + Here's another example with a carriage return \r. + - "ERROR 2020-08-25T20:38:36.895321 \r progress bar\n" + + Returns: + A 2-tuple of strings. + First str is prefix, either "ERROR {timestamp} " or "{timestamp} ". + Second str is the rest of the string. + + Example: + >>> chunk = Chunk( + ... filename="output.log", + ... data="ERROR 2020-08-25T20:38 this is my line of text\n", + ... ) + >>> split_chunk(chunk) + ("ERROR 2020-08-25T20:38 ", "this is my line of text\n") + """ + prefix = "" + token, rest = chunk.data.split(" ", 1) + if token == "ERROR": + prefix += token + " " + token, rest = rest.split(" ", 1) + prefix += token + " " + return prefix, rest + + def process_chunks(self, chunks: List[Chunk]) -> List["ProcessedChunk"]: + r"""Process chunks. + + Args: + chunks: List of Chunk objects. See description of chunk above in `split_chunk(...)`. + + Returns: + List[Dict]. Each dict in the list contains two keys: an `offset` which holds the line number + and `content` which maps to a list of consecutive lines starting from that offset. + `offset` here means global line number in our console on the UI. + + Example: + >>> chunks = [ + Chunk("output.log", "ERROR 2020-08-25T20:38 this is my line of text\nboom\n"), + Chunk("output.log", "2020-08-25T20:38 this is test\n"), + ] + >>> process_chunks(chunks) + [ + {"offset": 0, "content": [ + "ERROR 2020-08-25T20:38 this is my line of text\n", + "ERROR 2020-08-25T20:38 boom\n", + "2020-08-25T20:38 this is test\n" + ] + } + ] + """ + # Dict[int->str], each offset (line number) mapped to a line. + # Represents a mini-version of our console pane on the UI. + console = {} + sep = os.linesep + + for c in chunks: + prefix, logs_str = self.split_chunk(c) + logs = logs_str.split(sep) + + for line in logs: + stream = self.stderr if prefix.startswith("ERROR ") else self.stdout + if line.startswith("\r"): + # line starting with \r will always overwrite a previous offset. + offset: int = ( + stream.cr + if (stream.found_cr and stream.cr is not None) + else (stream.last_normal or 0) + ) + stream.cr = offset + stream.found_cr = True + console[offset] = prefix + line[1:] + "\n" + + # Usually logs_str = "\r progress bar\n" for progress bar updates. + # If instead logs_str = "\r progress bar\n text\n text\n", + # treat this as the end of a progress bar and reset accordingly. + if ( + logs_str.count(sep) > 1 + and logs_str.replace(sep, "").count("\r") == 1 + ): + stream.found_cr = False + + elif line: + console[self.global_offset] = prefix + line + "\n" + stream.last_normal = self.global_offset + self.global_offset += 1 + + intervals = self.get_consecutive_offsets(console) + ret = [] + for a, b in intervals: + processed_chunk: ProcessedChunk = { + "offset": self._chunk_id + a, + "content": [console[i] for i in range(a, b + 1)], + } + ret.append(processed_chunk) + return ret + + +class FileStreamApi: + """Pushes chunks of files to our streaming endpoint. + + This class is used as a singleton. It has a thread that serializes access to + the streaming endpoint and performs rate-limiting and batching. + + TODO: Differentiate between binary/text encoding. + """ + + class Finish(NamedTuple): + exitcode: int + + class Preempting(NamedTuple): + pass + + class PushSuccess(NamedTuple): + artifact_id: str + save_name: str + + MAX_ITEMS_PER_PUSH = 10000 + + def __init__( + self, + api: "internal_api.Api", + run_id: str, + start_time: float, + timeout: float = 0, + settings: Optional[dict] = None, + ) -> None: + settings = settings or dict() + # NOTE: exc_info is set in thread_except_body context and readable by calling threads + self._exc_info: Optional[ + Union[ + Tuple[Type[BaseException], BaseException, TracebackType], + Tuple[None, None, None], + ] + ] = None + self._settings = settings + self._api = api + self._run_id = run_id + self._start_time = start_time + self._client = requests.Session() + timeout = timeout or 0 + if timeout > 0: + self._client.post = functools.partial(self._client.post, timeout=timeout) # type: ignore[method-assign] + self._client.auth = api.client.transport.session.auth + self._client.headers.update(api.client.transport.headers or {}) + self._client.cookies.update(api.client.transport.cookies or {}) # type: ignore[no-untyped-call] + self._client.proxies.update(api.client.transport.session.proxies or {}) + self._file_policies: Dict[str, DefaultFilePolicy] = {} + self._dropped_chunks: int = 0 + self._queue: queue.Queue = queue.Queue() + self._thread = threading.Thread(target=self._thread_except_body) + # It seems we need to make this a daemon thread to get sync.py's atexit handler to run, which + # cleans this thread up. + self._thread.name = "FileStreamThread" + self._thread.daemon = True + self._init_endpoint() + + def _init_endpoint(self) -> None: + settings = self._api.settings() + settings.update(self._settings) + self._endpoint = "{base}/files/{entity}/{project}/{run}/file_stream".format( + base=settings["base_url"], + entity=settings["entity"], + project=settings["project"], + run=self._run_id, + ) + + def start(self) -> None: + self._init_endpoint() + self._thread.start() + + def set_default_file_policy( + self, filename: str, file_policy: "DefaultFilePolicy" + ) -> None: + """Set an upload policy for a file unless one has already been set.""" + if filename not in self._file_policies: + self._file_policies[filename] = file_policy + + def set_file_policy(self, filename: str, file_policy: "DefaultFilePolicy") -> None: + self._file_policies[filename] = file_policy + + @property + def heartbeat_seconds(self) -> Union[int, float]: + # Defaults to 30 + heartbeat_seconds: Union[int, float] = self._api.dynamic_settings[ + "heartbeat_seconds" + ] + return heartbeat_seconds + + def rate_limit_seconds(self) -> Union[int, float]: + run_time = time.time() - self._start_time + if run_time < 60: + return max(1.0, self.heartbeat_seconds / 15) + elif run_time < 300: + return max(2.5, self.heartbeat_seconds / 3) + else: + return max(5.0, self.heartbeat_seconds) + + def _read_queue(self) -> List: + # called from the push thread (_thread_body), this does an initial read + # that'll block for up to rate_limit_seconds. Then it tries to read + # as much out of the queue as it can. We do this because the http post + # to the server happens within _thread_body, and can take longer than + # our rate limit. So next time we get a chance to read the queue we want + # read all the stuff that queue'd up since last time. + # + # If we have more than MAX_ITEMS_PER_PUSH in the queue then the push thread + # will get behind and data will buffer up in the queue. + return util.read_many_from_queue( + self._queue, self.MAX_ITEMS_PER_PUSH, self.rate_limit_seconds() + ) + + def _thread_body(self) -> None: + posted_data_time = time.time() + posted_anything_time = time.time() + ready_chunks = [] + uploaded: Set[str] = set() + finished: Optional[FileStreamApi.Finish] = None + while finished is None: + items = self._read_queue() + for item in items: + if isinstance(item, self.Finish): + finished = item + elif isinstance(item, self.Preempting): + request_with_retry( + self._client.post, + self._endpoint, + json={ + "complete": False, + "preempting": True, + "dropped": self._dropped_chunks, + "uploaded": list(uploaded), + }, + ) + uploaded = set() + elif isinstance(item, self.PushSuccess): + uploaded.add(item.save_name) + else: + # item is Chunk + ready_chunks.append(item) + + cur_time = time.time() + + if ready_chunks and ( + finished or cur_time - posted_data_time > self.rate_limit_seconds() + ): + posted_data_time = cur_time + posted_anything_time = cur_time + success = self._send(ready_chunks, uploaded=uploaded) + ready_chunks = [] + if success: + uploaded = set() + + # If there aren't ready chunks or uploaded files, we still want to + # send regular heartbeats so the backend doesn't erroneously mark this + # run as crashed. + if cur_time - posted_anything_time > self.heartbeat_seconds: + posted_anything_time = cur_time + + # If we encountered an error trying to publish the + # list of uploaded files, don't reset the `uploaded` + # list. Retry publishing the list on the next attempt. + if not isinstance( + request_with_retry( + self._client.post, + self._endpoint, + json={ + "complete": False, + "failed": False, + "dropped": self._dropped_chunks, + "uploaded": list(uploaded), + }, + ), + Exception, + ): + uploaded = set() + + # post the final close message. (item is self.Finish instance now) + request_with_retry( + self._client.post, + self._endpoint, + json={ + "complete": True, + "exitcode": int(finished.exitcode), + "dropped": self._dropped_chunks, + "uploaded": list(uploaded), + }, + ) + + def _thread_except_body(self) -> None: + # TODO: Consolidate with internal_util.ExceptionThread + try: + self._thread_body() + except Exception: + exc_info = sys.exc_info() + self._exc_info = exc_info + logger.exception("generic exception in filestream thread") + wandb._sentry.exception(exc_info) + raise + + def _handle_response(self, response: Union[Exception, "requests.Response"]) -> None: + """Log dropped chunks and updates dynamic settings.""" + if isinstance(response, Exception): + wandb.termerror( + "Dropped streaming file chunk (see wandb/debug-internal.log)" + ) + logger.exception(f"dropped chunk {response}") + self._dropped_chunks += 1 + else: + parsed: Optional[dict] = None + try: + parsed = response.json() + except Exception: + pass + if isinstance(parsed, dict): + limits = parsed.get("limits") + if isinstance(limits, dict): + self._api.dynamic_settings.update(limits) + + def _send(self, chunks: List[Chunk], uploaded: Optional[Set[str]] = None) -> bool: + uploaded_list = list(uploaded or []) + # create files dict. dict of pairs where chunks are a list of + # [chunk_id, chunk_data] tuples (as lists since this will be json). + files = {} + # Groupby needs group keys to be consecutive, so sort first. + chunks.sort(key=lambda c: c.filename) + for filename, file_chunks in itertools.groupby(chunks, lambda c: c.filename): + file_chunks_list = list(file_chunks) # groupby returns iterator + # Specific file policies are set by internal/sender.py + self.set_default_file_policy(filename, DefaultFilePolicy()) + files[filename] = self._file_policies[filename].process_chunks( + file_chunks_list + ) + if not files[filename]: + del files[filename] + + for fs in file_stream_utils.split_files(files, max_bytes=util.MAX_LINE_BYTES): + self._handle_response( + request_with_retry( + self._client.post, + self._endpoint, + json={"files": fs, "dropped": self._dropped_chunks}, + retry_callback=self._api.retry_callback, + ) + ) + + if uploaded_list: + if isinstance( + request_with_retry( + self._client.post, + self._endpoint, + json={ + "complete": False, + "failed": False, + "dropped": self._dropped_chunks, + "uploaded": uploaded_list, + }, + ), + Exception, + ): + return False + return True + + def stream_file(self, path: str) -> None: + name = path.split("/")[-1] + with open(path) as f: + self._send([Chunk(name, line) for line in f]) + + def enqueue_preempting(self) -> None: + self._queue.put(self.Preempting()) + + def push(self, filename: str, data: str) -> None: + """Push a chunk of a file to the streaming endpoint. + + Args: + filename: Name of file to append to. + data: Text to append to the file. + """ + self._queue.put(Chunk(filename, data)) + + def push_success(self, artifact_id: str, save_name: str) -> None: + """Notification that a file upload has been successfully completed. + + Args: + artifact_id: ID of artifact + save_name: saved name of the uploaded file + """ + self._queue.put(self.PushSuccess(artifact_id, save_name)) + + def finish(self, exitcode: int) -> None: + """Clean up. + + Anything pushed after finish will be dropped. + + Args: + exitcode: The exitcode of the watched process. + """ + logger.info("file stream finish called") + self._queue.put(self.Finish(exitcode)) + # TODO(jhr): join on a thread which exited with an exception is a noop, clean up this path + self._thread.join() + logger.info("file stream finish is done") + if self._exc_info: + logger.error("FileStream exception", exc_info=self._exc_info) + # re-raising the original exception, will get re-caught in internal.py for the sender thread + if self._exc_info[1] is not None: + raise self._exc_info[1].with_traceback(self._exc_info[2]) + + +MAX_SLEEP_SECONDS = 60 * 5 + + +def request_with_retry( + func: Callable, + *args: Any, + **kwargs: Any, +) -> Union["requests.Response", "requests.RequestException"]: + """Perform a requests http call, retrying with exponential backoff. + + Args: + func: An http-requesting function to call, like requests.post + max_retries: Maximum retries before giving up. + By default, we retry 30 times in ~2 hours before dropping the chunk + *args: passed through to func + **kwargs: passed through to func + """ + max_retries: int = kwargs.pop("max_retries", 30) + retry_callback: Optional[Callable] = kwargs.pop("retry_callback", None) + sleep = 2 + retry_count = 0 + while True: + try: + response: requests.Response = func(*args, **kwargs) + response.raise_for_status() + return response + except ( + requests.exceptions.ConnectionError, + requests.exceptions.HTTPError, + requests.exceptions.Timeout, + ) as e: + if isinstance(e, requests.exceptions.HTTPError): + # Non-retriable HTTP errors. + # + # We retry 500s just to be cautious, and because the back end + # returns them when there are infrastructure issues. If retrying + # some request winds up being problematic, we'll change the + # back end to indicate that it shouldn't be retried. + if e.response is not None and e.response.status_code in { + 400, + 403, + 404, + 409, + }: + return e + + if retry_count == max_retries: + return e + retry_count += 1 + delay = sleep + random.random() * 0.25 * sleep + if isinstance(e, requests.exceptions.HTTPError) and ( + e.response is not None and e.response.status_code == 429 + ): + err_str = ( + f"Filestream rate limit exceeded, retrying in {delay:.1f} seconds. " + ) + if retry_callback: + retry_callback(e.response.status_code, err_str) + logger.info(err_str) + else: + logger.warning( + "requests_with_retry encountered retryable exception: %s. func: %s, args: %s, kwargs: %s", + e, + func, + args, + kwargs, + ) + time.sleep(delay) + sleep *= 2 + if sleep > MAX_SLEEP_SECONDS: + sleep = MAX_SLEEP_SECONDS + except requests.exceptions.RequestException as e: + error_message = "unknown error" + try: + error_message = response.json()["error"] # todo: clean this up + except Exception: + pass + logger.exception(f"requests_with_retry error: {error_message}") + return e diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/handler.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/handler.py new file mode 100644 index 0000000000000000000000000000000000000000..4defa1f2bc76f83bf267f5bc6f3fcd95780e950f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/handler.py @@ -0,0 +1,854 @@ +"""Handle Manager.""" + +import json +import logging +import math +import numbers +import time +from collections import defaultdict +from queue import Queue +from threading import Event +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + List, + Optional, + Sequence, + Tuple, + cast, +) + +from wandb.errors.links import url_registry +from wandb.proto.wandb_internal_pb2 import ( + HistoryRecord, + InternalMessages, + MetricRecord, + Record, + Result, + RunRecord, + SampledHistoryItem, + SummaryItem, + SummaryRecord, + SummaryRecordRequest, +) + +from ..interface.interface_queue import InterfaceQueue +from ..lib import handler_util, proto_util +from . import context, sample, tb_watcher +from .settings_static import SettingsStatic + +if TYPE_CHECKING: + from wandb.proto.wandb_internal_pb2 import MetricSummary + + +SummaryDict = Dict[str, Any] + +logger = logging.getLogger(__name__) + +# Update (March 5, 2024): Since ~2020/2021, when constructing the summary +# object, we had replaced the artifact path for media types with the latest +# artifact path. The primary purpose of this was to support live updating of +# media objects in the UI (since the default artifact path was fully qualified +# and would not update). However, in March of 2024, a bug was discovered with +# this approach which causes this path to be incorrect in cases where the media +# object is logged to another artifact before being logged to the run. Setting +# this to `False` disables this copy behavior. The impact is that users will +# need to refresh to see updates. Ironically, this updating behavior is not +# currently supported in the UI, so the impact of this change is minimal. +REPLACE_SUMMARY_ART_PATH_WITH_LATEST = False + + +def _dict_nested_set(target: Dict[str, Any], key_list: Sequence[str], v: Any) -> None: + # recurse down the dictionary structure: + + for k in key_list[:-1]: + target.setdefault(k, {}) + new_target = target.get(k) + if TYPE_CHECKING: + new_target = cast(Dict[str, Any], new_target) + target = new_target + # use the last element of the key to write the leaf: + target[key_list[-1]] = v + + +class HandleManager: + _consolidated_summary: SummaryDict + _sampled_history: Dict[str, sample.UniformSampleAccumulator] + _partial_history: Dict[str, Any] + _run_proto: Optional[RunRecord] + _settings: SettingsStatic + _record_q: "Queue[Record]" + _result_q: "Queue[Result]" + _stopped: Event + _writer_q: "Queue[Record]" + _interface: InterfaceQueue + _tb_watcher: Optional[tb_watcher.TBWatcher] + _metric_defines: Dict[str, MetricRecord] + _metric_globs: Dict[str, MetricRecord] + _metric_track: Dict[Tuple[str, ...], float] + _metric_copy: Dict[Tuple[str, ...], Any] + _track_time: Optional[float] + _accumulate_time: float + _run_start_time: Optional[float] + _context_keeper: context.ContextKeeper + + def __init__( + self, + settings: SettingsStatic, + record_q: "Queue[Record]", + result_q: "Queue[Result]", + stopped: Event, + writer_q: "Queue[Record]", + interface: InterfaceQueue, + context_keeper: context.ContextKeeper, + ) -> None: + self._settings = settings + self._record_q = record_q + self._result_q = result_q + self._stopped = stopped + self._writer_q = writer_q + self._interface = interface + self._context_keeper = context_keeper + + self._tb_watcher = None + self._step = 0 + + self._track_time = None + self._accumulate_time = 0 + self._run_start_time = None + + # keep track of summary from key/val updates + self._consolidated_summary = dict() + self._sampled_history = defaultdict(sample.UniformSampleAccumulator) + self._run_proto = None + self._partial_history = dict() + self._metric_defines = defaultdict(MetricRecord) + self._metric_globs = defaultdict(MetricRecord) + self._metric_track = dict() + self._metric_copy = dict() + self._internal_messages = InternalMessages() + + self._dropped_history = False + + def __len__(self) -> int: + return self._record_q.qsize() + + def handle(self, record: Record) -> None: + self._context_keeper.add_from_record(record) + record_type = record.WhichOneof("record_type") + assert record_type + handler_str = "handle_" + record_type + handler: Callable[[Record], None] = getattr(self, handler_str, None) # type: ignore + assert handler, f"unknown handle: {handler_str}" # type: ignore + handler(record) + + def handle_request(self, record: Record) -> None: + request_type = record.request.WhichOneof("request_type") + assert request_type + handler_str = "handle_request_" + request_type + handler: Callable[[Record], None] = getattr(self, handler_str, None) # type: ignore + if request_type != "network_status": + logger.debug(f"handle_request: {request_type}") + assert handler, f"unknown handle: {handler_str}" # type: ignore + handler(record) + + def _dispatch_record(self, record: Record, always_send: bool = False) -> None: + if always_send: + record.control.always_send = True + self._writer_q.put(record) + + def _respond_result(self, result: Result) -> None: + context_id = context.context_id_from_result(result) + self._context_keeper.release(context_id) + self._result_q.put(result) + + def debounce(self) -> None: + pass + + def handle_request_cancel(self, record: Record) -> None: + self._dispatch_record(record) + + def handle_request_defer(self, record: Record) -> None: + defer = record.request.defer + state = defer.state + + logger.info(f"handle defer: {state}") + if state == defer.FLUSH_TB: + if self._tb_watcher: + # shutdown tensorboard workers so we get all metrics flushed + self._tb_watcher.finish() + self._tb_watcher = None + elif state == defer.FLUSH_PARTIAL_HISTORY: + self._flush_partial_history() + elif state == defer.FLUSH_SUM: + self._save_summary(self._consolidated_summary, flush=True) + + # defer is used to drive the sender finish state machine + self._dispatch_record(record, always_send=True) + + def handle_request_python_packages(self, record: Record) -> None: + self._dispatch_record(record) + + def handle_run(self, record: Record) -> None: + if self._settings._offline: + self._run_proto = record.run + result = proto_util._result_from_record(record) + result.run_result.run.CopyFrom(record.run) + self._respond_result(result) + self._dispatch_record(record) + + def handle_stats(self, record: Record) -> None: + self._dispatch_record(record) + + def handle_config(self, record: Record) -> None: + self._dispatch_record(record) + + def handle_output(self, record: Record) -> None: + self._dispatch_record(record) + + def handle_output_raw(self, record: Record) -> None: + self._dispatch_record(record) + + def handle_files(self, record: Record) -> None: + self._dispatch_record(record) + + def handle_request_link_artifact(self, record: Record) -> None: + self._dispatch_record(record) + + def handle_use_artifact(self, record: Record) -> None: + self._dispatch_record(record) + + def handle_artifact(self, record: Record) -> None: + self._dispatch_record(record) + + def handle_alert(self, record: Record) -> None: + self._dispatch_record(record) + + def _save_summary(self, summary_dict: SummaryDict, flush: bool = False) -> None: + summary = SummaryRecord() + for k, v in summary_dict.items(): + update = summary.update.add() + update.key = k + update.value_json = json.dumps(v) + if flush: + record = Record(summary=summary) + self._dispatch_record(record) + elif not self._settings._offline: + # Send this summary update as a request since we aren't persisting every update + summary_record = SummaryRecordRequest(summary=summary) + request_record = self._interface._make_request( + summary_record=summary_record + ) + self._dispatch_record(request_record) + + def _save_history( + self, + history: HistoryRecord, + ) -> None: + for item in history.item: + # TODO(jhr) save nested keys? + k = item.key + v = json.loads(item.value_json) + if isinstance(v, numbers.Real): + self._sampled_history[k].add(v) + + def _update_summary_metrics( + self, + s: "MetricSummary", + kl: List[str], + v: "numbers.Real", + float_v: float, + goal_max: Optional[bool], + ) -> bool: + updated = False + best_key: Optional[Tuple[str, ...]] = None + if s.none: + return False + if s.copy: + # non-key list copy already done in _update_summary + if len(kl) > 1: + _dict_nested_set(self._consolidated_summary, kl, v) + return True + if s.last: + last_key = tuple(kl + ["last"]) + old_last = self._metric_track.get(last_key) + if old_last is None or float_v != old_last: + self._metric_track[last_key] = float_v + _dict_nested_set(self._consolidated_summary, last_key, v) + updated = True + if s.best: + best_key = tuple(kl + ["best"]) + if s.max or best_key and goal_max: + max_key = tuple(kl + ["max"]) + old_max = self._metric_track.get(max_key) + if old_max is None or float_v > old_max: + self._metric_track[max_key] = float_v + if s.max: + _dict_nested_set(self._consolidated_summary, max_key, v) + updated = True + if best_key: + _dict_nested_set(self._consolidated_summary, best_key, v) + updated = True + # defaulting to minimize if goal is not specified + if s.min or best_key and not goal_max: + min_key = tuple(kl + ["min"]) + old_min = self._metric_track.get(min_key) + if old_min is None or float_v < old_min: + self._metric_track[min_key] = float_v + if s.min: + _dict_nested_set(self._consolidated_summary, min_key, v) + updated = True + if best_key: + _dict_nested_set(self._consolidated_summary, best_key, v) + updated = True + if s.mean: + tot_key = tuple(kl + ["tot"]) + num_key = tuple(kl + ["num"]) + avg_key = tuple(kl + ["mean"]) + tot = self._metric_track.get(tot_key, 0.0) + num = self._metric_track.get(num_key, 0) + tot += float_v + num += 1 + self._metric_track[tot_key] = tot + self._metric_track[num_key] = num + _dict_nested_set(self._consolidated_summary, avg_key, tot / num) + updated = True + return updated + + def _update_summary_leaf( + self, + kl: List[str], + v: Any, + d: Optional[MetricRecord] = None, + ) -> bool: + has_summary = d and d.HasField("summary") + if len(kl) == 1: + copy_key = tuple(kl) + old_copy = self._metric_copy.get(copy_key) + if old_copy is None or v != old_copy: + self._metric_copy[copy_key] = v + # Store copy metric if not specified, or copy behavior + if not has_summary or (d and d.summary.copy): + self._consolidated_summary[kl[0]] = v + return True + if not d: + return False + if not has_summary: + return False + if not isinstance(v, numbers.Real): + return False + if math.isnan(v): + return False + float_v = float(v) + goal_max = None + if d.goal: + goal_max = d.goal == d.GOAL_MAXIMIZE + if self._update_summary_metrics( + d.summary, kl=kl, v=v, float_v=float_v, goal_max=goal_max + ): + return True + return False + + def _update_summary_list( + self, + kl: List[str], + v: Any, + d: Optional[MetricRecord] = None, + ) -> bool: + metric_key = ".".join([k.replace(".", "\\.") for k in kl]) + d = self._metric_defines.get(metric_key, d) + # if the dict has _type key, it's a wandb table object + if isinstance(v, dict) and not handler_util.metric_is_wandb_dict(v): + updated = False + for nk, nv in v.items(): + if self._update_summary_list(kl=kl[:] + [nk], v=nv, d=d): + updated = True + return updated + # If the dict is a media object, update the pointer to the latest alias + elif ( + REPLACE_SUMMARY_ART_PATH_WITH_LATEST + and isinstance(v, dict) + and handler_util.metric_is_wandb_dict(v) + ): + if "_latest_artifact_path" in v and "artifact_path" in v: + # TODO: Make non-destructive? + v["artifact_path"] = v["_latest_artifact_path"] + updated = self._update_summary_leaf(kl=kl, v=v, d=d) + return updated + + def _update_summary_media_objects(self, v: Dict[str, Any]) -> Dict[str, Any]: + # For now, non-recursive - just top level + for nk, nv in v.items(): + if REPLACE_SUMMARY_ART_PATH_WITH_LATEST and ( + isinstance(nv, dict) + and handler_util.metric_is_wandb_dict(nv) + and "_latest_artifact_path" in nv + and "artifact_path" in nv + ): + # TODO: Make non-destructive? + nv["artifact_path"] = nv["_latest_artifact_path"] + v[nk] = nv + return v + + def _update_summary(self, history_dict: Dict[str, Any]) -> List[str]: + # keep old behavior fast path if no define metrics have been used + if not self._metric_defines: + history_dict = self._update_summary_media_objects(history_dict) + self._consolidated_summary.update(history_dict) + return list(history_dict.keys()) + updated_keys = [] + for k, v in history_dict.items(): + if self._update_summary_list(kl=[k], v=v): + updated_keys.append(k) + return updated_keys + + def _history_assign_step( + self, + history: HistoryRecord, + history_dict: Dict[str, Any], + ) -> None: + has_step = history.HasField("step") + item = history.item.add() + item.key = "_step" + if has_step: + step = history.step.num + history_dict["_step"] = step + item.value_json = json.dumps(step) + self._step = step + 1 + else: + history_dict["_step"] = self._step + item.value_json = json.dumps(self._step) + self._step += 1 + + def _history_define_metric(self, hkey: str) -> Optional[MetricRecord]: + """Check for hkey match in glob metrics and return the defined metric.""" + # Dont define metric for internal metrics + if hkey.startswith("_"): + return None + for k, mglob in self._metric_globs.items(): + if k.endswith("*"): + if hkey.startswith(k[:-1]): + m = MetricRecord() + m.CopyFrom(mglob) + m.ClearField("glob_name") + m.options.defined = False + m.name = hkey + return m + return None + + def _history_update_leaf( + self, + kl: List[str], + v: Any, + history_dict: Dict[str, Any], + update_history: Dict[str, Any], + ) -> None: + hkey = ".".join([k.replace(".", "\\.") for k in kl]) + m = self._metric_defines.get(hkey) + if not m: + m = self._history_define_metric(hkey) + if not m: + return + mr = Record() + mr.metric.CopyFrom(m) + mr.control.local = True # Dont store this, just send it + self._handle_defined_metric(mr) + + if m.options.step_sync and m.step_metric: + if m.step_metric not in history_dict: + copy_key = tuple([m.step_metric]) + step = self._metric_copy.get(copy_key) + if step is not None: + update_history[m.step_metric] = step + + def _history_update_list( + self, + kl: List[str], + v: Any, + history_dict: Dict[str, Any], + update_history: Dict[str, Any], + ) -> None: + if isinstance(v, dict): + for nk, nv in v.items(): + self._history_update_list( + kl=kl[:] + [nk], + v=nv, + history_dict=history_dict, + update_history=update_history, + ) + return + self._history_update_leaf( + kl=kl, v=v, history_dict=history_dict, update_history=update_history + ) + + def _history_update( + self, + history: HistoryRecord, + history_dict: Dict[str, Any], + ) -> None: + # if syncing an old run, we can skip this logic + if history_dict.get("_step") is None: + self._history_assign_step(history, history_dict) + + update_history: Dict[str, Any] = {} + # Look for metric matches + if self._metric_defines or self._metric_globs: + for hkey, hval in history_dict.items(): + self._history_update_list([hkey], hval, history_dict, update_history) + + if update_history: + history_dict.update(update_history) + for k, v in update_history.items(): + item = history.item.add() + item.key = k + item.value_json = json.dumps(v) + + def handle_history(self, record: Record) -> None: + history_dict = proto_util.dict_from_proto_list(record.history.item) + + # Inject _runtime if it is not present + if history_dict is not None: + if "_runtime" not in history_dict: + self._history_assign_runtime(record.history, history_dict) + + self._history_update(record.history, history_dict) + self._dispatch_record(record) + self._save_history(record.history) + # update summary from history + updated_keys = self._update_summary(history_dict) + if updated_keys: + updated_items = {k: self._consolidated_summary[k] for k in updated_keys} + self._save_summary(updated_items) + + def _flush_partial_history( + self, + step: Optional[int] = None, + ) -> None: + if not self._partial_history: + return + + history = HistoryRecord() + for k, v in self._partial_history.items(): + item = history.item.add() + item.key = k + item.value_json = json.dumps(v) + if step is not None: + history.step.num = step + self.handle_history(Record(history=history)) + self._partial_history = {} + + def handle_request_sender_mark_report(self, record: Record) -> None: + self._dispatch_record(record, always_send=True) + + def handle_request_status_report(self, record: Record) -> None: + self._dispatch_record(record, always_send=True) + + def handle_request_partial_history(self, record: Record) -> None: + partial_history = record.request.partial_history + + flush = None + if partial_history.HasField("action"): + flush = partial_history.action.flush + + step = None + if partial_history.HasField("step"): + step = partial_history.step.num + + history_dict = proto_util.dict_from_proto_list(partial_history.item) + if step is not None: + if step < self._step: + if not self._dropped_history: + message = ( + "Step only supports monotonically increasing values, use define_metric to set a custom x " + f"axis. For details see: {url_registry.url('define-metric')}" + ) + self._internal_messages.warning.append(message) + self._dropped_history = True + message = ( + f"(User provided step: {step} is less than current step: {self._step}. " + f"Dropping entry: {history_dict})." + ) + self._internal_messages.warning.append(message) + return + elif step > self._step: + self._flush_partial_history() + self._step = step + elif flush is None: + flush = True + + self._partial_history.update(history_dict) + + if flush: + self._flush_partial_history(self._step) + + def handle_summary(self, record: Record) -> None: + summary = record.summary + for item in summary.update: + if len(item.nested_key) > 0: + # we use either key or nested_key -- not both + assert item.key == "" + key = tuple(item.nested_key) + else: + # no counter-assertion here, because technically + # summary[""] is valid + key = (item.key,) + + target = self._consolidated_summary + + # recurse down the dictionary structure: + for prop in key[:-1]: + target = target[prop] + + # use the last element of the key to write the leaf: + target[key[-1]] = json.loads(item.value_json) + + for item in summary.remove: + if len(item.nested_key) > 0: + # we use either key or nested_key -- not both + assert item.key == "" + key = tuple(item.nested_key) + else: + # no counter-assertion here, because technically + # summary[""] is valid + key = (item.key,) + + target = self._consolidated_summary + + # recurse down the dictionary structure: + for prop in key[:-1]: + target = target[prop] + + # use the last element of the key to erase the leaf: + del target[key[-1]] + + self._save_summary(self._consolidated_summary) + + def handle_exit(self, record: Record) -> None: + if self._track_time is not None: + self._accumulate_time += time.time() - self._track_time + record.exit.runtime = int(self._accumulate_time) + self._dispatch_record(record, always_send=True) + + def handle_final(self, record: Record) -> None: + self._dispatch_record(record, always_send=True) + + def handle_preempting(self, record: Record) -> None: + self._dispatch_record(record) + + def handle_header(self, record: Record) -> None: + self._dispatch_record(record) + + def handle_footer(self, record: Record) -> None: + self._dispatch_record(record) + + def handle_metadata(self, record: Record) -> None: + self._dispatch_record(record) + + def handle_request_attach(self, record: Record) -> None: + result = proto_util._result_from_record(record) + attach_id = record.request.attach.attach_id + assert attach_id + assert self._run_proto + result.response.attach_response.run.CopyFrom(self._run_proto) + self._respond_result(result) + + def handle_request_log_artifact(self, record: Record) -> None: + self._dispatch_record(record) + + def handle_telemetry(self, record: Record) -> None: + self._dispatch_record(record) + + def handle_request_run_start(self, record: Record) -> None: + run_start = record.request.run_start + assert run_start + assert run_start.run + + self._run_proto = run_start.run + + self._run_start_time = run_start.run.start_time.ToMicroseconds() / 1e6 + + self._track_time = time.time() + if run_start.run.resumed and run_start.run.runtime: + self._accumulate_time = run_start.run.runtime + else: + self._accumulate_time = 0 + + self._tb_watcher = tb_watcher.TBWatcher( + self._settings, interface=self._interface, run_proto=run_start.run + ) + + if run_start.run.resumed or run_start.run.forked: + self._step = run_start.run.starting_step + result = proto_util._result_from_record(record) + self._respond_result(result) + + def handle_request_resume(self, record: Record) -> None: + if self._track_time is not None: + self._accumulate_time += time.time() - self._track_time + self._track_time = time.time() + + def handle_request_pause(self, record: Record) -> None: + if self._track_time is not None: + self._accumulate_time += time.time() - self._track_time + self._track_time = None + + def handle_request_poll_exit(self, record: Record) -> None: + self._dispatch_record(record, always_send=True) + + def handle_request_stop_status(self, record: Record) -> None: + self._dispatch_record(record) + + def handle_request_network_status(self, record: Record) -> None: + self._dispatch_record(record) + + def handle_request_internal_messages(self, record: Record) -> None: + result = proto_util._result_from_record(record) + result.response.internal_messages_response.messages.CopyFrom( + self._internal_messages + ) + self._internal_messages.Clear() + self._respond_result(result) + + def handle_request_status(self, record: Record) -> None: + result = proto_util._result_from_record(record) + self._respond_result(result) + + def handle_request_get_summary(self, record: Record) -> None: + result = proto_util._result_from_record(record) + for key, value in self._consolidated_summary.items(): + item = SummaryItem() + item.key = key + item.value_json = json.dumps(value) + result.response.get_summary_response.item.append(item) + self._respond_result(result) + + def handle_tbrecord(self, record: Record) -> None: + logger.info("handling tbrecord: %s", record) + if self._tb_watcher: + tbrecord = record.tbrecord + self._tb_watcher.add(tbrecord.log_dir, tbrecord.save, tbrecord.root_dir) + self._dispatch_record(record) + + def _handle_defined_metric(self, record: Record) -> None: + metric = record.metric + if metric._control.overwrite: + self._metric_defines[metric.name].CopyFrom(metric) + else: + self._metric_defines[metric.name].MergeFrom(metric) + + # before dispatching, make sure step_metric is defined, if not define it and + # dispatch it locally first + metric = self._metric_defines[metric.name] + if metric.step_metric and metric.step_metric not in self._metric_defines: + m = MetricRecord(name=metric.step_metric) + self._metric_defines[metric.step_metric] = m + mr = Record() + mr.metric.CopyFrom(m) + mr.control.local = True # Don't store this, just send it + self._dispatch_record(mr) + + self._dispatch_record(record) + + def _handle_glob_metric(self, record: Record) -> None: + metric = record.metric + if metric._control.overwrite: + self._metric_globs[metric.glob_name].CopyFrom(metric) + else: + self._metric_globs[metric.glob_name].MergeFrom(metric) + self._dispatch_record(record) + + def handle_metric(self, record: Record) -> None: + """Handle MetricRecord. + + Walkthrough of the life of a MetricRecord: + + Metric defined: + - run.define_metric() parses arguments create wandb_metric.Metric + - build MetricRecord publish to interface + - handler (this function) keeps list of metrics published: + - self._metric_defines: Fully defined metrics + - self._metric_globs: metrics that have a wildcard + - dispatch writer and sender thread + - writer: records are saved to persistent store + - sender: fully defined metrics get mapped into metadata for UI + + History logged: + - handle_history + - check if metric matches _metric_defines + - if not, check if metric matches _metric_globs + - if _metric globs match, generate defined metric and call _handle_metric + + Args: + record (Record): Metric record to process + """ + if record.metric.name: + self._handle_defined_metric(record) + elif record.metric.glob_name: + self._handle_glob_metric(record) + + def handle_request_sampled_history(self, record: Record) -> None: + result = proto_util._result_from_record(record) + for key, sampled in self._sampled_history.items(): + item = SampledHistoryItem() + item.key = key + values: Iterable[Any] = sampled.get() + if all(isinstance(i, numbers.Integral) for i in values): + try: + item.values_int.extend(values) + except ValueError: + # it is safe to ignore these as this is for display information + pass + elif all(isinstance(i, numbers.Real) for i in values): + item.values_float.extend(values) + result.response.sampled_history_response.item.append(item) + self._respond_result(result) + + def handle_request_keepalive(self, record: Record) -> None: + """Handle a keepalive request. + + Keepalive is a noop, we just want to verify transport is alive. + """ + + def handle_request_run_status(self, record: Record) -> None: + self._dispatch_record(record, always_send=True) + + def handle_request_shutdown(self, record: Record) -> None: + # TODO(jhr): should we drain things and stop new requests from coming in? + result = proto_util._result_from_record(record) + self._respond_result(result) + self._stopped.set() + + def handle_request_operations(self, record: Record) -> None: + """No-op. Not implemented for the legacy-service.""" + self._respond_result(proto_util._result_from_record(record)) + + def finish(self) -> None: + logger.info("shutting down handler") + if self._tb_watcher: + self._tb_watcher.finish() + # self._context_keeper._debug_print_orphans() + + def __next__(self) -> Record: + return self._record_q.get(block=True) + + next = __next__ + + def _history_assign_runtime( + self, + history: HistoryRecord, + history_dict: Dict[str, Any], + ) -> None: + # _runtime calculation is meaningless if there is no _timestamp + if "_timestamp" not in history_dict: + return + # if it is offline sync, self._run_start_time is None + # in that case set it to the first tfevent timestamp + if self._run_start_time is None: + self._run_start_time = history_dict["_timestamp"] + history_dict["_runtime"] = history_dict["_timestamp"] - self._run_start_time + item = history.item.add() + item.key = "_runtime" + item.value_json = json.dumps(history_dict[item.key]) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/incremental_table_util.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/incremental_table_util.py new file mode 100644 index 0000000000000000000000000000000000000000..b1d53f7eac0cdc19328f05937427bbd173e0bdfd --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/internal_api.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/internal_api.py new file mode 100644 index 0000000000000000000000000000000000000000..5e93853938baf66e3a8b82ccfc0380d88c54d7fe --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/internal_api.py @@ -0,0 +1,4723 @@ +import base64 +import datetime +import functools +import http.client +import json +import logging +import os +import re +import socket +import sys +import threading +from copy import deepcopy +from pathlib import Path +from typing import ( + IO, + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + List, + Literal, + Mapping, + MutableMapping, + NamedTuple, + Optional, + Sequence, + TextIO, + Tuple, + Union, +) + +import click +import requests +import yaml +from wandb_gql import Client, gql +from wandb_gql.client import RetryError +from wandb_graphql.language.ast import Document + +import wandb +from wandb import env, util +from wandb.apis.normalize import normalize_exceptions, parse_backend_error_messages +from wandb.errors import AuthenticationError, CommError, UnsupportedError, UsageError +from wandb.integration.sagemaker import parse_sm_secrets +from wandb.old.settings import Settings +from wandb.proto.wandb_internal_pb2 import ServerFeature +from wandb.sdk.artifacts._validators import is_artifact_registry_project +from wandb.sdk.internal._generated import SERVER_FEATURES_QUERY_GQL, ServerFeaturesQuery +from wandb.sdk.internal.thread_local_settings import _thread_local_api_settings +from wandb.sdk.lib.gql_request import GraphQLSession +from wandb.sdk.lib.hashutil import B64MD5, md5_file_b64 + +from ..lib import credentials, retry +from ..lib.filenames import DIFF_FNAME, METADATA_FNAME +from ..lib.gitlib import GitRepo +from . import context +from .progress import Progress + +logger = logging.getLogger(__name__) + +LAUNCH_DEFAULT_PROJECT = "model-registry" + +if TYPE_CHECKING: + from typing import Literal, TypedDict + + from .progress import ProgressFn + + class CreateArtifactFileSpecInput(TypedDict, total=False): + """Corresponds to `type CreateArtifactFileSpecInput` in schema.graphql.""" + + artifactID: str + name: str + md5: str + mimetype: Optional[str] + artifactManifestID: Optional[str] + uploadPartsInput: Optional[List[Dict[str, object]]] + + class CreateArtifactFilesResponseFile(TypedDict): + id: str + name: str + displayName: str + uploadUrl: Optional[str] + uploadHeaders: Sequence[str] + uploadMultipartUrls: "UploadPartsResponse" + storagePath: str + artifact: "CreateArtifactFilesResponseFileNode" + + class CreateArtifactFilesResponseFileNode(TypedDict): + id: str + + class UploadPartsResponse(TypedDict): + uploadUrlParts: List["UploadUrlParts"] + uploadID: str + + class UploadUrlParts(TypedDict): + partNumber: int + uploadUrl: str + + class CompleteMultipartUploadArtifactInput(TypedDict): + """Corresponds to `type CompleteMultipartUploadArtifactInput` in schema.graphql.""" + + completeMultipartAction: str + completedParts: Dict[int, str] + artifactID: str + storagePath: str + uploadID: str + md5: str + + class CompleteMultipartUploadArtifactResponse(TypedDict): + digest: str + + class DefaultSettings(TypedDict): + section: str + git_remote: str + ignore_globs: Optional[List[str]] + base_url: Optional[str] + root_dir: Optional[str] + api_key: Optional[str] + entity: Optional[str] + organization: Optional[str] + project: Optional[str] + _extra_http_headers: Optional[Mapping[str, str]] + _proxies: Optional[Mapping[str, str]] + + _Response = MutableMapping + SweepState = Literal["RUNNING", "PAUSED", "CANCELED", "FINISHED"] + Number = Union[int, float] + +# class _MappingSupportsCopy(Protocol): +# def copy(self) -> "_MappingSupportsCopy": ... +# def keys(self) -> Iterable: ... +# def __getitem__(self, name: str) -> Any: ... + +httpclient_logger = logging.getLogger("http.client") +if os.environ.get("WANDB_DEBUG"): + httpclient_logger.setLevel(logging.DEBUG) + + +def check_httpclient_logger_handler() -> None: + # Only enable http.client logging if WANDB_DEBUG is set + if not os.environ.get("WANDB_DEBUG"): + return + if httpclient_logger.handlers: + return + + # Enable HTTPConnection debug logging to the logging framework + level = logging.DEBUG + + def httpclient_log(*args: Any) -> None: + httpclient_logger.log(level, " ".join(args)) + + # mask the print() built-in in the http.client module to use logging instead + http.client.print = httpclient_log # type: ignore[attr-defined] + # enable debugging + http.client.HTTPConnection.debuglevel = 1 + + root_logger = logging.getLogger("wandb") + if root_logger.handlers: + httpclient_logger.addHandler(root_logger.handlers[0]) + + +class _ThreadLocalData(threading.local): + context: Optional[context.Context] + + def __init__(self) -> None: + self.context = None + + +class _OrgNames(NamedTuple): + entity_name: str + display_name: str + + +def _match_org_with_fetched_org_entities( + organization: str, orgs: Sequence[_OrgNames] +) -> str: + """Match the organization provided in the path with the org entity or org name of the input entity. + + Args: + organization: The organization name to match + orgs: List of tuples containing (org_entity_name, org_display_name) + + Returns: + str: The matched org entity name + + Raises: + ValueError: If no matching organization is found or if multiple orgs exist without a match + """ + for org_names in orgs: + if organization in org_names: + return org_names.entity_name + + if len(orgs) == 1: + raise ValueError( + f"Expecting the organization name or entity name to match {orgs[0].display_name!r} " + f"and cannot be linked/fetched with {organization!r}. " + "Please update the target path with the correct organization name." + ) + + raise ValueError( + "Personal entity belongs to multiple organizations " + f"and cannot be linked/fetched with {organization!r}. " + "Please update the target path with the correct organization name " + "or use a team entity in the entity settings." + ) + + +class Api: + """W&B Internal Api wrapper. + + Note: + Settings are automatically overridden by looking for + a `wandb/settings` file in the current working directory or its parent + directory. If none can be found, we look in the current user's home + directory. + + Args: + default_settings(dict, optional): If you aren't using a settings + file, or you wish to override the section to use in the settings file + Override the settings here. + """ + + HTTP_TIMEOUT = env.get_http_timeout(20) + FILE_PUSHER_TIMEOUT = env.get_file_pusher_timeout() + _global_context: context.Context + _local_data: _ThreadLocalData + + def __init__( + self, + default_settings: Optional[ + Union[ + "wandb.sdk.wandb_settings.Settings", + "wandb.sdk.internal.settings_static.SettingsStatic", + Settings, + dict, + ] + ] = None, + load_settings: bool = True, + retry_timedelta: datetime.timedelta = datetime.timedelta( # okay because it's immutable + days=7 + ), + environ: MutableMapping = os.environ, + retry_callback: Optional[Callable[[int, str], Any]] = None, + api_key: Optional[str] = None, + ) -> None: + self._environ = environ + self._global_context = context.Context() + self._local_data = _ThreadLocalData() + self.default_settings: DefaultSettings = { + "section": "default", + "git_remote": "origin", + "ignore_globs": [], + "base_url": "https://api.wandb.ai", + "root_dir": None, + "api_key": None, + "entity": None, + "organization": None, + "project": None, + "_extra_http_headers": None, + "_proxies": None, + } + self.retry_timedelta = retry_timedelta + # todo: Old Settings do not follow the SupportsKeysAndGetItem Protocol + default_settings = default_settings or {} + self.default_settings.update(default_settings) # type: ignore + self.retry_uploads = 10 + self._settings = Settings( + load_settings=load_settings, + root_dir=self.default_settings.get("root_dir"), + ) + self.git = GitRepo(remote=self.settings("git_remote")) + # Mutable settings set by the _file_stream_api + self.dynamic_settings = { + "system_sample_seconds": 2, + "system_samples": 15, + "heartbeat_seconds": 30, + } + + # todo: remove these hacky hacks after settings refactor is complete + # keeping this code here to limit scope and so that it is easy to remove later + self._extra_http_headers = self.settings("_extra_http_headers") or json.loads( + self._environ.get("WANDB__EXTRA_HTTP_HEADERS", "{}") + ) + self._extra_http_headers.update(_thread_local_api_settings.headers or {}) + + auth = None + api_key = api_key or self.default_settings.get("api_key") + if api_key: + auth = ("api", api_key) + elif self.access_token is not None: + self._extra_http_headers["Authorization"] = f"Bearer {self.access_token}" + elif _thread_local_api_settings.cookies is None: + auth = ("api", self.api_key or "") + + proxies = self.settings("_proxies") or json.loads( + self._environ.get("WANDB__PROXIES", "{}") + ) + + self.client = Client( + transport=GraphQLSession( + headers={ + "User-Agent": self.user_agent, + "X-WANDB-USERNAME": env.get_username(env=self._environ), + "X-WANDB-USER-EMAIL": env.get_user_email(env=self._environ), + **self._extra_http_headers, + }, + use_json=True, + # this timeout won't apply when the DNS lookup fails. in that case, it will be 60s + # https://bugs.python.org/issue22889 + timeout=self.HTTP_TIMEOUT, + auth=auth, + url=f"{self.settings('base_url')}/graphql", + cookies=_thread_local_api_settings.cookies, + proxies=proxies, + ) + ) + + self.retry_callback = retry_callback + self._retry_gql = retry.Retry( + self.execute, + retry_timedelta=retry_timedelta, + check_retry_fn=util.no_retry_auth, + retryable_exceptions=(RetryError, requests.RequestException), + retry_callback=retry_callback, + ) + self._current_run_id: Optional[str] = None + self._file_stream_api = None + self._upload_file_session = requests.Session() + if self.FILE_PUSHER_TIMEOUT: + self._upload_file_session.put = functools.partial( # type: ignore + self._upload_file_session.put, + timeout=self.FILE_PUSHER_TIMEOUT, + ) + if proxies: + self._upload_file_session.proxies.update(proxies) + # This Retry class is initialized once for each Api instance, so this + # defaults to retrying 1 million times per process or 7 days + self.upload_file_retry = normalize_exceptions( + retry.retriable(retry_timedelta=retry_timedelta)(self.upload_file) + ) + self.upload_multipart_file_chunk_retry = normalize_exceptions( + retry.retriable(retry_timedelta=retry_timedelta)( + self.upload_multipart_file_chunk + ) + ) + self._client_id_mapping: Dict[str, str] = {} + # Large file uploads to azure can optionally use their SDK + self._azure_blob_module = util.get_module("azure.storage.blob") + + self.query_types: Optional[List[str]] = None + self.mutation_types: Optional[List[str]] = None + self.server_info_types: Optional[List[str]] = None + self.server_use_artifact_input_info: Optional[List[str]] = None + self.server_create_artifact_input_info: Optional[List[str]] = None + self.server_artifact_fields_info: Optional[List[str]] = None + self.server_organization_type_fields_info: Optional[List[str]] = None + self.server_supports_enabling_artifact_usage_tracking: Optional[bool] = None + self._max_cli_version: Optional[str] = None + self._server_settings_type: Optional[List[str]] = None + self.fail_run_queue_item_input_info: Optional[List[str]] = None + self.create_launch_agent_input_info: Optional[List[str]] = None + self.server_create_run_queue_supports_drc: Optional[bool] = None + self.server_create_run_queue_supports_priority: Optional[bool] = None + self.server_supports_template_variables: Optional[bool] = None + self.server_push_to_run_queue_supports_priority: Optional[bool] = None + + self._server_features_cache: Optional[Dict[str, bool]] = None + + def gql(self, *args: Any, **kwargs: Any) -> Any: + ret = self._retry_gql( + *args, + retry_cancel_event=self.context.cancel_event, + **kwargs, + ) + return ret + + def set_local_context(self, api_context: Optional[context.Context]) -> None: + self._local_data.context = api_context + + def clear_local_context(self) -> None: + self._local_data.context = None + + @property + def context(self) -> context.Context: + return self._local_data.context or self._global_context + + def reauth(self) -> None: + """Ensure the current api key is set in the transport.""" + self.client.transport.session.auth = ("api", self.api_key or "") + + def relocate(self) -> None: + """Ensure the current api points to the right server.""" + self.client.transport.url = "{}/graphql".format(self.settings("base_url")) + + def execute(self, *args: Any, **kwargs: Any) -> "_Response": + """Wrapper around execute that logs in cases of failure.""" + try: + return self.client.execute(*args, **kwargs) # type: ignore + except requests.exceptions.HTTPError as err: + response = err.response + assert response is not None + logger.exception("Error executing GraphQL.") + for error in parse_backend_error_messages(response): + wandb.termerror(f"Error while calling W&B API: {error} ({response})") + raise + + def validate_api_key(self) -> bool: + """Returns whether the API key stored on initialization is valid.""" + res = self.execute(gql("query { viewer { id } }")) + return res is not None and res["viewer"] is not None + + def set_current_run_id(self, run_id: str) -> None: + self._current_run_id = run_id + + @property + def current_run_id(self) -> Optional[str]: + return self._current_run_id + + @property + def user_agent(self) -> str: + return f"W&B Internal Client {wandb.__version__}" + + @property + def api_key(self) -> Optional[str]: + if _thread_local_api_settings.api_key: + return _thread_local_api_settings.api_key + auth = requests.utils.get_netrc_auth(self.api_url) + key = None + if auth: + key = auth[-1] + + # Environment should take precedence + env_key: Optional[str] = self._environ.get(env.API_KEY) + sagemaker_key: Optional[str] = parse_sm_secrets().get(env.API_KEY) + default_key: Optional[str] = self.default_settings.get("api_key") + return env_key or key or sagemaker_key or default_key + + @property + def access_token(self) -> Optional[str]: + """Retrieves an access token for authentication. + + This function attempts to exchange an identity token for a temporary + access token from the server, and save it to the credentials file. + It uses the path to the identity token as defined in the environment + variables. If the environment variable is not set, it returns None. + + Returns: + Optional[str]: The access token if available, otherwise None if + no identity token is supplied. + Raises: + AuthenticationError: If the path to the identity token is not found. + """ + token_file_str = self._environ.get(env.IDENTITY_TOKEN_FILE) + if not token_file_str: + return None + + token_file = Path(token_file_str) + if not token_file.exists(): + raise AuthenticationError(f"Identity token file not found: {token_file}") + + base_url = self.settings("base_url") + credentials_file = env.get_credentials_file( + str(credentials.DEFAULT_WANDB_CREDENTIALS_FILE), self._environ + ) + return credentials.access_token(base_url, token_file, credentials_file) + + @property + def api_url(self) -> str: + return self.settings("base_url") # type: ignore + + @property + def app_url(self) -> str: + return wandb.util.app_url(self.api_url) + + @property + def default_entity(self) -> str: + return self.viewer().get("entity") # type: ignore + + def settings(self, key: Optional[str] = None, section: Optional[str] = None) -> Any: + """The settings overridden from the wandb/settings file. + + Args: + key (str, optional): If provided only this setting is returned + section (str, optional): If provided this section of the setting file is + used, defaults to "default" + + Returns: + A dict with the current settings + + { + "entity": "models", + "base_url": "https://api.wandb.ai", + "project": None, + "organization": "my-org", + } + """ + result = self.default_settings.copy() + result.update(self._settings.items(section=section)) # type: ignore + result.update( + { + "entity": env.get_entity( + self._settings.get( + Settings.DEFAULT_SECTION, + "entity", + fallback=result.get("entity"), + ), + env=self._environ, + ), + "organization": env.get_organization( + self._settings.get( + Settings.DEFAULT_SECTION, + "organization", + fallback=result.get("organization"), + ), + env=self._environ, + ), + "project": env.get_project( + self._settings.get( + Settings.DEFAULT_SECTION, + "project", + fallback=result.get("project"), + ), + env=self._environ, + ), + "base_url": env.get_base_url( + self._settings.get( + Settings.DEFAULT_SECTION, + "base_url", + fallback=result.get("base_url"), + ), + env=self._environ, + ), + "ignore_globs": env.get_ignore( + self._settings.get( + Settings.DEFAULT_SECTION, + "ignore_globs", + fallback=result.get("ignore_globs"), + ), + env=self._environ, + ), + } + ) + + return result if key is None else result[key] # type: ignore + + def clear_setting( + self, key: str, globally: bool = False, persist: bool = False + ) -> None: + self._settings.clear( + Settings.DEFAULT_SECTION, key, globally=globally, persist=persist + ) + + def set_setting( + self, key: str, value: Any, globally: bool = False, persist: bool = False + ) -> None: + self._settings.set( + Settings.DEFAULT_SECTION, key, value, globally=globally, persist=persist + ) + if key == "entity": + env.set_entity(value, env=self._environ) + elif key == "project": + env.set_project(value, env=self._environ) + elif key == "base_url": + self.relocate() + + def parse_slug( + self, slug: str, project: Optional[str] = None, run: Optional[str] = None + ) -> Tuple[str, str]: + """Parse a slug into a project and run. + + Args: + slug (str): The slug to parse + project (str, optional): The project to use, if not provided it will be + inferred from the slug + run (str, optional): The run to use, if not provided it will be inferred + from the slug + + Returns: + A dict with the project and run + """ + if slug and "/" in slug: + parts = slug.split("/") + project = parts[0] + run = parts[1] + else: + project = project or self.settings().get("project") + if project is None: + raise CommError("No default project configured.") + run = run or slug or self.current_run_id or env.get_run(env=self._environ) + assert run, "run must be specified" + return project, run + + @normalize_exceptions + def server_info_introspection(self) -> Tuple[List[str], List[str], List[str]]: + query_string = """ + query ProbeServerCapabilities { + QueryType: __type(name: "Query") { + ...fieldData + } + MutationType: __type(name: "Mutation") { + ...fieldData + } + ServerInfoType: __type(name: "ServerInfo") { + ...fieldData + } + } + + fragment fieldData on __Type { + fields { + name + } + } + """ + if ( + self.query_types is None + or self.mutation_types is None + or self.server_info_types is None + ): + query = gql(query_string) + res = self.gql(query) + + self.query_types = [ + field.get("name", "") + for field in res.get("QueryType", {}).get("fields", [{}]) + ] + self.mutation_types = [ + field.get("name", "") + for field in res.get("MutationType", {}).get("fields", [{}]) + ] + self.server_info_types = [ + field.get("name", "") + for field in res.get("ServerInfoType", {}).get("fields", [{}]) + ] + return self.query_types, self.server_info_types, self.mutation_types + + @normalize_exceptions + def server_settings_introspection(self) -> None: + query_string = """ + query ProbeServerSettings { + ServerSettingsType: __type(name: "ServerSettings") { + ...fieldData + } + } + + fragment fieldData on __Type { + fields { + name + } + } + """ + if self._server_settings_type is None: + query = gql(query_string) + res = self.gql(query) + self._server_settings_type = ( + [ + field.get("name", "") + for field in res.get("ServerSettingsType", {}).get("fields", [{}]) + ] + if res + else [] + ) + + def server_use_artifact_input_introspection(self) -> List: + query_string = """ + query ProbeServerUseArtifactInput { + UseArtifactInputInfoType: __type(name: "UseArtifactInput") { + name + inputFields { + name + } + } + } + """ + + if self.server_use_artifact_input_info is None: + query = gql(query_string) + res = self.gql(query) + self.server_use_artifact_input_info = [ + field.get("name", "") + for field in res.get("UseArtifactInputInfoType", {}).get( + "inputFields", [{}] + ) + ] + return self.server_use_artifact_input_info + + @normalize_exceptions + def launch_agent_introspection(self) -> Optional[str]: + query = gql( + """ + query LaunchAgentIntrospection { + LaunchAgentType: __type(name: "LaunchAgent") { + name + } + } + """ + ) + + res = self.gql(query) + return res.get("LaunchAgentType") or None + + @normalize_exceptions + def create_run_queue_introspection(self) -> Tuple[bool, bool, bool]: + _, _, mutations = self.server_info_introspection() + query_string = """ + query ProbeCreateRunQueueInput { + CreateRunQueueInputType: __type(name: "CreateRunQueueInput") { + name + inputFields { + name + } + } + } + """ + if ( + self.server_create_run_queue_supports_drc is None + or self.server_create_run_queue_supports_priority is None + ): + query = gql(query_string) + res = self.gql(query) + if res is None: + raise CommError("Could not get CreateRunQueue input from GQL.") + self.server_create_run_queue_supports_drc = "defaultResourceConfigID" in [ + x["name"] + for x in ( + res.get("CreateRunQueueInputType", {}).get("inputFields", [{}]) + ) + ] + self.server_create_run_queue_supports_priority = "prioritizationMode" in [ + x["name"] + for x in ( + res.get("CreateRunQueueInputType", {}).get("inputFields", [{}]) + ) + ] + return ( + "createRunQueue" in mutations, + self.server_create_run_queue_supports_drc, + self.server_create_run_queue_supports_priority, + ) + + @normalize_exceptions + def upsert_run_queue_introspection(self) -> bool: + _, _, mutations = self.server_info_introspection() + return "upsertRunQueue" in mutations + + @normalize_exceptions + def push_to_run_queue_introspection(self) -> Tuple[bool, bool]: + query_string = """ + query ProbePushToRunQueueInput { + PushToRunQueueInputType: __type(name: "PushToRunQueueInput") { + name + inputFields { + name + } + } + } + """ + + if ( + self.server_supports_template_variables is None + or self.server_push_to_run_queue_supports_priority is None + ): + query = gql(query_string) + res = self.gql(query) + self.server_supports_template_variables = "templateVariableValues" in [ + x["name"] + for x in ( + res.get("PushToRunQueueInputType", {}).get("inputFields", [{}]) + ) + ] + self.server_push_to_run_queue_supports_priority = "priority" in [ + x["name"] + for x in ( + res.get("PushToRunQueueInputType", {}).get("inputFields", [{}]) + ) + ] + + return ( + self.server_supports_template_variables, + self.server_push_to_run_queue_supports_priority, + ) + + @normalize_exceptions + def create_default_resource_config_introspection(self) -> bool: + _, _, mutations = self.server_info_introspection() + return "createDefaultResourceConfig" in mutations + + @normalize_exceptions + def fail_run_queue_item_introspection(self) -> bool: + _, _, mutations = self.server_info_introspection() + return "failRunQueueItem" in mutations + + @normalize_exceptions + def fail_run_queue_item_fields_introspection(self) -> List: + if self.fail_run_queue_item_input_info: + return self.fail_run_queue_item_input_info + query_string = """ + query ProbeServerFailRunQueueItemInput { + FailRunQueueItemInputInfoType: __type(name:"FailRunQueueItemInput") { + inputFields{ + name + } + } + } + """ + + query = gql(query_string) + res = self.gql(query) + + self.fail_run_queue_item_input_info = [ + field.get("name", "") + for field in res.get("FailRunQueueItemInputInfoType", {}).get( + "inputFields", [{}] + ) + ] + return self.fail_run_queue_item_input_info + + @normalize_exceptions + def fail_run_queue_item( + self, + run_queue_item_id: str, + message: str, + stage: str, + file_paths: Optional[List[str]] = None, + ) -> bool: + if not self.fail_run_queue_item_introspection(): + return False + variable_values: Dict[str, Union[str, Optional[List[str]]]] = { + "runQueueItemId": run_queue_item_id, + } + if "message" in self.fail_run_queue_item_fields_introspection(): + variable_values.update({"message": message, "stage": stage}) + if file_paths is not None: + variable_values["filePaths"] = file_paths + mutation_string = """ + mutation failRunQueueItem($runQueueItemId: ID!, $message: String!, $stage: String!, $filePaths: [String!]) { + failRunQueueItem( + input: { + runQueueItemId: $runQueueItemId + message: $message + stage: $stage + filePaths: $filePaths + } + ) { + success + } + } + """ + else: + mutation_string = """ + mutation failRunQueueItem($runQueueItemId: ID!) { + failRunQueueItem( + input: { + runQueueItemId: $runQueueItemId + } + ) { + success + } + } + """ + + mutation = gql(mutation_string) + response = self.gql(mutation, variable_values=variable_values) + result: bool = response["failRunQueueItem"]["success"] + return result + + @normalize_exceptions + def update_run_queue_item_warning_introspection(self) -> bool: + _, _, mutations = self.server_info_introspection() + return "updateRunQueueItemWarning" in mutations + + def _server_features(self) -> Dict[str, bool]: + # NOTE: Avoid caching via `@cached_property`, due to undocumented + # locking behavior before Python 3.12. + # See: https://github.com/python/cpython/issues/87634 + query = gql(SERVER_FEATURES_QUERY_GQL) + try: + response = self.gql(query) + except Exception as e: + # Unfortunately we currently have to match on the text of the error message, + # as the `gql` client raises `Exception` rather than a more specific error. + if 'Cannot query field "features" on type "ServerInfo".' in str(e): + self._server_features_cache = {} + else: + raise + else: + info = ServerFeaturesQuery.model_validate(response).server_info + if info and (feats := info.features): + self._server_features_cache = {f.name: f.is_enabled for f in feats if f} + else: + self._server_features_cache = {} + return self._server_features_cache + + def _server_supports(self, feature: Union[int, str]) -> bool: + """Return whether the current server supports the given feature. + + This also caches the underlying lookup of server feature flags, + and it maps {feature_name (str) -> is_enabled (bool)}. + + Good to use for features that have a fallback mechanism for older servers. + """ + # If we're given the protobuf enum value, convert to a string name. + # NOTE: We deliberately use names (str) instead of enum values (int) + # as the keys here, since: + # - the server identifies features by their name, rather than (client-side) enum value + # - the defined list of client-side flags may be behind the server-side list of flags + key = ServerFeature.Name(feature) if isinstance(feature, int) else feature + return self._server_features().get(key) or False + + @normalize_exceptions + def update_run_queue_item_warning( + self, + run_queue_item_id: str, + message: str, + stage: str, + file_paths: Optional[List[str]] = None, + ) -> bool: + if not self.update_run_queue_item_warning_introspection(): + return False + mutation = gql( + """ + mutation updateRunQueueItemWarning($runQueueItemId: ID!, $message: String!, $stage: String!, $filePaths: [String!]) { + updateRunQueueItemWarning( + input: { + runQueueItemId: $runQueueItemId + message: $message + stage: $stage + filePaths: $filePaths + } + ) { + success + } + } + """ + ) + response = self.gql( + mutation, + variable_values={ + "runQueueItemId": run_queue_item_id, + "message": message, + "stage": stage, + "filePaths": file_paths, + }, + ) + result: bool = response["updateRunQueueItemWarning"]["success"] + return result + + @normalize_exceptions + def viewer(self) -> Dict[str, Any]: + query = gql( + """ + query Viewer{ + viewer { + id + entity + username + flags + teams { + edges { + node { + name + } + } + } + } + } + """ + ) + res = self.gql(query) + return res.get("viewer") or {} + + @normalize_exceptions + def max_cli_version(self) -> Optional[str]: + if self._max_cli_version is not None: + return self._max_cli_version + + query_types, server_info_types, _ = self.server_info_introspection() + cli_version_exists = ( + "serverInfo" in query_types and "cliVersionInfo" in server_info_types + ) + if not cli_version_exists: + return None + + _, server_info = self.viewer_server_info() + self._max_cli_version = server_info.get("cliVersionInfo", {}).get( + "max_cli_version" + ) + return self._max_cli_version + + @normalize_exceptions + def viewer_server_info(self) -> Tuple[Dict[str, Any], Dict[str, Any]]: + local_query = """ + latestLocalVersionInfo { + outOfDate + latestVersionString + versionOnThisInstanceString + } + """ + cli_query = """ + serverInfo { + cliVersionInfo + _LOCAL_QUERY_ + } + """ + query_template = """ + query Viewer{ + viewer { + id + entity + username + email + flags + teams { + edges { + node { + name + } + } + } + } + _CLI_QUERY_ + } + """ + query_types, server_info_types, _ = self.server_info_introspection() + + cli_version_exists = ( + "serverInfo" in query_types and "cliVersionInfo" in server_info_types + ) + + local_version_exists = ( + "serverInfo" in query_types + and "latestLocalVersionInfo" in server_info_types + ) + + cli_query_string = "" if not cli_version_exists else cli_query + local_query_string = "" if not local_version_exists else local_query + + query_string = query_template.replace("_CLI_QUERY_", cli_query_string).replace( + "_LOCAL_QUERY_", local_query_string + ) + query = gql(query_string) + res = self.gql(query) + return res.get("viewer") or {}, res.get("serverInfo") or {} + + @normalize_exceptions + def list_projects(self, entity: Optional[str] = None) -> List[Dict[str, str]]: + """List projects in W&B scoped by entity. + + Args: + entity (str, optional): The entity to scope this project to. + + Returns: + [{"id","name","description"}] + """ + query = gql( + """ + query EntityProjects($entity: String) { + models(first: 10, entityName: $entity) { + edges { + node { + id + name + description + } + } + } + } + """ + ) + project_list: List[Dict[str, str]] = self._flatten_edges( + self.gql( + query, variable_values={"entity": entity or self.settings("entity")} + )["models"] + ) + return project_list + + @normalize_exceptions + def project(self, project: str, entity: Optional[str] = None) -> "_Response": + """Retrieve project. + + Args: + project (str): The project to get details for + entity (str, optional): The entity to scope this project to. + + Returns: + [{"id","name","repo","dockerImage","description"}] + """ + query = gql( + """ + query ProjectDetails($entity: String, $project: String) { + model(name: $project, entityName: $entity) { + id + name + repo + dockerImage + description + } + } + """ + ) + response: _Response = self.gql( + query, variable_values={"entity": entity, "project": project} + )["model"] + return response + + @normalize_exceptions + def sweep( + self, + sweep: str, + specs: str, + project: Optional[str] = None, + entity: Optional[str] = None, + ) -> Dict[str, Any]: + """Retrieve sweep. + + Args: + sweep (str): The sweep to get details for + specs (str): history specs + project (str, optional): The project to scope this sweep to. + entity (str, optional): The entity to scope this sweep to. + + Returns: + [{"id","name","repo","dockerImage","description"}] + """ + query = gql( + """ + query SweepWithRuns($entity: String, $project: String, $sweep: String!, $specs: [JSONString!]!) { + project(name: $project, entityName: $entity) { + sweep(sweepName: $sweep) { + id + name + method + state + description + config + createdAt + heartbeatAt + updatedAt + earlyStopJobRunning + bestLoss + controller + scheduler + runs { + edges { + node { + name + state + config + exitcode + heartbeatAt + shouldStop + failed + stopped + running + summaryMetrics + sampledHistory(specs: $specs) + } + } + } + } + } + } + """ + ) + entity = entity or self.settings("entity") + project = project or self.settings("project") + response = self.gql( + query, + variable_values={ + "entity": entity, + "project": project, + "sweep": sweep, + "specs": specs, + }, + ) + if response["project"] is None or response["project"]["sweep"] is None: + raise ValueError(f"Sweep {entity}/{project}/{sweep} not found") + data: Dict[str, Any] = response["project"]["sweep"] + if data: + data["runs"] = self._flatten_edges(data["runs"]) + return data + + @normalize_exceptions + def list_runs( + self, project: str, entity: Optional[str] = None + ) -> List[Dict[str, str]]: + """List runs in W&B scoped by project. + + Args: + project (str): The project to scope the runs to + entity (str, optional): The entity to scope this project to. Defaults to public models + + Returns: + [{"id","name","description"}] + """ + query = gql( + """ + query ProjectRuns($model: String!, $entity: String) { + model(name: $model, entityName: $entity) { + buckets(first: 10) { + edges { + node { + id + name + displayName + description + } + } + } + } + } + """ + ) + return self._flatten_edges( + self.gql( + query, + variable_values={ + "entity": entity or self.settings("entity"), + "model": project or self.settings("project"), + }, + )["model"]["buckets"] + ) + + @normalize_exceptions + def run_config( + self, project: str, run: Optional[str] = None, entity: Optional[str] = None + ) -> Tuple[str, Dict[str, Any], Optional[str], Dict[str, Any]]: + """Get the relevant configs for a run. + + Args: + project (str): The project to download, (can include bucket) + run (str, optional): The run to download + entity (str, optional): The entity to scope this project to. + """ + check_httpclient_logger_handler() + + query = gql( + """ + query RunConfigs( + $name: String!, + $entity: String, + $run: String!, + $pattern: String!, + $includeConfig: Boolean!, + ) { + model(name: $name, entityName: $entity) { + bucket(name: $run) { + config @include(if: $includeConfig) + commit @include(if: $includeConfig) + files(pattern: $pattern) { + pageInfo { + hasNextPage + endCursor + } + edges { + node { + name + directUrl + } + } + } + } + } + } + """ + ) + + variable_values = { + "name": project, + "run": run, + "entity": entity, + "includeConfig": True, + } + + commit: str = "" + config: Dict[str, Any] = {} + patch: Optional[str] = None + metadata: Dict[str, Any] = {} + + # If we use the `names` parameter on the `files` node, then the server + # will helpfully give us and 'open' file handle to the files that don't + # exist. This is so that we can upload data to it. However, in this + # case, we just want to download that file and not upload to it, so + # let's instead query for the files that do exist using `pattern` + # (with no wildcards). + # + # Unfortunately we're unable to construct a single pattern that matches + # our 2 files, we would need something like regex for that. + for filename in [DIFF_FNAME, METADATA_FNAME]: + variable_values["pattern"] = filename + response = self.gql(query, variable_values=variable_values) + if response["model"] is None: + raise CommError(f"Run {entity}/{project}/{run} not found") + run_obj: Dict = response["model"]["bucket"] + # we only need to fetch this config once + if variable_values["includeConfig"]: + commit = run_obj["commit"] + config = json.loads(run_obj["config"] or "{}") + variable_values["includeConfig"] = False + if run_obj["files"] is not None: + for file_edge in run_obj["files"]["edges"]: + name = file_edge["node"]["name"] + url = file_edge["node"]["directUrl"] + res = requests.get(url) + res.raise_for_status() + if name == METADATA_FNAME: + metadata = res.json() + elif name == DIFF_FNAME: + patch = res.text + + return commit, config, patch, metadata + + @normalize_exceptions + def run_resume_status( + self, entity: str, project_name: str, name: str + ) -> Optional[Dict[str, Any]]: + """Check if a run exists and get resume information. + + Args: + entity (str): The entity to scope this project to. + project_name (str): The project to download, (can include bucket) + name (str): The run to download + """ + # Pulling wandbConfig.start_time is required so that we can determine if a run has actually started + query = gql( + """ + query RunResumeStatus($project: String, $entity: String, $name: String!) { + model(name: $project, entityName: $entity) { + id + name + entity { + id + name + } + + bucket(name: $name, missingOk: true) { + id + name + summaryMetrics + displayName + logLineCount + historyLineCount + eventsLineCount + historyTail + eventsTail + config + tags + wandbConfig(keys: ["t"]) + } + } + } + """ + ) + + response = self.gql( + query, + variable_values={ + "entity": entity, + "project": project_name, + "name": name, + }, + ) + + if "model" not in response or "bucket" not in (response["model"] or {}): + return None + + project = response["model"] + self.set_setting("project", project_name) + if "entity" in project: + self.set_setting("entity", project["entity"]["name"]) + + result: Dict[str, Any] = project["bucket"] + + return result + + @normalize_exceptions + def check_stop_requested( + self, project_name: str, entity_name: str, run_id: str + ) -> bool: + query = gql( + """ + query RunStoppedStatus($projectName: String, $entityName: String, $runId: String!) { + project(name:$projectName, entityName:$entityName) { + run(name:$runId) { + stopped + } + } + } + """ + ) + + response = self.gql( + query, + variable_values={ + "projectName": project_name, + "entityName": entity_name, + "runId": run_id, + }, + ) + + project = response.get("project", None) + if not project: + return False + run = project.get("run", None) + if not run: + return False + + status: bool = run["stopped"] + return status + + def format_project(self, project: str) -> str: + return re.sub(r"\W+", "-", project.lower()).strip("-_") + + @normalize_exceptions + def upsert_project( + self, + project: str, + id: Optional[str] = None, + description: Optional[str] = None, + entity: Optional[str] = None, + ) -> Dict[str, Any]: + """Create a new project. + + Args: + project (str): The project to create + description (str, optional): A description of this project + entity (str, optional): The entity to scope this project to. + """ + mutation = gql( + """ + mutation UpsertModel($name: String!, $id: String, $entity: String!, $description: String, $repo: String) { + upsertModel(input: { id: $id, name: $name, entityName: $entity, description: $description, repo: $repo }) { + model { + name + description + } + } + } + """ + ) + response = self.gql( + mutation, + variable_values={ + "name": self.format_project(project), + "entity": entity or self.settings("entity"), + "description": description, + "id": id, + }, + ) + # TODO(jhr): Commenting out 'repo' field for cling, add back + # 'description': description, 'repo': self.git.remote_url, 'id': id}) + result: Dict[str, Any] = response["upsertModel"]["model"] + return result + + @normalize_exceptions + def entity_is_team(self, entity: str) -> bool: + query = gql( + """ + query EntityIsTeam($entity: String!) { + entity(name: $entity) { + id + isTeam + } + } + """ + ) + variable_values = { + "entity": entity, + } + + res = self.gql(query, variable_values) + if res.get("entity") is None: + raise Exception( + f"Error fetching entity {entity} " + "check that you have access to this entity" + ) + + is_team: bool = res["entity"]["isTeam"] + return is_team + + @normalize_exceptions + def get_project_run_queues(self, entity: str, project: str) -> List[Dict[str, str]]: + query = gql( + """ + query ProjectRunQueues($entity: String!, $projectName: String!){ + project(entityName: $entity, name: $projectName) { + runQueues { + id + name + createdBy + access + } + } + } + """ + ) + variable_values = { + "projectName": project, + "entity": entity, + } + + res = self.gql(query, variable_values) + if res.get("project") is None: + # circular dependency: (LAUNCH_DEFAULT_PROJECT = model-registry) + if project == "model-registry": + msg = ( + f"Error fetching run queues for {entity} " + "check that you have access to this entity and project" + ) + else: + msg = ( + f"Error fetching run queues for {entity}/{project} " + "check that you have access to this entity and project" + ) + + raise Exception(msg) + + project_run_queues: List[Dict[str, str]] = res["project"]["runQueues"] + return project_run_queues + + @normalize_exceptions + def create_default_resource_config( + self, + entity: str, + resource: str, + config: str, + template_variables: Optional[Dict[str, Union[float, int, str]]], + ) -> Optional[Dict[str, Any]]: + if not self.create_default_resource_config_introspection(): + raise Exception() + supports_template_vars, _ = self.push_to_run_queue_introspection() + + mutation_params = """ + $entityName: String!, + $resource: String!, + $config: JSONString! + """ + mutation_inputs = """ + entityName: $entityName, + resource: $resource, + config: $config + """ + + if supports_template_vars: + mutation_params += ", $templateVariables: JSONString" + mutation_inputs += ", templateVariables: $templateVariables" + else: + if template_variables is not None: + raise UnsupportedError( + "server does not support template variables, please update server instance to >=0.46" + ) + + variable_values = { + "entityName": entity, + "resource": resource, + "config": config, + } + if supports_template_vars: + if template_variables is not None: + variable_values["templateVariables"] = json.dumps(template_variables) + else: + variable_values["templateVariables"] = "{}" + + query = gql( + f""" + mutation createDefaultResourceConfig( + {mutation_params} + ) {{ + createDefaultResourceConfig( + input: {{ + {mutation_inputs} + }} + ) {{ + defaultResourceConfigID + success + }} + }} + """ + ) + + result: Optional[Dict[str, Any]] = self.gql(query, variable_values)[ + "createDefaultResourceConfig" + ] + return result + + @normalize_exceptions + def create_run_queue( + self, + entity: str, + project: str, + queue_name: str, + access: str, + prioritization_mode: Optional[str] = None, + config_id: Optional[str] = None, + ) -> Optional[Dict[str, Any]]: + ( + create_run_queue, + supports_drc, + supports_prioritization, + ) = self.create_run_queue_introspection() + if not create_run_queue: + raise UnsupportedError( + "run queue creation is not supported by this version of " + "wandb server. Consider updating to the latest version." + ) + if not supports_drc and config_id is not None: + raise UnsupportedError( + "default resource configurations are not supported by this version " + "of wandb server. Consider updating to the latest version." + ) + if not supports_prioritization and prioritization_mode is not None: + raise UnsupportedError( + "launch prioritization is not supported by this version of " + "wandb server. Consider updating to the latest version." + ) + + if supports_prioritization: + query = gql( + """ + mutation createRunQueue( + $entity: String!, + $project: String!, + $queueName: String!, + $access: RunQueueAccessType!, + $prioritizationMode: RunQueuePrioritizationMode, + $defaultResourceConfigID: ID, + ) { + createRunQueue( + input: { + entityName: $entity, + projectName: $project, + queueName: $queueName, + access: $access, + prioritizationMode: $prioritizationMode + defaultResourceConfigID: $defaultResourceConfigID + } + ) { + success + queueID + } + } + """ + ) + variable_values = { + "entity": entity, + "project": project, + "queueName": queue_name, + "access": access, + "prioritizationMode": prioritization_mode, + "defaultResourceConfigID": config_id, + } + else: + query = gql( + """ + mutation createRunQueue( + $entity: String!, + $project: String!, + $queueName: String!, + $access: RunQueueAccessType!, + $defaultResourceConfigID: ID, + ) { + createRunQueue( + input: { + entityName: $entity, + projectName: $project, + queueName: $queueName, + access: $access, + defaultResourceConfigID: $defaultResourceConfigID + } + ) { + success + queueID + } + } + """ + ) + variable_values = { + "entity": entity, + "project": project, + "queueName": queue_name, + "access": access, + "defaultResourceConfigID": config_id, + } + + result: Optional[Dict[str, Any]] = self.gql(query, variable_values)[ + "createRunQueue" + ] + return result + + @normalize_exceptions + def upsert_run_queue( + self, + queue_name: str, + entity: str, + resource_type: str, + resource_config: dict, + project: str = LAUNCH_DEFAULT_PROJECT, + prioritization_mode: Optional[str] = None, + template_variables: Optional[dict] = None, + external_links: Optional[dict] = None, + ) -> Optional[Dict[str, Any]]: + if not self.upsert_run_queue_introspection(): + raise UnsupportedError( + "upserting run queues is not supported by this version of " + "wandb server. Consider updating to the latest version." + ) + query = gql( + """ + mutation upsertRunQueue( + $entityName: String! + $projectName: String! + $queueName: String! + $resourceType: String! + $resourceConfig: JSONString! + $templateVariables: JSONString + $prioritizationMode: RunQueuePrioritizationMode + $externalLinks: JSONString + $clientMutationId: String + ) { + upsertRunQueue( + input: { + entityName: $entityName + projectName: $projectName + queueName: $queueName + resourceType: $resourceType + resourceConfig: $resourceConfig + templateVariables: $templateVariables + prioritizationMode: $prioritizationMode + externalLinks: $externalLinks + clientMutationId: $clientMutationId + } + ) { + success + configSchemaValidationErrors + } + } + """ + ) + variable_values = { + "entityName": entity, + "projectName": project, + "queueName": queue_name, + "resourceType": resource_type, + "resourceConfig": json.dumps(resource_config), + "templateVariables": ( + json.dumps(template_variables) if template_variables else None + ), + "prioritizationMode": prioritization_mode, + "externalLinks": json.dumps(external_links) if external_links else None, + } + result: Dict[str, Any] = self.gql(query, variable_values) + return result["upsertRunQueue"] + + @normalize_exceptions + def push_to_run_queue_by_name( + self, + entity: str, + project: str, + queue_name: str, + run_spec: str, + template_variables: Optional[Dict[str, Union[int, float, str]]], + priority: Optional[int] = None, + ) -> Optional[Dict[str, Any]]: + self.push_to_run_queue_introspection() + """Queryless mutation, should be used before legacy fallback method.""" + + mutation_params = """ + $entityName: String!, + $projectName: String!, + $queueName: String!, + $runSpec: JSONString! + """ + + mutation_input = """ + entityName: $entityName, + projectName: $projectName, + queueName: $queueName, + runSpec: $runSpec + """ + + variables: Dict[str, Any] = { + "entityName": entity, + "projectName": project, + "queueName": queue_name, + "runSpec": run_spec, + } + if self.server_push_to_run_queue_supports_priority: + if priority is not None: + variables["priority"] = priority + mutation_params += ", $priority: Int" + mutation_input += ", priority: $priority" + else: + if priority is not None: + raise UnsupportedError( + "server does not support priority, please update server instance to >=0.46" + ) + + if self.server_supports_template_variables: + if template_variables is not None: + variables.update( + {"templateVariableValues": json.dumps(template_variables)} + ) + mutation_params += ", $templateVariableValues: JSONString" + mutation_input += ", templateVariableValues: $templateVariableValues" + else: + if template_variables is not None: + raise UnsupportedError( + "server does not support template variables, please update server instance to >=0.46" + ) + + mutation = gql( + f""" + mutation pushToRunQueueByName( + {mutation_params} + ) {{ + pushToRunQueueByName( + input: {{ + {mutation_input} + }} + ) {{ + runQueueItemId + runSpec + }} + }} + """ + ) + + try: + result: Optional[Dict[str, Any]] = self.gql( + mutation, variables, check_retry_fn=util.no_retry_4xx + ).get("pushToRunQueueByName") + if not result: + return None + + if result.get("runSpec"): + run_spec = json.loads(str(result["runSpec"])) + result["runSpec"] = run_spec + + return result + except Exception as e: + if ( + 'Cannot query field "runSpec" on type "PushToRunQueueByNamePayload"' + not in str(e) + ): + return None + + mutation_no_runspec = gql( + """ + mutation pushToRunQueueByName( + $entityName: String!, + $projectName: String!, + $queueName: String!, + $runSpec: JSONString!, + ) { + pushToRunQueueByName( + input: { + entityName: $entityName, + projectName: $projectName, + queueName: $queueName, + runSpec: $runSpec + } + ) { + runQueueItemId + } + } + """ + ) + + try: + result = self.gql( + mutation_no_runspec, variables, check_retry_fn=util.no_retry_4xx + ).get("pushToRunQueueByName") + except Exception: + result = None + + return result + + @normalize_exceptions + def push_to_run_queue( + self, + queue_name: str, + launch_spec: Dict[str, str], + template_variables: Optional[dict], + project_queue: str, + priority: Optional[int] = None, + ) -> Optional[Dict[str, Any]]: + self.push_to_run_queue_introspection() + entity = launch_spec.get("queue_entity") or launch_spec["entity"] + run_spec = json.dumps(launch_spec) + + push_result = self.push_to_run_queue_by_name( + entity, project_queue, queue_name, run_spec, template_variables, priority + ) + + if push_result: + return push_result + + if priority is not None: + # Cannot proceed with legacy method if priority is set + return None + + """ Legacy Method """ + queues_found = self.get_project_run_queues(entity, project_queue) + matching_queues = [ + q + for q in queues_found + if q["name"] == queue_name + # ensure user has access to queue + and ( + # TODO: User created queues in the UI have USER access + q["access"] in ["PROJECT", "USER"] + or q["createdBy"] == self.default_entity + ) + ] + if not matching_queues: + # in the case of a missing default queue. create it + if queue_name == "default": + wandb.termlog( + f"No default queue existing for entity: {entity} in project: {project_queue}, creating one." + ) + res = self.create_run_queue( + launch_spec["entity"], + project_queue, + queue_name, + access="PROJECT", + ) + + if res is None or res.get("queueID") is None: + wandb.termerror( + f"Unable to create default queue for entity: {entity} on project: {project_queue}. Run could not be added to a queue" + ) + return None + queue_id = res["queueID"] + + else: + if project_queue == "model-registry": + _msg = f"Unable to push to run queue {queue_name}. Queue not found." + else: + _msg = f"Unable to push to run queue {project_queue}/{queue_name}. Queue not found." + wandb.termwarn(_msg) + return None + elif len(matching_queues) > 1: + wandb.termerror( + f"Unable to push to run queue {queue_name}. More than one queue found with this name." + ) + return None + else: + queue_id = matching_queues[0]["id"] + spec_json = json.dumps(launch_spec) + variables = {"queueID": queue_id, "runSpec": spec_json} + + mutation_params = """ + $queueID: ID!, + $runSpec: JSONString! + """ + mutation_input = """ + queueID: $queueID, + runSpec: $runSpec + """ + if self.server_supports_template_variables: + if template_variables is not None: + mutation_params += ", $templateVariableValues: JSONString" + mutation_input += ", templateVariableValues: $templateVariableValues" + variables.update( + {"templateVariableValues": json.dumps(template_variables)} + ) + else: + if template_variables is not None: + raise UnsupportedError( + "server does not support template variables, please update server instance to >=0.46" + ) + + mutation = gql( + f""" + mutation pushToRunQueue( + {mutation_params} + ) {{ + pushToRunQueue( + input: {{{mutation_input}}} + ) {{ + runQueueItemId + }} + }} + """ + ) + + response = self.gql(mutation, variable_values=variables) + if not response.get("pushToRunQueue"): + raise CommError(f"Error pushing run queue item to queue {queue_name}.") + + result: Optional[Dict[str, Any]] = response["pushToRunQueue"] + return result + + @normalize_exceptions + def pop_from_run_queue( + self, + queue_name: str, + entity: Optional[str] = None, + project: Optional[str] = None, + agent_id: Optional[str] = None, + ) -> Optional[Dict[str, Any]]: + mutation = gql( + """ + mutation popFromRunQueue($entity: String!, $project: String!, $queueName: String!, $launchAgentId: ID) { + popFromRunQueue(input: { + entityName: $entity, + projectName: $project, + queueName: $queueName, + launchAgentId: $launchAgentId + }) { + runQueueItemId + runSpec + } + } + """ + ) + response = self.gql( + mutation, + variable_values={ + "entity": entity, + "project": project, + "queueName": queue_name, + "launchAgentId": agent_id, + }, + ) + result: Optional[Dict[str, Any]] = response["popFromRunQueue"] + return result + + @normalize_exceptions + def ack_run_queue_item(self, item_id: str, run_id: Optional[str] = None) -> bool: + mutation = gql( + """ + mutation ackRunQueueItem($itemId: ID!, $runId: String!) { + ackRunQueueItem(input: { runQueueItemId: $itemId, runName: $runId }) { + success + } + } + """ + ) + response = self.gql( + mutation, variable_values={"itemId": item_id, "runId": str(run_id)} + ) + if not response["ackRunQueueItem"]["success"]: + raise CommError( + "Error acking run queue item. Item may have already been acknowledged by another process" + ) + result: bool = response["ackRunQueueItem"]["success"] + return result + + @normalize_exceptions + def create_launch_agent_fields_introspection(self) -> List: + if self.create_launch_agent_input_info: + return self.create_launch_agent_input_info + query_string = """ + query ProbeServerCreateLaunchAgentInput { + CreateLaunchAgentInputInfoType: __type(name:"CreateLaunchAgentInput") { + inputFields{ + name + } + } + } + """ + + query = gql(query_string) + res = self.gql(query) + + self.create_launch_agent_input_info = [ + field.get("name", "") + for field in res.get("CreateLaunchAgentInputInfoType", {}).get( + "inputFields", [{}] + ) + ] + return self.create_launch_agent_input_info + + @normalize_exceptions + def create_launch_agent( + self, + entity: str, + project: str, + queues: List[str], + agent_config: Dict[str, Any], + version: str, + gorilla_agent_support: bool, + ) -> dict: + project_queues = self.get_project_run_queues(entity, project) + if not project_queues: + # create default queue if it doesn't already exist + default = self.create_run_queue( + entity, project, "default", access="PROJECT" + ) + if default is None or default.get("queueID") is None: + raise CommError( + f"Unable to create default queue for {entity}/{project}. No queues for agent to poll" + ) + project_queues = [{"id": default["queueID"], "name": "default"}] + polling_queue_ids = [ + q["id"] for q in project_queues if q["name"] in queues + ] # filter to poll specified queues + if len(polling_queue_ids) != len(queues): + raise CommError( + f"Could not start launch agent: Not all of requested queues ({', '.join(queues)}) found. " + f"Available queues for this project: {','.join([q['name'] for q in project_queues])}" + ) + + if not gorilla_agent_support: + # if gorilla doesn't support launch agents, return a client-generated id + return { + "success": True, + "launchAgentId": None, + } + + hostname = socket.gethostname() + + variable_values = { + "entity": entity, + "project": project, + "queues": polling_queue_ids, + "hostname": hostname, + } + + mutation_params = """ + $entity: String!, + $project: String!, + $queues: [ID!]!, + $hostname: String! + """ + + mutation_input = """ + entityName: $entity, + projectName: $project, + runQueues: $queues, + hostname: $hostname + """ + + if "agentConfig" in self.create_launch_agent_fields_introspection(): + variable_values["agentConfig"] = json.dumps(agent_config) + mutation_params += ", $agentConfig: JSONString" + mutation_input += ", agentConfig: $agentConfig" + if "version" in self.create_launch_agent_fields_introspection(): + variable_values["version"] = version + mutation_params += ", $version: String" + mutation_input += ", version: $version" + + mutation = gql( + f""" + mutation createLaunchAgent( + {mutation_params} + ) {{ + createLaunchAgent( + input: {{ + {mutation_input} + }} + ) {{ + launchAgentId + }} + }} + """ + ) + result: dict = self.gql(mutation, variable_values)["createLaunchAgent"] + return result + + @normalize_exceptions + def update_launch_agent_status( + self, + agent_id: str, + status: str, + gorilla_agent_support: bool, + ) -> dict: + if not gorilla_agent_support: + # if gorilla doesn't support launch agents, this is a no-op + return { + "success": True, + } + + mutation = gql( + """ + mutation updateLaunchAgent($agentId: ID!, $agentStatus: String){ + updateLaunchAgent( + input: { + launchAgentId: $agentId + agentStatus: $agentStatus + } + ) { + success + } + } + """ + ) + variable_values = { + "agentId": agent_id, + "agentStatus": status, + } + result: dict = self.gql(mutation, variable_values)["updateLaunchAgent"] + return result + + @normalize_exceptions + def get_launch_agent(self, agent_id: str, gorilla_agent_support: bool) -> dict: + if not gorilla_agent_support: + return { + "id": None, + "name": "", + "stopPolling": False, + } + query = gql( + """ + query LaunchAgent($agentId: ID!) { + launchAgent(id: $agentId) { + id + name + runQueues + hostname + agentStatus + stopPolling + heartbeatAt + } + } + """ + ) + variable_values = { + "agentId": agent_id, + } + result: dict = self.gql(query, variable_values)["launchAgent"] + return result + + @normalize_exceptions + def upsert_run( + self, + id: Optional[str] = None, + name: Optional[str] = None, + project: Optional[str] = None, + host: Optional[str] = None, + group: Optional[str] = None, + tags: Optional[List[str]] = None, + config: Optional[dict] = None, + description: Optional[str] = None, + entity: Optional[str] = None, + state: Optional[str] = None, + display_name: Optional[str] = None, + notes: Optional[str] = None, + repo: Optional[str] = None, + job_type: Optional[str] = None, + program_path: Optional[str] = None, + commit: Optional[str] = None, + sweep_name: Optional[str] = None, + summary_metrics: Optional[str] = None, + num_retries: Optional[int] = None, + ) -> Tuple[dict, bool, Optional[List]]: + """Update a run. + + Args: + id (str, optional): The existing run to update + name (str, optional): The name of the run to create + group (str, optional): Name of the group this run is a part of + project (str, optional): The name of the project + host (str, optional): The name of the host + tags (list, optional): A list of tags to apply to the run + config (dict, optional): The latest config params + description (str, optional): A description of this project + entity (str, optional): The entity to scope this project to. + display_name (str, optional): The display name of this project + notes (str, optional): Notes about this run + repo (str, optional): Url of the program's repository. + state (str, optional): State of the program. + job_type (str, optional): Type of job, e.g 'train'. + program_path (str, optional): Path to the program. + commit (str, optional): The Git SHA to associate the run with + sweep_name (str, optional): The name of the sweep this run is a part of + summary_metrics (str, optional): The JSON summary metrics + num_retries (int, optional): Number of retries + """ + query_string = """ + mutation UpsertBucket( + $id: String, + $name: String, + $project: String, + $entity: String, + $groupName: String, + $description: String, + $displayName: String, + $notes: String, + $commit: String, + $config: JSONString, + $host: String, + $debug: Boolean, + $program: String, + $repo: String, + $jobType: String, + $state: String, + $sweep: String, + $tags: [String!], + $summaryMetrics: JSONString, + ) { + upsertBucket(input: { + id: $id, + name: $name, + groupName: $groupName, + modelName: $project, + entityName: $entity, + description: $description, + displayName: $displayName, + notes: $notes, + config: $config, + commit: $commit, + host: $host, + debug: $debug, + jobProgram: $program, + jobRepo: $repo, + jobType: $jobType, + state: $state, + sweep: $sweep, + tags: $tags, + summaryMetrics: $summaryMetrics, + }) { + bucket { + id + name + displayName + description + config + sweepName + project { + id + name + entity { + id + name + } + } + historyLineCount + } + inserted + _Server_Settings_ + } + } + """ + self.server_settings_introspection() + + server_settings_string = ( + """ + serverSettings { + serverMessages{ + utfText + plainText + htmlText + messageType + messageLevel + } + } + """ + if self._server_settings_type + else "" + ) + + query_string = query_string.replace("_Server_Settings_", server_settings_string) + mutation = gql(query_string) + config_str = json.dumps(config) if config else None + if not description or description.isspace(): + description = None + + kwargs = {} + if num_retries is not None: + kwargs["num_retries"] = num_retries + + variable_values = { + "id": id, + "entity": entity or self.settings("entity"), + "name": name, + "project": project or util.auto_project_name(program_path), + "groupName": group, + "tags": tags, + "description": description, + "config": config_str, + "commit": commit, + "displayName": display_name, + "notes": notes, + "host": None + if self.settings().get("anonymous") in ["allow", "must"] + else host, + "debug": env.is_debug(env=self._environ), + "repo": repo, + "program": program_path, + "jobType": job_type, + "state": state, + "sweep": sweep_name, + "summaryMetrics": summary_metrics, + } + + # retry conflict errors for 2 minutes, default to no_auth_retry + check_retry_fn = util.make_check_retry_fn( + check_fn=util.check_retry_conflict_or_gone, + check_timedelta=datetime.timedelta(minutes=2), + fallback_retry_fn=util.no_retry_auth, + ) + + response = self.gql( + mutation, + variable_values=variable_values, + check_retry_fn=check_retry_fn, + **kwargs, + ) + + run_obj: Dict[str, Dict[str, Dict[str, str]]] = response["upsertBucket"][ + "bucket" + ] + project_obj: Dict[str, Dict[str, str]] = run_obj.get("project", {}) + if project_obj: + self.set_setting("project", project_obj["name"]) + entity_obj = project_obj.get("entity", {}) + if entity_obj: + self.set_setting("entity", entity_obj["name"]) + + server_messages = None + if self._server_settings_type: + server_messages = ( + response["upsertBucket"] + .get("serverSettings", {}) + .get("serverMessages", []) + ) + + return ( + response["upsertBucket"]["bucket"], + response["upsertBucket"]["inserted"], + server_messages, + ) + + @normalize_exceptions + def rewind_run( + self, + run_name: str, + metric_name: str, + metric_value: float, + program_path: Optional[str] = None, + entity: Optional[str] = None, + project: Optional[str] = None, + num_retries: Optional[int] = None, + ) -> dict: + """Rewinds a run to a previous state. + + Args: + run_name (str): The name of the run to rewind + metric_name (str): The name of the metric to rewind to + metric_value (float): The value of the metric to rewind to + program_path (str, optional): Path to the program + entity (str, optional): The entity to scope this project to + project (str, optional): The name of the project + num_retries (int, optional): Number of retries + + Returns: + A dict with the rewound run + + { + "id": "run_id", + "name": "run_name", + "displayName": "run_display_name", + "description": "run_description", + "config": "stringified_run_config_json", + "sweepName": "run_sweep_name", + "project": { + "id": "project_id", + "name": "project_name", + "entity": { + "id": "entity_id", + "name": "entity_name" + } + }, + "historyLineCount": 100, + } + """ + query_string = """ + mutation RewindRun($runName: String!, $entity: String, $project: String, $metricName: String!, $metricValue: Float!) { + rewindRun(input: {runName: $runName, entityName: $entity, projectName: $project, metricName: $metricName, metricValue: $metricValue}) { + rewoundRun { + id + name + displayName + description + config + sweepName + project { + id + name + entity { + id + name + } + } + historyLineCount + } + } + } + """ + + mutation = gql(query_string) + + kwargs = {} + if num_retries is not None: + kwargs["num_retries"] = num_retries + + variable_values = { + "runName": run_name, + "entity": entity or self.settings("entity"), + "project": project or util.auto_project_name(program_path), + "metricName": metric_name, + "metricValue": metric_value, + } + + # retry conflict errors for 2 minutes, default to no_auth_retry + check_retry_fn = util.make_check_retry_fn( + check_fn=util.check_retry_conflict_or_gone, + check_timedelta=datetime.timedelta(minutes=2), + fallback_retry_fn=util.no_retry_auth, + ) + + response = self.gql( + mutation, + variable_values=variable_values, + check_retry_fn=check_retry_fn, + **kwargs, + ) + + run_obj: Dict[str, Dict[str, Dict[str, str]]] = response.get( + "rewindRun", {} + ).get("rewoundRun", {}) + project_obj: Dict[str, Dict[str, str]] = run_obj.get("project", {}) + if project_obj: + self.set_setting("project", project_obj["name"]) + entity_obj = project_obj.get("entity", {}) + if entity_obj: + self.set_setting("entity", entity_obj["name"]) + + return run_obj + + @normalize_exceptions + def get_run_info( + self, + entity: str, + project: str, + name: str, + ) -> dict: + query = gql( + """ + query RunInfo($project: String!, $entity: String!, $name: String!) { + project(name: $project, entityName: $entity) { + run(name: $name) { + runInfo { + program + args + os + python + colab + executable + codeSaved + cpuCount + gpuCount + gpu + git { + remote + commit + } + } + } + } + } + """ + ) + variable_values = {"project": project, "entity": entity, "name": name} + res = self.gql(query, variable_values) + if res.get("project") is None: + raise CommError( + f"Error fetching run info for {entity}/{project}/{name}. Check that this project exists and you have access to this entity and project" + ) + elif res["project"].get("run") is None: + raise CommError( + f"Error fetching run info for {entity}/{project}/{name}. Check that this run id exists" + ) + run_info: dict = res["project"]["run"]["runInfo"] + return run_info + + @normalize_exceptions + def get_run_state(self, entity: str, project: str, name: str) -> str: + query = gql( + """ + query RunState( + $project: String!, + $entity: String!, + $name: String!) { + project(name: $project, entityName: $entity) { + run(name: $name) { + state + } + } + } + """ + ) + variable_values = { + "project": project, + "entity": entity, + "name": name, + } + res = self.gql(query, variable_values) + if res.get("project") is None or res["project"].get("run") is None: + raise CommError(f"Error fetching run state for {entity}/{project}/{name}.") + run_state: str = res["project"]["run"]["state"] + return run_state + + @normalize_exceptions + def create_run_files_introspection(self) -> bool: + _, _, mutations = self.server_info_introspection() + return "createRunFiles" in mutations + + @normalize_exceptions + def upload_urls( + self, + project: str, + files: Union[List[str], Dict[str, IO]], + run: Optional[str] = None, + entity: Optional[str] = None, + description: Optional[str] = None, + ) -> Tuple[str, List[str], Dict[str, Dict[str, Any]]]: + """Generate temporary resumable upload urls. + + Args: + project (str): The project to download + files (list or dict): The filenames to upload + run (str, optional): The run to upload to + entity (str, optional): The entity to scope this project to. + description (str, optional): description + + Returns: + (run_id, upload_headers, file_info) + run_id: id of run we uploaded files to + upload_headers: A list of headers to use when uploading files. + file_info: A dict of filenames and urls. + { + "run_id": "run_id", + "upload_headers": [""], + "file_info": [ + { "weights.h5": { "uploadUrl": "https://weights.url" } }, + { "model.json": { "uploadUrl": "https://model.json" } } + ] + } + """ + run_name = run or self.current_run_id + assert run_name, "run must be specified" + entity = entity or self.settings("entity") + assert entity, "entity must be specified" + + has_create_run_files_mutation = self.create_run_files_introspection() + if not has_create_run_files_mutation: + return self.legacy_upload_urls(project, files, run, entity, description) + + query = gql( + """ + mutation CreateRunFiles($entity: String!, $project: String!, $run: String!, $files: [String!]!) { + createRunFiles(input: {entityName: $entity, projectName: $project, runName: $run, files: $files}) { + runID + uploadHeaders + files { + name + uploadUrl + } + } + } + """ + ) + + query_result = self.gql( + query, + variable_values={ + "project": project, + "run": run_name, + "entity": entity, + "files": [file for file in files], + }, + ) + + result = query_result["createRunFiles"] + run_id = result["runID"] + if not run_id: + raise CommError( + f"Error uploading files to {entity}/{project}/{run_name}. Check that this project exists and you have access to this entity and project" + ) + file_name_urls = {file["name"]: file for file in result["files"]} + return run_id, result["uploadHeaders"], file_name_urls + + def legacy_upload_urls( + self, + project: str, + files: Union[List[str], Dict[str, IO]], + run: Optional[str] = None, + entity: Optional[str] = None, + description: Optional[str] = None, + ) -> Tuple[str, List[str], Dict[str, Dict[str, Any]]]: + """Generate temporary resumable upload urls. + + A new mutation createRunFiles was introduced after 0.15.4. + This function is used to support older versions. + """ + query = gql( + """ + query RunUploadUrls($name: String!, $files: [String]!, $entity: String, $run: String!, $description: String) { + model(name: $name, entityName: $entity) { + bucket(name: $run, desc: $description) { + id + files(names: $files) { + uploadHeaders + edges { + node { + name + url(upload: true) + updatedAt + } + } + } + } + } + } + """ + ) + run_id = run or self.current_run_id + assert run_id, "run must be specified" + entity = entity or self.settings("entity") + query_result = self.gql( + query, + variable_values={ + "name": project, + "run": run_id, + "entity": entity, + "files": [file for file in files], + "description": description, + }, + ) + + run_obj = query_result["model"]["bucket"] + if run_obj: + for file_node in run_obj["files"]["edges"]: + file = file_node["node"] + # we previously used "url" field but now use "uploadUrl" + # replace the "url" field with "uploadUrl for downstream compatibility + if "url" in file and "uploadUrl" not in file: + file["uploadUrl"] = file.pop("url") + + result = { + file["name"]: file for file in self._flatten_edges(run_obj["files"]) + } + return run_obj["id"], run_obj["files"]["uploadHeaders"], result + else: + raise CommError(f"Run does not exist {entity}/{project}/{run_id}.") + + @normalize_exceptions + def download_urls( + self, + project: str, + run: Optional[str] = None, + entity: Optional[str] = None, + ) -> Dict[str, Dict[str, str]]: + """Generate download urls. + + Args: + project (str): The project to download + run (str): The run to upload to + entity (str, optional): The entity to scope this project to. Defaults to wandb models + + Returns: + A dict of extensions and urls + + { + 'weights.h5': { "url": "https://weights.url", "updatedAt": '2013-04-26T22:22:23.832Z', 'md5': 'mZFLkyvTelC5g8XnyQrpOw==' }, + 'model.json': { "url": "https://model.url", "updatedAt": '2013-04-26T22:22:23.832Z', 'md5': 'mZFLkyvTelC5g8XnyQrpOw==' } + } + """ + query = gql( + """ + query RunDownloadUrls($name: String!, $entity: String, $run: String!) { + model(name: $name, entityName: $entity) { + bucket(name: $run) { + files { + edges { + node { + name + url + md5 + updatedAt + } + } + } + } + } + } + """ + ) + run = run or self.current_run_id + assert run, "run must be specified" + entity = entity or self.settings("entity") + query_result = self.gql( + query, + variable_values={ + "name": project, + "run": run, + "entity": entity, + }, + ) + if query_result["model"] is None: + raise CommError(f"Run does not exist {entity}/{project}/{run}.") + files = self._flatten_edges(query_result["model"]["bucket"]["files"]) + return {file["name"]: file for file in files if file} + + @normalize_exceptions + def download_url( + self, + project: str, + file_name: str, + run: Optional[str] = None, + entity: Optional[str] = None, + ) -> Optional[Dict[str, str]]: + """Generate download urls. + + Args: + project (str): The project to download + file_name (str): The name of the file to download + run (str): The run to upload to + entity (str, optional): The entity to scope this project to. Defaults to wandb models + + Returns: + A dict of extensions and urls + + { "url": "https://weights.url", "updatedAt": '2013-04-26T22:22:23.832Z', 'md5': 'mZFLkyvTelC5g8XnyQrpOw==' } + + """ + query = gql( + """ + query RunDownloadUrl($name: String!, $fileName: String!, $entity: String, $run: String!) { + model(name: $name, entityName: $entity) { + bucket(name: $run) { + files(names: [$fileName]) { + edges { + node { + name + url + md5 + updatedAt + } + } + } + } + } + } + """ + ) + run = run or self.current_run_id + assert run, "run must be specified" + query_result = self.gql( + query, + variable_values={ + "name": project, + "run": run, + "fileName": file_name, + "entity": entity or self.settings("entity"), + }, + ) + if query_result["model"]: + files = self._flatten_edges(query_result["model"]["bucket"]["files"]) + return files[0] if len(files) > 0 and files[0].get("updatedAt") else None + else: + return None + + @normalize_exceptions + def download_file(self, url: str) -> Tuple[int, requests.Response]: + """Initiate a streaming download. + + Args: + url (str): The url to download + + Returns: + A tuple of the content length and the streaming response + """ + check_httpclient_logger_handler() + + http_headers = _thread_local_api_settings.headers or {} + + auth = None + if self.access_token is not None: + http_headers["Authorization"] = f"Bearer {self.access_token}" + elif _thread_local_api_settings.cookies is None: + auth = ("api", self.api_key or "") + + response = requests.get( + url, + auth=auth, + cookies=_thread_local_api_settings.cookies or {}, + headers=http_headers, + stream=True, + ) + response.raise_for_status() + return int(response.headers.get("content-length", 0)), response + + @normalize_exceptions + def download_write_file( + self, + metadata: Dict[str, str], + out_dir: Optional[str] = None, + ) -> Tuple[str, Optional[requests.Response]]: + """Download a file from a run and write it to wandb/. + + Args: + metadata (obj): The metadata object for the file to download. Comes from Api.download_urls(). + out_dir (str, optional): The directory to write the file to. Defaults to wandb/ + + Returns: + A tuple of the file's local path and the streaming response. The streaming response is None if the file + already existed and was up-to-date. + """ + filename = metadata["name"] + path = os.path.join(out_dir or self.settings("wandb_dir"), filename) + if self.file_current(filename, B64MD5(metadata["md5"])): + return path, None + + size, response = self.download_file(metadata["url"]) + + with util.fsync_open(path, "wb") as file: + for data in response.iter_content(chunk_size=1024): + file.write(data) + + return path, response + + def upload_file_azure( + self, url: str, file: Any, extra_headers: Dict[str, str] + ) -> None: + """Upload a file to azure.""" + from azure.core.exceptions import AzureError # type: ignore + + # Configure the client without retries so our existing logic can handle them + client = self._azure_blob_module.BlobClient.from_blob_url( + url, retry_policy=self._azure_blob_module.LinearRetry(retry_total=0) + ) + try: + if extra_headers.get("Content-MD5") is not None: + md5: Optional[bytes] = base64.b64decode(extra_headers["Content-MD5"]) + else: + md5 = None + content_settings = self._azure_blob_module.ContentSettings( + content_md5=md5, + content_type=extra_headers.get("Content-Type"), + ) + client.upload_blob( + file, + max_concurrency=4, + length=len(file), + overwrite=True, + content_settings=content_settings, + ) + except AzureError as e: + if hasattr(e, "response"): + response = requests.models.Response() + response.status_code = e.response.status_code + response.headers = e.response.headers + raise requests.exceptions.RequestException(e.message, response=response) + else: + raise requests.exceptions.ConnectionError(e.message) + + def upload_multipart_file_chunk( + self, + url: str, + upload_chunk: bytes, + extra_headers: Optional[Dict[str, str]] = None, + ) -> Optional[requests.Response]: + """Upload a file chunk to S3 with failure resumption. + + Args: + url: The url to download + upload_chunk: The path to the file you want to upload + extra_headers: A dictionary of extra headers to send with the request + + Returns: + The `requests` library response object + """ + check_httpclient_logger_handler() + try: + if env.is_debug(env=self._environ): + logger.debug("upload_file: %s", url) + response = self._upload_file_session.put( + url, data=upload_chunk, headers=extra_headers + ) + if env.is_debug(env=self._environ): + logger.debug("upload_file: %s complete", url) + response.raise_for_status() + except requests.exceptions.RequestException as e: + logger.exception(f"upload_file exception for {url=}") + response_content = e.response.content if e.response is not None else "" + status_code = e.response.status_code if e.response is not None else 0 + # S3 reports retryable request timeouts out-of-band + is_aws_retryable = status_code == 400 and "RequestTimeout" in str( + response_content + ) + # Retry errors from cloud storage or local network issues + if ( + status_code in (308, 408, 409, 429, 500, 502, 503, 504) + or isinstance( + e, + (requests.exceptions.Timeout, requests.exceptions.ConnectionError), + ) + or is_aws_retryable + ): + _e = retry.TransientError(exc=e) + raise _e.with_traceback(sys.exc_info()[2]) + else: + wandb._sentry.reraise(e) + return response + + def upload_file( + self, + url: str, + file: IO[bytes], + callback: Optional["ProgressFn"] = None, + extra_headers: Optional[Dict[str, str]] = None, + ) -> Optional[requests.Response]: + """Upload a file to W&B with failure resumption. + + Args: + url: The url to download + file: The path to the file you want to upload + callback: A callback which is passed the number of + bytes uploaded since the last time it was called, used to report progress + extra_headers: A dictionary of extra headers to send with the request + + Returns: + The `requests` library response object + """ + check_httpclient_logger_handler() + extra_headers = extra_headers.copy() if extra_headers else {} + response: Optional[requests.Response] = None + progress = Progress(file, callback=callback) + try: + if "x-ms-blob-type" in extra_headers and self._azure_blob_module: + self.upload_file_azure(url, progress, extra_headers) + else: + if "x-ms-blob-type" in extra_headers: + wandb.termwarn( + "Azure uploads over 256MB require the azure SDK, install with pip install wandb[azure]", + repeat=False, + ) + if env.is_debug(env=self._environ): + logger.debug("upload_file: %s", url) + response = self._upload_file_session.put( + url, data=progress, headers=extra_headers + ) + if env.is_debug(env=self._environ): + logger.debug("upload_file: %s complete", url) + response.raise_for_status() + except requests.exceptions.RequestException as e: + logger.exception(f"upload_file exception for {url=}") + response_content = e.response.content if e.response is not None else "" + status_code = e.response.status_code if e.response is not None else 0 + # S3 reports retryable request timeouts out-of-band + is_aws_retryable = ( + "x-amz-meta-md5" in extra_headers + and status_code == 400 + and "RequestTimeout" in str(response_content) + ) + # We need to rewind the file for the next retry (the file passed in is `seek`'ed to 0) + progress.rewind() + # Retry errors from cloud storage or local network issues + if ( + status_code in (308, 408, 409, 429, 500, 502, 503, 504) + or isinstance( + e, + (requests.exceptions.Timeout, requests.exceptions.ConnectionError), + ) + or is_aws_retryable + ): + _e = retry.TransientError(exc=e) + raise _e.with_traceback(sys.exc_info()[2]) + else: + wandb._sentry.reraise(e) + + return response + + @normalize_exceptions + def register_agent( + self, + host: str, + sweep_id: Optional[str] = None, + project_name: Optional[str] = None, + entity: Optional[str] = None, + ) -> dict: + """Register a new agent. + + Args: + host (str): hostname + sweep_id (str): sweep id + project_name: (str): model that contains sweep + entity: (str): entity that contains sweep + """ + mutation = gql( + """ + mutation CreateAgent( + $host: String! + $projectName: String, + $entityName: String, + $sweep: String! + ) { + createAgent(input: { + host: $host, + projectName: $projectName, + entityName: $entityName, + sweep: $sweep, + }) { + agent { + id + } + } + } + """ + ) + if entity is None: + entity = self.settings("entity") + if project_name is None: + project_name = self.settings("project") + + response = self.gql( + mutation, + variable_values={ + "host": host, + "entityName": entity, + "projectName": project_name, + "sweep": sweep_id, + }, + check_retry_fn=util.no_retry_4xx, + ) + result: dict = response["createAgent"]["agent"] + return result + + def agent_heartbeat( + self, agent_id: str, metrics: dict, run_states: dict + ) -> List[Dict[str, Any]]: + """Notify server about agent state, receive commands. + + Args: + agent_id (str): agent_id + metrics (dict): system metrics + run_states (dict): run_id: state mapping + Returns: + List of commands to execute. + """ + mutation = gql( + """ + mutation Heartbeat( + $id: ID!, + $metrics: JSONString, + $runState: JSONString + ) { + agentHeartbeat(input: { + id: $id, + metrics: $metrics, + runState: $runState + }) { + agent { + id + } + commands + } + } + """ + ) + + if agent_id is None: + raise ValueError("Cannot call heartbeat with an unregistered agent.") + + try: + response = self.gql( + mutation, + variable_values={ + "id": agent_id, + "metrics": json.dumps(metrics), + "runState": json.dumps(run_states), + }, + timeout=60, + ) + except Exception: + logger.exception("Error communicating with W&B.") + return [] + else: + result: List[Dict[str, Any]] = json.loads( + response["agentHeartbeat"]["commands"] + ) + return result + + @staticmethod + def _validate_config_and_fill_distribution(config: dict) -> dict: + # verify that parameters are well specified. + # TODO(dag): deprecate this in favor of jsonschema validation once + # apiVersion 2 is released and local controller is integrated with + # wandb/client. + + # avoid modifying the original config dict in + # case it is reused outside the calling func + config = deepcopy(config) + + # explicitly cast to dict in case config was passed as a sweepconfig + # sweepconfig does not serialize cleanly to yaml and breaks graphql, + # but it is a subclass of dict, so this conversion is clean + config = dict(config) + + if "parameters" not in config: + # still shows an anaconda warning, but doesn't error + return config + + for parameter_name in config["parameters"]: + parameter = config["parameters"][parameter_name] + if "min" in parameter and "max" in parameter: + if "distribution" not in parameter: + if isinstance(parameter["min"], int) and isinstance( + parameter["max"], int + ): + parameter["distribution"] = "int_uniform" + elif isinstance(parameter["min"], float) and isinstance( + parameter["max"], float + ): + parameter["distribution"] = "uniform" + else: + raise ValueError( + f"Parameter {parameter_name} is ambiguous, please specify bounds as both floats (for a float_" + "uniform distribution) or ints (for an int_uniform distribution)." + ) + return config + + @normalize_exceptions + def upsert_sweep( + self, + config: dict, + controller: Optional[str] = None, + launch_scheduler: Optional[str] = None, + scheduler: Optional[str] = None, + obj_id: Optional[str] = None, + project: Optional[str] = None, + entity: Optional[str] = None, + state: Optional[str] = None, + prior_runs: Optional[List[str]] = None, + display_name: Optional[str] = None, + template_variable_values: Optional[Dict[str, Any]] = None, + ) -> Tuple[str, List[str]]: + """Upsert a sweep object. + + Args: + config (dict): sweep config (will be converted to yaml) + controller (str): controller to use + launch_scheduler (str): launch scheduler to use + scheduler (str): scheduler to use + obj_id (str): object id + project (str): project to use + entity (str): entity to use + state (str): state + prior_runs (list): IDs of existing runs to add to the sweep + display_name (str): display name for the sweep + template_variable_values (dict): template variable values + """ + project_query = """ + project { + id + name + entity { + id + name + } + } + """ + mutation_str = """ + mutation UpsertSweep( + $id: ID, + $config: String, + $description: String, + $entityName: String, + $projectName: String, + $controller: JSONString, + $scheduler: JSONString, + $state: String, + $priorRunsFilters: JSONString, + $displayName: String, + ) { + upsertSweep(input: { + id: $id, + config: $config, + description: $description, + entityName: $entityName, + projectName: $projectName, + controller: $controller, + scheduler: $scheduler, + state: $state, + priorRunsFilters: $priorRunsFilters, + displayName: $displayName, + }) { + sweep { + name + _PROJECT_QUERY_ + } + configValidationWarnings + } + } + """ + # TODO(jhr): we need protocol versioning to know schema is not supported + # for now we will just try both new and old query + mutation_5 = gql( + mutation_str.replace( + "$controller: JSONString,", + "$controller: JSONString,$launchScheduler: JSONString, $templateVariableValues: JSONString,", + ) + .replace( + "controller: $controller,", + "controller: $controller,launchScheduler: $launchScheduler,templateVariableValues: $templateVariableValues,", + ) + .replace("_PROJECT_QUERY_", project_query) + ) + # launchScheduler was introduced in core v0.14.0 + mutation_4 = gql( + mutation_str.replace( + "$controller: JSONString,", + "$controller: JSONString,$launchScheduler: JSONString,", + ) + .replace( + "controller: $controller,", + "controller: $controller,launchScheduler: $launchScheduler", + ) + .replace("_PROJECT_QUERY_", project_query) + ) + + # mutation 3 maps to backend that can support CLI version of at least 0.10.31 + mutation_3 = gql(mutation_str.replace("_PROJECT_QUERY_", project_query)) + mutation_2 = gql( + mutation_str.replace("_PROJECT_QUERY_", project_query).replace( + "configValidationWarnings", "" + ) + ) + mutation_1 = gql( + mutation_str.replace("_PROJECT_QUERY_", "").replace( + "configValidationWarnings", "" + ) + ) + + # TODO(dag): replace this with a query for protocol versioning + mutations = [mutation_5, mutation_4, mutation_3, mutation_2, mutation_1] + + config = self._validate_config_and_fill_distribution(config) + + # Silly, but attr-dicts like EasyDicts don't serialize correctly to yaml. + # This sanitizes them with a round trip pass through json to get a regular dict. + config_str = yaml.dump( + json.loads(json.dumps(config)), Dumper=util.NonOctalStringDumper + ) + filters = None + if prior_runs: + filters = json.dumps({"$or": [{"name": r} for r in prior_runs]}) + + err: Optional[Exception] = None + for mutation in mutations: + try: + variables = { + "id": obj_id, + "config": config_str, + "description": config.get("description"), + "entityName": entity or self.settings("entity"), + "projectName": project or self.settings("project"), + "controller": controller, + "launchScheduler": launch_scheduler, + "templateVariableValues": json.dumps(template_variable_values), + "scheduler": scheduler, + "priorRunsFilters": filters, + "displayName": display_name, + } + if state: + variables["state"] = state + + response = self.gql( + mutation, + variable_values=variables, + check_retry_fn=util.no_retry_4xx, + ) + except UsageError: + raise + except Exception as e: + # graphql schema exception is generic + err = e + continue + err = None + break + if err: + raise err + + sweep: Dict[str, Dict[str, Dict]] = response["upsertSweep"]["sweep"] + project_obj: Dict[str, Dict] = sweep.get("project", {}) + if project_obj: + self.set_setting("project", project_obj["name"]) + entity_obj: dict = project_obj.get("entity", {}) + if entity_obj: + self.set_setting("entity", entity_obj["name"]) + + warnings = response["upsertSweep"].get("configValidationWarnings", []) + return response["upsertSweep"]["sweep"]["name"], warnings + + @normalize_exceptions + def create_anonymous_api_key(self) -> str: + """Create a new API key belonging to a new anonymous user.""" + mutation = gql( + """ + mutation CreateAnonymousApiKey { + createAnonymousEntity(input: {}) { + apiKey { + name + } + } + } + """ + ) + + response = self.gql(mutation, variable_values={}) + key: str = str(response["createAnonymousEntity"]["apiKey"]["name"]) + return key + + @staticmethod + def file_current(fname: str, md5: B64MD5) -> bool: + """Checksum a file and compare the md5 with the known md5.""" + return os.path.isfile(fname) and md5_file_b64(fname) == md5 + + @normalize_exceptions + def pull( + self, project: str, run: Optional[str] = None, entity: Optional[str] = None + ) -> "List[requests.Response]": + """Download files from W&B. + + Args: + project (str): The project to download + run (str, optional): The run to upload to + entity (str, optional): The entity to scope this project to. Defaults to wandb models + + Returns: + The `requests` library response object + """ + project, run = self.parse_slug(project, run=run) + urls = self.download_urls(project, run, entity) + responses = [] + for filename in urls: + _, response = self.download_write_file(urls[filename]) + if response: + responses.append(response) + + return responses + + def get_project(self) -> str: + project: str = self.default_settings.get("project") or self.settings("project") + return project + + @normalize_exceptions + def push( + self, + files: Union[List[str], Dict[str, IO]], + run: Optional[str] = None, + entity: Optional[str] = None, + project: Optional[str] = None, + description: Optional[str] = None, + force: bool = True, + progress: Union[TextIO, Literal[False]] = False, + ) -> "List[Optional[requests.Response]]": + """Uploads multiple files to W&B. + + Args: + files (list or dict): The filenames to upload, when dict the values are open files + run (str, optional): The run to upload to + entity (str, optional): The entity to scope this project to. Defaults to wandb models + project (str, optional): The name of the project to upload to. Defaults to the one in settings. + description (str, optional): The description of the changes + force (bool, optional): Whether to prevent push if git has uncommitted changes + progress (callable, or stream): If callable, will be called with (chunk_bytes, + total_bytes) as argument. If TextIO, renders a progress bar to it. + + Returns: + A list of `requests.Response` objects + """ + if project is None: + project = self.get_project() + if project is None: + raise CommError("No project configured.") + if run is None: + run = self.current_run_id + + # TODO(adrian): we use a retriable version of self.upload_file() so + # will never retry self.upload_urls() here. Instead, maybe we should + # make push itself retriable. + _, upload_headers, result = self.upload_urls( + project, + files, + run, + entity, + ) + extra_headers = {} + for upload_header in upload_headers: + key, val = upload_header.split(":", 1) + extra_headers[key] = val + responses = [] + for file_name, file_info in result.items(): + file_url = file_info["uploadUrl"] + + # If the upload URL is relative, fill it in with the base URL, + # since it's a proxied file store like the on-prem VM. + if file_url.startswith("/"): + file_url = f"{self.api_url}{file_url}" + + try: + # To handle Windows paths + # TODO: this doesn't handle absolute paths... + normal_name = os.path.join(*file_name.split("/")) + open_file = ( + files[file_name] + if isinstance(files, dict) + else open(normal_name, "rb") + ) + except OSError: + print(f"{file_name} does not exist") # noqa: T201 + continue + if progress is False: + responses.append( + self.upload_file_retry( + file_info["uploadUrl"], open_file, extra_headers=extra_headers + ) + ) + else: + if callable(progress): + responses.append( # type: ignore + self.upload_file_retry( + file_url, open_file, progress, extra_headers=extra_headers + ) + ) + else: + length = os.fstat(open_file.fileno()).st_size + with click.progressbar( # type: ignore + file=progress, + length=length, + label=f"Uploading file: {file_name}", + fill_char=click.style("&", fg="green"), + ) as bar: + responses.append( + self.upload_file_retry( + file_url, + open_file, + lambda bites, _: bar.update(bites), + extra_headers=extra_headers, + ) + ) + open_file.close() + return responses + + def link_artifact( + self, + client_id: str, + server_id: str, + portfolio_name: str, + entity: str, + project: str, + aliases: Sequence[str], + organization: str, + ) -> Dict[str, Any]: + template = """ + mutation LinkArtifact( + $artifactPortfolioName: String!, + $entityName: String!, + $projectName: String!, + $aliases: [ArtifactAliasInput!], + ID_TYPE + ) { + linkArtifact(input: { + artifactPortfolioName: $artifactPortfolioName, + entityName: $entityName, + projectName: $projectName, + aliases: $aliases, + ID_VALUE + }) { + versionIndex + } + } + """ + + org_entity = "" + if is_artifact_registry_project(project): + try: + org_entity = self._resolve_org_entity_name( + entity=entity, organization=organization + ) + except ValueError as e: + wandb.termerror(str(e)) + raise + + def replace(a: str, b: str) -> None: + nonlocal template + template = template.replace(a, b) + + if server_id: + replace("ID_TYPE", "$artifactID: ID") + replace("ID_VALUE", "artifactID: $artifactID") + elif client_id: + replace("ID_TYPE", "$clientID: ID") + replace("ID_VALUE", "clientID: $clientID") + + variable_values = { + "clientID": client_id, + "artifactID": server_id, + "artifactPortfolioName": portfolio_name, + "entityName": org_entity or entity, + "projectName": project, + "aliases": [ + {"alias": alias, "artifactCollectionName": portfolio_name} + for alias in aliases + ], + } + + mutation = gql(template) + response = self.gql(mutation, variable_values=variable_values) + link_artifact: Dict[str, Any] = response["linkArtifact"] + return link_artifact + + def _resolve_org_entity_name(self, entity: str, organization: str = "") -> str: + # resolveOrgEntityName fetches the portfolio's org entity's name. + # + # The organization parameter may be empty, an org's display name, or an org entity name. + # + # If the server doesn't support fetching the org name of a portfolio, then this returns + # the organization parameter, or an error if it is empty. Otherwise, this returns the + # fetched value after validating that the given organization, if not empty, matches + # either the org's display or entity name. + + if not entity: + raise ValueError("Entity name is required to resolve org entity name.") + + org_fields = self.server_organization_type_introspection() + can_shorthand_org_entity = "orgEntity" in org_fields + if not organization and not can_shorthand_org_entity: + raise ValueError( + "Fetching Registry artifacts without inputting an organization " + "is unavailable for your server version. " + "Please upgrade your server to 0.50.0 or later." + ) + if not can_shorthand_org_entity: + # Server doesn't support fetching org entity to validate, + # assume org entity is correctly inputted + return organization + + orgs_from_entity = self._fetch_orgs_and_org_entities_from_entity(entity) + if organization: + return _match_org_with_fetched_org_entities(organization, orgs_from_entity) + + # If no input organization provided, error if entity belongs to multiple orgs because we + # cannot determine which one to use. + if len(orgs_from_entity) > 1: + raise ValueError( + f"Personal entity {entity!r} belongs to multiple organizations " + "and cannot be used without specifying the organization name. " + "Please specify the organization in the Registry path or use a team entity in the entity settings." + ) + return orgs_from_entity[0].entity_name + + def _fetch_orgs_and_org_entities_from_entity(self, entity: str) -> List[_OrgNames]: + """Fetches organization entity names and display names for a given entity. + + Args: + entity (str): Entity name to lookup. Can be either a personal or team entity. + + Returns: + List[_OrgNames]: List of _OrgNames tuples. (_OrgNames(entity_name, display_name)) + + Raises: + ValueError: If entity is not found, has no organizations, or other validation errors. + """ + query = gql( + """ + query FetchOrgEntityFromEntity($entityName: String!) { + entity(name: $entityName) { + organization { + name + orgEntity { + name + } + } + user { + organizations { + name + orgEntity { + name + } + } + } + } + } + """ + ) + response = self.gql( + query, + variable_values={ + "entityName": entity, + }, + ) + + # Parse organization from response + entity_resp = response["entity"]["organization"] + user_resp = response["entity"]["user"] + # Check for organization under team/org entity type + if entity_resp: + org_name = entity_resp.get("name") + org_entity_name = entity_resp.get("orgEntity") and entity_resp[ + "orgEntity" + ].get("name") + if not org_name or not org_entity_name: + raise ValueError( + f"Unable to find an organization under entity {entity!r}." + ) + return [_OrgNames(entity_name=org_entity_name, display_name=org_name)] + # Check for organization under personal entity type, where a user can belong to multiple orgs + elif user_resp: + orgs = user_resp.get("organizations", []) + org_entities_return = [ + _OrgNames( + entity_name=org["orgEntity"]["name"], display_name=org["name"] + ) + for org in orgs + if org.get("orgEntity") and org.get("name") + ] + if not org_entities_return: + raise ValueError( + f"Unable to resolve an organization associated with personal entity: {entity!r}. " + "This could be because its a personal entity that doesn't belong to any organizations. " + "Please specify the organization in the Registry path or use a team entity in the entity settings." + ) + return org_entities_return + else: + raise ValueError(f"Unable to find an organization under entity {entity!r}.") + + def _construct_use_artifact_query( + self, + artifact_id: str, + entity_name: Optional[str] = None, + project_name: Optional[str] = None, + run_name: Optional[str] = None, + use_as: Optional[str] = None, + artifact_entity_name: Optional[str] = None, + artifact_project_name: Optional[str] = None, + ) -> Tuple[Document, Dict[str, Any]]: + query_vars = [ + "$entityName: String!", + "$projectName: String!", + "$runName: String!", + "$artifactID: ID!", + ] + query_args = [ + "entityName: $entityName", + "projectName: $projectName", + "runName: $runName", + "artifactID: $artifactID", + ] + + artifact_types = self.server_use_artifact_input_introspection() + if "usedAs" in artifact_types and use_as: + query_vars.append("$usedAs: String") + query_args.append("usedAs: $usedAs") + + entity_name = entity_name or self.settings("entity") + project_name = project_name or self.settings("project") + run_name = run_name or self.current_run_id + + variable_values: Dict[str, Any] = { + "entityName": entity_name, + "projectName": project_name, + "runName": run_name, + "artifactID": artifact_id, + "usedAs": use_as, + } + + server_allows_entity_project_information = self._server_supports( + ServerFeature.USE_ARTIFACT_WITH_ENTITY_AND_PROJECT_INFORMATION + ) + if server_allows_entity_project_information: + query_vars.extend( + [ + "$artifactEntityName: String", + "$artifactProjectName: String", + ] + ) + query_args.extend( + [ + "artifactEntityName: $artifactEntityName", + "artifactProjectName: $artifactProjectName", + ] + ) + variable_values["artifactEntityName"] = artifact_entity_name + variable_values["artifactProjectName"] = artifact_project_name + + vars_str = ", ".join(query_vars) + args_str = ", ".join(query_args) + + query = gql( + f""" + mutation UseArtifact({vars_str}) {{ + useArtifact(input: {{{args_str}}}) {{ + artifact {{ + id + digest + description + state + createdAt + metadata + }} + }} + }} + """ + ) + return query, variable_values + + def use_artifact( + self, + artifact_id: str, + entity_name: Optional[str] = None, + project_name: Optional[str] = None, + run_name: Optional[str] = None, + artifact_entity_name: Optional[str] = None, + artifact_project_name: Optional[str] = None, + use_as: Optional[str] = None, + ) -> Optional[Dict[str, Any]]: + query, variable_values = self._construct_use_artifact_query( + artifact_id, + entity_name, + project_name, + run_name, + use_as, + artifact_entity_name, + artifact_project_name, + ) + response = self.gql(query, variable_values) + + if response["useArtifact"]["artifact"]: + artifact: Dict[str, Any] = response["useArtifact"]["artifact"] + return artifact + return None + + # Fetch fields available in backend of Organization type + def server_organization_type_introspection(self) -> List[str]: + query_string = """ + query ProbeServerOrganization { + OrganizationInfoType: __type(name:"Organization") { + fields { + name + } + } + } + """ + + if self.server_organization_type_fields_info is None: + query = gql(query_string) + res = self.gql(query) + input_fields = res.get("OrganizationInfoType", {}).get("fields", [{}]) + self.server_organization_type_fields_info = [ + field["name"] for field in input_fields if "name" in field + ] + + return self.server_organization_type_fields_info + + # Fetch input arguments for the "artifact" endpoint on the "Project" type + def server_project_type_introspection(self) -> bool: + if self.server_supports_enabling_artifact_usage_tracking is not None: + return self.server_supports_enabling_artifact_usage_tracking + + query_string = """ + query ProbeServerProjectInfo { + ProjectInfoType: __type(name:"Project") { + fields { + name + args { + name + } + } + } + } + """ + + query = gql(query_string) + res = self.gql(query) + input_fields = res.get("ProjectInfoType", {}).get("fields", [{}]) + artifact_args: List[Dict[str, str]] = next( + ( + field.get("args", []) + for field in input_fields + if field.get("name") == "artifact" + ), + [], + ) + self.server_supports_enabling_artifact_usage_tracking = any( + arg.get("name") == "enableTracking" for arg in artifact_args + ) + + return self.server_supports_enabling_artifact_usage_tracking + + def create_artifact_type( + self, + artifact_type_name: str, + entity_name: Optional[str] = None, + project_name: Optional[str] = None, + description: Optional[str] = None, + ) -> Optional[str]: + mutation = gql( + """ + mutation CreateArtifactType( + $entityName: String!, + $projectName: String!, + $artifactTypeName: String!, + $description: String + ) { + createArtifactType(input: { + entityName: $entityName, + projectName: $projectName, + name: $artifactTypeName, + description: $description + }) { + artifactType { + id + } + } + } + """ + ) + entity_name = entity_name or self.settings("entity") + project_name = project_name or self.settings("project") + response = self.gql( + mutation, + variable_values={ + "entityName": entity_name, + "projectName": project_name, + "artifactTypeName": artifact_type_name, + "description": description, + }, + ) + _id: Optional[str] = response["createArtifactType"]["artifactType"]["id"] + return _id + + def server_artifact_introspection(self) -> List[str]: + query_string = """ + query ProbeServerArtifact { + ArtifactInfoType: __type(name:"Artifact") { + fields { + name + } + } + } + """ + + if self.server_artifact_fields_info is None: + query = gql(query_string) + res = self.gql(query) + input_fields = res.get("ArtifactInfoType", {}).get("fields", [{}]) + self.server_artifact_fields_info = [ + field["name"] for field in input_fields if "name" in field + ] + + return self.server_artifact_fields_info + + def server_create_artifact_introspection(self) -> List[str]: + query_string = """ + query ProbeServerCreateArtifactInput { + CreateArtifactInputInfoType: __type(name:"CreateArtifactInput") { + inputFields{ + name + } + } + } + """ + + if self.server_create_artifact_input_info is None: + query = gql(query_string) + res = self.gql(query) + input_fields = res.get("CreateArtifactInputInfoType", {}).get( + "inputFields", [{}] + ) + self.server_create_artifact_input_info = [ + field["name"] for field in input_fields if "name" in field + ] + + return self.server_create_artifact_input_info + + def _get_create_artifact_mutation( + self, + fields: List, + history_step: Optional[int], + distributed_id: Optional[str], + ) -> str: + types = "" + values = "" + + if "historyStep" in fields and history_step not in [0, None]: + types += "$historyStep: Int64!," + values += "historyStep: $historyStep," + + if distributed_id: + types += "$distributedID: String," + values += "distributedID: $distributedID," + + if "clientID" in fields: + types += "$clientID: ID," + values += "clientID: $clientID," + + if "sequenceClientID" in fields: + types += "$sequenceClientID: ID," + values += "sequenceClientID: $sequenceClientID," + + if "enableDigestDeduplication" in fields: + values += "enableDigestDeduplication: true," + + if "ttlDurationSeconds" in fields: + types += "$ttlDurationSeconds: Int64," + values += "ttlDurationSeconds: $ttlDurationSeconds," + + if "tags" in fields: + types += "$tags: [TagInput!]," + values += "tags: $tags," + + query_template = """ + mutation CreateArtifact( + $artifactTypeName: String!, + $artifactCollectionNames: [String!], + $entityName: String!, + $projectName: String!, + $runName: String, + $description: String, + $digest: String!, + $aliases: [ArtifactAliasInput!], + $metadata: JSONString, + _CREATE_ARTIFACT_ADDITIONAL_TYPE_ + ) { + createArtifact(input: { + artifactTypeName: $artifactTypeName, + artifactCollectionNames: $artifactCollectionNames, + entityName: $entityName, + projectName: $projectName, + runName: $runName, + description: $description, + digest: $digest, + digestAlgorithm: MANIFEST_MD5, + aliases: $aliases, + metadata: $metadata, + _CREATE_ARTIFACT_ADDITIONAL_VALUE_ + }) { + artifact { + id + state + artifactSequence { + id + latestArtifact { + id + versionIndex + } + } + } + } + } + """ + + return query_template.replace( + "_CREATE_ARTIFACT_ADDITIONAL_TYPE_", types + ).replace("_CREATE_ARTIFACT_ADDITIONAL_VALUE_", values) + + def create_artifact( + self, + artifact_type_name: str, + artifact_collection_name: str, + digest: str, + client_id: Optional[str] = None, + sequence_client_id: Optional[str] = None, + entity_name: Optional[str] = None, + project_name: Optional[str] = None, + run_name: Optional[str] = None, + description: Optional[str] = None, + metadata: Optional[Dict] = None, + ttl_duration_seconds: Optional[int] = None, + aliases: Optional[List[Dict[str, str]]] = None, + tags: Optional[List[Dict[str, str]]] = None, + distributed_id: Optional[str] = None, + is_user_created: Optional[bool] = False, + history_step: Optional[int] = None, + ) -> Tuple[Dict, Dict]: + fields = self.server_create_artifact_introspection() + artifact_fields = self.server_artifact_introspection() + if ("ttlIsInherited" not in artifact_fields) and ttl_duration_seconds: + wandb.termwarn( + "Server not compatible with setting Artifact TTLs, please upgrade the server to use Artifact TTL" + ) + # ttlDurationSeconds is only usable if ttlIsInherited is also present + ttl_duration_seconds = None + if ("tags" not in artifact_fields) and tags: + wandb.termwarn( + "Server not compatible with Artifact tags. " + "To use Artifact tags, please upgrade the server to v0.85 or higher." + ) + + query_template = self._get_create_artifact_mutation( + fields, history_step, distributed_id + ) + + entity_name = entity_name or self.settings("entity") + project_name = project_name or self.settings("project") + if not is_user_created: + run_name = run_name or self.current_run_id + + mutation = gql(query_template) + response = self.gql( + mutation, + variable_values={ + "entityName": entity_name, + "projectName": project_name, + "runName": run_name, + "artifactTypeName": artifact_type_name, + "artifactCollectionNames": [artifact_collection_name], + "clientID": client_id, + "sequenceClientID": sequence_client_id, + "digest": digest, + "description": description, + "aliases": list(aliases or []), + "tags": list(tags or []), + "metadata": json.dumps(util.make_safe_for_json(metadata)) + if metadata + else None, + "ttlDurationSeconds": ttl_duration_seconds, + "distributedID": distributed_id, + "historyStep": history_step, + }, + ) + av = response["createArtifact"]["artifact"] + latest = response["createArtifact"]["artifact"]["artifactSequence"].get( + "latestArtifact" + ) + return av, latest + + def commit_artifact(self, artifact_id: str) -> "_Response": + mutation = gql( + """ + mutation CommitArtifact( + $artifactID: ID!, + ) { + commitArtifact(input: { + artifactID: $artifactID, + }) { + artifact { + id + digest + } + } + } + """ + ) + + response: _Response = self.gql( + mutation, + variable_values={"artifactID": artifact_id}, + timeout=60, + ) + return response + + def complete_multipart_upload_artifact( + self, + artifact_id: str, + storage_path: str, + completed_parts: List[Dict[str, Any]], + upload_id: Optional[str], + complete_multipart_action: str = "Complete", + ) -> Optional[str]: + mutation = gql( + """ + mutation CompleteMultipartUploadArtifact( + $completeMultipartAction: CompleteMultipartAction!, + $completedParts: [UploadPartsInput!]!, + $artifactID: ID! + $storagePath: String! + $uploadID: String! + ) { + completeMultipartUploadArtifact( + input: { + completeMultipartAction: $completeMultipartAction, + completedParts: $completedParts, + artifactID: $artifactID, + storagePath: $storagePath + uploadID: $uploadID + } + ) { + digest + } + } + """ + ) + response = self.gql( + mutation, + variable_values={ + "completeMultipartAction": complete_multipart_action, + "artifactID": artifact_id, + "storagePath": storage_path, + "completedParts": completed_parts, + "uploadID": upload_id, + }, + ) + digest: Optional[str] = response["completeMultipartUploadArtifact"]["digest"] + return digest + + def create_artifact_manifest( + self, + name: str, + digest: str, + artifact_id: Optional[str], + base_artifact_id: Optional[str] = None, + entity: Optional[str] = None, + project: Optional[str] = None, + run: Optional[str] = None, + include_upload: bool = True, + type: str = "FULL", + ) -> Tuple[str, Dict[str, Any]]: + mutation = gql( + """ + mutation CreateArtifactManifest( + $name: String!, + $digest: String!, + $artifactID: ID!, + $baseArtifactID: ID, + $entityName: String!, + $projectName: String!, + $runName: String!, + $includeUpload: Boolean!, + {} + ) {{ + createArtifactManifest(input: {{ + name: $name, + digest: $digest, + artifactID: $artifactID, + baseArtifactID: $baseArtifactID, + entityName: $entityName, + projectName: $projectName, + runName: $runName, + {} + }}) {{ + artifactManifest {{ + id + file {{ + id + name + displayName + uploadUrl @include(if: $includeUpload) + uploadHeaders @include(if: $includeUpload) + }} + }} + }} + }} + """.format( + "$type: ArtifactManifestType = FULL" if type != "FULL" else "", + "type: $type" if type != "FULL" else "", + ) + ) + + entity_name = entity or self.settings("entity") + project_name = project or self.settings("project") + run_name = run or self.current_run_id + + response = self.gql( + mutation, + variable_values={ + "name": name, + "digest": digest, + "artifactID": artifact_id, + "baseArtifactID": base_artifact_id, + "entityName": entity_name, + "projectName": project_name, + "runName": run_name, + "includeUpload": include_upload, + "type": type, + }, + ) + return ( + response["createArtifactManifest"]["artifactManifest"]["id"], + response["createArtifactManifest"]["artifactManifest"]["file"], + ) + + def update_artifact_manifest( + self, + artifact_manifest_id: str, + base_artifact_id: Optional[str] = None, + digest: Optional[str] = None, + include_upload: Optional[bool] = True, + ) -> Tuple[str, Dict[str, Any]]: + mutation = gql( + """ + mutation UpdateArtifactManifest( + $artifactManifestID: ID!, + $digest: String, + $baseArtifactID: ID, + $includeUpload: Boolean!, + ) { + updateArtifactManifest(input: { + artifactManifestID: $artifactManifestID, + digest: $digest, + baseArtifactID: $baseArtifactID, + }) { + artifactManifest { + id + file { + id + name + displayName + uploadUrl @include(if: $includeUpload) + uploadHeaders @include(if: $includeUpload) + } + } + } + } + """ + ) + + response = self.gql( + mutation, + variable_values={ + "artifactManifestID": artifact_manifest_id, + "digest": digest, + "baseArtifactID": base_artifact_id, + "includeUpload": include_upload, + }, + ) + + return ( + response["updateArtifactManifest"]["artifactManifest"]["id"], + response["updateArtifactManifest"]["artifactManifest"]["file"], + ) + + def update_artifact_metadata( + self, artifact_id: str, metadata: Dict[str, Any] + ) -> Dict[str, Any]: + """Set the metadata of the given artifact version.""" + mutation = gql( + """ + mutation UpdateArtifact( + $artifactID: ID!, + $metadata: JSONString, + ) { + updateArtifact(input: { + artifactID: $artifactID, + metadata: $metadata, + }) { + artifact { + id + } + } + } + """ + ) + response = self.gql( + mutation, + variable_values={ + "artifactID": artifact_id, + "metadata": json.dumps(metadata), + }, + ) + return response["updateArtifact"]["artifact"] + + def _resolve_client_id( + self, + client_id: str, + ) -> Optional[str]: + if client_id in self._client_id_mapping: + return self._client_id_mapping[client_id] + + query = gql( + """ + query ClientIDMapping($clientID: ID!) { + clientIDMapping(clientID: $clientID) { + serverID + } + } + """ + ) + response = self.gql( + query, + variable_values={ + "clientID": client_id, + }, + ) + server_id = None + if response is not None: + client_id_mapping = response.get("clientIDMapping") + if client_id_mapping is not None: + server_id = client_id_mapping.get("serverID") + if server_id is not None: + self._client_id_mapping[client_id] = server_id + return server_id + + def server_create_artifact_file_spec_input_introspection(self) -> List: + query_string = """ + query ProbeServerCreateArtifactFileSpecInput { + CreateArtifactFileSpecInputInfoType: __type(name:"CreateArtifactFileSpecInput") { + inputFields{ + name + } + } + } + """ + + query = gql(query_string) + res = self.gql(query) + create_artifact_file_spec_input_info = [ + field.get("name", "") + for field in res.get("CreateArtifactFileSpecInputInfoType", {}).get( + "inputFields", [{}] + ) + ] + return create_artifact_file_spec_input_info + + @normalize_exceptions + def create_artifact_files( + self, artifact_files: Iterable["CreateArtifactFileSpecInput"] + ) -> Mapping[str, "CreateArtifactFilesResponseFile"]: + query_template = """ + mutation CreateArtifactFiles( + $storageLayout: ArtifactStorageLayout! + $artifactFiles: [CreateArtifactFileSpecInput!]! + ) { + createArtifactFiles(input: { + artifactFiles: $artifactFiles, + storageLayout: $storageLayout, + }) { + files { + edges { + node { + id + name + displayName + uploadUrl + uploadHeaders + _MULTIPART_UPLOAD_FIELDS_ + artifact { + id + } + } + } + } + } + } + """ + multipart_upload_url_query = """ + storagePath + uploadMultipartUrls { + uploadID + uploadUrlParts { + partNumber + uploadUrl + } + } + """ + + # TODO: we should use constants here from interface/artifacts.py + # but probably don't want the dependency. We're going to remove + # this setting in a future release, so I'm just hard-coding the strings. + storage_layout = "V2" + if env.get_use_v1_artifacts(): + storage_layout = "V1" + + create_artifact_file_spec_input_fields = ( + self.server_create_artifact_file_spec_input_introspection() + ) + if "uploadPartsInput" in create_artifact_file_spec_input_fields: + query_template = query_template.replace( + "_MULTIPART_UPLOAD_FIELDS_", multipart_upload_url_query + ) + else: + query_template = query_template.replace("_MULTIPART_UPLOAD_FIELDS_", "") + + mutation = gql(query_template) + response = self.gql( + mutation, + variable_values={ + "storageLayout": storage_layout, + "artifactFiles": [af for af in artifact_files], + }, + ) + + result = {} + for edge in response["createArtifactFiles"]["files"]["edges"]: + node = edge["node"] + result[node["displayName"]] = node + return result + + @normalize_exceptions + def notify_scriptable_run_alert( + self, + title: str, + text: str, + level: Optional[str] = None, + wait_duration: Optional["Number"] = None, + ) -> bool: + mutation = gql( + """ + mutation NotifyScriptableRunAlert( + $entityName: String!, + $projectName: String!, + $runName: String!, + $title: String!, + $text: String!, + $severity: AlertSeverity = INFO, + $waitDuration: Duration + ) { + notifyScriptableRunAlert(input: { + entityName: $entityName, + projectName: $projectName, + runName: $runName, + title: $title, + text: $text, + severity: $severity, + waitDuration: $waitDuration + }) { + success + } + } + """ + ) + + response = self.gql( + mutation, + variable_values={ + "entityName": self.settings("entity"), + "projectName": self.settings("project"), + "runName": self.current_run_id, + "title": title, + "text": text, + "severity": level, + "waitDuration": wait_duration, + }, + ) + success: bool = response["notifyScriptableRunAlert"]["success"] + return success + + def get_sweep_state( + self, sweep: str, entity: Optional[str] = None, project: Optional[str] = None + ) -> "SweepState": + state: SweepState = self.sweep( + sweep=sweep, entity=entity, project=project, specs="{}" + )["state"] + return state + + def set_sweep_state( + self, + sweep: str, + state: "SweepState", + entity: Optional[str] = None, + project: Optional[str] = None, + ) -> None: + assert state in ("RUNNING", "PAUSED", "CANCELED", "FINISHED") + s = self.sweep(sweep=sweep, entity=entity, project=project, specs="{}") + curr_state = s["state"].upper() + if state == "PAUSED" and curr_state not in ("PAUSED", "RUNNING"): + raise Exception(f"Cannot pause {curr_state.lower()} sweep.") + elif state != "RUNNING" and curr_state not in ("RUNNING", "PAUSED", "PENDING"): + raise Exception(f"Sweep already {curr_state.lower()}.") + sweep_id = s["id"] + mutation = gql( + """ + mutation UpsertSweep( + $id: ID, + $state: String, + $entityName: String, + $projectName: String + ) { + upsertSweep(input: { + id: $id, + state: $state, + entityName: $entityName, + projectName: $projectName + }){ + sweep { + name + } + } + } + """ + ) + self.gql( + mutation, + variable_values={ + "id": sweep_id, + "state": state, + "entityName": entity or self.settings("entity"), + "projectName": project or self.settings("project"), + }, + ) + + def stop_sweep( + self, + sweep: str, + entity: Optional[str] = None, + project: Optional[str] = None, + ) -> None: + """Finish the sweep to stop running new runs and let currently running runs finish.""" + self.set_sweep_state( + sweep=sweep, state="FINISHED", entity=entity, project=project + ) + + def cancel_sweep( + self, + sweep: str, + entity: Optional[str] = None, + project: Optional[str] = None, + ) -> None: + """Cancel the sweep to kill all running runs and stop running new runs.""" + self.set_sweep_state( + sweep=sweep, state="CANCELED", entity=entity, project=project + ) + + def pause_sweep( + self, + sweep: str, + entity: Optional[str] = None, + project: Optional[str] = None, + ) -> None: + """Pause the sweep to temporarily stop running new runs.""" + self.set_sweep_state( + sweep=sweep, state="PAUSED", entity=entity, project=project + ) + + def resume_sweep( + self, + sweep: str, + entity: Optional[str] = None, + project: Optional[str] = None, + ) -> None: + """Resume the sweep to continue running new runs.""" + self.set_sweep_state( + sweep=sweep, state="RUNNING", entity=entity, project=project + ) + + def _status_request(self, url: str, length: int) -> requests.Response: + """Ask google how much we've uploaded.""" + check_httpclient_logger_handler() + return requests.put( + url=url, + headers={"Content-Length": "0", "Content-Range": f"bytes */{length}"}, + ) + + def _flatten_edges(self, response: "_Response") -> List[Dict]: + """Return an array from the nested graphql relay structure.""" + return [node["node"] for node in response["edges"]] + + @normalize_exceptions + def stop_run( + self, + run_id: str, + ) -> bool: + mutation = gql( + """ + mutation stopRun($id: ID!) { + stopRun(input: { + id: $id + }) { + clientMutationId + success + } + } + """ + ) + + response = self.gql( + mutation, + variable_values={ + "id": run_id, + }, + ) + + success: bool = response["stopRun"].get("success") + + return success + + @normalize_exceptions + def create_custom_chart( + self, + entity: str, + name: str, + display_name: str, + spec_type: str, + access: str, + spec: Union[str, Mapping[str, Any]], + ) -> Optional[Dict[str, Any]]: + if not isinstance(spec, str): + spec = json.dumps(spec) + + mutation = gql( + """ + mutation CreateCustomChart( + $entity: String! + $name: String! + $displayName: String! + $type: String! + $access: String! + $spec: JSONString! + ) { + createCustomChart( + input: { + entity: $entity + name: $name + displayName: $displayName + type: $type + access: $access + spec: $spec + } + ) { + chart { id } + } + } + """ + ) + + variable_values = { + "entity": entity, + "name": name, + "displayName": display_name, + "type": spec_type, + "access": access, + "spec": spec, + } + + result: Optional[Dict[str, Any]] = self.gql(mutation, variable_values)[ + "createCustomChart" + ] + return result diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/job_builder.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/job_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..b4830c37c764e45ee51645e1bfe7825a783d5a1a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/job_builder.py @@ -0,0 +1,639 @@ +"""job builder.""" + +import json +import logging +import os +import re +import sys +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + List, + Literal, + Optional, + Tuple, + TypedDict, + Union, +) + +import wandb +from wandb.sdk.artifacts._internal_artifact import InternalArtifact +from wandb.sdk.artifacts.artifact import Artifact +from wandb.sdk.data_types._dtypes import TypeRegistry +from wandb.sdk.internal.internal_api import Api +from wandb.sdk.lib.filenames import DIFF_FNAME, METADATA_FNAME, REQUIREMENTS_FNAME +from wandb.util import make_artifact_name_safe + +from .settings_static import SettingsStatic + +_logger = logging.getLogger(__name__) + +if TYPE_CHECKING: + from wandb.proto.wandb_internal_pb2 import ArtifactRecord + +FROZEN_REQUIREMENTS_FNAME = "requirements.frozen.txt" +JOB_FNAME = "wandb-job.json" +JOB_ARTIFACT_TYPE = "job" + +LOG_LEVEL = Literal["log", "warn", "error"] + + +class Version: + def __init__(self, major: int, minor: int, patch: int): + self._major = major + self._minor = minor + self._patch = patch + + def __repr__(self) -> str: + return f"{self._major}.{self._minor}.{self._patch}" + + def __lt__(self, other: "Version") -> bool: + if self._major < other._major: + return True + elif self._major == other._major: + if self._minor < other._minor: + return True + elif self._minor == other._minor: + if self._patch < other._patch: + return True + return False + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Version): + return NotImplemented + return ( + self._major == other._major + and self._minor == other._minor + and self._patch == other._patch + ) + + +# Minimum supported wandb version for keys in the source dict of wandb-job.json +SOURCE_KEYS_MIN_SUPPORTED_VERSION = { + "dockerfile": Version(0, 17, 0), + "build_context": Version(0, 17, 0), +} + + +class GitInfo(TypedDict): + remote: str + commit: str + + +class GitSourceDict(TypedDict): + git: GitInfo + entrypoint: List[str] + notebook: bool + build_context: Optional[str] + dockerfile: Optional[str] + + +class ArtifactSourceDict(TypedDict): + artifact: str + entrypoint: List[str] + notebook: bool + build_context: Optional[str] + dockerfile: Optional[str] + + +class ImageSourceDict(TypedDict): + image: str + + +class JobSourceDict(TypedDict, total=False): + _version: str + source_type: str + source: Union[GitSourceDict, ArtifactSourceDict, ImageSourceDict] + input_types: Dict[str, Any] + output_types: Dict[str, Any] + runtime: Optional[str] + services: Dict[str, str] + + +class ArtifactInfoForJob(TypedDict): + id: str + name: str + + +def get_min_supported_for_source_dict( + source: Union[GitSourceDict, ArtifactSourceDict, ImageSourceDict], +) -> Optional[Version]: + """Get the minimum supported wandb version the source dict of wandb-job.json.""" + min_seen = None + for key in source: + new_ver = SOURCE_KEYS_MIN_SUPPORTED_VERSION.get(key) + if new_ver: + if min_seen is None or new_ver < min_seen: + min_seen = new_ver + return min_seen + + +class JobBuilder: + _settings: SettingsStatic + _metadatafile_path: Optional[str] + _requirements_path: Optional[str] + _config: Optional[Dict[str, Any]] + _summary: Optional[Dict[str, Any]] + _logged_code_artifact: Optional[ArtifactInfoForJob] + _disable: bool + _partial_source_id: Optional[str] # Partial job source artifact id. + _aliases: List[str] + _job_seq_id: Optional[str] + _job_version_alias: Optional[str] + _is_notebook_run: bool + _verbose: bool + _services: Dict[str, str] + + def __init__(self, settings: SettingsStatic, verbose: bool = False): + self._settings = settings + self._metadatafile_path = None + self._requirements_path = None + self._config = None + self._summary = None + self._logged_code_artifact = None + self._job_seq_id = None + self._job_version_alias = None + self._disable = settings.disable_job_creation or settings.x_disable_machine_info + self._partial_source_id = None + self._aliases = [] + self._source_type: Optional[Literal["repo", "artifact", "image"]] = ( + settings.job_source # type: ignore[assignment] + ) + self._is_notebook_run = self._get_is_notebook_run() + self._verbose = verbose + self._partial = False + self._services = {} + + def set_config(self, config: Dict[str, Any]) -> None: + self._config = config + + def set_summary(self, summary: Dict[str, Any]) -> None: + self._summary = summary + + @property + def disable(self) -> bool: + return self._disable + + @disable.setter + def disable(self, val: bool) -> None: + self._disable = val + + @property + def input_types(self) -> Dict[str, Any]: + return TypeRegistry.type_of(self._config).to_json() + + @property + def output_types(self) -> Dict[str, Any]: + return TypeRegistry.type_of(self._summary).to_json() + + def set_partial_source_id(self, source_id: str) -> None: + self._partial_source_id = source_id + + def _handle_server_artifact( + self, res: Optional[Dict], artifact: "ArtifactRecord" + ) -> None: + if artifact.type == "job" and res is not None: + try: + if res["artifactSequence"]["latestArtifact"] is None: + self._job_version_alias = "v0" + elif res["artifactSequence"]["latestArtifact"]["id"] == res["id"]: + self._job_version_alias = ( + f"v{res['artifactSequence']['latestArtifact']['versionIndex']}" + ) + else: + self._job_version_alias = f"v{res['artifactSequence']['latestArtifact']['versionIndex'] + 1}" + self._job_seq_id = res["artifactSequence"]["id"] + except KeyError as e: + _logger.info(f"Malformed response from ArtifactSaver.save {e}") + if artifact.type == "code" and res is not None: + self._logged_code_artifact = ArtifactInfoForJob( + { + "id": res["id"], + "name": artifact.name, + } + ) + + def _build_repo_job_source( + self, + program_relpath: str, + metadata: Dict[str, Any], + ) -> Tuple[Optional[GitSourceDict], Optional[str]]: + git_info: Dict[str, str] = metadata.get("git", {}) + remote = git_info.get("remote") + commit = git_info.get("commit") + root = metadata.get("root") + assert remote is not None + assert commit is not None + if self._is_notebook_run: + if not os.path.exists( + os.path.join(os.getcwd(), os.path.basename(program_relpath)) + ): + return None, None + + if root is None or self._settings.x_jupyter_root is None: + _logger.info("target path does not exist, exiting") + return None, None + assert self._settings.x_jupyter_root is not None + # git notebooks set the root to the git root, + # jupyter_root contains the path where the jupyter notebook was started + # program_relpath contains the path from jupyter_root to the file + # full program path here is actually the relpath from the program to the git root + full_program_path = os.path.join( + os.path.relpath(str(self._settings.x_jupyter_root), root), + program_relpath, + ) + full_program_path = os.path.normpath(full_program_path) + # if the notebook server is started above the git repo need to clear all the ..s + if full_program_path.startswith(".."): + split_path = full_program_path.split("/") + count_dots = 0 + for p in split_path: + if p == "..": + count_dots += 1 + full_program_path = "/".join(split_path[2 * count_dots :]) + else: + full_program_path = program_relpath + + entrypoint = self._get_entrypoint(full_program_path, metadata) + # TODO: update executable to a method that supports pex + source: GitSourceDict = { + "git": {"remote": remote, "commit": commit}, + "entrypoint": entrypoint, + "notebook": self._is_notebook_run, + "build_context": metadata.get("build_context"), + "dockerfile": metadata.get("dockerfile"), + } + name = self._make_job_name(f"{remote}_{program_relpath}") + + return source, name + + def _log_if_verbose(self, message: str, level: LOG_LEVEL) -> None: + log_func: Optional[Union[Callable[[Any], None], Callable[[Any], None]]] = None + if level == "log": + _logger.info(message) + log_func = wandb.termlog + elif level == "warn": + _logger.warning(message) + log_func = wandb.termwarn + elif level == "error": + _logger.error(message) + log_func = wandb.termerror + + if self._verbose and log_func is not None: + log_func(message) + + def _build_artifact_job_source( + self, + program_relpath: str, + metadata: Dict[str, Any], + ) -> Tuple[Optional[ArtifactSourceDict], Optional[str]]: + assert isinstance(self._logged_code_artifact, dict) + # TODO: should we just always exit early if the path doesn't exist? + if self._is_notebook_run and not self._is_colab_run(): + full_program_relpath = os.path.relpath(program_relpath, os.getcwd()) + # if the resolved path doesn't exist, then we shouldn't make a job because it will fail + if not os.path.exists(full_program_relpath): + # when users call log code in a notebook the code artifact starts + # at the directory the notebook is in instead of the jupyter core + if not os.path.exists(os.path.basename(program_relpath)): + _logger.info("target path does not exist, exiting") + self._log_if_verbose( + "No program path found when generating artifact job source for a non-colab notebook run. See https://docs.wandb.ai/guides/launch/create-job", + "warn", + ) + return None, None + full_program_relpath = os.path.basename(program_relpath) + else: + full_program_relpath = program_relpath + + entrypoint = self._get_entrypoint(full_program_relpath, metadata) + # TODO: update executable to a method that supports pex + source: ArtifactSourceDict = { + "entrypoint": entrypoint, + "notebook": self._is_notebook_run, + "artifact": f"wandb-artifact://_id/{self._logged_code_artifact['id']}", + "build_context": metadata.get("build_context"), + "dockerfile": metadata.get("dockerfile"), + } + artifact_basename, *_ = self._logged_code_artifact["name"].split(":") + name = self._make_job_name(artifact_basename) + + return source, name + + def _build_image_job_source( + self, metadata: Dict[str, Any] + ) -> Tuple[ImageSourceDict, str]: + image_name = metadata.get("docker") + assert isinstance(image_name, str) + + raw_image_name = image_name + if ":" in image_name: + tag = image_name.split(":")[-1] + + # if tag looks properly formatted, assume its a tag + # regex: alphanumeric and "_" "-" "." + if re.fullmatch(r"([a-zA-Z0-9_\-\.]+)", tag): + raw_image_name = raw_image_name.replace(f":{tag}", "") + self._aliases += [tag] + + source: ImageSourceDict = { + "image": image_name, + } + name = self._make_job_name(raw_image_name) + + return source, name + + def _make_job_name(self, input_str: str) -> str: + """Use job name from settings if provided, else use programmatic name.""" + if self._settings.job_name: + return self._settings.job_name + + return make_artifact_name_safe(f"job-{input_str}") + + def _get_entrypoint( + self, + program_relpath: str, + metadata: Dict[str, Any], + ) -> List[str]: + # if building a partial job from CLI, overwrite entrypoint and notebook + # should already be in metadata from create_job + if self._partial: + if metadata.get("entrypoint"): + entrypoint: List[str] = metadata["entrypoint"] + return entrypoint + # job is being built from a run + entrypoint = [os.path.basename(sys.executable), program_relpath] + + return entrypoint + + def _get_is_notebook_run(self) -> bool: + return hasattr(self._settings, "_jupyter") and bool(self._settings._jupyter) + + def _is_colab_run(self) -> bool: + return hasattr(self._settings, "_colab") and bool(self._settings._colab) + + def _build_job_source( + self, + source_type: str, + program_relpath: Optional[str], + metadata: Dict[str, Any], + ) -> Tuple[ + Union[GitSourceDict, ArtifactSourceDict, ImageSourceDict, None], + Optional[str], + ]: + """Construct a job source dict and name from the current run. + + Args: + source_type (str): The type of source to build the job from. One of + "repo", "artifact", or "image". + """ + source: Union[ + GitSourceDict, + ArtifactSourceDict, + ImageSourceDict, + None, + ] = None + + if source_type == "repo": + source, name = self._build_repo_job_source( + program_relpath or "", + metadata, + ) + elif source_type == "artifact": + source, name = self._build_artifact_job_source( + program_relpath or "", + metadata, + ) + elif source_type == "image" and self._has_image_job_ingredients(metadata): + source, name = self._build_image_job_source(metadata) + else: + source = None + + if source is None: + if source_type: + self._log_if_verbose( + f"Source type is set to '{source_type}' but some required information is missing " + "from the environment. A job will not be created from this run. See " + "https://docs.wandb.ai/guides/launch/create-job", + "warn", + ) + return None, None + + return source, name + + def build( + self, + api: Api, + build_context: Optional[str] = None, + dockerfile: Optional[str] = None, + base_image: Optional[str] = None, + ) -> Optional[Artifact]: + """Build a job artifact from the current run. + + Args: + api (Api): The API object to use to create the job artifact. + build_context (Optional[str]): Path within the job source code to + the image build context. Saved as part of the job for future + builds. + dockerfile (Optional[str]): Path within the build context the + Dockerfile. Saved as part of the job for future builds. + base_image (Optional[str]): The base image used to run the job code. + + Returns: + Optional[Artifact]: The job artifact if it was successfully built, + otherwise None. + """ + _logger.info("Attempting to build job artifact") + + # If a partial job was used, write the input/output types to the metadata + # rather than building a new job version. + if self._partial_source_id is not None: + new_metadata = { + "input_types": {"@wandb.config": self.input_types}, + "output_types": self.output_types, + } + api.update_artifact_metadata( + self._partial_source_id, + new_metadata, + ) + return None + + if not os.path.exists( + os.path.join(self._settings.files_dir, REQUIREMENTS_FNAME) + ): + self._log_if_verbose( + "No requirements.txt found, not creating job artifact. See https://docs.wandb.ai/guides/launch/create-job", + "warn", + ) + return None + metadata = self._handle_metadata_file() + if metadata is None: + self._log_if_verbose( + f"Ensure read and write access to run files dir: {self._settings.files_dir}, control this via the WANDB_DIR env var. See https://docs.wandb.ai/guides/track/environment-variables", + "warn", + ) + return None + + runtime: Optional[str] = metadata.get("python") + # can't build a job without a python version + if runtime is None: + self._log_if_verbose( + "No python version found in metadata, not creating job artifact. " + "See https://docs.wandb.ai/guides/launch/create-job", + "warn", + ) + return None + + input_types = TypeRegistry.type_of(self._config).to_json() + output_types = TypeRegistry.type_of(self._summary).to_json() + + name: Optional[str] = None + source_info: Optional[JobSourceDict] = None + + # configure job from environment + source_type = self._get_source_type(metadata) + if not source_type: + # if source_type is None, then we don't have enough information to build a job + # if the user intended to create a job, warn. + if ( + self._settings.job_name + or self._settings.job_source + or self._source_type + ): + self._log_if_verbose( + "No source type found, not creating job artifact", "warn" + ) + return None + + program_relpath = self._get_program_relpath(source_type, metadata) + if not self._partial and source_type != "image" and not program_relpath: + self._log_if_verbose( + "No program path found, not creating job artifact. " + "See https://docs.wandb.ai/guides/launch/create-job", + "warn", + ) + return None + + source, name = self._build_job_source( + source_type, + program_relpath, + metadata, + ) + if source is None: + return None + + if build_context: + source["build_context"] = build_context # type: ignore[typeddict-item] + if dockerfile: + source["dockerfile"] = dockerfile # type: ignore[typeddict-item] + if base_image: + source["base_image"] = base_image # type: ignore[typeddict-item] + + # Pop any keys that are initialized to None. The current TypedDict + # system for source dicts requires all keys to be present, but we + # don't want to include keys that are None in the final dict. + for key in list(source.keys()): + if source[key] is None: # type: ignore[literal-required] + source.pop(key) # type: ignore[literal-require,misc] + + source_info = { + "_version": str(get_min_supported_for_source_dict(source) or "v0"), + "source_type": source_type, + "source": source, + "input_types": input_types, + "output_types": output_types, + "runtime": runtime, + } + + if self._services: + source_info["services"] = self._services + + assert source_info is not None + assert name is not None + + artifact = InternalArtifact(name, JOB_ARTIFACT_TYPE) + + _logger.info("adding wandb-job metadata file") + with artifact.new_file("wandb-job.json") as f: + f.write(json.dumps(source_info, indent=4)) + + artifact.add_file( + os.path.join(self._settings.files_dir, REQUIREMENTS_FNAME), + name=FROZEN_REQUIREMENTS_FNAME, + ) + + if source_type == "repo": + # add diff + if os.path.exists(os.path.join(self._settings.files_dir, DIFF_FNAME)): + artifact.add_file( + os.path.join(self._settings.files_dir, DIFF_FNAME), + name=DIFF_FNAME, + ) + + return artifact + + def _get_source_type(self, metadata: Dict[str, Any]) -> Optional[str]: + if self._source_type: + return self._source_type + + if self._has_git_job_ingredients(metadata): + _logger.info("is repo sourced job") + return "repo" + + if self._has_artifact_job_ingredients(): + _logger.info("is artifact sourced job") + return "artifact" + + if self._has_image_job_ingredients(metadata): + _logger.info("is image sourced job") + return "image" + + _logger.info("no source found") + return None + + def _get_program_relpath( + self, source_type: str, metadata: Dict[str, Any] + ) -> Optional[str]: + if self._is_notebook_run: + _logger.info("run is notebook based run") + program = metadata.get("program") + + if not program: + self._log_if_verbose( + "Notebook 'program' path not found in metadata. See https://docs.wandb.ai/guides/launch/create-job", + "warn", + ) + + return program + + if source_type == "artifact" or self._settings.job_source == "artifact": + # if the job is set to be an artifact, use relpath guaranteed + # to be correct. 'codePath' uses the root path when in git repo + # fallback to codePath if strictly local relpath not present + return metadata.get("codePathLocal") or metadata.get("codePath") + + return metadata.get("codePath") + + def _handle_metadata_file( + self, + ) -> Optional[Dict]: + if os.path.exists(os.path.join(self._settings.files_dir, METADATA_FNAME)): + with open(os.path.join(self._settings.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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/profiler.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..9973e42984580a3fca6dc6706728a58ed22d4277 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/run.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/run.py new file mode 100644 index 0000000000000000000000000000000000000000..885729a8b0c27eb91f9b0ff006576186be491235 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/sample.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/sample.py new file mode 100644 index 0000000000000000000000000000000000000000..7bffe7562e4b28614bad3e4c1cbf5be5423532fe --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/sender.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/sender.py new file mode 100644 index 0000000000000000000000000000000000000000..e87606d39e814175acd494e2014ed78c245a0a1b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/sender.py @@ -0,0 +1,1692 @@ +"""sender.""" + +import contextlib +import glob +import gzip +import json +import logging +import os +import queue +import threading +import time +import traceback +from collections import defaultdict +from datetime import datetime +from queue import Queue +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Generator, + List, + Literal, + Optional, + Tuple, + Type, + Union, +) + +import requests + +import wandb +from wandb import util +from wandb.errors import CommError, UsageError +from wandb.errors.util import ProtobufErrorHandler +from wandb.filesync.dir_watcher import DirWatcher +from wandb.proto import wandb_internal_pb2 +from wandb.sdk.artifacts.artifact_saver import ArtifactSaver +from wandb.sdk.interface import interface +from wandb.sdk.interface.interface_queue import InterfaceQueue +from wandb.sdk.internal import ( + context, + datastore, + file_stream, + internal_api, + sender_config, +) +from wandb.sdk.internal.file_pusher import FilePusher +from wandb.sdk.internal.job_builder import JobBuilder +from wandb.sdk.internal.settings_static import SettingsStatic +from wandb.sdk.lib import ( + config_util, + filenames, + filesystem, + proto_util, + redirect, + retry, + telemetry, +) +from wandb.sdk.lib.proto_util import message_to_dict + +if TYPE_CHECKING: + from wandb.proto.wandb_internal_pb2 import ( + ArtifactManifest, + ArtifactManifestEntry, + ArtifactRecord, + EnvironmentRecord, + HttpResponse, + LocalInfo, + Record, + Result, + RunExitResult, + RunRecord, + SummaryRecord, + ) + + StreamLiterals = Literal["stdout", "stderr"] + + +logger = logging.getLogger(__name__) + + +_OUTPUT_MIN_CALLBACK_INTERVAL = 2 # seconds + + +def _framework_priority() -> Generator[Tuple[str, str], None, None]: + yield from [ + ("lightgbm", "lightgbm"), + ("catboost", "catboost"), + ("xgboost", "xgboost"), + ("transformers_huggingface", "huggingface"), # backwards compatibility + ("transformers", "huggingface"), + ("pytorch_ignite", "ignite"), # backwards compatibility + ("ignite", "ignite"), + ("pytorch_lightning", "lightning"), + ("fastai", "fastai"), + ("torch", "torch"), + ("keras", "keras"), + ("tensorflow", "tensorflow"), + ("sklearn", "sklearn"), + ] + + +def _manifest_json_from_proto(manifest: "ArtifactManifest") -> Dict: + if manifest.version == 1: + if manifest.manifest_file_path: + contents = {} + with gzip.open(manifest.manifest_file_path, "rt") as f: + for line in f: + entry_json = json.loads(line) + path = entry_json.pop("path") + contents[path] = entry_json + else: + contents = { + content.path: _manifest_entry_from_proto(content) + for content in manifest.contents + } + else: + raise ValueError(f"unknown artifact manifest version: {manifest.version}") + + return { + "version": manifest.version, + "storagePolicy": manifest.storage_policy, + "storagePolicyConfig": { + config.key: json.loads(config.value_json) + for config in manifest.storage_policy_config + }, + "contents": contents, + } + + +def _manifest_entry_from_proto(entry: "ArtifactManifestEntry") -> Dict: + birth_artifact_id = entry.birth_artifact_id if entry.birth_artifact_id else None + return { + "digest": entry.digest, + "birthArtifactID": birth_artifact_id, + "ref": entry.ref if entry.ref else None, + "size": entry.size if entry.size is not None else None, + "local_path": entry.local_path if entry.local_path else None, + "skip_cache": entry.skip_cache, + "extra": {extra.key: json.loads(extra.value_json) for extra in entry.extra}, + } + + +class ResumeState: + resumed: bool + step: int + history: int + events: int + output: int + runtime: float + wandb_runtime: Optional[int] + summary: Optional[Dict[str, Any]] + config: Optional[Dict[str, Any]] + tags: Optional[List[str]] + + def __init__(self) -> None: + self.resumed = False + self.step = 0 + self.history = 0 + self.events = 0 + self.output = 0 + self.runtime = 0 + # wandb_runtime is the canonical runtime (stored in summary._wandb.runtime) + self.wandb_runtime = None + self.summary = None + self.config = None + self.tags = None + + def __str__(self) -> str: + obj = ",".join(map(lambda it: f"{it[0]}={it[1]}", vars(self).items())) + return f"ResumeState({obj})" + + +class _OutputRawStream: + _stopped: threading.Event + _queue: queue.Queue + _emulator: redirect.TerminalEmulator + _writer_thr: threading.Thread + _reader_thr: threading.Thread + + def __init__(self, stream: str, sm: "SendManager"): + self._stopped = threading.Event() + self._queue = queue.Queue() + self._emulator = redirect.TerminalEmulator() + self._writer_thr = threading.Thread( + target=sm._output_raw_writer_thread, + kwargs=dict(stream=stream), + daemon=True, + name=f"OutRawWr-{stream}", + ) + self._reader_thr = threading.Thread( + target=sm._output_raw_reader_thread, + kwargs=dict(stream=stream), + daemon=True, + name=f"OutRawRd-{stream}", + ) + + def start(self) -> None: + self._writer_thr.start() + self._reader_thr.start() + + +class SendManager: + UPDATE_CONFIG_TIME: int = 30 + UPDATE_STATUS_TIME: int = 5 + + _settings: SettingsStatic + _record_q: "Queue[Record]" + _result_q: "Queue[Result]" + _interface: InterfaceQueue + _api_settings: Dict[str, str] + _partial_output: Dict[str, str] + _context_keeper: context.ContextKeeper + + _telemetry_obj: telemetry.TelemetryRecord + _environment_obj: "EnvironmentRecord" + _fs: Optional["file_stream.FileStreamApi"] + _run: Optional["RunRecord"] + _entity: Optional[str] + _project: Optional[str] + _dir_watcher: Optional["DirWatcher"] + _pusher: Optional["FilePusher"] + _record_exit: Optional["Record"] + _exit_result: Optional["RunExitResult"] + _resume_state: ResumeState + _rewind_response: Optional[Dict[str, Any]] + _cached_server_info: Dict[str, Any] + _cached_viewer: Dict[str, Any] + _server_messages: List[Dict[str, Any]] + _ds: Optional[datastore.DataStore] + _output_raw_streams: Dict["StreamLiterals", _OutputRawStream] + _output_raw_file: Optional[filesystem.CRDedupedFile] + _send_record_num: int + _send_end_offset: int + _debounce_config_time: float + _debounce_status_time: float + + def __init__( + self, + settings: SettingsStatic, + record_q: "Queue[Record]", + result_q: "Queue[Result]", + interface: InterfaceQueue, + context_keeper: context.ContextKeeper, + ) -> None: + self._settings = settings + self._record_q = record_q + self._result_q = result_q + self._interface = interface + self._context_keeper = context_keeper + + self._ds = None + self._send_record_num = 0 + self._send_end_offset = 0 + + self._fs = None + self._pusher = None + self._dir_watcher = None + + # State updated by login + self._entity = None + self._flags = None + + # State updated by wandb.init + self._run = None + self._project = None + + # keep track of config from key/val updates + self._consolidated_config = sender_config.ConfigState() + + self._start_time: int = 0 + self._telemetry_obj = telemetry.TelemetryRecord() + self._environment_obj = wandb_internal_pb2.EnvironmentRecord() + self._config_metric_pbdict_list: List[Dict[int, Any]] = [] + self._metadata_summary: Dict[str, Any] = defaultdict() + self._cached_summary: Dict[str, Any] = dict() + self._config_metric_index_dict: Dict[str, int] = {} + self._config_metric_dict: Dict[str, wandb_internal_pb2.MetricRecord] = {} + self._consolidated_summary: Dict[str, Any] = dict() + + self._cached_server_info = dict() + self._cached_viewer = dict() + self._server_messages = [] + + # State updated by resuming + self._resume_state = ResumeState() + self._rewind_response = None + + # State added when run_exit is initiated and complete + self._record_exit = None + self._exit_result = None + + self._api = internal_api.Api( + default_settings=settings, retry_callback=self.retry_callback + ) + self._api_settings = dict() + + # queue filled by retry_callback + self._retry_q: Queue[HttpResponse] = queue.Queue() + + # do we need to debounce? + self._config_needs_debounce: bool = False + + # TODO(jhr): do something better, why do we need to send full lines? + self._partial_output = dict() + + self._exit_code = 0 + + # internal vars for handing raw console output + self._output_raw_streams = dict() + self._output_raw_file = None + + # job builder + self._job_builder = JobBuilder(settings) + + time_now = time.monotonic() + self._debounce_config_time = time_now + self._debounce_status_time = time_now + + @classmethod + def setup( + cls, + root_dir: str, + resume: Union[None, bool, str], + ) -> "SendManager": + """Set up a standalone SendManager. + + Exclusively used in `sync.py`. + """ + files_dir = os.path.join(root_dir, "files") + settings = wandb.Settings( + x_files_dir=files_dir, + root_dir=root_dir, + # _start_time=0, + resume=resume, + # ignore_globs=(), + x_sync=True, + disable_job_creation=False, + x_file_stream_timeout_seconds=0, + ) + record_q: Queue[Record] = queue.Queue() + result_q: Queue[Result] = queue.Queue() + publish_interface = InterfaceQueue(record_q=record_q) + context_keeper = context.ContextKeeper() + return SendManager( + settings=SettingsStatic(settings.to_proto()), + record_q=record_q, + result_q=result_q, + interface=publish_interface, + context_keeper=context_keeper, + ) + + def __len__(self) -> int: + return self._record_q.qsize() + + def __enter__(self) -> "SendManager": + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_value: Optional[BaseException], + exc_traceback: Optional[traceback.TracebackException], + ) -> Literal[False]: + while self: + data = next(self) + self.send(data) + self.finish() + return False + + def retry_callback(self, status: int, response_text: str) -> None: + response = wandb_internal_pb2.HttpResponse() + response.http_status_code = status + response.http_response_text = response_text + self._retry_q.put(response) + + def send(self, record: "Record") -> None: + self._update_record_num(record.num) + self._update_end_offset(record.control.end_offset) + + record_type = record.WhichOneof("record_type") + assert record_type + handler_str = "send_" + record_type + send_handler = getattr(self, handler_str, None) + # Don't log output to reduce log noise + if record_type not in {"output", "request", "output_raw"}: + logger.debug(f"send: {record_type}") + assert send_handler, f"unknown send handler: {handler_str}" + + context_id = context.context_id_from_record(record) + api_context = self._context_keeper.get(context_id) + try: + self._api.set_local_context(api_context) + send_handler(record) + except retry.RetryCancelledError: + logger.debug(f"Record cancelled: {record_type}") + self._context_keeper.release(context_id) + finally: + self._api.clear_local_context() + + def send_preempting(self, _: "Record") -> None: + if self._fs: + self._fs.enqueue_preempting() + + def send_request_sender_mark(self, _: "Record") -> None: + self._maybe_report_status(always=True) + + def send_request(self, record: "Record") -> None: + request_type = record.request.WhichOneof("request_type") + assert request_type + handler_str = "send_request_" + request_type + send_handler = getattr(self, handler_str, None) + if request_type != "network_status": + logger.debug(f"send_request: {request_type}") + assert send_handler, f"unknown handle: {handler_str}" + send_handler(record) + + def _respond_result(self, result: "Result") -> None: + context_id = context.context_id_from_result(result) + self._context_keeper.release(context_id) + self._result_q.put(result) + + def _flatten(self, dictionary: Dict) -> None: + if isinstance(dictionary, dict): + for k, v in list(dictionary.items()): + if isinstance(v, dict): + self._flatten(v) + dictionary.pop(k) + for k2, v2 in v.items(): + dictionary[k + "." + k2] = v2 + + def _update_record_num(self, record_num: int) -> None: + if not record_num: + return + # Currently how we handle offline mode and syncing is not + # compatible with this assertion due to how the exit record + # is (mis)handled: + # - using "always_send" in offline mode to trigger defer + # state machine + # - skipping the exit record in `wandb sync` mode so that + # it is always executed as the last record + if not self._settings._offline and not self._settings.x_sync: + assert record_num == self._send_record_num + 1 + self._send_record_num = record_num + + def _update_end_offset(self, end_offset: int) -> None: + if not end_offset: + return + self._send_end_offset = end_offset + + def send_request_sender_read(self, record: "Record") -> None: + if self._ds is None: + self._ds = datastore.DataStore() + self._ds.open_for_scan(self._settings.sync_file) + + # TODO(cancel_paused): implement cancel_set logic + # The idea is that there is an active request to cancel a + # message that is being read from the transaction log below + + start_offset = record.request.sender_read.start_offset + final_offset = record.request.sender_read.final_offset + self._ds.seek(start_offset) + + current_end_offset = 0 + while current_end_offset < final_offset: + data = self._ds.scan_data() + assert data + current_end_offset = self._ds.get_offset() + + send_record = wandb_internal_pb2.Record() + send_record.ParseFromString(data) + self._update_end_offset(current_end_offset) + self.send(send_record) + + # make sure we perform deferred operations + self.debounce() + + # make sure that we always update writer for every sended read request + self._maybe_report_status(always=True) + + def send_request_stop_status(self, record: "Record") -> None: + result = proto_util._result_from_record(record) + status_resp = result.response.stop_status_response + status_resp.run_should_stop = False + if self._entity and self._project and self._run and self._run.run_id: + try: + status_resp.run_should_stop = self._api.check_stop_requested( + self._project, self._entity, self._run.run_id + ) + except Exception as e: + logger.warning("Failed to check stop requested status: %s", e) + self._respond_result(result) + + def _maybe_update_config(self, always: bool = False) -> None: + time_now = time.monotonic() + if ( + not always + and time_now < self._debounce_config_time + self.UPDATE_CONFIG_TIME + ): + return + if self._config_needs_debounce: + self._debounce_config() + self._debounce_config_time = time_now + + def _maybe_report_status(self, always: bool = False) -> None: + time_now = time.monotonic() + if ( + not always + and time_now < self._debounce_status_time + self.UPDATE_STATUS_TIME + ): + return + self._debounce_status_time = time_now + + status_report = wandb_internal_pb2.StatusReportRequest( + record_num=self._send_record_num, + sent_offset=self._send_end_offset, + ) + status_time = time.time() + status_report.sync_time.FromMicroseconds(int(status_time * 1e6)) + record = self._interface._make_request(status_report=status_report) + self._interface._publish(record) + + def debounce(self, final: bool = False) -> None: + self._maybe_report_status(always=final) + self._maybe_update_config(always=final) + + def _debounce_config(self) -> None: + config_value_dict = self._config_backend_dict() + # TODO(jhr): check result of upsert_run? + if self._run: + self._api.upsert_run( + name=self._run.run_id, + config=config_value_dict, + **self._api_settings, # type: ignore + ) + self._config_save(config_value_dict) + self._config_needs_debounce = False + + def send_request_network_status(self, record: "Record") -> None: + result = proto_util._result_from_record(record) + status_resp = result.response.network_status_response + while True: + try: + status_resp.network_responses.append(self._retry_q.get_nowait()) + except queue.Empty: + break + except Exception as e: + logger.warning(f"Error emptying retry queue: {e}") + self._respond_result(result) + + def send_exit(self, record: "Record") -> None: + # track where the exit came from + self._record_exit = record + + run_exit = record.exit + self._exit_code = run_exit.exit_code + logger.info("handling exit code: %s", run_exit.exit_code) + runtime = run_exit.runtime + logger.info("handling runtime: %s", run_exit.runtime) + self._metadata_summary["runtime"] = runtime + self._update_summary() + + # We need to give the request queue a chance to empty between states + # so use handle_request_defer as a state machine. + logger.info("send defer") + self._interface.publish_defer() + + def send_final(self, record: "Record") -> None: + pass + + def _flush_run(self) -> None: + pass + + def send_request_status_report(self, record: "Record") -> None: + # todo? this is just a noop to please wandb sync + pass + + def send_request_defer(self, record: "Record") -> None: # noqa: C901 + defer = record.request.defer + state = defer.state + logger.info(f"handle sender defer: {state}") + + def transition_state() -> None: + state = defer.state + 1 + logger.info(f"send defer: {state}") + self._interface.publish_defer(state) + + done = False + if state == defer.BEGIN: + transition_state() + elif state == defer.FLUSH_RUN: + self._flush_run() + transition_state() + elif state == defer.FLUSH_STATS: + # NOTE: this is handled in handler.py:handle_request_defer() + transition_state() + elif state == defer.FLUSH_PARTIAL_HISTORY: + # NOTE: this is handled in handler.py:handle_request_defer() + transition_state() + elif state == defer.FLUSH_TB: + # NOTE: this is handled in handler.py:handle_request_defer() + transition_state() + elif state == defer.FLUSH_SUM: + # NOTE: this is handled in handler.py:handle_request_defer() + transition_state() + elif state == defer.FLUSH_DEBOUNCER: + self.debounce(final=True) + transition_state() + elif state == defer.FLUSH_OUTPUT: + self._output_raw_finish() + transition_state() + elif state == defer.FLUSH_JOB: + self._flush_job() + transition_state() + elif state == defer.FLUSH_DIR: + if self._dir_watcher: + self._dir_watcher.finish() + self._dir_watcher = None + transition_state() + elif state == defer.FLUSH_FP: + if self._pusher: + # FilePusher generates some events for FileStreamApi, so we + # need to wait for pusher to finish before going to the next + # state to ensure that filestream gets all the events that we + # want before telling it to finish up + self._pusher.finish(transition_state) + else: + transition_state() + elif state == defer.JOIN_FP: + if self._pusher: + self._pusher.join() + transition_state() + elif state == defer.FLUSH_FS: + if self._fs: + # TODO(jhr): now is a good time to output pending output lines + self._fs.finish(self._exit_code) + self._fs = None + transition_state() + elif state == defer.FLUSH_FINAL: + self._interface.publish_final() + self._interface.publish_footer() + transition_state() + elif state == defer.END: + done = True + else: + raise AssertionError("unknown state") + + if not done: + return + + exit_result = wandb_internal_pb2.RunExitResult() + + # mark exit done in case we are polling on exit + self._exit_result = exit_result + + # Report response to mailbox + if self._record_exit and self._record_exit.control.mailbox_slot: + result = proto_util._result_from_record(self._record_exit) + result.exit_result.CopyFrom(exit_result) + self._respond_result(result) + + def send_request_poll_exit(self, record: "Record") -> None: + if not record.control.req_resp and not record.control.mailbox_slot: + return + + result = proto_util._result_from_record(record) + + if self._pusher: + _alive, status = self._pusher.get_status() + file_counts = self._pusher.file_counts_by_category() + resp = result.response.poll_exit_response + resp.pusher_stats.uploaded_bytes = status.uploaded_bytes + resp.pusher_stats.total_bytes = status.total_bytes + resp.pusher_stats.deduped_bytes = status.deduped_bytes + resp.file_counts.wandb_count = file_counts.wandb + resp.file_counts.media_count = file_counts.media + resp.file_counts.artifact_count = file_counts.artifact + resp.file_counts.other_count = file_counts.other + + if self._exit_result: + result.response.poll_exit_response.done = True + result.response.poll_exit_response.exit_result.CopyFrom(self._exit_result) + + self._respond_result(result) + + def _setup_resume( + self, run: "RunRecord" + ) -> Optional["wandb_internal_pb2.ErrorInfo"]: + """Queries the backend for a run; fail if the settings are incompatible.""" + if not self._settings.resume: + return None + + # TODO: This causes a race, we need to make the upsert atomically + # only create or update depending on the resume config + # we use the runs entity if set, otherwise fallback to users entity + # todo: ensure entity is not None as self._entity is Optional[str] + entity = run.entity or self._entity + logger.info( + "checking resume status for %s/%s/%s", entity, run.project, run.run_id + ) + resume_status = self._api.run_resume_status( + entity=entity, # type: ignore + project_name=run.project, + name=run.run_id, + ) + # No resume status = run does not exist; No t key in wandbConfig = run exists but hasn't been inited + if not resume_status or '"t":' not in resume_status.get("wandbConfig", ""): + if self._settings.resume == "must": + error = wandb_internal_pb2.ErrorInfo() + error.code = wandb_internal_pb2.ErrorInfo.ErrorCode.USAGE + error.message = ( + "You provided an invalid value for the `resume` argument." + f" The value 'must' is not a valid option for resuming a run ({run.run_id}) that has not been initialized." + " Please check your inputs and try again with a valid run ID." + " If you are trying to start a new run, please omit the `resume` argument or use `resume='allow'`." + ) + return error + return None + + # + # handle cases where we have resume_status + # + if self._settings.resume == "never": + error = wandb_internal_pb2.ErrorInfo() + error.code = wandb_internal_pb2.ErrorInfo.ErrorCode.USAGE + error.message = ( + "You provided an invalid value for the `resume` argument." + f" The value 'never' is not a valid option for resuming a run ({run.run_id}) that already exists." + " Please check your inputs and try again with a valid value for the `resume` argument." + ) + return error + + history = {} + events = {} + config = {} + summary = {} + try: + events_rt = 0 + history_rt = 0 + history = json.loads(resume_status["historyTail"]) + if history: + history = json.loads(history[-1]) + history_rt = history.get("_runtime", 0) + events = json.loads(resume_status["eventsTail"]) + if events: + events = json.loads(events[-1]) + events_rt = events.get("_runtime", 0) + config = json.loads(resume_status["config"] or "{}") + summary = json.loads(resume_status["summaryMetrics"] or "{}") + new_runtime = summary.get("_wandb", {}).get("runtime", None) + if new_runtime is not None: + self._resume_state.wandb_runtime = new_runtime + tags = resume_status.get("tags") or [] + + except (IndexError, ValueError): + logger.exception("unable to load resume tails") + if self._settings.resume == "must": + error = wandb_internal_pb2.ErrorInfo() + error.code = wandb_internal_pb2.ErrorInfo.ErrorCode.USAGE + error.message = f"resume='must' but could not resume ({run.run_id}) " + return error + + # TODO: Do we need to restore config / summary? + # System metrics runtime is usually greater than history + self._resume_state.runtime = max(events_rt, history_rt) + last_step = history.get("_step", 0) + history_line_count = resume_status["historyLineCount"] + self._resume_state.step = last_step + 1 if history_line_count > 0 else last_step + self._resume_state.history = history_line_count + self._resume_state.events = resume_status["eventsLineCount"] + self._resume_state.output = resume_status["logLineCount"] + self._resume_state.config = config + self._resume_state.summary = summary + self._resume_state.tags = tags + self._resume_state.resumed = True + logger.info(f"configured resuming with: {self._resume_state}") + return None + + def _telemetry_get_framework(self) -> str: + """Get telemetry data for internal config structure.""" + # detect framework by checking what is loaded + imports: telemetry.TelemetryImports + if self._telemetry_obj.HasField("imports_finish"): + imports = self._telemetry_obj.imports_finish + elif self._telemetry_obj.HasField("imports_init"): + imports = self._telemetry_obj.imports_init + else: + return "" + framework = next( + (n for f, n in _framework_priority() if getattr(imports, f, False)), "" + ) + return framework + + def _config_backend_dict(self) -> sender_config.BackendConfigDict: + config = self._consolidated_config or sender_config.ConfigState() + return config.to_backend_dict( + telemetry_record=self._telemetry_obj, + framework=self._telemetry_get_framework(), + start_time_millis=self._start_time, + metric_pbdicts=self._config_metric_pbdict_list, + environment_record=self._environment_obj, + ) + + def _config_save( + self, + config_value_dict: sender_config.BackendConfigDict, + ) -> None: + config_path = os.path.join(self._settings.files_dir, "config.yaml") + config_util.save_config_file_from_dict(config_path, config_value_dict) + + def _sync_spell(self) -> None: + """Sync this run with spell.""" + if not self._run: + return + try: + env = os.environ + self._interface.publish_config( + key=("_wandb", "spell_url"), val=env.get("SPELL_RUN_URL") + ) + url = f"{self._api.app_url}/{self._run.entity}/{self._run.project}/runs/{self._run.run_id}" + requests.put( + env.get("SPELL_API_URL", "https://api.spell.run") + "/wandb_url", + json={"access_token": env.get("WANDB_ACCESS_TOKEN"), "url": url}, + timeout=2, + ) + except requests.RequestException: + pass + # TODO: do something if sync spell is not successful? + + def _setup_fork(self, server_run: dict): + assert self._run + assert self._run.branch_point + first_step = int(self._run.branch_point.value) + 1 + self._resume_state.step = first_step + self._resume_state.history = server_run.get("historyLineCount", 0) + self._run.forked = True + self._run.starting_step = first_step + + def _load_rewind_state(self, run: "RunRecord"): + assert run.branch_point + self._rewind_response = self._api.rewind_run( + run_name=run.run_id, + entity=run.entity or None, + project=run.project or None, + metric_name=run.branch_point.metric, + metric_value=run.branch_point.value, + program_path=self._settings.program or None, + ) + self._resume_state.history = self._rewind_response.get("historyLineCount", 0) + self._resume_state.config = json.loads( + self._rewind_response.get("config", "{}") + ) + + def _install_rewind_state(self): + assert self._run + assert self._run.branch_point + assert self._rewind_response + + first_step = int(self._run.branch_point.value) + 1 + self._resume_state.step = first_step + + # We set the fork flag here because rewind uses the forking + # infrastructure under the hood. Setting `forked` here + # ensures that run._step is properly set in the user process. + self._run.forked = True + self._run.starting_step = first_step + + def _handle_error( + self, + record: "Record", + error: "wandb_internal_pb2.ErrorInfo", + run: "RunRecord", + ) -> None: + if record.control.req_resp or record.control.mailbox_slot: + result = proto_util._result_from_record(record) + result.run_result.run.CopyFrom(run) + result.run_result.error.CopyFrom(error) + self._respond_result(result) + else: + logger.error("Got error in async mode: %s", error.message) + + def send_run(self, record: "Record", file_dir: Optional[str] = None) -> None: + run = record.run + error = None + is_wandb_init = self._run is None + + # save start time of a run + self._start_time = int(run.start_time.ToMicroseconds() // 1e6) + + # update telemetry + if run.telemetry: + self._telemetry_obj.MergeFrom(run.telemetry) + if self._settings.x_sync: + self._telemetry_obj.feature.sync = True + + # build config dict + config_value_dict: Optional[sender_config.BackendConfigDict] = None + if run.config: + self._consolidated_config.update_from_proto(run.config) + config_value_dict = self._config_backend_dict() + self._config_save(config_value_dict) + + do_rewind = run.branch_point.run == run.run_id + do_fork = not do_rewind and run.branch_point.run != "" + do_resume = bool(self._settings.resume) + + num_resume_options_set = sum([do_fork, do_rewind, do_resume]) + if num_resume_options_set > 1: + error = wandb_internal_pb2.ErrorInfo() + error.code = wandb_internal_pb2.ErrorInfo.ErrorCode.USAGE + error.message = ( + "Multiple resume options specified. " + "Please specify only one of `fork_from`, `resume`, or `resume_from`." + ) + self._handle_error(record, error, run) + + if is_wandb_init: + # Ensure we have a project to query for status + if run.project == "": + run.project = util.auto_project_name(self._settings.program) + # Only check resume status on `wandb.init` + + if do_resume: + error = self._setup_resume(run) + + elif do_rewind: + error = self._load_rewind_state(run) + + if error is not None: + self._handle_error(record, error, run) + return + + # Save the resumed config + if self._resume_state.config is not None: + self._consolidated_config.merge_resumed_config( + config_util.dict_strip_value_dict(self._resume_state.config) + ) + + config_value_dict = self._config_backend_dict() + self._config_save(config_value_dict) + + # handle empty config + # TODO(jhr): consolidate the 4 ways config is built: + # (passed config, empty config, resume config, send_config) + if not config_value_dict: + config_value_dict = self._config_backend_dict() + self._config_save(config_value_dict) + + try: + server_run = self._init_run(run, config_value_dict) + except (CommError, UsageError) as e: + logger.error(e, exc_info=True) + error = ProtobufErrorHandler.from_exception(e) + self._handle_error(record, error, run) + return + + assert self._run # self._run is configured in _init_run() + + if do_fork: + error = self._setup_fork(server_run) + + if error is not None: + self._handle_error(record, error, run) + return + + if record.control.req_resp or record.control.mailbox_slot: + result = proto_util._result_from_record(record) + # TODO: we could do self._interface.publish_defer(resp) to notify + # the handler not to actually perform server updates for this uuid + # because the user process will send a summary update when we resume + result.run_result.run.CopyFrom(self._run) + self._respond_result(result) + + # Only spin up our threads on the first run message + if is_wandb_init: + self._start_run_threads(file_dir) + else: + logger.info("updated run: %s", self._run.run_id) + + def _update_resume_state(self, is_rewinding: bool, inserted: bool): + assert self._run + if self._resume_state.resumed: + self._run.resumed = True + if self._resume_state.wandb_runtime is not None: + self._run.runtime = self._resume_state.wandb_runtime + elif is_rewinding: + # because is_rewinding is mutually exclusive with self._resume_state.resumed, + # this block will always execute if is_rewinding is set + self._install_rewind_state() + else: + # If the user is not resuming, and we didn't insert on upsert_run then + # it is likely that we are overwriting the run which we might want to + # prevent in the future. This could be a false signal since an upsert_run + # message which gets retried in the network could also show up as not + # inserted. + if not inserted: + # no need to flush this, it will get updated eventually + self._telemetry_obj.feature.maybe_run_overwrite = True + + def _init_run( + self, + run: "RunRecord", + config_dict: Optional[sender_config.BackendConfigDict], + ) -> dict: + # We subtract the previous runs runtime when resuming + start_time = ( + run.start_time.ToMicroseconds() / 1e6 + ) - self._resume_state.runtime + # TODO: we don't check inserted currently, ultimately we should make + # the upsert know the resume state and fail transactionally + + if self._resume_state and self._resume_state.tags and not run.tags: + run.tags.extend(self._resume_state.tags) + + is_rewinding = bool(self._settings.resume_from) + if is_rewinding: + assert self._rewind_response + server_run = self._rewind_response + server_messages = None + inserted = True + else: + server_run, inserted, server_messages = self._api.upsert_run( + name=run.run_id, + entity=run.entity or None, + project=run.project or None, + group=run.run_group or None, + job_type=run.job_type or None, + display_name=run.display_name or None, + notes=run.notes or None, + tags=run.tags[:] or None, + config=config_dict or None, + sweep_name=run.sweep_id or None, + host=run.host or None, + program_path=self._settings.program or None, + repo=run.git.remote_url or None, + commit=run.git.commit or None, + ) + + # TODO: we don't want to create jobs in sweeps, since the + # executable doesn't appear to be consistent + if run.sweep_id: + self._job_builder.disable = True + + self._server_messages = server_messages or [] + self._run = run + + if self._resume_state.resumed and is_rewinding: + # this should not ever be possible to hit, since we check for + # resumption above and raise an error if resumption is specified + # twice. + raise ValueError( + "Cannot attempt to rewind and resume a run - only one of " + "`resume` or `resume_from` can be specified." + ) + + self._update_resume_state(is_rewinding, inserted) + self._run.starting_step = self._resume_state.step + self._run.start_time.FromMicroseconds(int(start_time * 1e6)) + self._run.config.CopyFrom(self._interface._make_config(config_dict)) + if self._resume_state.summary is not None: + self._run.summary.CopyFrom( + self._interface._make_summary_from_dict(self._resume_state.summary) + ) + storage_id = server_run.get("id") + if storage_id: + self._run.storage_id = storage_id + id = server_run.get("name") + if id: + self._api.set_current_run_id(id) + display_name = server_run.get("displayName") + if display_name: + self._run.display_name = display_name + project = server_run.get("project") + # TODO: remove self._api.set_settings, and make self._project a property? + if project: + project_name = project.get("name") + if project_name: + self._run.project = project_name + self._project = project_name + self._api_settings["project"] = project_name + self._api.set_setting("project", project_name) + entity = project.get("entity") + if entity: + entity_name = entity.get("name") + if entity_name: + self._run.entity = entity_name + self._entity = entity_name + self._api_settings["entity"] = entity_name + self._api.set_setting("entity", entity_name) + sweep_id = server_run.get("sweepName") + if sweep_id: + self._run.sweep_id = sweep_id + if os.getenv("SPELL_RUN_URL"): + self._sync_spell() + return server_run + + def _start_run_threads(self, file_dir: Optional[str] = None) -> None: + assert self._run # self._run is configured by caller + self._fs = file_stream.FileStreamApi( + self._api, + self._run.run_id, + self._run.start_time.ToMicroseconds() / 1e6, + timeout=self._settings.x_file_stream_timeout_seconds or 0, + settings=self._api_settings, + ) + # Ensure the streaming polices have the proper offsets + self._fs.set_file_policy("wandb-summary.json", file_stream.SummaryFilePolicy()) + self._fs.set_file_policy( + "wandb-history.jsonl", + file_stream.JsonlFilePolicy(start_chunk_id=self._resume_state.history), + ) + self._fs.set_file_policy( + "wandb-events.jsonl", + file_stream.JsonlFilePolicy(start_chunk_id=self._resume_state.events), + ) + self._fs.set_file_policy( + "output.log", + file_stream.CRDedupeFilePolicy(start_chunk_id=self._resume_state.output), + ) + + # hack to merge run_settings and self._settings object together + # so that fields like entity or project are available to be attached to Sentry events. + run_settings = message_to_dict(self._run) + _settings = dict(self._settings) + _settings.update(run_settings) + wandb._sentry.configure_scope(tags=_settings, process_context="internal") + + self._fs.start() + self._pusher = FilePusher(self._api, self._fs, settings=self._settings) + self._dir_watcher = DirWatcher(self._settings, self._pusher, file_dir) + logger.info( + "run started: %s with start time %s", + self._run.run_id, + self._run.start_time.ToMicroseconds() / 1e6, + ) + + def _save_history(self, history_dict: Dict[str, Any]) -> None: + if self._fs: + self._fs.push(filenames.HISTORY_FNAME, json.dumps(history_dict)) + + def send_history(self, record: "Record") -> None: + history = record.history + history_dict = proto_util.dict_from_proto_list(history.item) + self._save_history(history_dict) + + def _update_summary_record(self, summary: "SummaryRecord") -> None: + summary_dict = proto_util.dict_from_proto_list(summary.update) + self._cached_summary = summary_dict + self._update_summary() + + def send_summary(self, record: "Record") -> None: + self._update_summary_record(record.summary) + + def send_request_summary_record(self, record: "Record") -> None: + self._update_summary_record(record.request.summary_record.summary) + + def _update_summary(self) -> None: + summary_dict = self._cached_summary.copy() + summary_dict.pop("_wandb", None) + if self._metadata_summary: + summary_dict["_wandb"] = self._metadata_summary + # merge with consolidated summary + self._consolidated_summary.update(summary_dict) + json_summary = json.dumps(self._consolidated_summary) + if self._fs: + self._fs.push(filenames.SUMMARY_FNAME, json_summary) + # TODO(jhr): we should only write this at the end of the script + summary_path = os.path.join(self._settings.files_dir, filenames.SUMMARY_FNAME) + with open(summary_path, "w") as f: + f.write(json_summary) + self._save_file(interface.GlobStr(filenames.SUMMARY_FNAME)) + + def send_stats(self, record: "Record") -> None: + stats = record.stats + if stats.stats_type != wandb_internal_pb2.StatsRecord.StatsType.SYSTEM: + return + if not self._fs: + return + if not self._run: + return + now_us = stats.timestamp.ToMicroseconds() + start_us = self._run.start_time.ToMicroseconds() + d = dict() + for item in stats.item: + try: + d[item.key] = json.loads(item.value_json) + except json.JSONDecodeError: + logger.exception("error decoding stats json: %s", item.value_json) + row: Dict[str, Any] = dict(system=d) + self._flatten(row) + row["_wandb"] = True + row["_timestamp"] = now_us / 1e6 + row["_runtime"] = (now_us - start_us) / 1e6 + self._fs.push(filenames.EVENTS_FNAME, json.dumps(row)) + # TODO(jhr): check fs.push results? + + def _output_raw_finish(self) -> None: + for stream, output_raw in self._output_raw_streams.items(): + output_raw._stopped.set() + + # shut down threads + output_raw._writer_thr.join(timeout=5) + if output_raw._writer_thr.is_alive(): + logger.info("processing output...") + output_raw._writer_thr.join() + output_raw._reader_thr.join() + + # flush output buffers and files + self._output_raw_flush(stream) + self._output_raw_streams = {} + if self._output_raw_file: + self._output_raw_file.close() + self._output_raw_file = None + + def _output_raw_writer_thread(self, stream: "StreamLiterals") -> None: + while True: + output_raw = self._output_raw_streams[stream] + if output_raw._queue.empty(): + if output_raw._stopped.is_set(): + return + time.sleep(0.5) + continue + data = [] + while not output_raw._queue.empty(): + data.append(output_raw._queue.get()) + if output_raw._stopped.is_set() and sum(map(len, data)) > 100000: + logger.warning("Terminal output too large. Logging without processing.") + self._output_raw_flush(stream) + for line in data: + self._output_raw_flush(stream, line) + # TODO: lets mark that this happened in telemetry + return + try: + output_raw._emulator.write("".join(data)) + except Exception as e: + logger.warning(f"problem writing to output_raw emulator: {e}") + + def _output_raw_reader_thread(self, stream: "StreamLiterals") -> None: + output_raw = self._output_raw_streams[stream] + while not (output_raw._stopped.is_set() and output_raw._queue.empty()): + self._output_raw_flush(stream) + time.sleep(_OUTPUT_MIN_CALLBACK_INTERVAL) + + def _output_raw_flush( + self, stream: "StreamLiterals", data: Optional[str] = None + ) -> None: + if data is None: + output_raw = self._output_raw_streams[stream] + try: + data = output_raw._emulator.read() + except Exception as e: + logger.warning(f"problem reading from output_raw emulator: {e}") + if data: + self._send_output_line(stream, data) + if self._output_raw_file: + self._output_raw_file.write(data.encode("utf-8")) + + def send_request_python_packages(self, record: "Record") -> None: + import os + + from wandb.sdk.lib.filenames import REQUIREMENTS_FNAME + + installed_packages_list = sorted( + f"{r.name}=={r.version}" for r in record.request.python_packages.package + ) + with open(os.path.join(self._settings.files_dir, REQUIREMENTS_FNAME), "w") as f: + f.write("\n".join(installed_packages_list)) + + def send_output(self, record: "Record") -> None: + if not self._fs: + return + out = record.output + stream: StreamLiterals = "stdout" + if out.output_type == wandb_internal_pb2.OutputRecord.OutputType.STDERR: + stream = "stderr" + line = out.line + self._send_output_line(stream, line) + + def send_output_raw(self, record: "Record") -> None: + if not self._fs: + return + out = record.output_raw + stream: StreamLiterals = "stdout" + if out.output_type == wandb_internal_pb2.OutputRawRecord.OutputType.STDERR: + stream = "stderr" + line = out.line + + output_raw = self._output_raw_streams.get(stream) + if not output_raw: + output_raw = _OutputRawStream(stream=stream, sm=self) + self._output_raw_streams[stream] = output_raw + + # open the console output file shared between both streams + if not self._output_raw_file: + output_log_path = os.path.join( + self._settings.files_dir, filenames.OUTPUT_FNAME + ) + output_raw_file = None + try: + output_raw_file = filesystem.CRDedupedFile( + open(output_log_path, "wb") + ) + except OSError as e: + logger.warning(f"could not open output_raw_file: {e}") + if output_raw_file: + self._output_raw_file = output_raw_file + output_raw.start() + + output_raw._queue.put(line) + + def _send_output_line(self, stream: "StreamLiterals", line: str) -> None: + """Combined writer for raw and non raw output lines. + + This is combined because they are both post emulator. + """ + prepend = "" + if stream == "stderr": + prepend = "ERROR " + if not line.endswith("\n"): + self._partial_output.setdefault(stream, "") + if line.startswith("\r"): + # TODO: maybe we shouldn't just drop this, what if there was some \ns in the partial + # that should probably be the check instead of not line.endswith(\n") + # logger.info(f"Dropping data {self._partial_output[stream]}") + self._partial_output[stream] = "" + self._partial_output[stream] += line + # TODO(jhr): how do we make sure this gets flushed? + # we might need this for other stuff like telemetry + else: + # TODO(jhr): use time from timestamp proto + # TODO(jhr): do we need to make sure we write full lines? + # seems to be some issues with line breaks + cur_time = time.time() + timestamp = datetime.utcfromtimestamp(cur_time).isoformat() + " " + prev_str = self._partial_output.get(stream, "") + line = f"{prepend}{timestamp}{prev_str}{line}" + if self._fs: + self._fs.push(filenames.OUTPUT_FNAME, line) + self._partial_output[stream] = "" + + def _update_config(self) -> None: + self._config_needs_debounce = True + + def send_config(self, record: "Record") -> None: + self._consolidated_config.update_from_proto(record.config) + self._update_config() + + def send_metric(self, record: "Record") -> None: + metric = record.metric + if metric.glob_name: + logger.warning("Seen metric with glob (shouldn't happen)") + return + + # merge or overwrite + old_metric = self._config_metric_dict.get( + metric.name, wandb_internal_pb2.MetricRecord() + ) + if metric._control.overwrite: + old_metric.CopyFrom(metric) + else: + old_metric.MergeFrom(metric) + self._config_metric_dict[metric.name] = old_metric + metric = old_metric + + # convert step_metric to index + if metric.step_metric: + find_step_idx = self._config_metric_index_dict.get(metric.step_metric) + if find_step_idx is not None: + # make a copy of this metric as we will be modifying it + rec = wandb_internal_pb2.Record() + rec.metric.CopyFrom(metric) + metric = rec.metric + + metric.ClearField("step_metric") + metric.step_metric_index = find_step_idx + 1 + + md: Dict[int, Any] = proto_util.proto_encode_to_dict(metric) + find_idx = self._config_metric_index_dict.get(metric.name) + if find_idx is not None: + self._config_metric_pbdict_list[find_idx] = md + else: + next_idx = len(self._config_metric_pbdict_list) + self._config_metric_pbdict_list.append(md) + self._config_metric_index_dict[metric.name] = next_idx + self._debounce_config() + + def _update_telemetry_record(self, telemetry: telemetry.TelemetryRecord) -> None: + self._telemetry_obj.MergeFrom(telemetry) + self._debounce_config() + + def send_telemetry(self, record: "Record") -> None: + self._update_telemetry_record(record.telemetry) + + def send_request_telemetry_record(self, record: "Record") -> None: + self._update_telemetry_record(record.request.telemetry_record.telemetry) + + def _save_file( + self, fname: interface.GlobStr, policy: "interface.PolicyName" = "end" + ) -> None: + logger.info("saving file %s with policy %s", fname, policy) + if self._dir_watcher: + self._dir_watcher.update_policy(fname, policy) + + def send_files(self, record: "Record") -> None: + files = record.files + for k in files.files: + # TODO(jhr): fix paths with directories + self._save_file( + interface.GlobStr(glob.escape(k.path)), + interface.file_enum_to_policy(k.policy), + ) + + def send_header(self, record: "Record") -> None: + pass + + def send_footer(self, record: "Record") -> None: + pass + + def send_tbrecord(self, record: "Record") -> None: + # tbrecord watching threads are handled by handler.py + pass + + def _update_environment_record(self, environment: "EnvironmentRecord") -> None: + self._environment_obj.MergeFrom(environment) + self._debounce_config() + + def send_environment(self, record: "Record") -> None: + """Inject environment info into config and upload as a JSON file.""" + self._update_environment_record(record.environment) + + environment_json = json.dumps(proto_util.message_to_dict(self._environment_obj)) + + with open( + os.path.join(self._settings.files_dir, filenames.METADATA_FNAME), "w" + ) as f: + f.write(environment_json) + + self._save_file(interface.GlobStr(filenames.METADATA_FNAME), policy="now") + + def send_request_link_artifact(self, record: "Record") -> None: + if not (record.control.req_resp or record.control.mailbox_slot): + raise ValueError( + f"Expected either `req_resp` or `mailbox_slot`, got: {record.control!r}" + ) + result = proto_util._result_from_record(record) + link = record.request.link_artifact + client_id = link.client_id + server_id = link.server_id + portfolio_name = link.portfolio_name + entity = link.portfolio_entity + project = link.portfolio_project + aliases = link.portfolio_aliases + organization = link.portfolio_organization + logger.debug( + f"link_artifact params - client_id={client_id}, server_id={server_id}, " + f"portfolio_name={portfolio_name}, entity={entity}, project={project}, " + f"organization={organization}" + ) + if (client_id or server_id) and portfolio_name and entity and project: + try: + response = self._api.link_artifact( + client_id, + server_id, + portfolio_name, + entity, + project, + aliases, + organization, + ) + result.response.link_artifact_response.version_index = response[ + "versionIndex" + ] + except Exception as e: + org_or_entity = organization or entity + result.response.link_artifact_response.error_message = ( + f"error linking artifact to " + f'"{org_or_entity}/{project}/{portfolio_name}"; error: {e}' + ) + logger.warning("Failed to link artifact to portfolio: %s", e) + self._respond_result(result) + + def send_use_artifact(self, record: "Record") -> None: + """Pretend to send a used artifact. + + This function doesn't actually send anything, it is just used internally. + """ + use = record.use_artifact + + if use.type == "job" and not use.partial.job_name: + self._job_builder.disable = True + elif use.partial.job_name: + # job is partial, let job builder rebuild job, set job source dict + self._job_builder.set_partial_source_id(use.id) + + def send_request_log_artifact(self, record: "Record") -> None: + result = proto_util._result_from_record(record) + artifact = record.request.log_artifact.artifact + history_step = record.request.log_artifact.history_step + + try: + res = self._send_artifact(artifact, history_step) + assert res, "Unable to send artifact" + result.response.log_artifact_response.artifact_id = res["id"] + logger.info(f"logged artifact {artifact.name} - {res}") + except Exception as e: + result.response.log_artifact_response.error_message = ( + f'error logging artifact "{artifact.type}/{artifact.name}": {e}' + ) + + self._respond_result(result) + + def send_artifact(self, record: "Record") -> None: + artifact = record.artifact + try: + res = self._send_artifact(artifact) + logger.info(f"sent artifact {artifact.name} - {res}") + except Exception: + logger.exception( + f'send_artifact: failed for artifact "{artifact.type}/{artifact.name}"' + ) + + def _send_artifact( + self, artifact: "ArtifactRecord", history_step: Optional[int] = None + ) -> Optional[Dict]: + from packaging.version import parse + + assert self._pusher + saver = ArtifactSaver( + api=self._api, + digest=artifact.digest, + manifest_json=_manifest_json_from_proto(artifact.manifest), + file_pusher=self._pusher, + is_user_created=artifact.user_created, + ) + + if artifact.distributed_id: + max_cli_version = self._max_cli_version() + if max_cli_version is None or parse(max_cli_version) < parse("0.10.16"): + logger.warning( + "This W&B Server doesn't support distributed artifacts, " + "have your administrator install wandb/local >= 0.9.37" + ) + return None + + metadata = json.loads(artifact.metadata) if artifact.metadata else None + res = saver.save( + entity=artifact.entity, + project=artifact.project, + type=artifact.type, + name=artifact.name, + client_id=artifact.client_id, + sequence_client_id=artifact.sequence_client_id, + metadata=metadata, + ttl_duration_seconds=artifact.ttl_duration_seconds or None, + description=artifact.description or None, + aliases=artifact.aliases, + tags=artifact.tags, + use_after_commit=artifact.use_after_commit, + distributed_id=artifact.distributed_id, + finalize=artifact.finalize, + incremental=artifact.incremental_beta1, + history_step=history_step, + base_id=artifact.base_id or None, + ) + + self._job_builder._handle_server_artifact(res, artifact) + + if artifact.manifest.manifest_file_path: + with contextlib.suppress(FileNotFoundError): + os.remove(artifact.manifest.manifest_file_path) + return res + + def send_alert(self, record: "Record") -> None: + from packaging.version import parse + + alert = record.alert + max_cli_version = self._max_cli_version() + if max_cli_version is None or parse(max_cli_version) < parse("0.10.9"): + logger.warning( + "This W&B server doesn't support alerts, " + "have your administrator install wandb/local >= 0.9.31" + ) + else: + try: + self._api.notify_scriptable_run_alert( + title=alert.title, + text=alert.text, + level=alert.level, + wait_duration=alert.wait_duration, + ) + except Exception: + logger.exception(f"send_alert: failed for alert {alert.title!r}") + + def finish(self) -> None: + logger.info("shutting down sender") + # if self._tb_watcher: + # self._tb_watcher.finish() + self._output_raw_finish() + if self._dir_watcher: + self._dir_watcher.finish() + self._dir_watcher = None + if self._pusher: + self._pusher.finish() + self._pusher.join() + self._pusher = None + if self._fs: + self._fs.finish(self._exit_code) + self._fs = None + wandb._sentry.end_session() + + def _max_cli_version(self) -> Optional[str]: + server_info = self.get_server_info() + max_cli_version = server_info.get("cliVersionInfo", {}).get( + "max_cli_version", None + ) + if not isinstance(max_cli_version, str): + return None + return max_cli_version + + def get_viewer_server_info(self) -> None: + if self._cached_server_info and self._cached_viewer: + return + self._cached_viewer, self._cached_server_info = self._api.viewer_server_info() + + def get_viewer_info(self) -> Dict[str, Any]: + if not self._cached_viewer: + self.get_viewer_server_info() + return self._cached_viewer + + def get_server_info(self) -> Dict[str, Any]: + if not self._cached_server_info: + self.get_viewer_server_info() + return self._cached_server_info + + def get_local_info(self) -> "LocalInfo": + """Queries the server to get the local version information. + + First, we perform an introspection, if it returns empty we deduce that the + docker image is out-of-date. Otherwise, we use the returned values to deduce the + state of the local server. + """ + local_info = wandb_internal_pb2.LocalInfo() + if self._settings._offline: + local_info.out_of_date = False + return local_info + + latest_local_version = "latest" + + # Assuming the query is successful if the result is empty it indicates that + # the backend is out of date since it doesn't have the desired field + server_info = self.get_server_info() + latest_local_version_info = server_info.get("latestLocalVersionInfo", {}) + if latest_local_version_info is None: + local_info.out_of_date = False + else: + local_info.out_of_date = latest_local_version_info.get("outOfDate", True) + local_info.version = latest_local_version_info.get( + "latestVersionString", latest_local_version + ) + return local_info + + def _flush_job(self) -> None: + if self._job_builder.disable or self._settings._offline: + return + self._job_builder.set_config(self._consolidated_config.non_internal_config()) + summary_dict = self._cached_summary.copy() + summary_dict.pop("_wandb", None) + self._job_builder.set_summary(summary_dict) + + artifact = self._job_builder.build(api=self._api) + if artifact is not None and self._run is not None: + proto_artifact = self._interface._make_artifact(artifact) + proto_artifact.run_id = self._run.run_id + proto_artifact.project = self._run.project + proto_artifact.entity = self._run.entity + # TODO: this should be removed when the latest tag is handled + # by the backend (WB-12116) + proto_artifact.aliases.append("latest") + # add docker image tag + for alias in self._job_builder._aliases: + proto_artifact.aliases.append(alias) + + proto_artifact.user_created = True + proto_artifact.use_after_commit = True + proto_artifact.finalize = True + + self._interface._publish_artifact(proto_artifact) + + def __next__(self) -> "Record": + return self._record_q.get(block=True) + + next = __next__ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/sender_config.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/sender_config.py new file mode 100644 index 0000000000000000000000000000000000000000..0cc478958173637fefba1c620977af1d52faad0d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/sender_config.py @@ -0,0 +1,203 @@ +import json +from typing import Any, Dict, NewType, Optional, Sequence + +from wandb.proto import wandb_internal_pb2 +from wandb.sdk.lib import proto_util, telemetry + +BackendConfigDict = NewType("BackendConfigDict", Dict[str, Any]) +"""Run config dictionary in the format used by the backend.""" + +_WANDB_INTERNAL_KEY = "_wandb" + + +class ConfigState: + """The configuration of a run.""" + + def __init__(self, tree: Optional[Dict[str, Any]] = None) -> None: + self._tree: Dict[str, Any] = tree or {} + """A tree with string-valued nodes and JSON leaves. + + Leaves are Python objects that are valid JSON values: + + * Primitives like strings and numbers + * Dictionaries from strings to JSON objects + * Lists of JSON objects + """ + + def non_internal_config(self) -> Dict[str, Any]: + """Returns the config settings minus "_wandb".""" + return {k: v for k, v in self._tree.items() if k != _WANDB_INTERNAL_KEY} + + def update_from_proto( + self, + config_record: wandb_internal_pb2.ConfigRecord, + ) -> None: + """Applies update and remove commands.""" + for config_item in config_record.update: + self._update_at_path( + _key_path(config_item), + json.loads(config_item.value_json), + ) + + for config_item in config_record.remove: + self._delete_at_path(_key_path(config_item)) + + def merge_resumed_config(self, old_config_tree: Dict[str, Any]) -> None: + """Merges the config from a run that's being resumed.""" + # Add any top-level keys that aren't already set. + self._add_unset_keys_from_subtree(old_config_tree, []) + + # When resuming a run, we want to ensure the some of the old configs keys + # are maintained. So we have this logic here to add back + # any keys that were in the old config but not in the new config + for key in ["viz", "visualize", "mask/class_labels"]: + self._add_unset_keys_from_subtree( + old_config_tree, + [_WANDB_INTERNAL_KEY, key], + ) + + def _add_unset_keys_from_subtree( + self, + old_config_tree: Dict[str, Any], + path: Sequence[str], + ) -> None: + """Uses the given subtree for keys that aren't already set.""" + old_subtree = _subtree(old_config_tree, path, create=False) + if not old_subtree: + return + + new_subtree = _subtree(self._tree, path, create=True) + assert new_subtree is not None + + for key, value in old_subtree.items(): + if key not in new_subtree: + new_subtree[key] = value + + def to_backend_dict( + self, + telemetry_record: telemetry.TelemetryRecord, + framework: Optional[str], + start_time_millis: int, + metric_pbdicts: Sequence[Dict[int, Any]], + environment_record: wandb_internal_pb2.EnvironmentRecord, + ) -> BackendConfigDict: + """Returns a dictionary representation expected by the backend. + + The backend expects the configuration in a specific format, and the + config is also used to store additional metadata about the run. + + Args: + telemetry_record: Telemetry information to insert. + framework: The detected framework used in the run (e.g. TensorFlow). + start_time_millis: The run's start time in Unix milliseconds. + metric_pbdicts: List of dict representations of metric protobuffers. + """ + backend_dict = self._tree.copy() + wandb_internal = backend_dict.setdefault(_WANDB_INTERNAL_KEY, {}) + + ################################################### + # Telemetry information + ################################################### + py_version = telemetry_record.python_version + if py_version: + wandb_internal["python_version"] = py_version + + cli_version = telemetry_record.cli_version + if cli_version: + wandb_internal["cli_version"] = cli_version + + if framework: + wandb_internal["framework"] = framework + + huggingface_version = telemetry_record.huggingface_version + if huggingface_version: + wandb_internal["huggingface_version"] = huggingface_version + + wandb_internal["is_jupyter_run"] = telemetry_record.env.jupyter + wandb_internal["is_kaggle_kernel"] = telemetry_record.env.kaggle + wandb_internal["start_time"] = start_time_millis + + # The full telemetry record. + wandb_internal["t"] = proto_util.proto_encode_to_dict(telemetry_record) + + ################################################### + # Metrics + ################################################### + if metric_pbdicts: + wandb_internal["m"] = metric_pbdicts + + ################################################### + # Environment + ################################################### + writer_id = environment_record.writer_id + if writer_id: + environment_dict = proto_util.message_to_dict(environment_record) + wandb_internal["e"] = {writer_id: environment_dict} + + return BackendConfigDict( + { + key: { + # Configurations can be stored in a hand-written YAML file, + # and users can add descriptions to their hyperparameters + # there. However, we don't support a way to set descriptions + # via code, so this is always None. + "desc": None, + "value": value, + } + for key, value in self._tree.items() + } + ) + + def _update_at_path( + self, + key_path: Sequence[str], + value: Any, + ) -> None: + """Sets the value at the path in the config tree.""" + subtree = _subtree(self._tree, key_path[:-1], create=True) + assert subtree is not None + + subtree[key_path[-1]] = value + + def _delete_at_path( + self, + key_path: Sequence[str], + ) -> None: + """Removes the subtree at the path in the config tree.""" + subtree = _subtree(self._tree, key_path[:-1], create=False) + if subtree: + del subtree[key_path[-1]] + + +def _key_path(config_item: wandb_internal_pb2.ConfigItem) -> Sequence[str]: + """Returns the key path referenced by the config item.""" + if config_item.nested_key: + return config_item.nested_key + elif config_item.key: + return [config_item.key] + else: + raise AssertionError( + "Invalid ConfigItem: either key or nested_key must be set", + ) + + +def _subtree( + tree: Dict[str, Any], + key_path: Sequence[str], + *, + create: bool = False, +) -> Optional[Dict[str, Any]]: + """Returns a subtree at the given path.""" + for key in key_path: + subtree = tree.get(key) + + if not subtree: + if create: + subtree = {} + tree[key] = subtree + else: + return None + + tree = subtree + + return tree diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/settings_static.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/settings_static.py new file mode 100644 index 0000000000000000000000000000000000000000..f3dfd6b25315f300e6461c74021a77b0fad207ad --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/settings_static.py @@ -0,0 +1,121 @@ +from __future__ import annotations + +from typing import Any, Iterable + +from wandb.proto import wandb_settings_pb2 +from wandb.sdk.lib import RunMoment +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, proto: wandb_settings_pb2.Settings) -> None: + data = self._proto_to_dict(proto) + super().__init__(**data) + + def _proto_to_dict(self, proto: wandb_settings_pb2.Settings) -> dict: + data = {} + + exclude_fields = { + "model_config", + "model_fields", + "model_fields_set", + "__fields__", + "__model_fields_set", + "__pydantic_self__", + "__pydantic_initialised__", + } + + fields = ( + Settings.model_fields + if hasattr(Settings, "model_fields") + else Settings.__fields__ + ) # type: ignore [attr-defined] + + fields = {k: v for k, v in fields.items() if k not in exclude_fields} # type: ignore [union-attr] + + forks_specified: list[str] = [] + for key in fields: + # Skip Python-only keys that do not exist on the proto. + if key in ("reinit",): + continue + + value: Any = None + + field_info = fields[key] + annotation = str(field_info.annotation) + + if key == "_stats_open_metrics_filters": + # todo: it's an underscored field, refactor into + # something more elegant? + # I'm really about this. It's ugly, but it works. + # Do not try to repeat this at home. + value_type = getattr(proto, key).WhichOneof("value") + if value_type == "sequence": + value = list(getattr(proto, key).sequence.value) + elif value_type == "mapping": + unpacked_mapping = {} + for outer_key, outer_value in getattr( + proto, key + ).mapping.value.items(): + unpacked_inner = {} + for inner_key, inner_value in outer_value.value.items(): + unpacked_inner[inner_key] = inner_value + unpacked_mapping[outer_key] = unpacked_inner + value = unpacked_mapping + elif key == "fork_from" or key == "resume_from": + value = getattr(proto, key) + if value.run: + value = RunMoment( + run=value.run, value=value.value, metric=value.metric + ) + forks_specified.append(key) + else: + value = None + else: + if proto.HasField(key): # type: ignore [arg-type] + value = getattr(proto, key).value + # Convert to list if the field is a sequence + if any(t in annotation for t in ("tuple", "Sequence", "list")): + value = list(value) + else: + value = None + + if value is not None: + data[key] = value + + if len(forks_specified) > 1: + raise ValueError( + "Only one of fork_from or resume_from can be specified, not both" + ) + + return 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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/tb_watcher.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/tb_watcher.py new file mode 100644 index 0000000000000000000000000000000000000000..67cd1b5e6aac85cdd7a93bf1d393fa55c09aefcc --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/tb_watcher.py @@ -0,0 +1,519 @@ +"""tensorboard watcher.""" + +import glob +import logging +import os +import queue +import socket +import sys +import threading +import time +from typing import TYPE_CHECKING, Any, Dict, List, Optional + +import wandb +from wandb import util +from wandb.plot import CustomChart +from wandb.sdk.interface.interface import GlobStr +from wandb.sdk.lib import filesystem + +from . import run as internal_run + +if TYPE_CHECKING: + from queue import PriorityQueue + + from tensorboard.backend.event_processing.event_file_loader import EventFileLoader + from tensorboard.compat.proto.event_pb2 import ProtoEvent + + from wandb.proto.wandb_internal_pb2 import RunRecord + from wandb.sdk.interface.interface import FilesDict + + from ..interface.interface_queue import InterfaceQueue + from .settings_static import SettingsStatic + + HistoryDict = Dict[str, Any] + +# Give some time for tensorboard data to be flushed +SHUTDOWN_DELAY = 5 +ERROR_DELAY = 5 +REMOTE_FILE_TOKEN = "://" +logger = logging.getLogger(__name__) + + +def _link_and_save_file( + path: str, base_path: str, interface: "InterfaceQueue", settings: "SettingsStatic" +) -> None: + # TODO(jhr): should this logic be merged with Run.save() + files_dir = settings.files_dir + file_name = os.path.relpath(path, base_path) + abs_path = os.path.abspath(path) + wandb_path = os.path.join(files_dir, file_name) + filesystem.mkdir_exists_ok(os.path.dirname(wandb_path)) + # We overwrite existing symlinks because namespaces can change in Tensorboard + if os.path.islink(wandb_path) and abs_path != os.readlink(wandb_path): + os.remove(wandb_path) + os.symlink(abs_path, wandb_path) + elif not os.path.exists(wandb_path): + os.symlink(abs_path, wandb_path) + # TODO(jhr): need to figure out policy, live/throttled? + interface.publish_files(dict(files=[(GlobStr(glob.escape(file_name)), "live")])) + + +def is_tfevents_file_created_by( + path: str, hostname: Optional[str], start_time: Optional[float] +) -> bool: + """Check if a path is a tfevents file. + + Optionally checks that it was created by [hostname] after [start_time]. + + tensorboard tfevents filename format: + https://github.com/tensorflow/tensorboard/blob/f3f26b46981da5bd46a5bb93fcf02d9eb7608bc1/tensorboard/summary/writer/event_file_writer.py#L81 + tensorflow tfevents filename format: + https://github.com/tensorflow/tensorflow/blob/8f597046dc30c14b5413813d02c0e0aed399c177/tensorflow/core/util/events_writer.cc#L68 + """ + if not path: + raise ValueError("Path must be a nonempty string") + basename = os.path.basename(path) + if basename.endswith((".profile-empty", ".sagemaker-uploaded")): + return False + fname_components = basename.split(".") + try: + tfevents_idx = fname_components.index("tfevents") + except ValueError: + return False + # check the hostname, which may have dots + if hostname is not None: + for i, part in enumerate(hostname.split(".")): + try: + fname_component_part = fname_components[tfevents_idx + 2 + i] + except IndexError: + return False + if part != fname_component_part: + return False + if start_time is not None: + try: + created_time = int(fname_components[tfevents_idx + 1]) + except (ValueError, IndexError): + return False + # Ensure that the file is newer then our start time, and that it was + # created from the same hostname. + # TODO: we should also check the PID (also contained in the tfevents + # filename). Can we assume that our parent pid is the user process + # that wrote these files? + if created_time < int(start_time): + return False + return True + + +class TBWatcher: + _logdirs: "Dict[str, TBDirWatcher]" + _watcher_queue: "PriorityQueue" + + def __init__( + self, + settings: "SettingsStatic", + run_proto: "RunRecord", + interface: "InterfaceQueue", + force: bool = False, + ) -> None: + self._logdirs = {} + self._consumer: Optional[TBEventConsumer] = None + self._settings = settings + self._interface = interface + self._run_proto = run_proto + self._force = force + # TODO(jhr): do we need locking in this queue? + self._watcher_queue = queue.PriorityQueue() + wandb.tensorboard.reset_state() # type: ignore + + def _calculate_namespace(self, logdir: str, rootdir: str) -> Optional[str]: + namespace: Optional[str] + dirs = list(self._logdirs) + [logdir] + + if os.path.isfile(logdir): + filename = os.path.basename(logdir) + else: + filename = "" + + if rootdir == "": + rootdir = util.to_forward_slash_path( + os.path.dirname(os.path.commonprefix(dirs)) + ) + # Tensorboard loads all tfevents files in a directory and prepends + # their values with the path. Passing namespace to log allows us + # to nest the values in wandb + # Note that we strip '/' instead of os.sep, because elsewhere we've + # converted paths to forward slash. + namespace = logdir.replace(filename, "").replace(rootdir, "").strip("/") + + # TODO: revisit this heuristic, it exists because we don't know the + # root log directory until more than one tfevents file is written to + if len(dirs) == 1 and namespace not in ["train", "validation"]: + namespace = None + else: + namespace = logdir.replace(filename, "").replace(rootdir, "").strip("/") + + return namespace + + def add(self, logdir: str, save: bool, root_dir: str) -> None: + logdir = util.to_forward_slash_path(logdir) + root_dir = util.to_forward_slash_path(root_dir) + if logdir in self._logdirs: + return + namespace = self._calculate_namespace(logdir, root_dir) + # TODO(jhr): implement the deferred tbdirwatcher to find namespace + + if not self._consumer: + self._consumer = TBEventConsumer( + self, self._watcher_queue, self._run_proto, self._settings + ) + self._consumer.start() + + tbdir_watcher = TBDirWatcher( + self, logdir, save, namespace, self._watcher_queue, self._force + ) + self._logdirs[logdir] = tbdir_watcher + tbdir_watcher.start() + + def finish(self) -> None: + for tbdirwatcher in self._logdirs.values(): + tbdirwatcher.shutdown() + for tbdirwatcher in self._logdirs.values(): + tbdirwatcher.finish() + if self._consumer: + self._consumer.finish() + + +class TBDirWatcher: + def __init__( + self, + tbwatcher: "TBWatcher", + logdir: str, + save: bool, + namespace: Optional[str], + queue: "PriorityQueue", + force: bool = False, + ) -> None: + self.directory_watcher = util.get_module( + "tensorboard.backend.event_processing.directory_watcher", + required="Please install tensorboard package", + ) + # self.event_file_loader = util.get_module( + # "tensorboard.backend.event_processing.event_file_loader", + # required="Please install tensorboard package", + # ) + self.tf_compat = util.get_module( + "tensorboard.compat", required="Please install tensorboard package" + ) + self._tbwatcher = tbwatcher + self._generator = self.directory_watcher.DirectoryWatcher( + logdir, self._loader(save, namespace), self._is_our_tfevents_file + ) + self._thread = threading.Thread(target=self._thread_except_body) + self._first_event_timestamp = None + self._shutdown = threading.Event() + self._queue = queue + self._file_version = None + self._namespace = namespace + self._logdir = logdir + self._hostname = socket.gethostname() + self._force = force + self._process_events_lock = threading.Lock() + + def start(self) -> None: + self._thread.start() + + def _is_our_tfevents_file(self, path: str) -> bool: + """Check if a path has been modified since launch and contains tfevents.""" + if not path: + raise ValueError("Path must be a nonempty string") + path = self.tf_compat.tf.compat.as_str_any(path) + if self._force: + return is_tfevents_file_created_by(path, None, None) + else: + return is_tfevents_file_created_by( + path, self._hostname, self._tbwatcher._settings.x_start_time + ) + + def _loader( + self, save: bool = True, namespace: Optional[str] = None + ) -> "EventFileLoader": + """Incredibly hacky class generator to optionally save / prefix tfevent files.""" + _loader_interface = self._tbwatcher._interface + _loader_settings = self._tbwatcher._settings + try: + from tensorboard.backend.event_processing import event_file_loader + except ImportError: + raise Exception("Please install tensorboard package") + + class EventFileLoader(event_file_loader.EventFileLoader): + def __init__(self, file_path: str) -> None: + super().__init__(file_path) + if save: + if REMOTE_FILE_TOKEN in file_path: + logger.warning( + "Not persisting remote tfevent file: %s", file_path + ) + else: + # TODO: save plugins? + logdir = os.path.dirname(file_path) + parts = list(os.path.split(logdir)) + if namespace and parts[-1] == namespace: + parts.pop() + logdir = os.path.join(*parts) + _link_and_save_file( + path=file_path, + base_path=logdir, + interface=_loader_interface, + settings=_loader_settings, + ) + + return EventFileLoader + + def _process_events(self, shutdown_call: bool = False) -> None: + try: + with self._process_events_lock: + for event in self._generator.Load(): + self.process_event(event) + except ( + self.directory_watcher.DirectoryDeletedError, + StopIteration, + RuntimeError, + OSError, + ) as e: + # When listing s3 the directory may not yet exist, or could be empty + logger.debug("Encountered tensorboard directory watcher error: %s", e) + if not self._shutdown.is_set() and not shutdown_call: + time.sleep(ERROR_DELAY) + + def _thread_except_body(self) -> None: + try: + self._thread_body() + except Exception: + logger.exception("generic exception in TBDirWatcher thread") + raise + + def _thread_body(self) -> None: + """Check for new events every second.""" + shutdown_time: Optional[float] = None + while True: + self._process_events() + if self._shutdown.is_set(): + now = time.time() + if not shutdown_time: + shutdown_time = now + SHUTDOWN_DELAY + elif now > shutdown_time: + break + time.sleep(1) + + def process_event(self, event: "ProtoEvent") -> None: + # print("\nEVENT:::", self._logdir, self._namespace, event, "\n") + if self._first_event_timestamp is None: + self._first_event_timestamp = event.wall_time + + if event.HasField("file_version"): + self._file_version = event.file_version + + if event.HasField("summary"): + self._queue.put(Event(event, self._namespace)) + + def shutdown(self) -> None: + self._process_events(shutdown_call=True) + self._shutdown.set() + + def finish(self) -> None: + self.shutdown() + self._thread.join() + + +class Event: + """An event wrapper to enable priority queueing.""" + + def __init__(self, event: "ProtoEvent", namespace: Optional[str]): + self.event = event + self.namespace = namespace + self.created_at = time.time() + + def __lt__(self, other: "Event") -> bool: + if self.event.wall_time < other.event.wall_time: + return True + return False + + +class TBEventConsumer: + """Consume tfevents from a priority queue. + + There should always only be one of these per run_manager. We wait for 10 seconds of + queued events to reduce the chance of multiple tfevent files triggering out of order + steps. + """ + + def __init__( + self, + tbwatcher: TBWatcher, + queue: "PriorityQueue", + run_proto: "RunRecord", + settings: "SettingsStatic", + delay: int = 10, + ) -> None: + self._tbwatcher = tbwatcher + self._queue = queue + self._thread = threading.Thread(target=self._thread_except_body) + self._shutdown = threading.Event() + self.tb_history = TBHistory() + self._delay = delay + + # This is a bit of a hack to get file saving to work as it does in the user + # process. Since we don't have a real run object, we have to define the + # datatypes callback ourselves. + def datatypes_cb(fname: GlobStr) -> None: + files: FilesDict = dict(files=[(fname, "now")]) + self._tbwatcher._interface.publish_files(files) + + # this is only used for logging artifacts + self._internal_run = internal_run.InternalRun(run_proto, settings, datatypes_cb) + self._internal_run._set_internal_run_interface(self._tbwatcher._interface) + + def start(self) -> None: + self._start_time = time.time() + self._thread.start() + + def finish(self) -> None: + self._delay = 0 + self._shutdown.set() + self._thread.join() + while not self._queue.empty(): + event = self._queue.get(True, 1) + if event: + self._handle_event(event, history=self.tb_history) + items = self.tb_history._get_and_reset() + for item in items: + self._save_row( + item, + ) + + def _thread_except_body(self) -> None: + try: + self._thread_body() + except Exception: + logger.exception("generic exception in TBEventConsumer thread") + raise + + def _thread_body(self) -> None: + while True: + try: + event = self._queue.get(True, 1) + # Wait self._delay seconds from consumer start before logging events + if ( + time.time() < self._start_time + self._delay + and not self._shutdown.is_set() + ): + self._queue.put(event) + time.sleep(0.1) + continue + except queue.Empty: + event = None + if self._shutdown.is_set(): + break + if event: + self._handle_event(event, history=self.tb_history) + items = self.tb_history._get_and_reset() + for item in items: + self._save_row( + item, + ) + # flush uncommitted data + self.tb_history._flush() + items = self.tb_history._get_and_reset() + for item in items: + self._save_row(item) + + def _handle_event( + self, event: "ProtoEvent", history: Optional["TBHistory"] = None + ) -> None: + wandb.tensorboard._log( # type: ignore + event.event, + step=event.event.step, + namespace=event.namespace, + history=history, + ) + + def _save_row(self, row: "HistoryDict") -> None: + chart_keys = set() + for k, v in row.items(): + if isinstance(v, CustomChart): + chart_keys.add(k) + v.set_key(k) + self._tbwatcher._interface.publish_config( + key=v.spec.config_key, + val=v.spec.config_value, + ) + + for k in chart_keys: + chart = row.pop(k) + if isinstance(chart, CustomChart): + row[chart.spec.table_key] = chart.table + + self._tbwatcher._interface.publish_history( + self._internal_run, + row, + publish_step=False, + ) + + +class TBHistory: + _data: "HistoryDict" + _added: "List[HistoryDict]" + + def __init__(self) -> None: + self._step = 0 + self._step_size = 0 + self._data = dict() + self._added = [] + + def _flush(self) -> None: + if not self._data: + return + # A single tensorboard step may have too much data + # we just drop the largest keys in the step if it does. + # TODO: we could flush the data across multiple steps + if self._step_size > util.MAX_LINE_BYTES: + metrics = [(k, sys.getsizeof(v)) for k, v in self._data.items()] + metrics.sort(key=lambda t: t[1], reverse=True) + bad = 0 + dropped_keys = [] + for k, v in metrics: + # TODO: (cvp) Added a buffer of 100KiB, this feels rather brittle. + if self._step_size - bad < util.MAX_LINE_BYTES - 100000: + break + else: + bad += v + dropped_keys.append(k) + del self._data[k] + wandb.termwarn( + f"Step {self._step} exceeds max data limit, dropping {len(dropped_keys)} of the largest keys:" + ) + print("\t" + ("\n\t".join(dropped_keys))) # noqa: T201 + self._data["_step"] = self._step + self._added.append(self._data) + self._step += 1 + self._step_size = 0 + + def add(self, d: "HistoryDict") -> None: + self._flush() + self._data = dict() + self._data.update(self._track_history_dict(d)) + + def _track_history_dict(self, d: "HistoryDict") -> "HistoryDict": + e = {} + for k in d.keys(): + e[k] = d[k] + self._step_size += sys.getsizeof(e[k]) + return e + + def _row_update(self, d: "HistoryDict") -> None: + self._data.update(self._track_history_dict(d)) + + def _get_and_reset(self) -> "List[HistoryDict]": + added = self._added[:] + self._added = [] + return added diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/thread_local_settings.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/thread_local_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..2ee0e74cc44151617cb90e7eb45996e0d1a3859d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/internal/thread_local_settings.py @@ -0,0 +1,18 @@ +import threading +from typing import Dict, Optional + + +# Context variable for setting API settings (api keys, etc.) for internal and public apis thread-locally +# TODO: move this into actual settings +class _ThreadLocalApiSettings(threading.local): + api_key: Optional[str] + cookies: Optional[Dict] + headers: Optional[Dict] + + def __init__(self) -> None: + self.api_key = None + self.cookies = None + self.headers = None + + +_thread_local_api_settings: _ThreadLocalApiSettings = _ThreadLocalApiSettings() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7e904eff616c9977433debc96586b56665825708 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/_launch.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/_launch.py new file mode 100644 index 0000000000000000000000000000000000000000..a52e7efc95a40a23e1ba8556b81f1192da12c50d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/_launch.py @@ -0,0 +1,331 @@ +import asyncio +import logging +import os +import sys +from typing import Any, Dict, List, Optional, Tuple + +import yaml + +import wandb +from wandb.apis.internal import Api + +from . import loader +from ._project_spec import LaunchProject +from .agent import LaunchAgent +from .agent.agent import construct_agent_configs +from .environment.local_environment import LocalEnvironment +from .errors import ExecutionError, LaunchError +from .runner.abstract import AbstractRun +from .utils import ( + LAUNCH_CONFIG_FILE, + PROJECT_SYNCHRONOUS, + construct_launch_spec, + validate_launch_spec_source, +) + +_logger = logging.getLogger(__name__) + + +def set_launch_logfile(logfile: str) -> None: + """Set the logfile for the launch agent.""" + # Get logger of parent module + _launch_logger = logging.getLogger("wandb.sdk.launch") + if logfile == "-": + logfile_stream = sys.stdout + else: + try: + logfile_stream = open(logfile, "w") + # check if file is writable + except Exception as e: + wandb.termerror( + f"Could not open {logfile} for writing logs. Please check " + f"the path and permissions.\nError: {e}" + ) + return + + wandb.termlog( + f"Internal agent logs printing to {'stdout' if logfile == '-' else logfile}. " + ) + handler = logging.StreamHandler(logfile_stream) + handler.formatter = logging.Formatter( + "%(asctime)s %(levelname)-7s %(threadName)-10s:%(process)d " + "[%(filename)s:%(funcName)s():%(lineno)s] %(message)s" + ) + _launch_logger.addHandler(handler) + _launch_logger.log(logging.INFO, "Internal agent logs printing to %s", logfile) + + +def resolve_agent_config( + entity: Optional[str], + max_jobs: Optional[int], + queues: Optional[Tuple[str]], + config: Optional[str], + verbosity: Optional[int], +) -> Tuple[Dict[str, Any], Api]: + """Resolve the agent config. + + Arguments: + api (Api): The api. + entity (str): The entity. + max_jobs (int): The max number of jobs. + queues (Tuple[str]): The queues. + config (str): The config. + verbosity (int): How verbose to print, 0 or None = default, 1 = print status every 20 seconds, 2 = also print debugging information + + Returns: + Tuple[Dict[str, Any], Api]: The resolved config and api. + """ + defaults = { + "max_jobs": 1, + "max_schedulers": 1, + "queues": [], + "registry": {}, + "builder": {}, + "verbosity": 0, + } + resolved_config: Dict[str, Any] = defaults + config_path = config or os.path.expanduser(LAUNCH_CONFIG_FILE) + if os.path.isfile(config_path): + launch_config = {} + with open(config_path) as f: + try: + launch_config = yaml.safe_load(f) + # This is considered unreachable by mypy, but it's not. + if launch_config is None: + launch_config = {} # type: ignore + except yaml.YAMLError as e: + raise LaunchError(f"Invalid launch agent config: {e}") + resolved_config.update(launch_config.items()) + elif config is not None: + raise LaunchError( + f"Could not find use specified launch config file: {config_path}" + ) + if os.environ.get("WANDB_ENTITY") is not None: + resolved_config.update({"entity": os.environ.get("WANDB_ENTITY")}) + if os.environ.get("WANDB_LAUNCH_MAX_JOBS") is not None: + resolved_config.update( + {"max_jobs": int(os.environ.get("WANDB_LAUNCH_MAX_JOBS", 1))} + ) + + if entity is not None: + resolved_config.update({"entity": entity}) + if max_jobs is not None: + resolved_config.update({"max_jobs": int(max_jobs)}) + if queues: + resolved_config.update({"queues": list(queues)}) + if verbosity: + resolved_config.update({"verbosity": int(verbosity)}) + # queue -> queues + if resolved_config.get("queue"): + if isinstance(resolved_config.get("queue"), str): + resolved_config["queues"].append(resolved_config["queue"]) + else: + msg = ( + "Invalid launch agent config for key 'queue' with type: {type(resolved_config.get('queue'))} " + "(expected str). Specify multiple queues with the 'queues' key" + ) + raise LaunchError(msg) + + keys = ["entity"] + settings = { + k: resolved_config.get(k) for k in keys if resolved_config.get(k) is not None + } + + api = Api(default_settings=settings) + + if resolved_config.get("entity") is None: + resolved_config.update({"entity": api.default_entity}) + + return resolved_config, api + + +def create_and_run_agent( + api: Api, + config: Dict[str, Any], +) -> None: + try: + from wandb.sdk.launch.agent import config as agent_config + except ModuleNotFoundError: + raise LaunchError( + "wandb launch-agent requires pydantic to be installed. " + "Please install with `pip install wandb[launch]`" + ) + try: + agent_config.AgentConfig(**config) + except agent_config.ValidationError as e: + errors = e.errors() + for error in errors: + loc = ".".join([str(x) for x in error.get("loc", [])]) + msg = f"Agent config error in field {loc}" + value = error.get("input") + if not isinstance(value, dict): + msg += f" (value: {value})" + msg += f": {error['msg']}" + wandb.termerror(msg) + raise LaunchError("Invalid launch agent config") + agent = LaunchAgent(api, config) + try: + asyncio.run(agent.loop()) + except asyncio.CancelledError: + pass + + +async def _launch( + api: Api, + job: Optional[str] = None, + name: Optional[str] = None, + project: Optional[str] = None, + entity: Optional[str] = None, + docker_image: Optional[str] = None, + entry_point: Optional[List[str]] = None, + version: Optional[str] = None, + resource: Optional[str] = None, + resource_args: Optional[Dict[str, Any]] = None, + launch_config: Optional[Dict[str, Any]] = None, + synchronous: Optional[bool] = None, + run_id: Optional[str] = None, + repository: Optional[str] = None, +) -> AbstractRun: + """Helper that delegates to the project-running method corresponding to the passed-in backend.""" + if launch_config is None: + launch_config = {} + if resource is None: + resource = "local-container" + launch_spec = construct_launch_spec( + None, + job, + api, + name, + project, + entity, + docker_image, + resource, + entry_point, + version, + resource_args, + launch_config, + run_id, + repository, + author=None, + ) + validate_launch_spec_source(launch_spec) + launch_project = LaunchProject.from_spec(launch_spec, api) + launch_project.fetch_and_validate_project() + entrypoint = launch_project.get_job_entry_point() + image_uri = ( + launch_project.docker_image or launch_project.job_base_image + ) # Either set by user or None. + + # construct runner config. + runner_config: Dict[str, Any] = {} + runner_config[PROJECT_SYNCHRONOUS] = synchronous + + config = launch_config or {} + environment_config, build_config, registry_config = construct_agent_configs(config) + environment = loader.environment_from_config(environment_config) + if environment is not None and not isinstance(environment, LocalEnvironment): + await environment.verify() + registry = loader.registry_from_config(registry_config, environment) + builder = loader.builder_from_config(build_config, environment, registry) + if not (launch_project.docker_image or launch_project.job_base_image): + assert entrypoint + image_uri = await builder.build_image(launch_project, entrypoint, None) + backend = loader.runner_from_config( + resource, api, runner_config, environment, registry + ) + if backend: + assert image_uri + submitted_run = await backend.run(launch_project, image_uri) + # this check will always pass, run is only optional in the agent case where + # a run queue id is present on the backend config + assert submitted_run + return submitted_run + else: + raise ExecutionError( + f"Unavailable backend {resource}, available backends: {', '.join(loader.WANDB_RUNNERS)}" + ) + + +def launch( + api: Api, + job: Optional[str] = None, + entry_point: Optional[List[str]] = None, + version: Optional[str] = None, + name: Optional[str] = None, + resource: Optional[str] = None, + resource_args: Optional[Dict[str, Any]] = None, + project: Optional[str] = None, + entity: Optional[str] = None, + docker_image: Optional[str] = None, + config: Optional[Dict[str, Any]] = None, + synchronous: Optional[bool] = True, + run_id: Optional[str] = None, + repository: Optional[str] = None, +) -> AbstractRun: + """Launch a W&B launch experiment. + + Arguments: + job: string reference to a wandb.Job eg: wandb/test/my-job:latest + api: An instance of a wandb Api from wandb.apis.internal. + entry_point: Entry point to run within the project. Defaults to using the entry point used + in the original run for wandb URIs, or main.py for git repository URIs. + version: For Git-based projects, either a commit hash or a branch name. + name: Name run under which to launch the run. + resource: Execution backend for the run. + resource_args: Resource related arguments for launching runs onto a remote backend. + Will be stored on the constructed launch config under ``resource_args``. + project: Target project to send launched run to + entity: Target entity to send launched run to + config: A dictionary containing the configuration for the run. May also contain + resource specific arguments under the key "resource_args". + synchronous: Whether to block while waiting for a run to complete. Defaults to True. + Note that if ``synchronous`` is False and ``backend`` is "local-container", this + method will return, but the current process will block when exiting until + the local run completes. If the current process is interrupted, any + asynchronous runs launched via this method will be terminated. If + ``synchronous`` is True and the run fails, the current process will + error out as well. + run_id: ID for the run (To ultimately replace the :name: field) + repository: string name of repository path for remote registry + + Example: + ```python + from wandb.sdk.launch import launch + + job = "wandb/jobs/Hello World:latest" + params = {"epochs": 5} + # Run W&B project and create a reproducible docker environment + # on a local host + api = wandb.apis.internal.Api() + launch(api, job, parameters=params) + ``` + + + Returns: + an instance of`wandb.launch.SubmittedRun` exposing information (e.g. run ID) + about the launched run. + + Raises: + `wandb.exceptions.ExecutionError` If a run launched in blocking mode + is unsuccessful. + """ + submitted_run_obj = asyncio.run( + _launch( + job=job, + name=name, + project=project, + entity=entity, + docker_image=docker_image, + entry_point=entry_point, + version=version, + resource=resource, + resource_args=resource_args, + launch_config=config, + synchronous=synchronous, + api=api, + run_id=run_id, + repository=repository, + ) + ) + + return submitted_run_obj diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/_launch_add.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/_launch_add.py new file mode 100644 index 0000000000000000000000000000000000000000..d65a638cd81b0f6ad3f456a23c648bd025d99f98 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/_launch_add.py @@ -0,0 +1,255 @@ +import asyncio +import pprint +from typing import Any, Dict, List, Optional, Union + +import wandb +import wandb.apis.public as public +from wandb.apis.internal import Api +from wandb.errors import CommError +from wandb.sdk.launch.builder.build import build_image_from_project +from wandb.sdk.launch.errors import LaunchError +from wandb.sdk.launch.utils import ( + LAUNCH_DEFAULT_PROJECT, + LOG_PREFIX, + construct_launch_spec, + validate_launch_spec_source, +) + +from ._project_spec import LaunchProject + + +def push_to_queue( + api: Api, + queue_name: str, + launch_spec: Dict[str, Any], + template_variables: Optional[dict], + project_queue: str, + priority: Optional[int] = None, +) -> Any: + return api.push_to_run_queue( + queue_name, launch_spec, template_variables, project_queue, priority + ) + + +def launch_add( + uri: Optional[str] = None, + job: Optional[str] = None, + config: Optional[Dict[str, Any]] = None, + template_variables: Optional[Dict[str, Union[float, int, str]]] = None, + project: Optional[str] = None, + entity: Optional[str] = None, + queue_name: Optional[str] = None, + resource: Optional[str] = None, + entry_point: Optional[List[str]] = None, + name: Optional[str] = None, + version: Optional[str] = None, + docker_image: Optional[str] = None, + project_queue: Optional[str] = None, + resource_args: Optional[Dict[str, Any]] = None, + run_id: Optional[str] = None, + build: Optional[bool] = False, + repository: Optional[str] = None, + sweep_id: Optional[str] = None, + author: Optional[str] = None, + priority: Optional[int] = None, +) -> "public.QueuedRun": + """Enqueue a W&B launch experiment. With either a source uri, job or docker_image. + + Arguments: + uri: URI of experiment to run. A wandb run uri or a Git repository URI. + job: string reference to a wandb.Job eg: wandb/test/my-job:latest + config: A dictionary containing the configuration for the run. May also contain + resource specific arguments under the key "resource_args" + template_variables: A dictionary containing values of template variables for a run queue. + Expected format of `{"VAR_NAME": VAR_VALUE}` + project: Target project to send launched run to + entity: Target entity to send launched run to + queue: the name of the queue to enqueue the run to + priority: the priority level of the job, where 1 is the highest priority + resource: Execution backend for the run: W&B provides built-in support for "local-container" backend + entry_point: Entry point to run within the project. Defaults to using the entry point used + in the original run for wandb URIs, or main.py for git repository URIs. + name: Name run under which to launch the run. + version: For Git-based projects, either a commit hash or a branch name. + docker_image: The name of the docker image to use for the run. + resource_args: Resource related arguments for launching runs onto a remote backend. + Will be stored on the constructed launch config under ``resource_args``. + run_id: optional string indicating the id of the launched run + build: optional flag defaulting to false, requires queue to be set + if build, an image is created, creates a job artifact, pushes a reference + to that job artifact to queue + repository: optional string to control the name of the remote repository, used when + pushing images to a registry + project_queue: optional string to control the name of the project for the queue. Primarily used + for back compatibility with project scoped queues + + + Example: + ```python + from wandb.sdk.launch import launch_add + + project_uri = "https://github.com/wandb/examples" + params = {"alpha": 0.5, "l1_ratio": 0.01} + # Run W&B project and create a reproducible docker environment + # on a local host + api = wandb.apis.internal.Api() + launch_add(uri=project_uri, parameters=params) + ``` + + + Returns: + an instance of`wandb.api.public.QueuedRun` which gives information about the + queued run, or if `wait_until_started` or `wait_until_finished` are called, gives access + to the underlying Run information. + + Raises: + `wandb.exceptions.LaunchError` if unsuccessful + """ + api = Api() + + return _launch_add( + api, + job, + config, + template_variables, + project, + entity, + queue_name, + resource, + entry_point, + name, + version, + docker_image, + project_queue, + resource_args, + run_id=run_id, + build=build, + repository=repository, + sweep_id=sweep_id, + author=author, + priority=priority, + ) + + +def _launch_add( + api: Api, + job: Optional[str], + config: Optional[Dict[str, Any]], + template_variables: Optional[dict], + project: Optional[str], + entity: Optional[str], + queue_name: Optional[str], + resource: Optional[str], + entry_point: Optional[List[str]], + name: Optional[str], + version: Optional[str], + docker_image: Optional[str], + project_queue: Optional[str], + resource_args: Optional[Dict[str, Any]] = None, + run_id: Optional[str] = None, + build: Optional[bool] = False, + repository: Optional[str] = None, + sweep_id: Optional[str] = None, + author: Optional[str] = None, + priority: Optional[int] = None, +) -> "public.QueuedRun": + launch_spec = construct_launch_spec( + None, + job, + api, + name, + project, + entity, + docker_image, + resource, + entry_point, + version, + resource_args, + config, + run_id, + repository, + author, + sweep_id, + ) + + if build: + if resource == "local-process": + raise LaunchError( + "Cannot build a docker image for the resource: local-process" + ) + + if launch_spec.get("job") is not None: + wandb.termwarn("Build doesn't support setting a job. Overwriting job.") + launch_spec["job"] = None + + launch_project = LaunchProject.from_spec(launch_spec, api) + docker_image_uri = asyncio.run( + build_image_from_project(launch_project, api, config or {}) + ) + run = wandb.run or wandb.init( + project=launch_spec["project"], + entity=launch_spec["entity"], + job_type="launch_job", + ) + + job_artifact = run._log_job_artifact_with_image( # type: ignore + docker_image_uri, launch_project.override_args + ) + job_name = job_artifact.wait().name + + job = f"{launch_spec['entity']}/{launch_spec['project']}/{job_name}" + launch_spec["job"] = job + launch_spec["uri"] = None # Remove given URI --> now in job + + if queue_name is None: + queue_name = "default" + if project_queue is None: + project_queue = LAUNCH_DEFAULT_PROJECT + spec_template_vars = launch_spec.get("template_variables") + if isinstance(spec_template_vars, dict): + launch_spec.pop("template_variables") + if template_variables is None: + template_variables = spec_template_vars + else: + template_variables = { + **spec_template_vars, + **template_variables, + } + + validate_launch_spec_source(launch_spec) + res = push_to_queue( + api, queue_name, launch_spec, template_variables, project_queue, priority + ) + + if res is None or "runQueueItemId" not in res: + raise LaunchError("Error adding run to queue") + + updated_spec = res.get("runSpec") + if updated_spec: + if updated_spec.get("resource_args"): + launch_spec["resource_args"] = updated_spec.get("resource_args") + if updated_spec.get("resource"): + launch_spec["resource"] = updated_spec.get("resource") + + if project_queue == LAUNCH_DEFAULT_PROJECT: + wandb.termlog(f"{LOG_PREFIX}Added run to queue {queue_name}.") + else: + wandb.termlog(f"{LOG_PREFIX}Added run to queue {project_queue}/{queue_name}.") + wandb.termlog(f"{LOG_PREFIX}Launch spec:\n{pprint.pformat(launch_spec)}\n") + + public_api = public.Api() + if job is not None: + try: + public_api._artifact(job, type="job") + except (ValueError, CommError) as e: + raise LaunchError(f"Unable to fetch job with name {job}: {e}") + + queued_run = public_api.queued_run( + launch_spec["entity"], + launch_spec["project"], + queue_name, + res["runQueueItemId"], + project_queue, + priority, + ) + return queued_run # type: ignore diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/_project_spec.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/_project_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..8d7bb079bdb4a924172a2481a3cd44329865847b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/_project_spec.py @@ -0,0 +1,565 @@ +"""Convert launch arguments into a runnable wandb launch script. + +Arguments can come from a launch spec or call to wandb launch. +""" + +import enum +import json +import logging +import os +import shlex +import shutil +import tempfile +from copy import deepcopy +from typing import TYPE_CHECKING, Any, Dict, List, Optional, cast + +import wandb +from wandb.apis.internal import Api +from wandb.errors import CommError +from wandb.sdk.launch.utils import get_entrypoint_file +from wandb.sdk.lib.runid import generate_id + +from .errors import LaunchError +from .utils import LOG_PREFIX, recursive_macro_sub + +if TYPE_CHECKING: + from wandb.sdk.artifacts.artifact import Artifact + +_logger = logging.getLogger(__name__) + + +# need to make user root for sagemaker, so users have access to /opt/ml directories +# that let users create artifacts and access input data +RESOURCE_UID_MAP = {"local": 1000, "sagemaker": 0} +IMAGE_TAG_MAX_LENGTH = 32 + + +class LaunchSource(enum.IntEnum): + """Enumeration of possible sources for a launch project. + + Attributes: + DOCKER: Source is a Docker image. This can happen if a user runs + `wandb launch -d `. + JOB: Source is a job. This is standard case. + SCHEDULER: Source is a wandb sweep scheduler command. + """ + + DOCKER = 1 + JOB = 2 + SCHEDULER = 3 + + +class LaunchProject: + """A launch project specification. + + The LaunchProject is initialized from a raw launch spec an internal API + object. The project encapsulates logic for taking a launch spec and converting + it into the executable code. + + The LaunchProject needs to ultimately produce a full container spec for + execution in docker, k8s, sagemaker, or vertex. This container spec includes: + - container image uri + - environment variables for configuring wandb etc. + - entrypoint command and arguments + - additional arguments specific to the target resource (e.g. instance type, node selector) + + This class is stateful and certain methods can only be called after + `LaunchProject.fetch_and_validate_project()` has been called. + + Notes on the entrypoint: + - The entrypoint is the command that will be run inside the container. + - The LaunchProject stores two entrypoints + - The job entrypoint is the entrypoint specified in the job's config. + - The override entrypoint is the entrypoint specified in the launch spec. + - The override entrypoint takes precedence over the job entrypoint. + """ + + # This init is way to long, and there are too many attributes on this sucker. + def __init__( + self, + uri: Optional[str], + job: Optional[str], + api: Api, + launch_spec: Dict[str, Any], + target_entity: str, + target_project: str, + name: Optional[str], + docker_config: Dict[str, Any], + git_info: Dict[str, str], + overrides: Dict[str, Any], + resource: str, + resource_args: Dict[str, Any], + run_id: Optional[str], + sweep_id: Optional[str] = None, + ): + self.uri = uri + self.job = job + if job is not None: + wandb.termlog(f"{LOG_PREFIX}Launching job: {job}") + self._job_artifact: Optional[Artifact] = None + self.api = api + self.launch_spec = launch_spec + self.target_entity = target_entity + self.target_project = target_project.lower() + self.name = name # TODO: replace with run_id + # the builder key can be passed in through the resource args + # but these resource_args are then passed to the appropriate + # runner, so we need to pop the builder key out + resource_args_copy = deepcopy(resource_args) + resource_args_build = resource_args_copy.get(resource, {}).pop("builder", {}) + self.resource = resource + self.resource_args = resource_args_copy + self.sweep_id = sweep_id + self.author = launch_spec.get("author") + self.python_version: Optional[str] = launch_spec.get("python_version") + self._job_dockerfile: Optional[str] = None + self._job_build_context: Optional[str] = None + self._job_base_image: Optional[str] = None + self.accelerator_base_image: Optional[str] = resource_args_build.get( + "accelerator", {} + ).get("base_image") or resource_args_build.get("cuda", {}).get("base_image") + self.docker_image: Optional[str] = docker_config.get( + "docker_image" + ) or launch_spec.get("image_uri") # type: ignore [assignment] + self.docker_user_id = docker_config.get("user_id", 1000) + self._entry_point: Optional[EntryPoint] = ( + None # todo: keep multiple entrypoint support? + ) + self.init_overrides(overrides) + self.init_source() + self.init_git(git_info) + self.deps_type: Optional[str] = None + self._runtime: Optional[str] = None + self.run_id = run_id or generate_id() + self._queue_name: Optional[str] = None + self._queue_entity: Optional[str] = None + self._run_queue_item_id: Optional[str] = None + + def init_source(self) -> None: + if self.docker_image is not None: + self.source = LaunchSource.DOCKER + self.project_dir = None + elif self.job is not None: + self.source = LaunchSource.JOB + self.project_dir = tempfile.mkdtemp() + elif self.uri and self.uri.startswith("placeholder"): + self.source = LaunchSource.SCHEDULER + self.project_dir = os.getcwd() + self._entry_point = self.override_entrypoint + + def change_project_dir(self, new_dir: str) -> None: + """Change the project directory to a new directory.""" + # Copy the contents of the old project dir to the new project dir. + old_dir = self.project_dir + if old_dir is not None: + shutil.copytree( + old_dir, + new_dir, + symlinks=True, + dirs_exist_ok=True, + ignore=shutil.ignore_patterns("fsmonitor--daemon.ipc", ".git"), + ) + shutil.rmtree(old_dir) + self.project_dir = new_dir + + def init_git(self, git_info: Dict[str, str]) -> None: + self.git_version = git_info.get("version") + self.git_repo = git_info.get("repo") + + def init_overrides(self, overrides: Dict[str, Any]) -> None: + """Initialize override attributes for a launch project.""" + self.overrides = overrides + self.override_args: List[str] = overrides.get("args", []) + self.override_config: Dict[str, Any] = overrides.get("run_config", {}) + self.override_artifacts: Dict[str, Any] = overrides.get("artifacts", {}) + self.override_files: Dict[str, Any] = overrides.get("files", {}) + self.override_entrypoint: Optional[EntryPoint] = None + self.override_dockerfile: Optional[str] = overrides.get("dockerfile") + override_entrypoint = overrides.get("entry_point") + if override_entrypoint: + _logger.info("Adding override entry point") + self.override_entrypoint = EntryPoint( + name=get_entrypoint_file(override_entrypoint), + command=override_entrypoint, + ) + + def __repr__(self) -> str: + """String representation of LaunchProject.""" + if self.source == LaunchSource.JOB: + return f"{self.job}" + return f"{self.uri}" + + @classmethod + def from_spec(cls, launch_spec: Dict[str, Any], api: Api) -> "LaunchProject": + """Constructs a LaunchProject instance using a launch spec. + + Arguments: + launch_spec: Dictionary representation of launch spec + api: Instance of wandb.apis.internal Api + + Returns: + An initialized `LaunchProject` object + """ + name: Optional[str] = None + if launch_spec.get("name"): + name = launch_spec["name"] + return LaunchProject( + launch_spec.get("uri"), + launch_spec.get("job"), + api, + launch_spec, + launch_spec["entity"], + launch_spec["project"], + name, + launch_spec.get("docker", {}), + launch_spec.get("git", {}), + launch_spec.get("overrides", {}), + launch_spec.get("resource", None), # type: ignore [arg-type] + launch_spec.get("resource_args", {}), + launch_spec.get("run_id", None), + launch_spec.get("sweep_id", {}), + ) + + @property + def job_dockerfile(self) -> Optional[str]: + return self._job_dockerfile + + @property + def job_build_context(self) -> Optional[str]: + return self._job_build_context + + @property + def job_base_image(self) -> Optional[str]: + return self._job_base_image + + def set_job_dockerfile(self, dockerfile: str) -> None: + self._job_dockerfile = dockerfile + + def set_job_build_context(self, build_context: str) -> None: + self._job_build_context = build_context + + def set_job_base_image(self, base_image: str) -> None: + self._job_base_image = base_image + + @property + def image_name(self) -> str: + if self.job_base_image is not None: + return self.job_base_image + if self.docker_image is not None: + return self.docker_image + elif self.uri is not None: + cleaned_uri = self.uri.replace("https://", "/") + first_sep = cleaned_uri.find("/") + shortened_uri = cleaned_uri[first_sep:] + return wandb.util.make_docker_image_name_safe(shortened_uri) + else: + # this will always pass since one of these 3 is required + assert self.job is not None + return wandb.util.make_docker_image_name_safe(self.job.split(":")[0]) + + @property + def queue_name(self) -> Optional[str]: + return self._queue_name + + @queue_name.setter + def queue_name(self, value: str) -> None: + self._queue_name = value + + @property + def queue_entity(self) -> Optional[str]: + return self._queue_entity + + @queue_entity.setter + def queue_entity(self, value: str) -> None: + self._queue_entity = value + + @property + def run_queue_item_id(self) -> Optional[str]: + return self._run_queue_item_id + + @run_queue_item_id.setter + def run_queue_item_id(self, value: str) -> None: + self._run_queue_item_id = value + + def fill_macros(self, image: str) -> Dict[str, Any]: + """Substitute values for macros in resource arguments. + + Certain macros can be used in resource args. These macros allow the + user to set resource args dynamically in the context of the + run being launched. The macros are given in the ${macro} format. The + following macros are currently supported: + + ${project_name} - the name of the project the run is being launched to. + ${entity_name} - the owner of the project the run being launched to. + ${run_id} - the id of the run being launched. + ${run_name} - the name of the run that is launching. + ${image_uri} - the URI of the container image for this run. + + Additionally, you may use ${} to refer to the value of any + environment variables that you plan to set in the environment of any + agents that will receive these resource args. + + Calling this method will overwrite the contents of self.resource_args + with the substituted values. + + Args: + image (str): The image name to fill in for ${wandb-image}. + + Returns: + Dict[str, Any]: The resource args with all macros filled in. + """ + update_dict = { + "project_name": self.target_project, + "entity_name": self.target_entity, + "run_id": self.run_id, + "run_name": self.name, + "image_uri": image, + "author": self.author, + } + update_dict.update(os.environ) + result = recursive_macro_sub(self.resource_args, update_dict) + # recursive_macro_sub given a dict returns a dict with the same keys + # but with other input types behaves differently. The cast is for mypy. + return cast(Dict[str, Any], result) + + def build_required(self) -> bool: + """Checks the source to see if a build is required.""" + if self.job_base_image is not None: + return False + if self.source != LaunchSource.JOB: + return True + return False + + @property + def docker_image(self) -> Optional[str]: + """Returns the Docker image associated with this LaunchProject. + + This will only be set if an image_uri is being run outside a job. + + Returns: + Optional[str]: The Docker image or None if not specified. + """ + if self._docker_image: + return self._docker_image + return None + + @docker_image.setter + def docker_image(self, value: str) -> None: + """Sets the Docker image for the project. + + Args: + value (str): The Docker image to set. + + Returns: + None + """ + self._docker_image = value + self._ensure_not_docker_image_and_local_process() + + def get_job_entry_point(self) -> Optional["EntryPoint"]: + """Returns the job entrypoint for the project.""" + # assuming project only has 1 entry point, pull that out + # tmp fn until we figure out if we want to support multiple entry points or not + if not self._entry_point: + if not self.docker_image and not self.job_base_image: + raise LaunchError( + "Project must have at least one entry point unless docker image is specified." + ) + return None + return self._entry_point + + def set_job_entry_point(self, command: List[str]) -> "EntryPoint": + """Set job entrypoint for the project.""" + assert self._entry_point is None, ( + "Cannot set entry point twice. Use LaunchProject.override_entrypoint" + ) + new_entrypoint = EntryPoint(name=command[-1], command=command) + self._entry_point = new_entrypoint + return new_entrypoint + + def fetch_and_validate_project(self) -> None: + """Fetches a project into a local directory, adds the config values to the directory, and validates the first entrypoint for the project. + + Arguments: + launch_project: LaunchProject to fetch and validate. + api: Instance of wandb.apis.internal Api + + Returns: + A validated `LaunchProject` object. + + """ + if self.source == LaunchSource.DOCKER: + return + elif self.source == LaunchSource.JOB: + self._fetch_job() + assert self.project_dir is not None + + # Let's make sure we document this very clearly. + def get_image_source_string(self) -> str: + """Returns a unique string identifying the source of an image.""" + if self.source == LaunchSource.JOB: + assert self._job_artifact is not None + return f"{self._job_artifact.name}:v{self._job_artifact.version}" + elif self.source == LaunchSource.DOCKER: + assert isinstance(self.docker_image, str) + return self.docker_image + else: + raise LaunchError( + "Unknown source type when determining image source string" + ) + + def _ensure_not_docker_image_and_local_process(self) -> None: + """Ensure that docker image is not specified with local-process resource runner. + + Raises: + LaunchError: If docker image is specified with local-process resource runner. + """ + if self.docker_image is not None and self.resource == "local-process": + raise LaunchError( + "Cannot specify docker image with local-process resource runner" + ) + + def _fetch_job(self) -> None: + """Fetches the job details from the public API and configures the launch project. + + Raises: + LaunchError: If there is an error accessing the job. + """ + public_api = wandb.apis.public.Api() + job_dir = tempfile.mkdtemp() + try: + job = public_api.job(self.job, path=job_dir) + except CommError as e: + msg = e.message + raise LaunchError( + f"Error accessing job {self.job}: {msg} on {public_api.settings.get('base_url')}" + ) + job.configure_launch_project(self) # Why is this a method of the job? + self._job_artifact = job._job_artifact + + def get_env_vars_dict(self, api: Api, max_env_length: int) -> Dict[str, str]: + """Generate environment variables for the project. + + Arguments: + launch_project: LaunchProject to generate environment variables for. + + Returns: + Dictionary of environment variables. + """ + env_vars = {} + env_vars["WANDB_BASE_URL"] = api.settings("base_url") + override_api_key = self.launch_spec.get("_wandb_api_key") + env_vars["WANDB_API_KEY"] = override_api_key or api.api_key + if self.target_project: + env_vars["WANDB_PROJECT"] = self.target_project + env_vars["WANDB_ENTITY"] = self.target_entity + env_vars["WANDB_LAUNCH"] = "True" + env_vars["WANDB_RUN_ID"] = self.run_id + if self.docker_image: + env_vars["WANDB_DOCKER"] = self.docker_image + if self.name is not None: + env_vars["WANDB_NAME"] = self.name + if "author" in self.launch_spec and not override_api_key: + env_vars["WANDB_USERNAME"] = self.launch_spec["author"] + if self.sweep_id: + env_vars["WANDB_SWEEP_ID"] = self.sweep_id + if self.launch_spec.get("_resume_count", 0) > 0: + env_vars["WANDB_RESUME"] = "allow" + if self.queue_name: + env_vars[wandb.env.LAUNCH_QUEUE_NAME] = self.queue_name + if self.queue_entity: + env_vars[wandb.env.LAUNCH_QUEUE_ENTITY] = self.queue_entity + if self.run_queue_item_id: + env_vars[wandb.env.LAUNCH_TRACE_ID] = self.run_queue_item_id + + _inject_wandb_config_env_vars(self.override_config, env_vars, max_env_length) + _inject_file_overrides_env_vars(self.override_files, env_vars, max_env_length) + + artifacts = {} + # if we're spinning up a launch process from a job + # we should tell the run to use that artifact + if self.job: + artifacts = {wandb.util.LAUNCH_JOB_ARTIFACT_SLOT_NAME: self.job} + env_vars["WANDB_ARTIFACTS"] = json.dumps( + {**artifacts, **self.override_artifacts} + ) + return env_vars + + def parse_existing_requirements(self) -> str: + from packaging.requirements import InvalidRequirement, Requirement + + requirements_line = "" + assert self.project_dir is not None + base_requirements = os.path.join(self.project_dir, "requirements.txt") + if os.path.exists(base_requirements): + include_only = set() + with open(base_requirements) as f2: + for line in f2: + if line.strip() == "": + continue + + try: + req = Requirement(line) + name = req.name.lower() + include_only.add(shlex.quote(name)) + except InvalidRequirement: + _logger.warning( + "Unable to parse line %s in requirements.txt", + line, + exc_info=True, + ) + continue + + requirements_line += "WANDB_ONLY_INCLUDE={} ".format(",".join(include_only)) + if "wandb" not in requirements_line: + wandb.termwarn(f"{LOG_PREFIX}wandb is not present in requirements.txt.") + return requirements_line + + +class EntryPoint: + """An entry point into a wandb launch specification.""" + + def __init__(self, name: Optional[str], command: List[str]): + self.name = name + self.command = command + + def update_entrypoint_path(self, new_path: str) -> None: + """Updates the entrypoint path to a new path.""" + if len(self.command) == 2 and ( + self.command[0].startswith("python") or self.command[0] == "bash" + ): + self.command[1] = new_path + + +def _inject_wandb_config_env_vars( + config: Dict[str, Any], env_dict: Dict[str, Any], maximum_env_length: int +) -> None: + str_config = json.dumps(config) + if len(str_config) <= maximum_env_length: + env_dict["WANDB_CONFIG"] = str_config + return + + chunks = [ + str_config[i : i + maximum_env_length] + for i in range(0, len(str_config), maximum_env_length) + ] + config_chunks_dict = {f"WANDB_CONFIG_{i}": chunk for i, chunk in enumerate(chunks)} + env_dict.update(config_chunks_dict) + + +def _inject_file_overrides_env_vars( + overrides: Dict[str, Any], env_dict: Dict[str, Any], maximum_env_length: int +) -> None: + str_overrides = json.dumps(overrides) + if len(str_overrides) <= maximum_env_length: + env_dict["WANDB_LAUNCH_FILE_OVERRIDES"] = str_overrides + return + + chunks = [ + str_overrides[i : i + maximum_env_length] + for i in range(0, len(str_overrides), maximum_env_length) + ] + overrides_chunks_dict = { + f"WANDB_LAUNCH_FILE_OVERRIDES_{i}": chunk for i, chunk in enumerate(chunks) + } + env_dict.update(overrides_chunks_dict) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/create_job.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/create_job.py new file mode 100644 index 0000000000000000000000000000000000000000..0e613b4cee02a99a40d552339b2e226680c786dd --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/create_job.py @@ -0,0 +1,530 @@ +import json +import logging +import os +import re +import sys +import tempfile +from typing import Any, Dict, List, Optional, Tuple + +import wandb +from wandb.apis.internal import Api +from wandb.sdk.artifacts.artifact import Artifact +from wandb.sdk.internal.job_builder import JobBuilder +from wandb.sdk.launch.git_reference import GitReference +from wandb.sdk.launch.utils import ( + _is_git_uri, + get_current_python_version, + get_entrypoint_file, +) +from wandb.sdk.lib import filesystem +from wandb.util import make_artifact_name_safe + +logging.basicConfig(stream=sys.stdout, level=logging.INFO) +_logger = logging.getLogger("wandb") + + +CODE_ARTIFACT_EXCLUDE_PATHS = ["wandb", ".git"] + + +def create_job( + path: str, + job_type: str, + entity: Optional[str] = None, + project: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + aliases: Optional[List[str]] = None, + runtime: Optional[str] = None, + entrypoint: Optional[str] = None, + git_hash: Optional[str] = None, + build_context: Optional[str] = None, + dockerfile: Optional[str] = None, +) -> Optional[Artifact]: + """Create a job from a path, not as the output of a run. + + Arguments: + path (str): Path to the job directory. + job_type (str): Type of the job. One of "git", "code", or "image". + entity (Optional[str]): Entity to create the job under. + project (Optional[str]): Project to create the job under. + name (Optional[str]): Name of the job. + description (Optional[str]): Description of the job. + aliases (Optional[List[str]]): Aliases for the job. + runtime (Optional[str]): Python runtime of the job, like 3.9. + entrypoint (Optional[str]): Entrypoint of the job. If build_context is + provided, path is relative to build_context. + git_hash (Optional[str]): Git hash of a specific commit, when using git type jobs. + build_context (Optional[str]): Path to the build context, when using image type jobs. + dockerfile (Optional[str]): Path to the Dockerfile, when using image type jobs. + If build_context is provided, path is relative to build_context. + + Returns: + Optional[Artifact]: The artifact created by the job, the action (for printing), and job aliases. + None if job creation failed. + + Example: + ```python + artifact_job = wandb.create_job( + job_type="code", + path=".", + entity="wandb", + project="jobs", + name="my-train-job", + description="My training job", + aliases=["train"], + runtime="3.9", + entrypoint="train.py", + ) + # then run the newly created job + artifact_job.call() + ``` + """ + api = Api() + + artifact_job, _action, _aliases = _create_job( + api, + job_type, + path, + entity, + project, + name, + description, + aliases, + runtime, + entrypoint, + git_hash, + build_context, + dockerfile, + ) + + return artifact_job + + +def _create_job( + api: Api, + job_type: str, + path: str, + entity: Optional[str] = None, + project: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + aliases: Optional[List[str]] = None, + runtime: Optional[str] = None, + entrypoint: Optional[str] = None, + git_hash: Optional[str] = None, + build_context: Optional[str] = None, + dockerfile: Optional[str] = None, + base_image: Optional[str] = None, + services: Optional[Dict[str, str]] = None, +) -> Tuple[Optional[Artifact], str, List[str]]: + wandb.termlog(f"Creating launch job of type: {job_type}...") + + if name and name != make_artifact_name_safe(name): + wandb.termerror( + f"Artifact names may only contain alphanumeric characters, dashes, underscores, and dots. Did you mean: {make_artifact_name_safe(name)}" + ) + return None, "", [] + + if runtime is not None: + if not re.match(r"^3\.\d+$", runtime): + wandb.termerror( + f"Runtime (-r, --runtime) must be a minor version of Python 3, " + f"e.g. 3.9 or 3.10, received {runtime}" + ) + return None, "", [] + aliases = aliases or [] + tempdir = tempfile.TemporaryDirectory() + try: + metadata, requirements = _make_metadata_for_partial_job( + job_type=job_type, + tempdir=tempdir, + git_hash=git_hash, + runtime=runtime, + path=path, + entrypoint=entrypoint, + ) + if not metadata: + return None, "", [] + except Exception as e: + wandb.termerror(f"Error creating job: {e}") + return None, "", [] + + _dump_metadata_and_requirements( + metadata=metadata, + tmp_path=tempdir.name, + requirements=requirements, + ) + + try: + # init hidden wandb run with job building disabled (handled manually) + run = wandb.init( + dir=tempdir.name, + settings={"silent": True, "disable_job_creation": True}, + entity=entity, + project=project, + job_type="cli_create_job", + ) + except Exception: + # Error printed by wandb.init + return None, "", [] + + job_builder = _configure_job_builder_for_partial(tempdir.name, job_source=job_type) + job_builder._settings.job_name = name + job_builder._services = services or {} + if job_type == "code": + assert entrypoint is not None + job_name = _make_code_artifact( + api=api, + job_builder=job_builder, + path=path, + entrypoint=entrypoint, + run=run, # type: ignore + entity=entity, + project=project, + name=name, + ) + if not job_name: + return None, "", [] + name = job_name + + # build job artifact, loads wandb-metadata and creates wandb-job.json here + artifact = job_builder.build( + api.api, + dockerfile=dockerfile, + build_context=build_context, + base_image=base_image, + ) + if not artifact: + wandb.termerror("JobBuilder failed to build a job") + _logger.debug("Failed to build job, check job source and metadata") + return None, "", [] + + if not name: + name = artifact.name + + aliases += job_builder._aliases + if "latest" not in aliases: + aliases += ["latest"] + + 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={"_partial": True}, + is_user_created=True, + aliases=[{"artifactCollectionName": name, "alias": a} for a in aliases], + ) + action = "No changes detected for" + if not res.get("artifactSequence", {}).get("latestArtifact"): + # When there is no latestArtifact, we are creating new + action = "Created" + elif res.get("state") == "PENDING": + # updating an existing artifafct, state is pending awaiting call to + # log_artifact to upload and finalize artifact. If not pending, digest + # is the same as latestArtifact, so no changes detected + action = "Updated" + + run.log_artifact(artifact, aliases=aliases) # type: ignore + artifact.wait() + run.finish() # type: ignore + + # fetch, then delete hidden run + _run = wandb.Api().run(f"{entity}/{project}/{run.id}") # type: ignore + _run.delete() + + return artifact, action, aliases + + +def _make_metadata_for_partial_job( + job_type: str, + tempdir: tempfile.TemporaryDirectory, + git_hash: Optional[str], + runtime: Optional[str], + path: str, + entrypoint: Optional[str], +) -> Tuple[Optional[Dict[str, Any]], Optional[List[str]]]: + """Create metadata for partial jobs, return metadata and requirements.""" + metadata = {} + if job_type == "git": + assert entrypoint is not None + repo_metadata = _create_repo_metadata( + path=path, + tempdir=tempdir.name, + entrypoint=entrypoint, + git_hash=git_hash, + runtime=runtime, + ) + if not repo_metadata: + tempdir.cleanup() # otherwise git can pollute + return None, None + metadata.update(repo_metadata) + return metadata, None + + if job_type == "code": + assert entrypoint is not None + artifact_metadata, requirements = _create_artifact_metadata( + path=path, entrypoint=entrypoint, runtime=runtime + ) + if not artifact_metadata: + return None, None + metadata.update(artifact_metadata) + return metadata, requirements + + if job_type == "image": + if runtime: + wandb.termwarn( + "Setting runtime is not supported for image jobs, ignoring runtime" + ) + # TODO(gst): support entrypoint for image based jobs + if entrypoint: + wandb.termwarn( + "Setting an entrypoint is not currently supported for image jobs, ignoring entrypoint argument" + ) + metadata.update({"python": runtime or "", "docker": path}) + return metadata, None + + wandb.termerror(f"Invalid job type: {job_type}") + return None, None + + +def _maybe_warn_python_no_executable(entrypoint: str): + entrypoint_list = entrypoint.split(" ") + if len(entrypoint_list) == 1 and entrypoint_list[0].endswith(".py"): + wandb.termwarn( + f"Entrypoint {entrypoint} is a python file without an executable, you may want to use `python {entrypoint}` as the entrypoint instead." + ) + + +def _create_repo_metadata( + path: str, + tempdir: str, + entrypoint: str, + git_hash: Optional[str] = None, + runtime: Optional[str] = None, +) -> Optional[Dict[str, Any]]: + # Make sure the entrypoint doesn't contain any backward path traversal + if entrypoint and ".." in entrypoint: + wandb.termerror("Entrypoint cannot contain backward path traversal") + return None + + _maybe_warn_python_no_executable(entrypoint) + + if not _is_git_uri(path): + wandb.termerror("Path must be a git URI") + return None + + ref = GitReference(path, git_hash) + if not ref: + wandb.termerror("Could not parse git URI") + return None + + ref.fetch(tempdir) + + commit = ref.commit_hash + if not commit: + if not ref.commit_hash: + wandb.termerror("Could not find git commit hash") + return None + commit = ref.commit_hash + + local_dir = os.path.join(tempdir, ref.path or "") + python_version = runtime + if not python_version: + if os.path.exists(os.path.join(local_dir, "runtime.txt")): + with open(os.path.join(local_dir, "runtime.txt")) as f: + python_version = f.read().strip() + elif os.path.exists(os.path.join(local_dir, ".python-version")): + with open(os.path.join(local_dir, ".python-version")) as f: + python_version = f.read().strip().splitlines()[0] + else: + python_version, _ = get_current_python_version() + + python_version = _clean_python_version(python_version) + + metadata = { + "git": { + "commit": commit, + "remote": ref.url, + }, + "entrypoint": entrypoint.split(" "), + "python": python_version, # used to build container + "notebook": False, # partial jobs from notebooks not supported + } + + return metadata + + +def _create_artifact_metadata( + path: str, entrypoint: str, runtime: Optional[str] = None +) -> Tuple[Optional[Dict[str, Any]], Optional[List[str]]]: + if not os.path.isdir(path): + wandb.termerror("Path must be a valid file or directory") + return {}, [] + + _maybe_warn_python_no_executable(entrypoint) + + entrypoint_list = entrypoint.split(" ") + entrypoint_file = get_entrypoint_file(entrypoint_list) + + # read local requirements.txt and dump to temp dir for builder + requirements = [] + depspath = os.path.join(path, "requirements.txt") + if os.path.exists(depspath): + with open(depspath) as f: + requirements = f.read().splitlines() + + if not any(["wandb" in r for r in requirements]): + wandb.termwarn("wandb is not present in requirements.txt.") + + if runtime: + python_version = _clean_python_version(runtime) + else: + python_version, _ = get_current_python_version() + python_version = _clean_python_version(python_version) + + metadata = { + "python": python_version, + "codePath": entrypoint_file, + "entrypoint": entrypoint_list, + } + return metadata, requirements + + +def _configure_job_builder_for_partial(tmpdir: str, job_source: str) -> JobBuilder: + """Configure job builder with temp dir and job source.""" + # adjust git source to repo + if job_source == "git": + job_source = "repo" + + # adjust code source to artifact + if job_source == "code": + job_source = "artifact" + + settings = wandb.Settings(x_files_dir=tmpdir, job_source=job_source) + job_builder = JobBuilder( + settings=settings, # type: ignore + verbose=True, + ) + job_builder._partial = True + # never allow notebook runs + job_builder._is_notebook_run = False + # set run inputs and outputs to empty dicts + job_builder.set_config({}) + job_builder.set_summary({}) + return job_builder + + +def _make_code_artifact( + api: Api, + job_builder: JobBuilder, + run: "wandb.Run", + path: str, + entrypoint: str, + entity: Optional[str], + project: Optional[str], + name: Optional[str], +) -> Optional[str]: + """Helper for creating and logging code artifacts. + + Returns the name of the eventual job. + """ + entrypoint_list = entrypoint.split(" ") + # We no longer require the entrypoint to end in an existing file. But we + # need something to use as the default job artifact name. In the future we + # may require the user to provide a job name explicitly when calling + # wandb job create. + entrypoint_file = entrypoint_list[-1] + artifact_name = _make_code_artifact_name(os.path.join(path, entrypoint_file), name) + code_artifact = wandb.Artifact( + name=artifact_name, + type="code", + description="Code artifact for job", + ) + + try: + code_artifact.add_dir(path) + except Exception as e: + if os.path.islink(path): + wandb.termerror( + "Symlinks are not supported for code artifact jobs, please copy the code into a directory and try again" + ) + wandb.termerror(f"Error adding to code artifact: {e}") + return None + + # Remove paths we don't want to include, if present + for item in CODE_ARTIFACT_EXCLUDE_PATHS: + try: + code_artifact.remove(item) + except FileNotFoundError: + pass + + res, _ = api.create_artifact( + artifact_type_name="code", + artifact_collection_name=artifact_name, + digest=code_artifact.digest, + client_id=code_artifact._client_id, + sequence_client_id=code_artifact._sequence_client_id, + entity_name=entity, + project_name=project, + run_name=run.id, # run will be deleted after creation + description="Code artifact for job", + metadata={"codePath": path, "entrypoint": entrypoint_file}, + is_user_created=True, + aliases=[ + {"artifactCollectionName": artifact_name, "alias": a} for a in ["latest"] + ], + ) + run.log_artifact(code_artifact) + code_artifact.wait() + job_builder._handle_server_artifact(res, code_artifact) # type: ignore + + # code artifacts have "code" prefix, remove it and alias + if not name: + name = code_artifact.name.replace("code", "job").split(":")[0] + + return name + + +def _make_code_artifact_name(path: str, name: Optional[str]) -> str: + """Make a code artifact name from a path and user provided name.""" + if name: + return f"code-{name}" + + clean_path = path.replace("./", "") + if clean_path[0] == "/": + clean_path = clean_path[1:] + if clean_path[-1] == "/": + clean_path = clean_path[:-1] + + path_name = f"code-{make_artifact_name_safe(clean_path)}" + return path_name + + +def _dump_metadata_and_requirements( + tmp_path: str, metadata: Dict[str, Any], requirements: Optional[List[str]] +) -> None: + """Dump manufactured metadata and requirements.txt. + + File used by the job_builder to create a job from provided metadata. + """ + filesystem.mkdir_exists_ok(tmp_path) + with open(os.path.join(tmp_path, "wandb-metadata.json"), "w") as f: + json.dump(metadata, f) + + requirements = requirements or [] + with open(os.path.join(tmp_path, "requirements.txt"), "w") as f: + f.write("\n".join(requirements)) + + +def _clean_python_version(python_version: str) -> str: + # remove micro if present + if python_version.count(".") > 1: + python_version = ".".join(python_version.split(".")[:2]) + _logger.debug(f"micro python version stripped. Now: {python_version}") + return python_version diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/loader.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..d8015a25d233688ab2e2e1634d0bed621121235d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/loader.py @@ -0,0 +1,249 @@ +"""Utilities for the agent.""" + +from typing import Any, Dict, Optional + +import wandb +from wandb.apis.internal import Api +from wandb.docker import is_docker_installed +from wandb.sdk.launch.errors import LaunchError + +from .builder.abstract import AbstractBuilder +from .environment.abstract import AbstractEnvironment +from .registry.abstract import AbstractRegistry +from .runner.abstract import AbstractRunner + +WANDB_RUNNERS = { + "local-container", + "local-process", + "kubernetes", + "vertex", + "sagemaker", +} + + +def environment_from_config(config: Optional[Dict[str, Any]]) -> AbstractEnvironment: + """Create an environment from a config. + + This helper function is used to create an environment from a config. The + config should have a "type" key that specifies the type of environment to + create. The remaining keys are passed to the environment's from_config + method. If the config is None or empty, a LocalEnvironment is returned. + + Arguments: + config (Dict[str, Any]): The config. + + Returns: + Environment: The environment constructed. + """ + if not config: + from .environment.local_environment import LocalEnvironment + + return LocalEnvironment() # This is the default, dummy environment. + env_type = config.get("type") + if not env_type: + raise LaunchError( + "Could not create environment from config. Environment type not specified!" + ) + if env_type == "local": + from .environment.local_environment import LocalEnvironment + + return LocalEnvironment.from_config(config) + if env_type == "aws": + from .environment.aws_environment import AwsEnvironment + + return AwsEnvironment.from_config(config) + if env_type == "gcp": + from .environment.gcp_environment import GcpEnvironment + + return GcpEnvironment.from_config(config) + if env_type == "azure": + from .environment.azure_environment import AzureEnvironment + + return AzureEnvironment.from_config(config) + raise LaunchError( + f"Could not create environment from config. Invalid type: {env_type}" + ) + + +def registry_from_config( + config: Optional[Dict[str, Any]], environment: AbstractEnvironment +) -> AbstractRegistry: + """Create a registry from a config. + + This helper function is used to create a registry from a config. The + config should have a "type" key that specifies the type of registry to + create. The remaining keys are passed to the registry's from_config + method. If the config is None or empty, a LocalRegistry is returned. + + Arguments: + config (Dict[str, Any]): The registry config. + environment (Environment): The environment of the registry. + + Returns: + The registry if config is not None, otherwise None. + + Raises: + LaunchError: If the registry is not configured correctly. + """ + if not config: + from .registry.local_registry import LocalRegistry + + return LocalRegistry() # This is the default, dummy registry. + + wandb.termwarn( + "The `registry` block of the launch agent config is being deprecated. " + "Please specify an image repository URI under the `builder.destination` " + "key of your launch agent config. See " + "https://docs.wandb.ai/guides/launch/setup-agent-advanced#agent-configuration " + "for more information." + ) + + registry_type = config.get("type") + if registry_type is None or registry_type == "local": + from .registry.local_registry import LocalRegistry + + return LocalRegistry() # This is the default, dummy registry. + if registry_type == "ecr": + from .registry.elastic_container_registry import ElasticContainerRegistry + + return ElasticContainerRegistry.from_config(config) + if registry_type == "gcr": + from .registry.google_artifact_registry import GoogleArtifactRegistry + + return GoogleArtifactRegistry.from_config(config) + if registry_type == "acr": + from .registry.azure_container_registry import AzureContainerRegistry + + return AzureContainerRegistry.from_config(config) + raise LaunchError( + f"Could not create registry from config. Invalid registry type: {registry_type}" + ) + + +def builder_from_config( + config: Optional[Dict[str, Any]], + environment: AbstractEnvironment, + registry: AbstractRegistry, +) -> AbstractBuilder: + """Create a builder from a config. + + This helper function is used to create a builder from a config. The + config should have a "type" key that specifies the type of builder to import + and create. The remaining keys are passed to the builder's from_config + method. If the config is None or empty, a default builder is returned. + + The default builder will be a DockerBuilder if we find a working docker cli + on the system, otherwise it will be a NoOpBuilder. + + Arguments: + config (Dict[str, Any]): The builder config. + registry (Registry): The registry of the builder. + + Returns: + The builder. + + Raises: + LaunchError: If the builder is not configured correctly. + """ + if not config: + if is_docker_installed(): + from .builder.docker_builder import DockerBuilder + + return DockerBuilder.from_config( + {}, environment, registry + ) # This is the default builder. + + from .builder.noop import NoOpBuilder + + return NoOpBuilder.from_config({}, environment, registry) + + builder_type = config.get("type") + if builder_type is None: + raise LaunchError( + "Could not create builder from config. Builder type not specified" + ) + if builder_type == "docker": + from .builder.docker_builder import DockerBuilder + + return DockerBuilder.from_config(config, environment, registry) + if builder_type == "kaniko": + from .builder.kaniko_builder import KanikoBuilder + + return KanikoBuilder.from_config(config, environment, registry) + if builder_type == "noop": + from .builder.noop import NoOpBuilder + + return NoOpBuilder.from_config(config, environment, registry) + raise LaunchError( + f"Could not create builder from config. Invalid builder type: {builder_type}" + ) + + +def runner_from_config( + runner_name: str, + api: Api, + runner_config: Dict[str, Any], + environment: AbstractEnvironment, + registry: AbstractRegistry, +) -> AbstractRunner: + """Create a runner from a config. + + This helper function is used to create a runner from a config. The + config should have a "type" key that specifies the type of runner to import + and create. The remaining keys are passed to the runner's from_config + method. If the config is None or empty, a LocalContainerRunner is returned. + + Arguments: + runner_name (str): The name of the backend. + api (Api): The API. + runner_config (Dict[str, Any]): The backend config. + + Returns: + The runner. + + Raises: + LaunchError: If the runner is not configured correctly. + """ + if not runner_name or runner_name in ["local-container", "local"]: + from .runner.local_container import LocalContainerRunner + + return LocalContainerRunner(api, runner_config, environment, registry) + if runner_name == "local-process": + from .runner.local_process import LocalProcessRunner + + return LocalProcessRunner(api, runner_config) + if runner_name == "sagemaker": + from .environment.aws_environment import AwsEnvironment + + if not isinstance(environment, AwsEnvironment): + try: + environment = AwsEnvironment.from_default() + except LaunchError as e: + raise LaunchError( + "Could not create Sagemaker runner. " + "Environment must be an instance of AwsEnvironment." + ) from e + from .runner.sagemaker_runner import SageMakerRunner + + return SageMakerRunner(api, runner_config, environment, registry) + if runner_name in ["vertex", "gcp-vertex"]: + from .environment.gcp_environment import GcpEnvironment + + if not isinstance(environment, GcpEnvironment): + try: + environment = GcpEnvironment.from_default() + except LaunchError as e: + raise LaunchError( + "Could not create Vertex runner. " + "Environment must be an instance of GcpEnvironment." + ) from e + from .runner.vertex_runner import VertexRunner + + return VertexRunner(api, runner_config, environment, registry) + if runner_name == "kubernetes": + from .runner.kubernetes_runner import KubernetesRunner + + return KubernetesRunner(api, runner_config, environment, registry) + raise LaunchError( + f"Could not create runner from config. Invalid runner name: {runner_name}" + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e170975a3d511d04382c6f0a6a3af19aa8e75372 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/utils.py @@ -0,0 +1,746 @@ +import asyncio +import json +import logging +import os +import platform +import re +import subprocess +import sys +from collections import defaultdict +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, cast + +import click + +import wandb +import wandb.docker as docker +from wandb import util +from wandb.apis.internal import Api +from wandb.sdk.launch.errors import LaunchError +from wandb.sdk.launch.git_reference import GitReference +from wandb.sdk.launch.wandb_reference import WandbReference +from wandb.sdk.wandb_config import Config + +from .builder.templates._wandb_bootstrap import ( + FAILED_PACKAGES_POSTFIX, + FAILED_PACKAGES_PREFIX, +) + +FAILED_PACKAGES_REGEX = re.compile( + f"{re.escape(FAILED_PACKAGES_PREFIX)}(.*){re.escape(FAILED_PACKAGES_POSTFIX)}" +) + +if TYPE_CHECKING: # pragma: no cover + from wandb.sdk.launch.agent.job_status_tracker import JobAndRunStatusTracker + + +# TODO: this should be restricted to just Git repos and not S3 and stuff like that +_GIT_URI_REGEX = re.compile( + r"^[^/|^~|^\.].*(git|bitbucket|dev\.azure\.com|\.visualstudio\.com)" +) +_VALID_IP_REGEX = r"^https?://[0-9]+(?:\.[0-9]+){3}(:[0-9]+)?" +_VALID_PIP_PACKAGE_REGEX = r"^[a-zA-Z0-9_.-]+$" +_VALID_WANDB_REGEX = r"^https?://(api.)?wandb" +_WANDB_URI_REGEX = re.compile(r"|".join([_VALID_WANDB_REGEX, _VALID_IP_REGEX])) +_WANDB_QA_URI_REGEX = re.compile( + r"^https?://ap\w.qa.wandb" +) # for testing, not sure if we wanna keep this +_WANDB_DEV_URI_REGEX = re.compile( + r"^https?://ap\w.wandb.test" +) # for testing, not sure if we wanna keep this +_WANDB_LOCAL_DEV_URI_REGEX = re.compile( + r"^https?://localhost" +) # for testing, not sure if we wanna keep this + +API_KEY_REGEX = r"WANDB_API_KEY=\w+(-\w+)?" + +MACRO_REGEX = re.compile(r"\$\{(\w+)\}") + +AZURE_CONTAINER_REGISTRY_URI_REGEX = re.compile( + r"^(?:https://)?([\w]+)\.azurecr\.io/(?P[\w\-]+):?(?P.*)" +) + +ELASTIC_CONTAINER_REGISTRY_URI_REGEX = re.compile( + r"^(?:https://)?(?P[\w-]+)\.dkr\.ecr\.(?P[\w-]+)\.amazonaws\.com/(?P[\.\/\w-]+):?(?P.*)$" +) + +GCP_ARTIFACT_REGISTRY_URI_REGEX = re.compile( + r"^(?:https://)?(?P[\w-]+)-docker\.pkg\.dev/(?P[\w-]+)/(?P[\w-]+)/?(?P[\w-]+)?(?P:.*)?$", + re.IGNORECASE, +) + +S3_URI_RE = re.compile(r"s3://([^/]+)(/(.*))?") +GCS_URI_RE = re.compile(r"gs://([^/]+)(?:/(.*))?") +AZURE_BLOB_REGEX = re.compile( + r"^https://([^\.]+)\.blob\.core\.windows\.net/([^/]+)/?(.*)$" +) + +ARN_PARTITION_RE = re.compile(r"^arn:([^:]+):[^:]*:[^:]*:[^:]*:[^:]*$") + +PROJECT_SYNCHRONOUS = "SYNCHRONOUS" + +LAUNCH_CONFIG_FILE = "~/.config/wandb/launch-config.yaml" +LAUNCH_DEFAULT_PROJECT = "model-registry" + +_logger = logging.getLogger(__name__) +LOG_PREFIX = f"{click.style('launch:', fg='magenta')} " + +MAX_ENV_LENGTHS: Dict[str, int] = defaultdict(lambda: 32670) +MAX_ENV_LENGTHS["SageMakerRunner"] = 512 + +CODE_MOUNT_DIR = "/mnt/wandb" + + +def load_wandb_config() -> Config: + """Load wandb config from WANDB_CONFIG environment variable(s). + + The WANDB_CONFIG environment variable is a json string that can contain + multiple config keys. The WANDB_CONFIG_[0-9]+ environment variables are + used for environments where there is a limit on the length of environment + variables. In that case, we shard the contents of WANDB_CONFIG into + multiple environment variables numbered from 0. + + Returns: + A dictionary of wandb config values. + """ + config_str = os.environ.get("WANDB_CONFIG") + if config_str is None: + config_str = "" + idx = 0 + while True: + chunk = os.environ.get(f"WANDB_CONFIG_{idx}") + if chunk is None: + break + config_str += chunk + idx += 1 + if idx < 1: + raise LaunchError( + "No WANDB_CONFIG or WANDB_CONFIG_[0-9]+ environment variables found" + ) + wandb_config = Config() + try: + env_config = json.loads(config_str) + except json.JSONDecodeError as e: + raise LaunchError(f"Failed to parse WANDB_CONFIG: {e}") from e + + wandb_config.update(env_config) + return wandb_config + + +def event_loop_thread_exec(func: Any) -> Any: + """Wrapper for running any function in an awaitable thread on an event loop. + + Example usage: + ``` + def my_func(arg1, arg2): + return arg1 + arg2 + + + future = event_loop_thread_exec(my_func)(2, 2) + assert await future == 4 + ``` + + The returned function must be called within an active event loop. + """ + + async def wrapper(*args: Any, **kwargs: Any) -> Any: + loop = asyncio.get_event_loop() + result = cast( + Any, await loop.run_in_executor(None, lambda: func(*args, **kwargs)) + ) + return result + + return wrapper + + +def _is_wandb_uri(uri: str) -> bool: + return ( + _WANDB_URI_REGEX.match(uri) + or _WANDB_DEV_URI_REGEX.match(uri) + or _WANDB_LOCAL_DEV_URI_REGEX.match(uri) + or _WANDB_QA_URI_REGEX.match(uri) + ) is not None + + +def _is_wandb_dev_uri(uri: str) -> bool: + return bool(_WANDB_DEV_URI_REGEX.match(uri)) + + +def _is_wandb_local_uri(uri: str) -> bool: + return bool(_WANDB_LOCAL_DEV_URI_REGEX.match(uri)) + + +def _is_git_uri(uri: str) -> bool: + return bool(_GIT_URI_REGEX.match(uri)) + + +def sanitize_wandb_api_key(s: str) -> str: + return str(re.sub(API_KEY_REGEX, "WANDB_API_KEY", s)) + + +def get_project_from_job(job: str) -> Optional[str]: + job_parts = job.split("/") + if len(job_parts) == 3: + return job_parts[1] + return None + + +def set_project_entity_defaults( + uri: Optional[str], + job: Optional[str], + api: Api, + project: Optional[str], + entity: Optional[str], + launch_config: Optional[Dict[str, Any]], +) -> Tuple[Optional[str], str]: + # set the target project and entity if not provided + source_uri = None + if uri is not None: + if _is_wandb_uri(uri): + _, source_uri, _ = parse_wandb_uri(uri) + elif _is_git_uri(uri): + source_uri = os.path.splitext(os.path.basename(uri))[0] + elif job is not None: + source_uri = get_project_from_job(job) + if project is None: + config_project = None + if launch_config: + config_project = launch_config.get("project") + project = config_project or source_uri or "" + if entity is None: + entity = get_default_entity(api, launch_config) + prefix = "" + if platform.system() != "Windows" and sys.stdout.encoding == "UTF-8": + prefix = "🚀 " + wandb.termlog( + f"{LOG_PREFIX}{prefix}Launching run into {entity}{'/' + project if project else ''}" + ) + return project, entity + + +def get_default_entity(api: Api, launch_config: Optional[Dict[str, Any]]): + config_entity = None + if launch_config: + config_entity = launch_config.get("entity") + return config_entity or api.default_entity + + +def strip_resource_args_and_template_vars(launch_spec: Dict[str, Any]) -> None: + if launch_spec.get("resource_args", None) and launch_spec.get( + "template_variables", None + ): + wandb.termwarn( + "Launch spec contains both resource_args and template_variables, " + "only one can be set. Using template_variables." + ) + launch_spec.pop("resource_args") + + +def construct_launch_spec( + uri: Optional[str], + job: Optional[str], + api: Api, + name: Optional[str], + project: Optional[str], + entity: Optional[str], + docker_image: Optional[str], + resource: Optional[str], + entry_point: Optional[List[str]], + version: Optional[str], + resource_args: Optional[Dict[str, Any]], + launch_config: Optional[Dict[str, Any]], + run_id: Optional[str], + repository: Optional[str], + author: Optional[str], + sweep_id: Optional[str] = None, +) -> Dict[str, Any]: + """Construct the launch specification from CLI arguments.""" + # override base config (if supplied) with supplied args + launch_spec = launch_config if launch_config is not None else {} + if uri is not None: + launch_spec["uri"] = uri + if job is not None: + launch_spec["job"] = job + project, entity = set_project_entity_defaults( + uri, + job, + api, + project, + entity, + launch_config, + ) + launch_spec["entity"] = entity + if author: + launch_spec["author"] = author + + launch_spec["project"] = project + if name: + launch_spec["name"] = name + if "docker" not in launch_spec: + launch_spec["docker"] = {} + if docker_image: + launch_spec["docker"]["docker_image"] = docker_image + if sweep_id: # all runs in a sweep have this set + launch_spec["sweep_id"] = sweep_id + + if "resource" not in launch_spec: + launch_spec["resource"] = resource if resource else None + + if "git" not in launch_spec: + launch_spec["git"] = {} + if version: + launch_spec["git"]["version"] = version + + if "overrides" not in launch_spec: + launch_spec["overrides"] = {} + + if not isinstance(launch_spec["overrides"].get("args", []), list): + raise LaunchError("override args must be a list of strings") + + if resource_args: + launch_spec["resource_args"] = resource_args + + if entry_point: + launch_spec["overrides"]["entry_point"] = entry_point + + if run_id is not None: + launch_spec["run_id"] = run_id + + if repository: + launch_config = launch_config or {} + if launch_config.get("registry"): + launch_config["registry"]["url"] = repository + else: + launch_config["registry"] = {"url": repository} + + # dont send both resource args and template variables + strip_resource_args_and_template_vars(launch_spec) + + return launch_spec + + +def validate_launch_spec_source(launch_spec: Dict[str, Any]) -> None: + job = launch_spec.get("job") + docker_image = launch_spec.get("docker", {}).get("docker_image") + if bool(job) == bool(docker_image): + raise LaunchError( + "Exactly one of job or docker_image must be specified in the launch spec." + ) + + +def parse_wandb_uri(uri: str) -> Tuple[str, str, str]: + """Parse wandb uri to retrieve entity, project and run name.""" + ref = WandbReference.parse(uri) + if not ref or not ref.entity or not ref.project or not ref.run_id: + raise LaunchError(f"Trouble parsing wandb uri {uri}") + return (ref.entity, ref.project, ref.run_id) + + +def get_local_python_deps( + dir: str, filename: str = "requirements.local.txt" +) -> Optional[str]: + try: + env = os.environ + with open(os.path.join(dir, filename), "w") as f: + subprocess.call(["pip", "freeze"], env=env, stdout=f) + return filename + except subprocess.CalledProcessError as e: + wandb.termerror(f"Command failed: {e}") + return None + + +def diff_pip_requirements(req_1: List[str], req_2: List[str]) -> Dict[str, str]: + """Return a list of pip requirements that are not in req_1 but are in req_2.""" + + def _parse_req(req: List[str]) -> Dict[str, str]: + # TODO: This can be made more exhaustive, but for 99% of cases this is fine + # see https://pip.pypa.io/en/stable/reference/requirements-file-format/#example + d: Dict[str, str] = dict() + for line in req: + _name: str = None # type: ignore + _version: str = None # type: ignore + if line.startswith("#"): # Ignore comments + continue + elif "git+" in line or "hg+" in line: + _name = line.split("#egg=")[1] + _version = line.split("@")[-1].split("#")[0] + elif "==" in line: + _s = line.split("==") + _name = _s[0].lower() + _version = _s[1].split("#")[0].strip() + elif ">=" in line: + _s = line.split(">=") + _name = _s[0].lower() + _version = _s[1].split("#")[0].strip() + elif ">" in line: + _s = line.split(">") + _name = _s[0].lower() + _version = _s[1].split("#")[0].strip() + elif re.match(_VALID_PIP_PACKAGE_REGEX, line) is not None: + _name = line + else: + raise ValueError(f"Unable to parse pip requirements file line: {line}") + if _name is not None: + assert re.match(_VALID_PIP_PACKAGE_REGEX, _name), ( + f"Invalid pip package name {_name}" + ) + d[_name] = _version + return d + + # Use symmetric difference between dict representation to print errors + try: + req_1_dict: Dict[str, str] = _parse_req(req_1) + req_2_dict: Dict[str, str] = _parse_req(req_2) + except (AssertionError, ValueError, IndexError, KeyError) as e: + raise LaunchError(f"Failed to parse pip requirements: {e}") + diff: List[Tuple[str, str]] = [] + for item in set(req_1_dict.items()) ^ set(req_2_dict.items()): + diff.append(item) + # Parse through the diff to make it pretty + pretty_diff: Dict[str, str] = {} + for name, version in diff: + if pretty_diff.get(name) is None: + pretty_diff[name] = version + else: + pretty_diff[name] = f"v{version} and v{pretty_diff[name]}" + return pretty_diff + + +def validate_wandb_python_deps( + requirements_file: Optional[str], + dir: str, +) -> None: + """Warn if local python dependencies differ from wandb requirements.txt.""" + if requirements_file is not None: + requirements_path = os.path.join(dir, requirements_file) + with open(requirements_path) as f: + wandb_python_deps: List[str] = f.read().splitlines() + + local_python_file = get_local_python_deps(dir) + if local_python_file is not None: + local_python_deps_path = os.path.join(dir, local_python_file) + with open(local_python_deps_path) as f: + local_python_deps: List[str] = f.read().splitlines() + + diff_pip_requirements(wandb_python_deps, local_python_deps) + return + _logger.warning("Unable to validate local python dependencies") + + +def apply_patch(patch_string: str, dst_dir: str) -> None: + """Applies a patch file to a directory.""" + _logger.info("Applying diff.patch") + with open(os.path.join(dst_dir, "diff.patch"), "w") as fp: + fp.write(patch_string) + try: + subprocess.check_call( + [ + "patch", + "-s", + f"--directory={dst_dir}", + "-p1", + "-i", + "diff.patch", + ] + ) + except subprocess.CalledProcessError: + raise wandb.Error("Failed to apply diff.patch associated with run.") + + +def _fetch_git_repo(dst_dir: str, uri: str, version: Optional[str]) -> Optional[str]: + """Clones the git repo at ``uri`` into ``dst_dir``. + + checks out commit ``version``. Assumes authentication parameters are + specified by the environment, e.g. by a Git credential helper. + """ + # We defer importing git until the last moment, because the import requires that the git + # executable is available on the PATH, so we only want to fail if we actually need it. + + _logger.info("Fetching git repo") + ref = GitReference(uri, version) + if ref is None: + raise LaunchError(f"Unable to parse git uri: {uri}") + ref.fetch(dst_dir) + if version is None: + version = ref.ref + return version + + +def convert_jupyter_notebook_to_script(fname: str, project_dir: str) -> str: + nbconvert = wandb.util.get_module( + "nbconvert", "nbformat and nbconvert are required to use launch with notebooks" + ) + nbformat = wandb.util.get_module( + "nbformat", "nbformat and nbconvert are required to use launch with notebooks" + ) + + _logger.info("Converting notebook to script") + new_name = fname.replace(".ipynb", ".py") + with open(os.path.join(project_dir, fname)) as fh: + nb = nbformat.reads(fh.read(), nbformat.NO_CONVERT) + for cell in nb.cells: + if cell.cell_type == "code": + source_lines = cell.source.split("\n") + modified_lines = [] + for line in source_lines: + if not line.startswith("!"): + modified_lines.append(line) + cell.source = "\n".join(modified_lines) + + exporter = nbconvert.PythonExporter() + source, meta = exporter.from_notebook_node(nb) + + with open(os.path.join(project_dir, new_name), "w+") as fh: + fh.writelines(source) + return new_name + + +def to_camel_case(maybe_snake_str: str) -> str: + if "_" not in maybe_snake_str: + return maybe_snake_str + components = maybe_snake_str.split("_") + return "".join(x.title() if x else "_" for x in components) + + +def validate_build_and_registry_configs( + build_config: Dict[str, Any], registry_config: Dict[str, Any] +) -> None: + build_config_credentials = build_config.get("credentials", {}) + registry_config_credentials = registry_config.get("credentials", {}) + if ( + build_config_credentials + and registry_config_credentials + and build_config_credentials != registry_config_credentials + ): + raise LaunchError("registry and build config credential mismatch") + + +async def get_kube_context_and_api_client( + kubernetes: Any, + resource_args: Dict[str, Any], +) -> Tuple[Any, Any]: + config_file = resource_args.get("configFile", None) + context = None + if config_file is not None or os.path.exists(os.path.expanduser("~/.kube/config")): + # context only exist in the non-incluster case + ( + all_contexts, + active_context, + ) = kubernetes.config.list_kube_config_contexts(config_file) + context = None + if resource_args.get("context"): + context_name = resource_args["context"] + for c in all_contexts: + if c["name"] == context_name: + context = c + break + raise LaunchError(f"Specified context {context_name} was not found.") + else: + context = active_context + # TODO: We should not really be performing this check if the user is not + # using EKS but I don't see an obvious way to make an eks specific code path + # right here. + util.get_module( + "awscli", + "awscli is required to load a kubernetes context " + "from eks. Please run `pip install wandb[launch]` to install it.", + ) + await kubernetes.config.load_kube_config(config_file, context["name"]) + api_client = await kubernetes.config.new_client_from_config( + config_file, context=context["name"] + ) + return context, api_client + else: + kubernetes.config.load_incluster_config() + api_client = kubernetes.client.api_client.ApiClient() + return context, api_client + + +def resolve_build_and_registry_config( + default_launch_config: Optional[Dict[str, Any]], + build_config: Optional[Dict[str, Any]], + registry_config: Optional[Dict[str, Any]], +) -> Tuple[Dict[str, Any], Dict[str, Any]]: + resolved_build_config: Dict[str, Any] = {} + if build_config is None and default_launch_config is not None: + resolved_build_config = default_launch_config.get("builder", {}) + elif build_config is not None: + resolved_build_config = build_config + resolved_registry_config: Dict[str, Any] = {} + if registry_config is None and default_launch_config is not None: + resolved_registry_config = default_launch_config.get("registry", {}) + elif registry_config is not None: + resolved_registry_config = registry_config + validate_build_and_registry_configs(resolved_build_config, resolved_registry_config) + return resolved_build_config, resolved_registry_config + + +def check_logged_in(api: Api) -> bool: + """Check if a user is logged in. + + Raises an error if the viewer doesn't load (likely a broken API key). Expected time + cost is 0.1-0.2 seconds. + """ + res = api.api.viewer() + if not res: + raise LaunchError( + "Could not connect with current API-key. " + "Please relogin using `wandb login --relogin`" + " and try again (see `wandb login --help` for more options)" + ) + + return True + + +def make_name_dns_safe(name: str) -> str: + resp = name.replace("_", "-").lower() + resp = re.sub(r"[^a-z\.\-]", "", resp) + # Actual length limit is 253, but we want to leave room for the generated suffix + resp = resp[:200] + return resp + + +def warn_failed_packages_from_build_logs( + log: str, image_uri: str, api: Api, job_tracker: Optional["JobAndRunStatusTracker"] +) -> None: + match = FAILED_PACKAGES_REGEX.search(log) + if match: + _msg = f"Failed to install the following packages: {match.group(1)} for image: {image_uri}. Will attempt to launch image without them." + wandb.termwarn(_msg) + if job_tracker is not None: + res = job_tracker.saver.save_contents( + _msg, "failed-packages.log", "warning" + ) + api.update_run_queue_item_warning( + job_tracker.run_queue_item_id, + "Some packages were not successfully installed during the build", + "build", + res, + ) + + +def docker_image_exists(docker_image: str, should_raise: bool = False) -> bool: + """Check if a specific image is already available. + + Optionally raises an exception if the image is not found. + """ + _logger.info("Checking if base image exists...") + try: + docker.run(["docker", "image", "inspect", docker_image]) + return True + except (docker.DockerError, ValueError): + if should_raise: + raise + _logger.info("Base image not found. Generating new base image") + return False + + +def pull_docker_image(docker_image: str) -> None: + """Pull the requested docker image.""" + try: + docker.run(["docker", "pull", docker_image]) + except docker.DockerError as e: + raise LaunchError(f"Docker server returned error: {e}") + + +def macro_sub(original: str, sub_dict: Dict[str, Optional[str]]) -> str: + """Substitute macros in a string. + + Macros occur in the string in the ${macro} format. The macro names are + substituted with their values from the given dictionary. If a macro + is not found in the dictionary, it is left unchanged. + + Args: + original: The string to substitute macros in. + sub_dict: A dictionary mapping macro names to their values. + + Returns: + The string with the macros substituted. + """ + return MACRO_REGEX.sub( + lambda match: str(sub_dict.get(match.group(1), match.group(0))), original + ) + + +def recursive_macro_sub(source: Any, sub_dict: Dict[str, Optional[str]]) -> Any: + """Recursively substitute macros in a parsed JSON or YAML blob. + + Macros occur in strings at leaves of the blob in the ${macro} format. + The macro names are substituted with their values from the given dictionary. + If a macro is not found in the dictionary, it is left unchanged. + + Arguments: + source: The JSON or YAML blob to substitute macros in. + sub_dict: A dictionary mapping macro names to their values. + + Returns: + The blob with the macros substituted. + """ + if isinstance(source, str): + return macro_sub(source, sub_dict) + elif isinstance(source, list): + return [recursive_macro_sub(item, sub_dict) for item in source] + elif isinstance(source, dict): + return { + key: recursive_macro_sub(value, sub_dict) for key, value in source.items() + } + else: + return source + + +def fetch_and_validate_template_variables( + runqueue: Any, fields: dict +) -> Dict[str, Any]: + template_variables = {} + + variable_schemas = {} + for tv in runqueue.template_variables: + variable_schemas[tv["name"]] = json.loads(tv["schema"]) + + for field in fields: + field_parts = field.split("=") + if len(field_parts) != 2: + raise LaunchError( + f'--set-var value must be in the format "--set-var key1=value1", instead got: {field}' + ) + key, val = field_parts + if key not in variable_schemas: + raise LaunchError( + f"Queue {runqueue.name} does not support overriding {key}." + ) + schema = variable_schemas.get(key, {}) + field_type = schema.get("type") + try: + if field_type == "integer": + val = int(val) + elif field_type == "number": + val = float(val) + + except ValueError: + raise LaunchError(f"Value for {key} must be of type {field_type}.") + template_variables[key] = val + return template_variables + + +def get_entrypoint_file(entrypoint: List[str]) -> Optional[str]: + """Get the entrypoint file from the given command. + + Args: + entrypoint (List[str]): List of command and arguments. + + Returns: + Optional[str]: The entrypoint file if found, otherwise None. + """ + if not entrypoint: + return None + if entrypoint[0].endswith(".py") or entrypoint[0].endswith(".sh"): + return entrypoint[0] + if len(entrypoint) < 2: + return None + return entrypoint[1] + + +def get_current_python_version() -> Tuple[str, str]: + full_version = sys.version.split()[0].split(".") + major = full_version[0] + version = ".".join(full_version[:2]) if len(full_version) >= 2 else major + ".0" + return version, major diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/wandb_reference.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/wandb_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5de34c04bf3aa77068da19cb6b4af8f1e163709d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/launch/wandb_reference.py @@ -0,0 +1,138 @@ +"""Support for parsing W&B URLs (which might be user provided) into constituent parts.""" + +from dataclasses import dataclass +from enum import IntEnum +from typing import Optional +from urllib.parse import urlparse + +PREFIX_HTTP = "http://" +PREFIX_HTTPS = "https://" + + +class ReferenceType(IntEnum): + RUN = 1 + JOB = 2 + + +# Ideally we would not overload the URL paths as we do. +# TODO: Not sure these are exhaustive, and even if so more special paths might get added. +# Would be good to have restrictions that we could check. +RESERVED_NON_ENTITIES = ( + "create-team", + "fully-connected", + "registry", + "settings", + "subscriptions", +) +RESERVED_NON_PROJECTS = ( + "likes", + "projects", +) +RESERVED_JOB_PATHS = ("_view",) + + +@dataclass +class WandbReference: + # TODO: This will include port, should we separate that out? + host: Optional[str] = None + + entity: Optional[str] = None + project: Optional[str] = None + + # Set when we don't know how to parse yet + path: Optional[str] = None + + # Reference type will determine what other fields are set + ref_type: Optional[ReferenceType] = None + + run_id: Optional[str] = None + + job_name: Optional[str] = None + job_alias: str = "latest" # In addition to an alias can be a version specifier + + def is_bare(self) -> bool: + return self.host is None + + def is_job(self) -> bool: + return self.ref_type == ReferenceType.JOB + + def is_run(self) -> bool: + return self.ref_type == ReferenceType.RUN + + def is_job_or_run(self) -> bool: + return self.is_job() or self.is_run() + + def job_reference(self) -> str: + assert self.is_job() + return f"{self.job_name}:{self.job_alias}" + + def job_reference_scoped(self) -> str: + assert self.entity + assert self.project + unscoped = self.job_reference() + return f"{self.entity}/{self.project}/{unscoped}" + + def url_host(self) -> str: + return f"{PREFIX_HTTPS}{self.host}" if self.host else "" + + def url_entity(self) -> str: + assert self.entity + return f"{self.url_host()}/{self.entity}" + + def url_project(self) -> str: + assert self.project + return f"{self.url_entity()}/{self.project}" + + @staticmethod + def parse(uri: str) -> Optional["WandbReference"]: + """Attempt to parse a string as a W&B URL.""" + # TODO: Error if HTTP and host is not localhost? + if ( + not uri.startswith("/") + and not uri.startswith(PREFIX_HTTP) + and not uri.startswith(PREFIX_HTTPS) + ): + return None + + ref = WandbReference() + + # This takes care of things like query and fragment + parsed = urlparse(uri) + if parsed.netloc: + ref.host = parsed.netloc + + if not parsed.path.startswith("/"): + return ref + + ref.path = parsed.path[1:] + parts = ref.path.split("/") + if len(parts) > 0: + if parts[0] not in RESERVED_NON_ENTITIES: + ref.path = None + ref.entity = parts[0] + if len(parts) > 1: + if parts[1] not in RESERVED_NON_PROJECTS: + ref.project = parts[1] + if len(parts) > 3 and parts[2] == "runs": + ref.ref_type = ReferenceType.RUN + ref.run_id = parts[3] + elif ( + len(parts) > 4 + and parts[2] == "artifacts" + and parts[3] == "job" + ): + ref.ref_type = ReferenceType.JOB + ref.job_name = parts[4] + if len(parts) > 5 and parts[5] not in RESERVED_JOB_PATHS: + ref.job_alias = parts[5] + # TODO: Right now we are not tracking selection as part of URL state in the Jobs tab. + # If that changes we'll want to update this. + + return ref + + @staticmethod + def is_uri_job_or_run(uri: str) -> bool: + ref = WandbReference.parse(uri) + if ref and ref.is_job_or_run(): + return True + return False diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4289765c6c7c4fda2dbe42dddc1f5f7d69da0c45 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/__pycache__/capped_dict.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/__pycache__/capped_dict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e9fb3a0567a7d6d9950cb3ef55ac74b43cdbf8a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/__pycache__/capped_dict.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/apikey.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/apikey.py new file mode 100644 index 0000000000000000000000000000000000000000..f30e791de800d4d4996b403d163ac9c0a4af9f45 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/apikey.py @@ -0,0 +1,334 @@ +"""apikey util.""" + +from __future__ import annotations + +import dataclasses +import os +import platform +import stat +import sys +import textwrap +from functools import partial + +# import Literal +from typing import TYPE_CHECKING, Callable, Literal +from urllib.parse import urlparse + +import click +from requests.utils import NETRC_FILES, get_netrc_auth + +import wandb +from wandb.apis import InternalApi +from wandb.errors import term +from wandb.errors.links import url_registry +from wandb.sdk import wandb_setup +from wandb.util import _is_databricks, isatty, prompt_choices + +if TYPE_CHECKING: + from wandb.sdk.wandb_settings import Settings + +LOGIN_CHOICE_ANON = "Private W&B dashboard, no account required" +LOGIN_CHOICE_NEW = "Create a W&B account" +LOGIN_CHOICE_EXISTS = "Use an existing W&B account" +LOGIN_CHOICE_DRYRUN = "Don't visualize my results" +LOGIN_CHOICE_NOTTY = "Unconfigured" +LOGIN_CHOICES = [ + LOGIN_CHOICE_ANON, + LOGIN_CHOICE_NEW, + LOGIN_CHOICE_EXISTS, + LOGIN_CHOICE_DRYRUN, +] + + +@dataclasses.dataclass(frozen=True) +class _NetrcPermissions: + exists: bool + read_access: bool + write_access: bool + + +class WriteNetrcError(Exception): + """Raised when we cannot write to the netrc file.""" + + +Mode = Literal["allow", "must", "never", "false", "true"] + + +getpass = partial(click.prompt, hide_input=True, err=True) + + +def _fixup_anon_mode(default: Mode | None) -> Mode | None: + # Convert weird anonymode values from legacy settings files + # into one of our expected values. + anon_mode = default or "never" + mapping: dict[Mode, Mode] = {"true": "allow", "false": "never"} + return mapping.get(anon_mode, anon_mode) + + +def get_netrc_file_path() -> str: + """Return the path to the netrc file.""" + # if the NETRC environment variable is set, use that + netrc_file = os.environ.get("NETRC") + if netrc_file: + return os.path.expanduser(netrc_file) + + # if either .netrc or _netrc exists in the home directory, use that + for netrc_file in NETRC_FILES: + home_dir = os.path.expanduser("~") + if os.path.exists(os.path.join(home_dir, netrc_file)): + return os.path.join(home_dir, netrc_file) + + # otherwise, use .netrc on non-Windows platforms and _netrc on Windows + netrc_file = ".netrc" if platform.system() != "Windows" else "_netrc" + + return os.path.join(os.path.expanduser("~"), netrc_file) + + +def _api_key_prompt_str(app_url: str, referrer: str | None = None) -> str: + """Generate a prompt string for API key authorization. + + Creates a URL string that directs users to the authorization page where they + can find their API key. + + Args: + app_url: The base URL of the W&B application. + referrer: Optional referrer parameter to include in the URL. + + Returns: + A formatted string with instructions and the authorization URL. + """ + ref = "" + if referrer: + ref = f"?ref={referrer}" + return f"You can find your API key in your browser here: {app_url}/authorize{ref}" + + +def prompt_api_key( # noqa: C901 + settings: Settings, + api: InternalApi | None = None, + input_callback: Callable | None = None, + browser_callback: Callable | None = None, + no_offline: bool = False, + no_create: bool = False, + local: bool = False, + referrer: str | None = None, +) -> str | bool | None: + """Prompt for api key. + + Returns: + str - if key is configured + None - if dryrun is selected + False - if unconfigured (notty) + """ + input_callback = input_callback or getpass + log_string = term.LOG_STRING + api = api or InternalApi(settings) + anon_mode = _fixup_anon_mode(settings.anonymous) # type: ignore + jupyter = settings._jupyter or False + app_url = api.app_url + + choices = [choice for choice in LOGIN_CHOICES] + if anon_mode == "never": + # Omit LOGIN_CHOICE_ANON as a choice if the env var is set to never + choices.remove(LOGIN_CHOICE_ANON) + if (jupyter and not settings.login_timeout) or no_offline: + choices.remove(LOGIN_CHOICE_DRYRUN) + if (jupyter and not settings.login_timeout) or no_create: + choices.remove(LOGIN_CHOICE_NEW) + + if jupyter and "google.colab" in sys.modules: + log_string = term.LOG_STRING_NOCOLOR + key = wandb.jupyter.attempt_colab_login(app_url) # type: ignore + if key is not None: + return key # type: ignore + + if anon_mode == "must": + result = LOGIN_CHOICE_ANON + # If we're not in an interactive environment, default to dry-run. + elif ( + not jupyter and (not isatty(sys.stdout) or not isatty(sys.stdin)) + ) or _is_databricks(): + result = LOGIN_CHOICE_NOTTY + elif local: + result = LOGIN_CHOICE_EXISTS + elif len(choices) == 1: + result = choices[0] + else: + result = prompt_choices( + choices, input_timeout=settings.login_timeout, jupyter=jupyter + ) + + key = None + api_ask = ( + f"{log_string}: Paste an API key from your profile and hit enter" + if jupyter + else f"{log_string}: Paste an API key from your profile and hit enter, or press ctrl+c to quit" + ) + if result == LOGIN_CHOICE_ANON: + key = api.create_anonymous_api_key() + elif result == LOGIN_CHOICE_NEW: + key = browser_callback(signup=True) if browser_callback else None + + if not key: + ref = f"&ref={referrer}" if referrer else "" + wandb.termlog( + f"Create an account here: {app_url}/authorize?signup=true{ref}" + ) + key = input_callback(api_ask).strip() + elif result == LOGIN_CHOICE_EXISTS: + key = browser_callback() if browser_callback else None + + if not key: + if not (settings.is_local or local): + host = app_url + for prefix in ("http://", "https://"): + if app_url.startswith(prefix): + host = app_url[len(prefix) :] + wandb.termlog( + f"Logging into {host}. (Learn how to deploy a W&B server " + f"locally: {url_registry.url('wandb-server')})" + ) + wandb.termlog(_api_key_prompt_str(app_url, referrer)) + key = input_callback(api_ask).strip() + elif result == LOGIN_CHOICE_NOTTY: + # TODO: Needs refactor as this needs to be handled by caller + return False + elif result == LOGIN_CHOICE_DRYRUN: + return None + else: + # Jupyter environments don't have a tty, but we can still try logging in using + # the browser callback if one is supplied. + key, anonymous = ( + browser_callback() if jupyter and browser_callback else (None, False) + ) + + if not key: + raise ValueError("No API key specified.") + return key + + +def check_netrc_access( + netrc_path: str, +) -> _NetrcPermissions: + """Check if we can read and write to the netrc file.""" + file_exists = False + write_access = False + read_access = False + try: + st = os.stat(netrc_path) + file_exists = True + write_access = bool(st.st_mode & stat.S_IWUSR) + read_access = bool(st.st_mode & stat.S_IRUSR) + except FileNotFoundError: + # If the netrc file doesn't exist, we will create it. + write_access = True + read_access = True + except OSError as e: + wandb.termerror(f"Unable to read permissions for {netrc_path}, {e}") + + return _NetrcPermissions( + exists=file_exists, + write_access=write_access, + read_access=read_access, + ) + + +def write_netrc(host: str, entity: str, key: str): + """Add our host and key to .netrc.""" + _, key_suffix = key.split("-", 1) if "-" in key else ("", key) + if len(key_suffix) != 40: + raise ValueError( + f"API-key must be exactly 40 characters long: {key_suffix} ({len(key_suffix)} chars)" + ) + + normalized_host = urlparse(host).netloc + netrc_path = get_netrc_file_path() + netrc_access = check_netrc_access(netrc_path) + + if not netrc_access.write_access or not netrc_access.read_access: + raise WriteNetrcError( + f"Cannot access {netrc_path}. In order to persist your API key, " + "grant read and write permissions for your user to the file " + 'or specify a different file with the environment variable "NETRC=".' + ) + + machine_line = f"machine {normalized_host}" + orig_lines = None + try: + with open(netrc_path) as f: + orig_lines = f.read().strip().split("\n") + except FileNotFoundError: + wandb.termlog("No netrc file found, creating one.") + except OSError as e: + raise WriteNetrcError(f"Unable to read {netrc_path}") from e + + try: + with open(netrc_path, "w") as f: + if orig_lines: + # delete this machine from the file if it's already there. + skip = 0 + for line in orig_lines: + # we fix invalid netrc files with an empty host that we wrote before + # verifying host... + if line == "machine " or machine_line in line: + skip = 2 + elif skip: + skip -= 1 + else: + f.write(f"{line}\n") + + wandb.termlog( + f"Appending key for {normalized_host} to your netrc file: {netrc_path}" + ) + f.write( + textwrap.dedent( + """\ + machine {host} + login {entity} + password {key} + """ + ).format(host=normalized_host, entity=entity, key=key) + ) + os.chmod(netrc_path, stat.S_IRUSR | stat.S_IWUSR) + except OSError as e: + raise WriteNetrcError(f"Unable to write {netrc_path}") from e + + +def write_key( + settings: Settings, + key: str | None, + api: InternalApi | None = None, +) -> None: + if not key: + raise ValueError("No API key specified.") + + # TODO(jhr): api shouldn't be optional or it shouldn't be passed, clean up callers + api = api or InternalApi() + + # Normal API keys are 40-character hex strings. On-prem API keys have a + # variable-length prefix, a dash, then the 40-char string. + _, suffix = key.split("-", 1) if "-" in key else ("", key) + + if len(suffix) != 40: + raise ValueError(f"API key must be 40 characters long, yours was {len(key)}") + + write_netrc(settings.base_url, "user", key) + + +def api_key(settings: Settings | None = None) -> str | None: + if settings is None: + settings = wandb_setup.singleton().settings + if settings.api_key: + return settings.api_key + + netrc_access = check_netrc_access(get_netrc_file_path()) + if netrc_access.exists and not netrc_access.read_access: + wandb.termwarn(f"Cannot access {get_netrc_file_path()}.") + return None + + if netrc_access.exists: + auth = get_netrc_auth(settings.base_url) + if auth: + return auth[-1] + + return None diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_compat.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..b35c8e75b6c479e2a51f8073c552affc604d9a07 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/asyncio_compat.py @@ -0,0 +1,213 @@ +"""Functions for compatibility with asyncio.""" + +from __future__ import annotations + +import asyncio +import concurrent +import concurrent.futures +import contextlib +import threading +from typing import Any, AsyncIterator, Callable, Coroutine, Iterator, 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 = _Runner() + future = executor.submit(runner.run, fn) + + try: + return future.result() + + finally: + runner.cancel() + + +class _RunnerCancelledError(Exception): + """The `_Runner.run()` invocation was cancelled.""" + + +class _Runner: + """Runs an asyncio event loop allowing cancellation. + + This is like `asyncio.run()`, except it provides a `cancel()` method + meant to be called in a `finally` block. + + Without this, it is impossible to make `asyncio.run()` stop if it runs + in a non-main thread. In particular, a KeyboardInterrupt causes the + ThreadPoolExecutor above to block until the asyncio thread completes, + but there is no way to tell the asyncio thread to cancel its work. + A second KeyboardInterrupt makes ThreadPoolExecutor give up while the + asyncio thread still runs in the background, with terrible effects if it + prints to the user's terminal. + """ + + def __init__(self) -> None: + self._lock = threading.Lock() + + self._is_cancelled = False + self._started = False + self._done = False + + self._loop: asyncio.AbstractEventLoop | None = None + self._cancel_event: asyncio.Event | None = None + + def run(self, fn: Callable[[], Coroutine[Any, Any, _T]]) -> _T: + """Run a coroutine in asyncio, cancelling it on `cancel()`. + + Returns: + The result of the coroutine returned by `fn`. + + Raises: + _RunnerCancelledError: If `cancel()` is called. + """ + return asyncio.run(self._run_or_cancel(fn)) + + async def _run_or_cancel( + self, + fn: Callable[[], Coroutine[Any, Any, _T]], + ) -> _T: + with self._lock: + if self._is_cancelled: + raise _RunnerCancelledError() + + self._loop = asyncio.get_running_loop() + self._cancel_event = asyncio.Event() + self._started = True + + cancellation_task = asyncio.create_task(self._cancel_event.wait()) + fn_task = asyncio.create_task(fn()) + + try: + await asyncio.wait( + [cancellation_task, fn_task], + return_when=asyncio.FIRST_COMPLETED, + ) + + if fn_task.done(): + return fn_task.result() + else: + raise _RunnerCancelledError() + + finally: + # NOTE: asyncio.run() cancels all tasks after the main task exits, + # but this is not documented, so we cancel them explicitly here + # as well. It also blocks until canceled tasks complete. + cancellation_task.cancel() + fn_task.cancel() + + with self._lock: + self._done = True + + def cancel(self) -> None: + """Cancel all asyncio work started by `run()`.""" + with self._lock: + if self._is_cancelled: + return + self._is_cancelled = True + + if self._done or not self._started: + # If the runner already finished, no need to cancel it. + # + # If the runner hasn't started the loop yet, then it will not + # as we already set _is_cancelled. + return + + assert self._loop + assert self._cancel_event + self._loop.call_soon_threadsafe(self._cancel_event.set) + + +class TaskGroup: + """Object that `open_task_group()` yields.""" + + def __init__(self) -> None: + self._tasks: list[asyncio.Task] = [] + + def start_soon(self, coro: Coroutine[Any, Any, Any]) -> None: + """Schedule a task in the group. + + Args: + coro: The return value of the `async` function defining the task. + """ + self._tasks.append(asyncio.create_task(coro)) + + async def _wait_all(self) -> None: + """Block until all tasks complete. + + Raises: + Exception: If one or more tasks raises an exception, one of these + is raised arbitrarily. + """ + done, _ = await asyncio.wait( + self._tasks, + # NOTE: Cancelling a task counts as a normal exit, + # not an exception. + return_when=concurrent.futures.FIRST_EXCEPTION, + ) + + for task in done: + try: + if exc := task.exception(): + raise exc + except asyncio.CancelledError: + pass + + def _cancel_all(self) -> None: + """Cancel all tasks.""" + for task in self._tasks: + # NOTE: It is safe to cancel tasks that have already completed. + task.cancel() + + +@contextlib.asynccontextmanager +async def open_task_group() -> 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 . + """ + task_group = TaskGroup() + + try: + yield task_group + await task_group._wait_all() + finally: + task_group._cancel_all() + + +@contextlib.contextmanager +def cancel_on_exit(coro: Coroutine[Any, Any, Any]) -> Iterator[None]: + """Schedule a task, cancelling it when exiting the context manager. + + If the given coroutine raises an exception, that exception is raised + when exiting the context manager. + """ + task = asyncio.create_task(coro) + + try: + yield + finally: + if task.done() and (exception := task.exception()): + raise exception + + task.cancel() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/capped_dict.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/capped_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..5e162109926cf7c115bf835323de4d292f8725e8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/capped_dict.py @@ -0,0 +1,26 @@ +import collections +from typing import Any, Optional + + +class CappedDict(collections.OrderedDict): + default_max_size = 50 + + def __init__(self, max_size: Optional[int] = None) -> None: + self.max_size = max_size or self.default_max_size + super().__init__() + + def __setitem__(self, key: str, val: Any) -> None: + if key not in self: + max_size = self.max_size - 1 + self._prune_dict(max_size) + super().__setitem__(key, val) + + def update(self, **kwargs: Any) -> None: # type: ignore[override] + super().update(**kwargs) + self._prune_dict(self.max_size) + + def _prune_dict(self, max_size: int) -> None: + if len(self) >= max_size: + diff = len(self) - max_size + for k in list(self.keys())[:diff]: + del self[k] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/console_capture.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/console_capture.py new file mode 100644 index 0000000000000000000000000000000000000000..f9d56af0d74f518969de5a8c62811b30d49e36b6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/console_capture.py @@ -0,0 +1,219 @@ +"""Module for intercepting stdout/stderr. + +This patches the `write()` method of `stdout` and `stderr` on import. +Once patched, it is not possible to unpatch or repatch, though individual +callbacks can be removed. + +We assume that all other writing methods on the object delegate to `write()`, +like `writelines()`. This is not guaranteed to be true, but it is true for +common implementations. In particular, CPython's implementation of IOBase's +`writelines()` delegates to `write()`. + +It is important to note that this technique interacts poorly with other +code that performs similar patching if it also allows unpatching as this +discards our modification. This is why we patch on import and do not support +unpatching: + + with contextlib.redirect_stderr(...): + from ... import console_capture + # Here, everything works fine. + # Here, callbacks are never called again. + +In particular, it does not work with some combinations of pytest's +`capfd` / `capsys` fixtures and pytest's `--capture` option. +""" + +from __future__ import annotations + +import logging +import sys +import threading +from typing import IO, AnyStr, Callable, Protocol + +from . import wb_logging + +_logger = logging.getLogger(__name__) + + +class CannotCaptureConsoleError(Exception): + """The module failed to patch stdout or stderr.""" + + +class _WriteCallback(Protocol): + """A callback that receives intercepted bytes or string data. + + This may be called from any thread, but is only called from one thread + at a time. + + Note on errors: Any error raised during the callback will clear all + callbacks. This means that if a user presses Ctrl-C at an unlucky time + during a run, we will stop uploading console output---but it's not + likely to be a problem unless something catches the KeyboardInterrupt. + + Regular Exceptions are caught and logged instead of bubbling up to the + user's print() statements; other exceptions like KeyboardInterrupt are + re-raised. + + Callbacks should handle all exceptions---a callback that raises any + Exception is considered buggy. + """ + + def __call__( + self, + data: bytes | str, + written: int, + /, + ) -> None: + """Intercept data passed to `write()`. + + See the protocol docstring for information about exceptions. + + Args: + data: The object passed to stderr's or stdout's `write()`. + written: The number of bytes or characters written. + This is the return value of `write()`. + """ + + +# A reentrant lock is used to catch callbacks that write to stderr/stdout. +_module_rlock = threading.RLock() +_is_writing = False + +_patch_exception: CannotCaptureConsoleError | None = None + +_next_callback_id: int = 1 + +_stdout_callbacks: dict[int, _WriteCallback] = {} +_stderr_callbacks: dict[int, _WriteCallback] = {} + + +def capture_stdout(callback: _WriteCallback) -> Callable[[], None]: + """Install a callback that runs after every write to sys.stdout. + + Args: + callback: A callback to invoke after running `sys.stdout.write`. + + Returns: + A function to uninstall the callback. + + Raises: + CannotCaptureConsoleError: If patching failed on import. + """ + with _module_rlock: + if _patch_exception: + raise _patch_exception + + return _insert_disposably( + _stdout_callbacks, + callback, + ) + + +def capture_stderr(callback: _WriteCallback) -> Callable[[], None]: + """Install a callback that runs after every write to sys.sdterr. + + Args: + callback: A callback to invoke after running `sys.stderr.write`. + + Returns: + A function to uninstall the callback. + + Raises: + CannotCaptureConsoleError: If patching failed on import. + """ + with _module_rlock: + if _patch_exception: + raise _patch_exception + + return _insert_disposably( + _stderr_callbacks, + callback, + ) + + +def _insert_disposably( + callback_dict: dict[int, _WriteCallback], + callback: _WriteCallback, +) -> Callable[[], None]: + global _next_callback_id + id = _next_callback_id + _next_callback_id += 1 + + disposed = False + + def dispose() -> None: + nonlocal disposed + + with _module_rlock: + if disposed: + return + + callback_dict.pop(id, None) + + disposed = True + + callback_dict[id] = callback + return dispose + + +def _patch( + stdout_or_stderr: IO[AnyStr], + callbacks: dict[int, _WriteCallback], +) -> None: + orig_write: Callable[[AnyStr], int] + + @wb_logging.log_to_all_runs() + def write_with_callbacks(s: AnyStr, /) -> int: + global _is_writing + n = orig_write(s) + + # NOTE: Since _module_rlock is reentrant, this is safe. It will not + # deadlock if a callback invokes write() again. + with _module_rlock: + if _is_writing: + return n + + _is_writing = True + try: + for cb in callbacks.values(): + cb(s, n) + + except BaseException as e: + # Clear all callbacks on any exception to avoid infinite loops: + # + # * If we re-raise, an exception handler is likely to print + # the exception to the console and trigger callbacks again + # * If we log, we can't guarantee that this doesn't print + # to console. + # + # This is especially important for KeyboardInterrupt. + _stderr_callbacks.clear() + _stdout_callbacks.clear() + + if isinstance(e, Exception): + # We suppress Exceptions so that bugs in W&B code don't + # cause the user's print() statements to raise errors. + _logger.exception("Error in console callback, clearing all!") + else: + # Re-raise errors like KeyboardInterrupt. + raise + + finally: + _is_writing = False + + return n + + orig_write = stdout_or_stderr.write + + # mypy==1.14.1 fails to type-check this: + # Incompatible types in assignment (expression has type + # "Callable[[bytes], int]", variable has type overloaded function) + stdout_or_stderr.write = write_with_callbacks # type: ignore + + +try: + _patch(sys.stdout, _stdout_callbacks) + _patch(sys.stderr, _stderr_callbacks) +except Exception as _patch_exception_cause: + _patch_exception = CannotCaptureConsoleError() + _patch_exception.__cause__ = _patch_exception_cause diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/credentials.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/credentials.py new file mode 100644 index 0000000000000000000000000000000000000000..422cf0efe6e219c9edd38f8edd7a8d23b9c89d9d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/credentials.py @@ -0,0 +1,141 @@ +import json +import os +from datetime import datetime, timedelta +from pathlib import Path + +import requests.utils + +from wandb.errors import AuthenticationError + +DEFAULT_WANDB_CREDENTIALS_FILE = Path( + os.path.expanduser("~/.config/wandb/credentials.json") +) + +_expires_at_fmt = "%Y-%m-%d %H:%M:%S" + + +def access_token(base_url: str, token_file: Path, credentials_file: Path) -> str: + """Retrieve an access token from the credentials file. + + If no access token exists, create a new one by exchanging the identity + token from the token file, and save it to the credentials file. + + Args: + base_url (str): The base URL of the server + token_file (pathlib.Path): The path to the file containing the + identity token + credentials_file (pathlib.Path): The path to file used to save + temporary access tokens + + Returns: + str: The access token + """ + if not credentials_file.exists(): + _write_credentials_file(base_url, token_file, credentials_file) + + data = _fetch_credentials(base_url, token_file, credentials_file) + return data["access_token"] + + +def _write_credentials_file(base_url: str, token_file: Path, credentials_file: Path): + """Obtain an access token from the server and write it to the credentials file. + + Args: + base_url (str): The base URL of the server + token_file (pathlib.Path): The path to the file containing the + identity token + credentials_file (pathlib.Path): The path to file used to save + temporary access tokens + """ + credentials = _create_access_token(base_url, token_file) + data = {"credentials": {base_url: credentials}} + with open(credentials_file, "w") as file: + json.dump(data, file, indent=4) + + # Set file permissions to be read/write by the owner only + os.chmod(credentials_file, 0o600) + + +def _fetch_credentials(base_url: str, token_file: Path, credentials_file: Path) -> dict: + """Fetch the access token from the credentials file. + + If the access token has expired, fetch a new one from the server and save it + to the credentials file. + + Args: + base_url (str): The base URL of the server + token_file (pathlib.Path): The path to the file containing the + identity token + credentials_file (pathlib.Path): The path to file used to save + temporary access tokens + + Returns: + dict: The credentials including the access token. + """ + creds = {} + with open(credentials_file) as file: + data = json.load(file) + if "credentials" not in data: + data["credentials"] = {} + if base_url in data["credentials"]: + creds = data["credentials"][base_url] + + expires_at = datetime.utcnow() + if "expires_at" in creds: + expires_at = datetime.strptime(creds["expires_at"], _expires_at_fmt) + + if expires_at <= datetime.utcnow(): + creds = _create_access_token(base_url, token_file) + with open(credentials_file, "w") as file: + data["credentials"][base_url] = creds + json.dump(data, file, indent=4) + + return creds + + +def _create_access_token(base_url: str, token_file: Path) -> dict: + """Exchange an identity token for an access token from the server. + + Args: + base_url (str): The base URL of the server. + token_file (pathlib.Path): The path to the file containing the + identity token + + Returns: + dict: The access token and its expiration. + + Raises: + FileNotFoundError: If the token file is not found. + OSError: If there is an issue reading the token file. + AuthenticationError: If the server fails to provide an access token. + """ + try: + with open(token_file) as file: + token = file.read().strip() + except FileNotFoundError as e: + raise FileNotFoundError(f"Identity token file not found: {token_file}") from e + except OSError as e: + raise OSError( + f"Failed to read the identity token from file: {token_file}" + ) from e + + url = f"{base_url}/oidc/token" + data = { + "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", + "assertion": token, + } + headers = {"Content-Type": "application/x-www-form-urlencoded"} + + response = requests.post(url, data=data, headers=headers) + + if response.status_code != 200: + raise AuthenticationError( + f"Failed to retrieve access token: {response.status_code}, {response.text}" + ) + + resp_json = response.json() + expires_at = datetime.utcnow() + timedelta(seconds=float(resp_json["expires_in"])) + resp_json["expires_at"] = expires_at.strftime(_expires_at_fmt) + del resp_json["expires_in"] + + return resp_json diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/deprecate.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/deprecate.py new file mode 100644 index 0000000000000000000000000000000000000000..29eb633ce036717d1e566752779e93bf6bcb6623 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/deprecate.py @@ -0,0 +1,27 @@ +from __future__ import annotations + +import wandb +from wandb.proto.wandb_deprecated import DEPRECATED_FEATURES +from wandb.sdk.lib import telemetry + + +def deprecate( + field_name: DEPRECATED_FEATURES, + warning_message: str, + run: wandb.Run | None = None, +) -> None: + """Warn the user that a feature has been deprecated. + + If a run is provided, the given field on its telemetry is updated. + Otherwise, the global run is used. + + Args: + field_name: The field on the Deprecated proto for this deprecation. + warning_message: The message to display to the user. + run: The run whose telemetry to update. + """ + _run = run or wandb.run + with telemetry.context(run=_run) as tel: + setattr(tel.deprecated, field_name, True) + + wandb.termwarn(warning_message, repeat=False) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/disabled.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/disabled.py new file mode 100644 index 0000000000000000000000000000000000000000..9c2a9b2f49b9a77c903ab742125cd69b9aac4cf9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/disabled.py @@ -0,0 +1,30 @@ +from typing import Any + +from wandb.proto.wandb_deprecated import Deprecated +from wandb.sdk.lib import deprecate + + +class SummaryDisabled(dict): + __setattr__ = dict.__setitem__ + __delattr__ = dict.__delitem__ + + def __getattr__(self, key): + return self[key] + + def __getitem__(self, key): + val = dict.__getitem__(self, key) + if isinstance(val, dict) and not isinstance(val, SummaryDisabled): + val = SummaryDisabled(val) + self[key] = val + return val + + +class RunDisabled: + """Compatibility class for integrations that explicitly check for wandb.RunDisabled.""" + + def __getattr__(self, name: str) -> Any: + deprecate.deprecate( + field_name=Deprecated.run_disabled, + warning_message="RunDisabled is deprecated and is a no-op. " + '`wandb.init(mode="disabled")` now returns an instance of `wandb.Run`.', + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/exit_hooks.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/exit_hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..aa747495299a646041f7deaeb72c1a9bcc050660 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/exit_hooks.py @@ -0,0 +1,54 @@ +import sys +import traceback +from types import TracebackType +from typing import TYPE_CHECKING, Optional, Type + +import wandb +from wandb.errors import Error + +if TYPE_CHECKING: + from typing import NoReturn + + +class ExitHooks: + exception: Optional[BaseException] = None + + def __init__(self) -> None: + self.exit_code = 0 + self.exception = None + + def hook(self) -> None: + self._orig_exit = sys.exit + sys.exit = self.exit + self._orig_excepthook = ( + sys.excepthook + if sys.excepthook + != sys.__excepthook__ # respect hooks by other libraries like pdb + else None + ) + sys.excepthook = self.exc_handler # type: ignore + + def exit(self, code: object = 0) -> "NoReturn": + orig_code = code + code = code if code is not None else 0 + code = code if isinstance(code, int) else 1 + self.exit_code = code + self._orig_exit(orig_code) # type: ignore + + def was_ctrl_c(self) -> bool: + return isinstance(self.exception, KeyboardInterrupt) + + def exc_handler( + self, exc_type: Type[BaseException], exc: BaseException, tb: TracebackType + ) -> None: + self.exit_code = 1 + self.exception = exc + if issubclass(exc_type, Error): + wandb.termerror(str(exc), repeat=False) + + if self.was_ctrl_c(): + self.exit_code = 255 + + traceback.print_exception(exc_type, exc, tb) + if self._orig_excepthook: + self._orig_excepthook(exc_type, exc, tb) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/file_stream_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/file_stream_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b7420b99706f8cd413da35b50ab76c1bd1e8fce6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/file_stream_utils.py @@ -0,0 +1,118 @@ +# +from typing import Any, Dict, Iterable + + +def split_files( + files: Dict[str, Any], max_bytes: int = 10 * 1024 * 1024 +) -> Iterable[Dict[str, Dict]]: + """Split a file's dict (see `files` arg) into smaller dicts. + + Each smaller dict will have at most `MAX_BYTES` size. + + This method is used in `FileStreamAPI._send()` to limit the size of post requests + sent to wandb server. + + Args: + files (dict): `dict` of form {file_name: {'content': ".....", 'offset': 0}} + The key `file_name` can also be mapped to a List [{"offset": int, "content": str}] + `max_bytes`: max size for chunk in bytes + """ + current_volume: Dict[str, Dict] = {} + current_size = 0 + + def _str_size(x): + return len(x) if isinstance(x, bytes) else len(x.encode("utf-8")) + + def _file_size(file): + size = file.get("_size") + if size is None: + size = sum(map(_str_size, file["content"])) + file["_size"] = size + return size + + def _split_file(file, num_lines): + offset = file["offset"] + content = file["content"] + name = file["name"] + f1 = {"offset": offset, "content": content[:num_lines], "name": name} + f2 = { + "offset": offset + num_lines, + "content": content[num_lines:], + "name": name, + } + return f1, f2 + + def _num_lines_from_num_bytes(file, num_bytes): + size = 0 + num_lines = 0 + content = file["content"] + while num_lines < len(content): + size += _str_size(content[num_lines]) + if size > num_bytes: + break + num_lines += 1 + return num_lines + + files_stack = [] + for k, v in files.items(): + if isinstance(v, list): + for item in v: + files_stack.append( + {"name": k, "offset": item["offset"], "content": item["content"]} + ) + else: + files_stack.append( + {"name": k, "offset": v["offset"], "content": v["content"]} + ) + + while files_stack: + f = files_stack.pop() + if f["name"] in current_volume: + files_stack.append(f) + yield current_volume + current_volume = {} + current_size = 0 + continue + # For each file, we have to do 1 of 4 things: + # - Add the file as such to the current volume if possible. + # - Split the file and add the first part to the current volume and push the second part back onto the stack. + # - If that's not possible, check if current volume is empty: + # - If empty, add first line of file to current volume and push rest onto stack (This volume will exceed MAX_MB). + # - If not, push file back to stack and yield current volume. + fsize = _file_size(f) + rem = max_bytes - current_size + if fsize <= rem: + current_volume[f["name"]] = { + "offset": f["offset"], + "content": f["content"], + } + current_size += fsize + else: + num_lines = _num_lines_from_num_bytes(f, rem) + if not num_lines and not current_volume: + num_lines = 1 + if num_lines: + f1, f2 = _split_file(f, num_lines) + current_volume[f1["name"]] = { + "offset": f1["offset"], + "content": f1["content"], + } + files_stack.append(f2) + yield current_volume + current_volume = {} + current_size = 0 + continue + else: + files_stack.append(f) + yield current_volume + current_volume = {} + current_size = 0 + continue + if current_size >= max_bytes: + yield current_volume + current_volume = {} + current_size = 0 + continue + + if current_volume: + yield current_volume diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/filenames.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/filenames.py new file mode 100644 index 0000000000000000000000000000000000000000..c272b7a2c3337ddb6d91ce03ed800e84affcc5ff --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/filenames.py @@ -0,0 +1,64 @@ +import os +from typing import Callable, Generator, Union + +WANDB_DIRS = ("wandb", ".wandb") + +CONFIG_FNAME = "config.yaml" +OUTPUT_FNAME = "output.log" +DIFF_FNAME = "diff.patch" +SUMMARY_FNAME = "wandb-summary.json" +METADATA_FNAME = "wandb-metadata.json" +REQUIREMENTS_FNAME = "requirements.txt" +HISTORY_FNAME = "wandb-history.jsonl" +EVENTS_FNAME = "wandb-events.jsonl" +JOBSPEC_FNAME = "wandb-jobspec.json" +CONDA_ENVIRONMENTS_FNAME = "conda-environment.yaml" + + +def is_wandb_file(name: str) -> bool: + return ( + name.startswith("wandb") + or name == METADATA_FNAME + or name == CONFIG_FNAME + or name == REQUIREMENTS_FNAME + or name == OUTPUT_FNAME + or name == DIFF_FNAME + or name == CONDA_ENVIRONMENTS_FNAME + ) + + +def filtered_dir( + root: str, + include_fn: Union[Callable[[str, str], bool], Callable[[str], bool]], + exclude_fn: Union[Callable[[str, str], bool], Callable[[str], bool]], +) -> Generator[str, None, None]: + """Simple generator to walk a directory.""" + import inspect + + # compatibility with old API, which didn't pass root + def _include_fn(path: str, root: str) -> bool: + return ( + include_fn(path, root) # type: ignore + if len(inspect.signature(include_fn).parameters) == 2 + else include_fn(path) # type: ignore + ) + + def _exclude_fn(path: str, root: str) -> bool: + return ( + exclude_fn(path, root) # type: ignore + if len(inspect.signature(exclude_fn).parameters) == 2 + else exclude_fn(path) # type: ignore + ) + + for dirpath, _, files in os.walk(root): + for fname in files: + file_path = os.path.join(dirpath, fname) + if _include_fn(file_path, root) and not _exclude_fn(file_path, root): + yield file_path + + +def exclude_wandb_fn(path: str, root: str) -> bool: + return any( + os.path.relpath(path, root).startswith(wandb_dir + os.sep) + for wandb_dir in WANDB_DIRS + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/filesystem.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/filesystem.py new file mode 100644 index 0000000000000000000000000000000000000000..180ebbb2c19aaa522e9d839141c9c0a740666117 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/filesystem.py @@ -0,0 +1,372 @@ +import contextlib +import ctypes +import errno +import logging +import os +import platform +import re +import shutil +import tempfile +import threading +from pathlib import Path +from typing import IO, Any, BinaryIO, Generator, Optional + +from wandb.sdk.lib.paths import StrPath + +logger = logging.getLogger(__name__) + +# https://en.wikipedia.org/wiki/Filename#Comparison_of_filename_limitations +PROBLEMATIC_PATH_CHARS = "".join(chr(i) for i in range(32)) + ':"*<>?|' + + +def mkdir_exists_ok(dir_name: StrPath) -> None: + """Create `dir_name` and any parent directories if they don't exist. + + Raises: + FileExistsError: if `dir_name` exists and is not a directory. + PermissionError: if `dir_name` is not writable. + """ + try: + os.makedirs(dir_name, exist_ok=True) + except FileExistsError as e: + raise FileExistsError(f"{dir_name!s} exists and is not a directory") from e + except PermissionError as e: + raise PermissionError(f"{dir_name!s} is not writable") from e + + +def path_fallbacks(path: StrPath) -> Generator[str, None, None]: + """Yield variations of `path` that may exist on the filesystem. + + Return a sequence of paths that should be checked in order for existence or + create-ability. Essentially, keep replacing "suspect" characters until we run out. + """ + path = str(path) + root, tail = os.path.splitdrive(path) + yield os.path.join(root, tail) + for char in PROBLEMATIC_PATH_CHARS: + if char in tail: + tail = tail.replace(char, "-") + yield os.path.join(root, tail) + + +def mkdir_allow_fallback(dir_name: StrPath) -> StrPath: + """Create `dir_name`, removing invalid path characters if necessary. + + Returns: + The path to the created directory, which may not be the original path. + """ + for new_name in path_fallbacks(dir_name): + try: + os.makedirs(new_name, exist_ok=True) + if Path(new_name) != Path(dir_name): + logger.warning(f"Creating '{new_name}' instead of '{dir_name}'") + return Path(new_name) if isinstance(dir_name, Path) else new_name + except (ValueError, NotADirectoryError): + pass + except OSError as e: + if e.errno != 22: + raise + + raise OSError(f"Unable to create directory '{dir_name}'") + + +def files_in(path: StrPath) -> Generator[os.DirEntry, None, None]: + """Yield a directory entry for each file under a given path (recursive).""" + if not os.path.isdir(path): + return + for entry in os.scandir(path): + if entry.is_dir(): + yield from files_in(entry.path) + else: + yield entry + + +class WriteSerializingFile: + """Wrapper for a file object that serializes writes.""" + + def __init__(self, f: BinaryIO) -> None: + self.lock = threading.Lock() + self.f = f + + def write(self, *args, **kargs) -> None: # type: ignore + self.lock.acquire() + try: + self.f.write(*args, **kargs) + self.f.flush() + finally: + self.lock.release() + + def close(self) -> None: + self.lock.acquire() # wait for pending writes + try: + self.f.close() + finally: + self.lock.release() + + +class CRDedupedFile(WriteSerializingFile): + def __init__(self, f: BinaryIO) -> None: + super().__init__(f=f) + self._buff = b"" + + def write(self, data) -> None: # type: ignore + lines = re.split(b"\r\n|\n", data) + ret = [] # type: ignore + for line in lines: + if line[:1] == b"\r": + if ret: + ret.pop() + elif self._buff: + self._buff = b"" + line = line.split(b"\r")[-1] + if line: + ret.append(line) + if self._buff: + ret.insert(0, self._buff) + if ret: + self._buff = ret.pop() + super().write(b"\n".join(ret) + b"\n") + + def close(self) -> None: + if self._buff: + super().write(self._buff) + super().close() + + +def copy_or_overwrite_changed(source_path: StrPath, target_path: StrPath) -> StrPath: + """Copy source_path to target_path, unless it already exists with the same mtime. + + We liberally add write permissions to deal with the case of multiple users needing + to share the same cache or run directory. + + Args: + source_path: The path to the file to copy. + target_path: The path to copy the file to. + + Returns: + The path to the copied file (which may be different from target_path). + """ + return_type = type(target_path) + + target_path = system_preferred_path(target_path, warn=True) + + need_copy = ( + not os.path.isfile(target_path) + or os.stat(source_path).st_mtime != os.stat(target_path).st_mtime + ) + + permissions_plus_write = os.stat(source_path).st_mode + if need_copy: + dir_name, file_name = os.path.split(target_path) + target_path = os.path.join(mkdir_allow_fallback(dir_name), file_name) + try: + # Use copy2 to preserve file metadata (including modified time). + shutil.copy2(source_path, target_path) + except PermissionError: + # If the file is read-only try to make it writable. + try: + os.chmod(target_path, permissions_plus_write) + shutil.copy2(source_path, target_path) + except PermissionError as e: + raise PermissionError("Unable to overwrite '{target_path!s}'") from e + # Prevent future permissions issues by universal write permissions now. + os.chmod(target_path, permissions_plus_write) + + return return_type(target_path) # type: ignore # 'os.PathLike' is abstract. + + +@contextlib.contextmanager +def safe_open( + path: StrPath, mode: str = "r", *args: Any, **kwargs: Any +) -> Generator[IO, None, None]: + """Open a file, ensuring any changes only apply atomically after close. + + This context manager ensures that even unsuccessful writes will not leave a "dirty" + file or overwrite good data, and that all temp data is cleaned up. + + The semantics and behavior are intended to be nearly identical to the built-in + open() function. Differences: + - It creates any parent directories that don't exist, rather than raising. + - In 'x' mode, it checks at the beginning AND end of the write and fails if the + file exists either time. + """ + path = Path(path).resolve() + path.parent.mkdir(parents=True, exist_ok=True) + + if "x" in mode and path.exists(): + raise FileExistsError(f"{path!s} already exists") + + if "r" in mode and "+" not in mode: + # This is read-only, so we can just open the original file. + # TODO (hugh): create a reflink and read from that. + with path.open(mode, *args, **kwargs) as f: + yield f + return + + with tempfile.TemporaryDirectory(dir=path.parent) as tmp_dir: + tmp_path = Path(tmp_dir) / path.name + + if ("r" in mode or "a" in mode) and path.exists(): + # We need to copy the original file in order to support reads and appends. + # TODO (hugh): use reflinks to avoid the copy on platforms that support it. + shutil.copy2(path, tmp_path) + + with tmp_path.open(mode, *args, **kwargs) as f: + yield f + f.flush() + os.fsync(f.fileno()) + + if "x" in mode: + # Ensure that if another process has beaten us to writing the file we raise + # rather than overwrite. os.link() atomically creates a hard link to the + # target file and will raise FileExistsError if the target already exists. + os.link(tmp_path, path) + os.unlink(tmp_path) + else: + tmp_path.replace(path) + + +def safe_copy(source_path: StrPath, target_path: StrPath) -> StrPath: + """Copy a file atomically. + + Copying is not usually atomic, and on operating systems that allow multiple + writers to the same file, the result can get corrupted. If two writers copy + to the same file, the contents can become interleaved. + + We mitigate the issue somewhat by copying to a temporary file first and + then renaming. Renaming is atomic: if process 1 renames file A to X and + process 2 renames file B to X, then X will either contain the contents + of A or the contents of B, not some mixture of both. + """ + # TODO (hugh): check that there is enough free space. + output_path = Path(target_path).resolve() + output_path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(dir=output_path.parent) as tmp_dir: + tmp_path = (Path(tmp_dir) / Path(source_path).name).with_suffix(".tmp") + shutil.copy2(source_path, tmp_path) + tmp_path.replace(output_path) + return target_path + + +def _reflink_linux(existing_path: Path, new_path: Path) -> None: + """Create a reflink to `existing_path` at `new_path` on Linux.""" + import fcntl + + FICLONE = 0x40049409 # magic number from # noqa: N806 + with open(existing_path, "rb") as t_f, open(new_path, "wb+") as l_f: + fcntl.ioctl(l_f.fileno(), FICLONE, t_f.fileno()) + + +def _reflink_macos(existing_path: Path, new_path: Path) -> None: + try: + clib = ctypes.CDLL("libc.dylib", use_errno=True) + except (FileNotFoundError, OSError) as e: + if ctypes.get_errno() != errno.ENOENT and not isinstance(e, FileNotFoundError): + raise + # Before macOS 11 ( None: + """Create a reflink to `existing_path` at `new_path`. + + A reflink (reflective link) is a copy-on-write reference to a file. Once linked, the + file and link are both "real" files (not symbolic or hard links) and each can be + modified independently without affecting the other; however, they share the same + underlying data blocks on disk so until one is modified they are "zero-cost" copies. + + Reflinks have all the functionality of copies, so we should use them wherever they + are supported if we would otherwise copy a file. (This is not particularly radical-- + GNU `cp` defaults to `reflink=auto`, using it whenever available) However, support + for them is limited to a small number of filesystems. They should work on: + - Linux with a Btrfs or XFS filesystem (NOT ext4) + - macOS 10.13 or later with an APFS filesystem (called clone files) + + Reflinks are also supported on Solaris and Windows with ReFSv2, but we haven't + implemented support for them. + + Like hard links, a reflink can only be created on the same filesystem as the target. + """ + if platform.system() == "Linux": + link_fn = _reflink_linux + elif platform.system() == "Darwin": + link_fn = _reflink_macos + else: + raise OSError( + errno.ENOTSUP, f"reflinks are not supported on {platform.system()}" + ) + + new_path = Path(new_path).resolve() + existing_path = Path(existing_path).resolve() + if new_path.exists(): + if not overwrite: + raise FileExistsError(f"{new_path} already exists") + logger.warning(f"Overwriting existing file {new_path}.") + new_path.unlink() + + # Create any missing parent directories. + new_path.parent.mkdir(parents=True, exist_ok=True) + + try: + link_fn(existing_path, new_path) + except OSError as e: + base_msg = f"failed to create reflink from {existing_path} to {new_path}." + if e.errno in (errno.EPERM, errno.EACCES): + raise PermissionError(f"Insufficient permissions; {base_msg}") from e + if e.errno == errno.ENOENT: + raise FileNotFoundError(f"File not found; {base_msg}") from e + if e.errno == errno.EXDEV: + raise ValueError(f"Cannot link across filesystems; {base_msg}") from e + if e.errno == errno.EISDIR: + raise IsADirectoryError(f"Cannot reflink a directory; {base_msg}") from e + if e.errno in (errno.EOPNOTSUPP, errno.ENOTSUP): + raise OSError( + errno.ENOTSUP, + f"Filesystem does not support reflinks; {base_msg}", + ) from e + if e.errno == errno.EINVAL: + raise ValueError(f"Cannot link file ranges; {base_msg}") from e + raise + + +def check_exists(path: StrPath) -> Optional[StrPath]: + """Look for variations of `path` and return the first found. + + This exists to support former behavior around system-dependent paths; we used to use + ':' in Artifact paths unless we were on Windows, but this has issues when e.g. a + Linux machine is accessing an NTFS filesystem; we might need to look for the + alternate path. This checks all the possible directories we would consider creating. + """ + for dest in path_fallbacks(path): + if os.path.exists(dest): + return Path(dest) if isinstance(path, Path) else dest + return None + + +def system_preferred_path(path: StrPath, warn: bool = False) -> StrPath: + """Replace ':' with '-' in paths on Windows. + + Args: + path: The path to convert. + warn: Whether to warn if ':' is replaced. + """ + if platform.system() != "Windows": + return path + head, tail = os.path.splitdrive(path) + if warn and ":" in tail: + logger.warning(f"Replacing ':' in {tail} with '-'") + new_path = head + tail.replace(":", "-") + return Path(new_path) if isinstance(path, Path) else new_path diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/handler_util.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/handler_util.py new file mode 100644 index 0000000000000000000000000000000000000000..b4efd8d571baebab80f9a7702efdd962f0c9028d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/hashutil.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/hashutil.py new file mode 100644 index 0000000000000000000000000000000000000000..fe4b9a74ef705025bcd8ee005a9788b120699d23 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/hashutil.py @@ -0,0 +1,97 @@ +from __future__ import annotations + +import base64 +import hashlib +import logging +import mmap +import sys +import time +from typing import TYPE_CHECKING, NewType + +from wandb.sdk.lib.paths import StrPath + +if TYPE_CHECKING: + import _hashlib # type: ignore[import-not-found] + +ETag = NewType("ETag", str) +HexMD5 = NewType("HexMD5", str) +B64MD5 = NewType("B64MD5", str) + +logger = logging.getLogger(__name__) + + +def _md5(data: bytes = b"") -> _hashlib.HASH: + """Allow FIPS-compliant md5 hash when supported.""" + if sys.version_info >= (3, 9): + return hashlib.md5(data, usedforsecurity=False) + else: + return hashlib.md5(data) + + +def md5_string(string: str) -> B64MD5: + return _b64_from_hasher(_md5(string.encode("utf-8"))) + + +def _b64_from_hasher(hasher: _hashlib.HASH) -> B64MD5: + return B64MD5(base64.b64encode(hasher.digest()).decode("ascii")) + + +def b64_to_hex_id(string: B64MD5) -> HexMD5: + return HexMD5(base64.standard_b64decode(string).hex()) + + +def hex_to_b64_id(encoded_string: str | bytes) -> B64MD5: + if isinstance(encoded_string, bytes): + encoded_string = encoded_string.decode("utf-8") + as_str = bytes.fromhex(encoded_string) + return B64MD5(base64.standard_b64encode(as_str).decode("utf-8")) + + +def md5_file_b64(*paths: StrPath) -> B64MD5: + start_time = time.monotonic() + digest = _b64_from_hasher(_md5_file_hasher(*paths)) + hash_time_seconds = time.monotonic() - start_time + if hash_time_seconds > 1.0: + logger.debug( + "Computed MD5 hash for file. paths=%s, hashTimeMs=%d", + paths, + int(hash_time_seconds * 1000), + ) + return digest + + +def md5_file_hex(*paths: StrPath) -> HexMD5: + return HexMD5(_md5_file_hasher(*paths).hexdigest()) + + +_KB: int = 1_024 +_CHUNKSIZE: int = 128 * _KB +"""Chunk size (in bytes) for iteratively reading from file, if needed.""" + + +def _md5_file_hasher(*paths: StrPath) -> _hashlib.HASH: + md5_hash = _md5() + + # Note: We use str paths (instead of pathlib.Path objs) for minor perf improvements. + for path in sorted(map(str, paths)): + with open(path, "rb") as f: + try: + with mmap.mmap(f.fileno(), length=0, access=mmap.ACCESS_READ) as mview: + md5_hash.update(mview) + except OSError: + # This occurs if the mmap-ed file is on a different/mounted filesystem, + # so we'll fall back on a less performant implementation. + + # Note: At the time of implementation, the walrus operator `:=` + # is avoided to maintain support for users on python 3.7. + # Consider revisiting once 3.7 support is no longer needed. + chunk = f.read(_CHUNKSIZE) + while chunk: + md5_hash.update(chunk) + chunk = f.read(_CHUNKSIZE) + except ValueError: + # This occurs when mmap-ing an empty file, which can be skipped. + # See: https://github.com/python/cpython/blob/986a4e1b6fcae7fe7a1d0a26aea446107dd58dd2/Modules/mmapmodule.c#L1589 + pass + + return md5_hash diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/interrupt.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/interrupt.py new file mode 100644 index 0000000000000000000000000000000000000000..19cc0fe914674d1a328b278024c03efef8b61ad9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/lazyloader.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/lazyloader.py new file mode 100644 index 0000000000000000000000000000000000000000..0c7aec3f94ac6bab37154c3fb796ac0ac63ba9a4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/progress.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/progress.py new file mode 100644 index 0000000000000000000000000000000000000000..7ae1c6e1103faf4990a9df1e6a643b5e3bfee0dc --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/progress.py @@ -0,0 +1,320 @@ +"""Defines an object for printing run progress at the end of a script.""" + +from __future__ import annotations + +import asyncio +import contextlib +import time +from typing import Iterable, Iterator, NoReturn + +from wandb.proto import wandb_internal_pb2 as pb +from wandb.sdk.interface import interface +from wandb.sdk.lib import asyncio_compat + +from . import printer as p + + +async def loop_printing_operation_stats( + progress: ProgressPrinter, + interface: interface.InterfaceBase, +) -> None: + """Poll and display ongoing tasks in the internal service process. + + This never returns and must be cancelled. This is meant to be used with + `mailbox.wait_with_progress()`. + + Args: + progress: The printer to update with operation stats. + interface: The interface to use to poll for updates. + + Raises: + HandleAbandonedError: If the mailbox associated with the interface + becomes closed. + Exception: Any other problem communicating with the service process. + """ + stats: pb.OperationStats | None = None + + async def loop_update_screen() -> NoReturn: + while True: + if stats: + progress.update(stats) + await asyncio.sleep(0.1) + + async def loop_poll_stats() -> NoReturn: + nonlocal stats + while True: + start_time = time.monotonic() + + handle = interface.deliver_operation_stats() + 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: + yield ProgressPrinter( + printer, + text_area, + default_text=default_text, + ) + 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._show_operation_stats = True + self._printer = printer + self._progress_text_area = progress_text_area + self._default_text = default_text + self._tick = 0 + self._last_printed_line = "" + + def update( + self, + progress: list[pb.PollExitResponse] | pb.OperationStats, + ) -> None: + """Update the displayed information.""" + if not progress: + return + + if isinstance(progress, pb.OperationStats): + self._update_operation_stats([progress]) + elif self._show_operation_stats: + self._update_operation_stats( + list(response.operation_stats for response in progress) + ) + elif len(progress) == 1: + self._update_single_run(progress[0]) + else: + self._update_multiple_runs(progress) + + self._tick += 1 + + def _update_operation_stats(self, stats_list: list[pb.OperationStats]) -> None: + if self._progress_text_area: + _DynamicOperationStatsPrinter( + self._printer, + self._progress_text_area, + max_lines=6, + loading_symbol=self._printer.loading_symbol(self._tick), + default_text=self._default_text, + ).display(stats_list) + + else: + top_level_operations: list[str] = [] + extra_operations = 0 + for stats in stats_list: + for op in stats.operations: + if len(top_level_operations) < 5: + top_level_operations.append(op.desc) + else: + extra_operations += 1 + + line = "; ".join(top_level_operations) + if extra_operations > 0: + line += f" (+ {extra_operations} more)" + + if line != self._last_printed_line: + self._printer.display(line) + + self._last_printed_line = line + + def _update_single_run( + self, + progress: pb.PollExitResponse, + ) -> None: + stats = progress.pusher_stats + line = ( + f"{_megabytes(stats.uploaded_bytes):.3f} MB" + f" of {_megabytes(stats.total_bytes):.3f} MB uploaded" + ) + + if stats.deduped_bytes > 0: + line += f" ({_megabytes(stats.deduped_bytes):.3f} MB deduped)" + + if stats.total_bytes > 0: + self._update_progress_text( + line, + stats.uploaded_bytes / stats.total_bytes, + ) + else: + self._update_progress_text(line, 1.0) + + def _update_multiple_runs( + self, + progress_list: list[pb.PollExitResponse], + ) -> None: + total_files = 0 + uploaded_bytes = 0 + total_bytes = 0 + + for progress in progress_list: + total_files += progress.file_counts.wandb_count + total_files += progress.file_counts.media_count + total_files += progress.file_counts.artifact_count + total_files += progress.file_counts.other_count + + uploaded_bytes += progress.pusher_stats.uploaded_bytes + total_bytes += progress.pusher_stats.total_bytes + + line = ( + f"Processing {len(progress_list)} runs with {total_files} files" + f" ({_megabytes(uploaded_bytes):.2f} MB" + f" / {_megabytes(total_bytes):.2f} MB)" + ) + + if total_bytes > 0: + self._update_progress_text(line, uploaded_bytes / total_bytes) + else: + self._update_progress_text(line, 1.0) + + def _update_progress_text(self, text: str, progress: float) -> None: + if text == self._last_printed_line: + return + self._last_printed_line = text + + if self._progress_text_area: + self._progress_text_area.set_text(text) + else: + self._printer.progress_update(text + "\r", progress) + + +class _DynamicOperationStatsPrinter: + """Single-use object that writes operation stats into a text area.""" + + def __init__( + self, + printer: p.Printer, + text_area: p.DynamicText, + max_lines: int, + loading_symbol: str, + default_text: str, + ) -> None: + self._printer = printer + self._text_area = text_area + self._max_lines = max_lines + self._loading_symbol = loading_symbol + self._default_text = default_text + + self._lines: list[str] = [] + self._ops_shown = 0 + + def display( + self, + stats_list: Iterable[pb.OperationStats], + ) -> None: + """Show the given stats in the text area.""" + total_operations = 0 + for stats in stats_list: + for op in stats.operations: + self._add_operation(op, is_subtask=False, indent="") + total_operations += stats.total_operations + + if self._ops_shown < total_operations: + if 1 <= self._max_lines <= len(self._lines): + self._lines.pop() + + remaining = total_operations - self._ops_shown + + self._lines.append(f"+ {remaining} more task(s)") + + if len(self._lines) == 0: + if self._loading_symbol: + self._text_area.set_text(f"{self._loading_symbol} {self._default_text}") + else: + self._text_area.set_text(self._default_text) + else: + self._text_area.set_text("\n".join(self._lines)) + + def _add_operation(self, op: pb.Operation, is_subtask: bool, indent: str) -> None: + """Add the operation to `self._lines`.""" + if len(self._lines) >= self._max_lines: + return + + if not is_subtask: + self._ops_shown += 1 + + parts = [] + + # Subtask indicator. + if is_subtask and self._printer.supports_unicode: + parts.append("↳") + + # Loading symbol. + if self._loading_symbol: + parts.append(self._loading_symbol) + + # Task name. + parts.append(op.desc) + + # Progress information. + if op.progress: + parts.append(f"{op.progress}") + + # Task duration. + parts.append(f"({_time_to_string(seconds=op.runtime_seconds)})") + + # Error status. + self._lines.append(indent + " ".join(parts)) + if op.error_status: + error_word = self._printer.error("ERROR") + error_desc = self._printer.secondary_text(op.error_status) + subtask_indent = " " if is_subtask else "" + self._lines.append( + f"{indent}{subtask_indent} {error_word} {error_desc}", + ) + + # Subtasks. + if op.subtasks: + subtask_indent = indent + " " + for task in op.subtasks: + self._add_operation( + task, + is_subtask=True, + indent=subtask_indent, + ) + + +def _time_to_string(seconds: float) -> str: + """Returns a short string representing the duration.""" + if seconds < 10: + return f"{seconds:.1f}s" + if seconds < 60: + return f"{seconds:.0f}s" + if seconds < 60 * 60: + minutes = seconds / 60 + return f"{minutes:.1f}m" + + hours = int(seconds / (60 * 60)) + minutes = int((seconds / 60) % 60) + return f"{hours}h{minutes}m" + + +def _megabytes(bytes: int) -> float: + """Returns the number of megabytes in `bytes`.""" + return bytes / (1 << 20) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/redirect.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/redirect.py new file mode 100644 index 0000000000000000000000000000000000000000..087c5b0661b3ed8d812f38b7c87a2f268d2db60a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/redirect.py @@ -0,0 +1,876 @@ +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 typing import Callable, Iterable, 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): + for k in self.__slots__: + if self[k] != other[k]: + return False + return True + + +_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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/runid.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/runid.py new file mode 100644 index 0000000000000000000000000000000000000000..355d24df01a2fc9b5a6174a343e84ed083696277 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/runid.py @@ -0,0 +1,12 @@ +"""runid util.""" + +import secrets +import string + + +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. + alphabet = string.ascii_lowercase + string.digits + return "".join(secrets.choice(alphabet) for _ in range(length)) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/sparkline.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/sparkline.py new file mode 100644 index 0000000000000000000000000000000000000000..e7328cc328cb0df804ca9a8cfc68f6ce9a5ea9ec --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/sparkline.py @@ -0,0 +1,44 @@ +# +# From pysparklines (BSD License): https://pypi.python.org/pypi/pysparklines + +import math +from typing import List, Union + +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[Union[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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/telemetry.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/telemetry.py new file mode 100644 index 0000000000000000000000000000000000000000..b1fc67efe9cb6a89f7906909519b8314f7f2bb81 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/telemetry.py @@ -0,0 +1,100 @@ +import re +import sys +from types import TracebackType +from typing import TYPE_CHECKING, ContextManager, Dict, List, Optional, Set, Type + +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: Optional["wandb_run.Run"] + _obj: TelemetryRecord + + def __init__( + self, + run: Optional["wandb_run.Run"] = None, + obj: Optional[TelemetryRecord] = None, + ) -> None: + self._run = run or wandb.run + self._obj = obj or TelemetryRecord() + + def __enter__(self) -> TelemetryRecord: + return self._obj + + def __exit__( + self, + exctype: Optional[Type[BaseException]], + excinst: Optional[BaseException], + exctb: Optional[TracebackType], + ) -> None: + if not self._run: + return + self._run._telemetry_callback(self._obj) + + +def context( + run: Optional["wandb_run.Run"] = None, obj: Optional[TelemetryRecord] = None +) -> ContextManager[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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/timer.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/timer.py new file mode 100644 index 0000000000000000000000000000000000000000..0ff2be95dc9dcfd5a307558ad936d1b22242f882 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/lib/timer.py @@ -0,0 +1,19 @@ +import time +from typing import Any + + +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) -> "Timer": + 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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/wandb_require.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/wandb_require.py new file mode 100644 index 0000000000000000000000000000000000000000..b1540e29afe1156b5ed994d662203c68855ac46a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/wandb_require.py @@ -0,0 +1,88 @@ +"""Feature Flags Module. + +This module implements a feature flag system for the wandb library to require experimental features +and notify the user when features have been deprecated. + +Example: + import wandb + wandb.require("wandb-service@beta") + wandb.require("incremental-artifacts@beta") +""" + +from __future__ import annotations + +from typing import Iterable + +import wandb +from wandb.errors import UnsupportedError + + +class _Requires: + """Internal feature class.""" + + _features: tuple[str, ...] + + def __init__(self, features: str | Iterable[str]) -> None: + self._features = ( + tuple([features]) if isinstance(features, str) else tuple(features) + ) + + def require_require(self) -> None: + pass + + def require_service(self) -> None: + # Legacy no-op kept solely for backward compatibility: + # some integrations (e.g. PyTorch Lightning) still call + # `wandb.require('service')`, which routes here. + wandb.termwarn( + "`wandb.require('service')` is a no-op as it is now the default behavior." + ) + + def require_core(self) -> None: + # Legacy no-op kept solely for backward compatibility: + # many public codebases still call `wandb.require('core')`. + wandb.termwarn( + "`wandb.require('core')` is a no-op as it is now the default behavior." + ) + + def apply(self) -> None: + """Call require_* method for supported features.""" + last_message: str = "" + for feature_item in self._features: + full_feature = feature_item.split("@", 2)[0] + feature = full_feature.split(":", 2)[0] + func_str = "require_{}".format(feature.replace("-", "_")) + func = getattr(self, func_str, None) + if not func: + last_message = f"require() unsupported requirement: {feature}" + wandb.termwarn(last_message) + continue + func() + + if last_message: + raise UnsupportedError(last_message) + + +def require( + requirement: str | Iterable[str] | None = None, + experiment: str | Iterable[str] | None = None, +) -> None: + """Indicate which experimental features are used by the script. + + This should be called before any other `wandb` functions, ideally right + after importing `wandb`. + + Args: + requirement: The name of a feature to require or an iterable of + feature names. + experiment: An alias for `requirement`. + + Raises: + wandb.errors.UnsupportedError: If a feature name is unknown. + """ + features = requirement or experiment + if not features: + return + + f = _Requires(features=features) + f.apply() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/wandb_run.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/wandb_run.py new file mode 100644 index 0000000000000000000000000000000000000000..4b05ce4eafbfd135b74a6eacae871ce7ec113890 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/wandb_run.py @@ -0,0 +1,4052 @@ +from __future__ import annotations + +import asyncio +import functools +import glob +import json +import logging +import numbers +import os +import pathlib +import re +import sys +import threading +import time +import traceback +from collections.abc import Mapping +from dataclasses import dataclass, field +from datetime import datetime, timedelta, timezone +from enum import IntEnum +from types import TracebackType +from typing import TYPE_CHECKING, Callable, Sequence, TextIO, TypeVar + +import requests +from typing_extensions import Any, Concatenate, Literal, NamedTuple, ParamSpec + +import wandb +import wandb.env +import wandb.util +from wandb import trigger +from wandb.apis import internal, public +from wandb.apis.public import Api as PublicApi +from wandb.errors import CommError, UsageError +from wandb.errors.links import url_registry +from wandb.integration.torch import wandb_torch +from wandb.plot import CustomChart, Visualize +from wandb.proto.wandb_deprecated import Deprecated +from wandb.proto.wandb_internal_pb2 import ( + MetricRecord, + PollExitResponse, + Result, + RunRecord, +) +from wandb.sdk.artifacts._internal_artifact import InternalArtifact +from wandb.sdk.artifacts._validators import is_artifact_registry_project +from wandb.sdk.artifacts.artifact import Artifact +from wandb.sdk.internal import job_builder +from wandb.sdk.lib import asyncio_compat, wb_logging +from wandb.sdk.lib.import_hooks import ( + register_post_import_hook, + unregister_post_import_hook, +) +from wandb.sdk.lib.paths import FilePathStr, StrPath +from wandb.util import ( + _is_artifact_object, + _is_artifact_string, + _is_artifact_version_weave_dict, + _is_py_requirements_or_dockerfile, + _resolve_aliases, + add_import_hook, + parse_artifact_string, +) + +from . import wandb_config, wandb_metric, wandb_summary +from .artifacts._validators import ( + MAX_ARTIFACT_METADATA_KEYS, + ArtifactPath, + validate_aliases, + validate_tags, +) +from .data_types._dtypes import TypeRegistry +from .interface.interface import FilesDict, GlobStr, InterfaceBase, PolicyName +from .interface.summary_record import SummaryRecord +from .lib import ( + config_util, + deprecate, + filenames, + filesystem, + interrupt, + ipython, + module, + printer, + progress, + proto_util, + redirect, + telemetry, +) +from .lib.exit_hooks import ExitHooks +from .mailbox import ( + HandleAbandonedError, + MailboxClosedError, + MailboxHandle, + wait_with_progress, +) +from .wandb_alerts import AlertLevel +from .wandb_settings import Settings +from .wandb_setup import _WandbSetup + +if TYPE_CHECKING: + from typing import TypedDict + + import torch # type: ignore [import-not-found] + + import wandb.apis.public + import wandb.sdk.backend.backend + import wandb.sdk.interface.interface_queue + from wandb.proto.wandb_internal_pb2 import ( + GetSummaryResponse, + InternalMessagesResponse, + SampledHistoryResponse, + ) + + class GitSourceDict(TypedDict): + remote: str + commit: str + entrypoint: list[str] + args: Sequence[str] + + class ArtifactSourceDict(TypedDict): + artifact: str + entrypoint: list[str] + args: Sequence[str] + + class ImageSourceDict(TypedDict): + image: str + args: Sequence[str] + + class JobSourceDict(TypedDict, total=False): + _version: str + source_type: str + source: GitSourceDict | ArtifactSourceDict | ImageSourceDict + input_types: dict[str, Any] + output_types: dict[str, Any] + runtime: str | None + services: dict[str, str] + + +logger = logging.getLogger("wandb") +EXIT_TIMEOUT = 60 +RE_LABEL = re.compile(r"[a-zA-Z0-9_-]+$") + + +class TeardownStage(IntEnum): + EARLY = 1 + LATE = 2 + + +class TeardownHook(NamedTuple): + call: Callable[[], None] + stage: TeardownStage + + +class RunStatusChecker: + """Periodically polls the background process for relevant updates. + + - check if the user has requested a stop. + - check the network status. + - check the run sync status. + """ + + _stop_status_lock: threading.Lock + _stop_status_handle: MailboxHandle[Result] | None + _network_status_lock: threading.Lock + _network_status_handle: MailboxHandle[Result] | None + _internal_messages_lock: threading.Lock + _internal_messages_handle: MailboxHandle[Result] | None + + def __init__( + self, + run_id: str, + interface: InterfaceBase, + settings: Settings, + stop_polling_interval: int = 15, + retry_polling_interval: int = 5, + internal_messages_polling_interval: int = 10, + ) -> None: + self._run_id = run_id + self._interface = interface + self._stop_polling_interval = stop_polling_interval + self._retry_polling_interval = retry_polling_interval + self._internal_messages_polling_interval = internal_messages_polling_interval + self._settings = settings + + self._join_event = threading.Event() + + self._stop_status_lock = threading.Lock() + self._stop_status_handle = None + self._stop_thread = threading.Thread( + target=self.check_stop_status, + name="ChkStopThr", + daemon=True, + ) + + self._network_status_lock = threading.Lock() + self._network_status_handle = None + self._network_status_thread = threading.Thread( + target=self.check_network_status, + name="NetStatThr", + daemon=True, + ) + + self._internal_messages_lock = threading.Lock() + self._internal_messages_handle = None + self._internal_messages_thread = threading.Thread( + target=self.check_internal_messages, + name="IntMsgThr", + daemon=True, + ) + + def start(self) -> None: + self._stop_thread.start() + self._network_status_thread.start() + self._internal_messages_thread.start() + + @staticmethod + def _abandon_status_check( + lock: threading.Lock, + handle: MailboxHandle[Result] | None, + ): + with lock: + if handle: + handle.abandon() + + def _loop_check_status( + self, + *, + lock: threading.Lock, + set_handle: Any, + timeout: int, + request: Any, + process: Any, + ) -> None: + local_handle: MailboxHandle[Result] | None = None + join_requested = False + while not join_requested: + time_probe = time.monotonic() + if not local_handle: + try: + local_handle = request() + except MailboxClosedError: + # This can happen if the service process dies. + break + assert local_handle + + with lock: + if self._join_event.is_set(): + break + set_handle(local_handle) + + try: + result = local_handle.wait_or(timeout=timeout) + except HandleAbandonedError: + # This can happen if the service process dies. + break + except TimeoutError: + result = None + + with lock: + set_handle(None) + + if result: + process(result) + local_handle = None + + time_elapsed = time.monotonic() - time_probe + wait_time = max(timeout - time_elapsed, 0) + join_requested = self._join_event.wait(timeout=wait_time) + + def check_network_status(self) -> None: + def _process_network_status(result: Result) -> None: + network_status = result.response.network_status_response + for hr in network_status.network_responses: + if ( + hr.http_status_code == 200 or hr.http_status_code == 0 + ): # we use 0 for non-http errors (eg wandb errors) + wandb.termlog(f"{hr.http_response_text}") + else: + wandb.termlog( + f"{hr.http_status_code} encountered ({hr.http_response_text.rstrip()}), retrying request" + ) + + with wb_logging.log_to_run(self._run_id): + try: + self._loop_check_status( + lock=self._network_status_lock, + set_handle=lambda x: setattr(self, "_network_status_handle", x), + timeout=self._retry_polling_interval, + request=self._interface.deliver_network_status, + process=_process_network_status, + ) + except BrokenPipeError: + self._abandon_status_check( + self._network_status_lock, + self._network_status_handle, + ) + + def check_stop_status(self) -> None: + def _process_stop_status(result: Result) -> None: + stop_status = result.response.stop_status_response + if stop_status.run_should_stop: + # TODO(frz): This check is required + # until WB-3606 is resolved on server side. + if not wandb.agents.pyagent.is_running(): # type: ignore + interrupt.interrupt_main() + return + + with wb_logging.log_to_run(self._run_id): + try: + self._loop_check_status( + lock=self._stop_status_lock, + set_handle=lambda x: setattr(self, "_stop_status_handle", x), + timeout=self._stop_polling_interval, + request=self._interface.deliver_stop_status, + process=_process_stop_status, + ) + except BrokenPipeError: + self._abandon_status_check( + self._stop_status_lock, + self._stop_status_handle, + ) + + def check_internal_messages(self) -> None: + def _process_internal_messages(result: Result) -> None: + if ( + not self._settings.show_warnings + or self._settings.quiet + or self._settings.silent + ): + return + internal_messages = result.response.internal_messages_response + for msg in internal_messages.messages.warning: + wandb.termwarn(msg, repeat=False) + + with wb_logging.log_to_run(self._run_id): + try: + self._loop_check_status( + lock=self._internal_messages_lock, + set_handle=lambda x: setattr(self, "_internal_messages_handle", x), + timeout=self._internal_messages_polling_interval, + request=self._interface.deliver_internal_messages, + process=_process_internal_messages, + ) + except BrokenPipeError: + self._abandon_status_check( + self._internal_messages_lock, + self._internal_messages_handle, + ) + + def stop(self) -> None: + self._join_event.set() + self._abandon_status_check( + self._stop_status_lock, + self._stop_status_handle, + ) + self._abandon_status_check( + self._network_status_lock, + self._network_status_handle, + ) + self._abandon_status_check( + self._internal_messages_lock, + self._internal_messages_handle, + ) + + def join(self) -> None: + self.stop() + self._stop_thread.join() + self._network_status_thread.join() + self._internal_messages_thread.join() + + +_P = ParamSpec("_P") +_T = TypeVar("_T") + + +def _log_to_run( + func: Callable[Concatenate[Run, _P], _T], +) -> Callable[Concatenate[Run, _P], _T]: + """Decorate a Run method to set the run ID in the logging context. + + Any logs during the execution of the method go to the run's log file + and not to other runs' log files. + + This is meant for use on all public methods and some callbacks. Private + methods can be assumed to be called from some public method somewhere. + The general rule is to use it on methods that can be called from a + context that isn't specific to this run (such as all user code or + internal methods that aren't run-specific). + """ + + @functools.wraps(func) + def wrapper(self: Run, *args, **kwargs) -> _T: + # In "attach" usage, many properties of the Run are not initially + # populated. + if hasattr(self, "_settings"): + run_id = self._settings.run_id + else: + run_id = self._attach_id + + with wb_logging.log_to_run(run_id): + return func(self, *args, **kwargs) + + return wrapper + + +_is_attaching: str = "" + + +def _attach( + func: Callable[Concatenate[Run, _P], _T], +) -> Callable[Concatenate[Run, _P], _T]: + """Decorate a Run method to auto-attach when in a new process. + + When in a forked process or using a pickled Run instance, this automatically + connects to the service process to "attach" to the existing run. + """ + + @functools.wraps(func) + def wrapper(self: Run, *args, **kwargs) -> _T: + global _is_attaching + + # The _attach_id attribute is only None when running in the "disable + # service" mode. + # + # Since it is set early in `__init__` and included in the run's pickled + # state, the attribute always exists. + is_using_service = self._attach_id is not None + + # The _attach_pid attribute is not pickled, so it might not exist. + # It is set when the run is initialized. + attach_pid = getattr(self, "_attach_pid", None) + + if is_using_service and attach_pid != os.getpid(): + if _is_attaching: + raise RuntimeError( + f"Trying to attach `{func.__name__}`" + f" while in the middle of attaching `{_is_attaching}`" + ) + + _is_attaching = func.__name__ + try: + wandb._attach(run=self) # type: ignore + finally: + _is_attaching = "" + + return func(self, *args, **kwargs) + + return wrapper + + +def _raise_if_finished( + func: Callable[Concatenate[Run, _P], _T], +) -> Callable[Concatenate[Run, _P], _T]: + """Decorate a Run method to raise an error after the run is finished.""" + + @functools.wraps(func) + def wrapper_fn(self: Run, *args, **kwargs) -> _T: + if not getattr(self, "_is_finished", False): + return func(self, *args, **kwargs) + + message = ( + f"Run ({self.id}) is finished. The call to" + f" `{func.__name__}` will be ignored." + f" Please make sure that you are using an active run." + ) + + raise UsageError(message) + + return wrapper_fn + + +@dataclass +class RunStatus: + sync_items_total: int = field(default=0) + sync_items_pending: int = field(default=0) + sync_time: datetime | None = field(default=None) + + +class Run: + """A unit of computation logged by W&B. Typically, this is an ML experiment. + + Call [`wandb.init()`](https://docs.wandb.ai/ref/python/init/) to create a + new run. `wandb.init()` starts a new run and returns a `wandb.Run` object. + Each run is associated with a unique ID (run ID). W&B recommends using + a context (`with` statement) manager to automatically finish the run. + + For distributed training experiments, you can either track each process + separately using one run per process or track all processes to a single run. + See [Log distributed training experiments](https://docs.wandb.ai/guides/track/log/distributed-training) + for more information. + + You can log data to a run with `wandb.Run.log()`. Anything you log using + `wandb.Run.log()` is sent to that run. See + [Create an experiment](https://docs.wandb.ai/guides/track/launch) or + [`wandb.init`](https://docs.wandb.ai/ref/python/init/) API reference page + or more information. + + There is a another `Run` object in the + [`wandb.apis.public`](https://docs.wandb.ai/ref/python/public-api/api/) + namespace. Use this object is to interact with runs that have already been + created. + + Attributes: + summary: (Summary) A summary of the run, which is a dictionary-like + object. For more information, see + [Log summary metrics](https://docs.wandb.ai/guides/track/log/log-summary/). + + Examples: + Create a run with `wandb.init()`: + + ```python + import wandb + + # Start a new run and log some data + # Use context manager (`with` statement) to automatically finish the run + with wandb.init(entity="entity", project="project") as run: + run.log({"accuracy": acc, "loss": loss}) + ``` + + + """ + + _telemetry_obj: telemetry.TelemetryRecord + _telemetry_obj_active: bool + _telemetry_obj_dirty: bool + _telemetry_obj_flushed: bytes + + _teardown_hooks: list[TeardownHook] + + _backend: wandb.sdk.backend.backend.Backend | None + _internal_run_interface: wandb.sdk.interface.interface_queue.InterfaceQueue | None + _wl: _WandbSetup | None + + _out_redir: redirect.RedirectBase | None + _err_redir: redirect.RedirectBase | None + _redirect_cb: Callable[[str, str], None] | None + _redirect_raw_cb: Callable[[str, str], None] | None + _output_writer: filesystem.CRDedupedFile | None + + _atexit_cleanup_called: bool + _hooks: ExitHooks | None + _exit_code: int | None + + _run_status_checker: RunStatusChecker | None + + _sampled_history: SampledHistoryResponse | None + _final_summary: GetSummaryResponse | None + _poll_exit_handle: MailboxHandle[Result] | None + _poll_exit_response: PollExitResponse | None + _internal_messages_response: InternalMessagesResponse | None + + _stdout_slave_fd: int | None + _stderr_slave_fd: int | None + _artifact_slots: list[str] + + _init_pid: int + _attach_pid: int + + _attach_id: str | None + _is_attached: bool + _is_finished: bool + _settings: Settings + + _forked: bool + + _launch_artifacts: dict[str, Any] | None + _printer: printer.Printer + + summary: wandb_summary.Summary + + def __init__( + self, + settings: Settings, + config: dict[str, Any] | None = None, + sweep_config: dict[str, Any] | None = None, + launch_config: dict[str, Any] | None = None, + ) -> None: + # pid is set, so we know if this run object was initialized by this process + self._init_pid = os.getpid() + self._attach_id = None + + if settings._noop: + # TODO: properly handle setting for disabled mode + self._settings = settings + return + + self._init( + settings=settings, + config=config, + sweep_config=sweep_config, + launch_config=launch_config, + ) + + def _init( + self, + settings: Settings, + config: dict[str, Any] | None = None, + sweep_config: dict[str, Any] | None = None, + launch_config: dict[str, Any] | None = None, + ) -> None: + self._settings = settings + + self._config = wandb_config.Config() + self._config._set_callback(self._config_callback) + self._config._set_artifact_callback(self._config_artifact_callback) + self._config._set_settings(self._settings) + + # The _wandb key is always expected on the run config. + wandb_key = "_wandb" + self._config._update({wandb_key: dict()}) + + # TODO: perhaps this should be a property that is a noop on a finished run + self.summary = wandb_summary.Summary( + self._summary_get_current_summary_callback, + ) + self.summary._set_update_callback(self._summary_update_callback) + + self._step = 0 + self._starting_step = 0 + self._start_runtime = 0 + # TODO: eventually would be nice to make this configurable using self._settings._start_time + # need to test (jhr): if you set start time to 2 days ago and run a test for 15 minutes, + # does the total time get calculated right (not as 2 days and 15 minutes)? + self._start_time = time.time() + + self._printer = printer.new_printer(settings) + + self._torch_history: wandb_torch.TorchHistory | None = None # type: ignore + + self._backend = None + self._internal_run_interface = None + self._wl = None + + self._hooks = None + self._teardown_hooks = [] + + self._output_writer = None + self._out_redir = None + self._err_redir = None + self._stdout_slave_fd = None + self._stderr_slave_fd = None + + self._exit_code = None + self._exit_result = None + + self._used_artifact_slots: dict[str, str] = {} + + # Created when the run "starts". + self._run_status_checker = None + + self._sampled_history = None + self._final_summary = None + self._poll_exit_response = None + self._internal_messages_response = None + self._poll_exit_handle = None + + # Initialize telemetry object + self._telemetry_obj = telemetry.TelemetryRecord() + self._telemetry_obj_active = False + self._telemetry_obj_flushed = b"" + self._telemetry_obj_dirty = False + + self._atexit_cleanup_called = False + + # Initial scope setup for sentry. + # This might get updated when the actual run comes back. + wandb._sentry.configure_scope( + tags=dict(self._settings), + process_context="user", + ) + + self._launch_artifact_mapping: dict[str, Any] = {} + self._unique_launch_artifact_sequence_names: dict[str, Any] = {} + + # Populate config + config = config or dict() + self._config._update(config, allow_val_change=True, ignore_locked=True) + + if sweep_config: + self._config.merge_locked( + sweep_config, user="sweep", _allow_val_change=True + ) + + if launch_config: + self._config.merge_locked( + launch_config, user="launch", _allow_val_change=True + ) + + # if run is from a launch queue, add queue id to _wandb config + launch_queue_name = wandb.env.get_launch_queue_name() + if launch_queue_name: + self._config[wandb_key]["launch_queue_name"] = launch_queue_name + + launch_queue_entity = wandb.env.get_launch_queue_entity() + if launch_queue_entity: + self._config[wandb_key]["launch_queue_entity"] = launch_queue_entity + + launch_trace_id = wandb.env.get_launch_trace_id() + if launch_trace_id: + self._config[wandb_key]["launch_trace_id"] = launch_trace_id + + self._attach_id = None + self._is_attached = False + self._is_finished = False + + self._attach_pid = os.getpid() + self._forked = False + # for now, use runid as attach id, this could/should be versioned in the future + self._attach_id = self._settings.run_id + + def _handle_launch_artifact_overrides(self) -> None: + if self._settings.launch and (os.environ.get("WANDB_ARTIFACTS") is not None): + try: + artifacts: dict[str, Any] = json.loads( + os.environ.get("WANDB_ARTIFACTS", "{}") + ) + except (ValueError, SyntaxError): + wandb.termwarn("Malformed WANDB_ARTIFACTS, using original artifacts") + else: + self._initialize_launch_artifact_maps(artifacts) + + elif ( + self._settings.launch + and self._settings.launch_config_path + and os.path.exists(self._settings.launch_config_path) + ): + self.save(self._settings.launch_config_path) + with open(self._settings.launch_config_path) as fp: + launch_config = json.loads(fp.read()) + if launch_config.get("overrides", {}).get("artifacts") is not None: + artifacts = launch_config.get("overrides").get("artifacts") + self._initialize_launch_artifact_maps(artifacts) + + def _initialize_launch_artifact_maps(self, artifacts: dict[str, Any]) -> None: + for key, item in artifacts.items(): + self._launch_artifact_mapping[key] = item + artifact_sequence_tuple_or_slot = key.split(":") + + if len(artifact_sequence_tuple_or_slot) == 2: + sequence_name = artifact_sequence_tuple_or_slot[0].split("/")[-1] + if self._unique_launch_artifact_sequence_names.get(sequence_name): + self._unique_launch_artifact_sequence_names.pop(sequence_name) + else: + self._unique_launch_artifact_sequence_names[sequence_name] = item + + def _telemetry_callback(self, telem_obj: telemetry.TelemetryRecord) -> None: + if not hasattr(self, "_telemetry_obj") or self._is_finished: + return + + self._telemetry_obj.MergeFrom(telem_obj) + self._telemetry_obj_dirty = True + self._telemetry_flush() + + def _telemetry_flush(self) -> None: + if not hasattr(self, "_telemetry_obj"): + return + if not self._telemetry_obj_active: + return + if not self._telemetry_obj_dirty: + return + if self._backend and self._backend.interface: + serialized = self._telemetry_obj.SerializeToString() + if serialized == self._telemetry_obj_flushed: + return + self._backend.interface._publish_telemetry(self._telemetry_obj) + self._telemetry_obj_flushed = serialized + self._telemetry_obj_dirty = False + + def _freeze(self) -> None: + self._frozen = True + + def __setattr__(self, attr: str, value: object) -> None: + if getattr(self, "_frozen", None) and not hasattr(self, attr): + raise Exception(f"Attribute {attr} is not supported on Run object.") + super().__setattr__(attr, value) + + def __deepcopy__(self, memo: dict[int, Any]) -> Run: + return self + + def __getstate__(self) -> Any: + """Return run state as a custom pickle.""" + # We only pickle in service mode + if not self._settings: + return + + _attach_id = self._attach_id + if not _attach_id: + return + + return dict( + _attach_id=_attach_id, + _init_pid=self._init_pid, + _is_finished=self._is_finished, + ) + + def __setstate__(self, state: Any) -> None: + """Set run state from a custom pickle.""" + if not state: + return + + _attach_id = state.get("_attach_id") + if not _attach_id: + return + + if state["_init_pid"] == os.getpid(): + raise RuntimeError("attach in the same process is not supported currently") + + self.__dict__.update(state) + + @property + def _torch(self) -> wandb_torch.TorchHistory: # type: ignore + if self._torch_history is None: + self._torch_history = wandb_torch.TorchHistory() # type: ignore + return self._torch_history + + @property + @_log_to_run + @_attach + def settings(self) -> Settings: + """A frozen copy of run's Settings object.""" + return self._settings.model_copy(deep=True) + + @property + @_log_to_run + @_attach + def dir(self) -> str: + """The directory where files associated with the run are saved.""" + return self._settings.files_dir + + @property + @_log_to_run + @_attach + def config(self) -> wandb_config.Config: + """Config object associated with this run.""" + return self._config + + @property + @_log_to_run + @_attach + def config_static(self) -> wandb_config.ConfigStatic: + """Static config object associated with this run.""" + return wandb_config.ConfigStatic(self._config) + + @property + @_log_to_run + @_attach + def name(self) -> str | None: + """Display name of the run. + + Display names are not guaranteed to be unique and may be descriptive. + By default, they are randomly generated. + """ + return self._settings.run_name + + @name.setter + @_log_to_run + @_raise_if_finished + def name(self, name: str) -> None: + with telemetry.context(run=self) as tel: + tel.feature.set_run_name = True + self._settings.run_name = name + if self._backend and self._backend.interface: + self._backend.interface.publish_run(self) + + @property + @_log_to_run + @_attach + def notes(self) -> str | None: + """Notes associated with the run, if there are any. + + Notes can be a multiline string and can also use markdown and latex + equations inside `$$`, like `$x + 3$`. + """ + return self._settings.run_notes + + @notes.setter + @_log_to_run + @_raise_if_finished + def notes(self, notes: str) -> None: + self._settings.run_notes = notes + if self._backend and self._backend.interface: + self._backend.interface.publish_run(self) + + @property + @_log_to_run + @_attach + def tags(self) -> tuple | None: + """Tags associated with the run, if there are any.""" + return self._settings.run_tags or () + + @tags.setter + @_log_to_run + @_raise_if_finished + def tags(self, tags: Sequence) -> None: + with telemetry.context(run=self) as tel: + tel.feature.set_run_tags = True + self._settings.run_tags = tuple(tags) + if self._backend and self._backend.interface: + self._backend.interface.publish_run(self) + + @property + @_log_to_run + @_attach + def id(self) -> str: + """Identifier for this run.""" + assert self._settings.run_id is not None + return self._settings.run_id + + @property + @_log_to_run + @_attach + def sweep_id(self) -> str | None: + """Identifier for the sweep associated with the run, if there is one.""" + return self._settings.sweep_id + + def _get_path(self) -> str: + return "/".join( + e + for e in [ + self._settings.entity, + self._settings.project, + self._settings.run_id, + ] + if e is not None + ) + + @property + @_log_to_run + @_attach + def path(self) -> str: + """Path to the run. + + Run paths include entity, project, and run ID, in the format + `entity/project/run_id`. + """ + return self._get_path() + + @property + @_log_to_run + @_attach + def start_time(self) -> float: + """Unix timestamp (in seconds) of when the run started.""" + return self._start_time + + @property + @_log_to_run + @_attach + def starting_step(self) -> int: + """The first step of the run. + + + """ + return self._starting_step + + @property + @_log_to_run + @_attach + def resumed(self) -> bool: + """True if the run was resumed, False otherwise.""" + return self._settings.resumed + + @property + @_log_to_run + @_attach + def step(self) -> int: + """Current value of the step. + + This counter is incremented by `wandb.Run.log()`. + + + """ + return self._step + + @property + @_log_to_run + @_attach + def offline(self) -> bool: + """True if the run is offline, False otherwise.""" + return self._settings._offline + + @property + @_log_to_run + @_attach + def disabled(self) -> bool: + """True if the run is disabled, False otherwise.""" + return self._settings._noop + + @property + @_log_to_run + @_attach + def group(self) -> str: + """Returns the name of the group associated with this run. + + Grouping runs together allows related experiments to be organized and + visualized collectively in the W&B UI. This is especially useful for + scenarios such as distributed training or cross-validation, where + multiple runs should be viewed and managed as a unified experiment. + + In shared mode, where all processes share the same run object, + setting a group is usually unnecessary, since there is only one + run and no grouping is required. + """ + return self._settings.run_group or "" + + @property + @_log_to_run + @_attach + def job_type(self) -> str: + """Name of the job type associated with the run. + + View a run's job type in the run's Overview page in the W&B App. + + You can use this to categorize runs by their job type, such as + "training", "evaluation", or "inference". This is useful for organizing + and filtering runs in the W&B UI, especially when you have multiple + runs with different job types in the same project. For more + information, see [Organize runs](https://docs.wandb.ai/guides/runs/#organize-runs). + """ + return self._settings.run_job_type or "" + + def project_name(self) -> str: + """This method is deprecated and will be removed in a future release. Use `run.project` instead. + + Name of the W&B project associated with the run. + + + """ + deprecate.deprecate( + field_name=Deprecated.run__project_name, + warning_message=( + "The project_name method is deprecated and will be removed in a" + " future release. Please use `run.project` instead." + ), + ) + return self.project + + @property + @_log_to_run + @_attach + def project(self) -> str: + """Name of the W&B project associated with the run.""" + assert self._settings.project is not None + return self._settings.project + + @_log_to_run + def get_project_url(self) -> str | None: + """This method is deprecated and will be removed in a future release. Use `run.project_url` instead. + + URL of the W&B project associated with the run, if there is one. + Offline runs do not have a project URL. + + + """ + deprecate.deprecate( + field_name=Deprecated.run__get_project_url, + warning_message=( + "The get_project_url method is deprecated and will be removed in a" + " future release. Please use `run.project_url` instead." + ), + ) + return self.project_url + + @property + @_log_to_run + @_attach + def project_url(self) -> str | None: + """URL of the W&B project associated with the run, if there is one. + + Offline runs do not have a project URL. + """ + if self._settings._offline: + wandb.termwarn("URL not available in offline run") + return None + return self._settings.project_url + + @_raise_if_finished + @_log_to_run + @_attach + def log_code( + self, + root: str | None = ".", + name: str | None = None, + include_fn: Callable[[str, str], bool] + | Callable[[str], bool] = _is_py_requirements_or_dockerfile, + exclude_fn: Callable[[str, str], bool] + | Callable[[str], bool] = filenames.exclude_wandb_fn, + ) -> Artifact | None: + """Save the current state of your code to a W&B Artifact. + + By default, it walks the current directory and logs all files that end with `.py`. + + Args: + root: The relative (to `os.getcwd()`) or absolute path to recursively find code from. + name: (str, optional) The name of our code artifact. By default, we'll name + the artifact `source-$PROJECT_ID-$ENTRYPOINT_RELPATH`. There may be scenarios where you want + many runs to share the same artifact. Specifying name allows you to achieve that. + include_fn: A callable that accepts a file path and (optionally) root path and + returns True when it should be included and False otherwise. This + defaults to `lambda path, root: path.endswith(".py")`. + exclude_fn: A callable that accepts a file path and (optionally) root path and + returns `True` when it should be excluded and `False` otherwise. This + defaults to a function that excludes all files within `/.wandb/` + and `/wandb/` directories. + + Examples: + Basic usage + + ```python + import wandb + + with wandb.init() as run: + run.log_code() + ``` + + Advanced usage + + ```python + import wandb + + with wandb.init() as run: + run.log_code( + root="../", + include_fn=lambda path: path.endswith(".py") or path.endswith(".ipynb"), + exclude_fn=lambda path, root: os.path.relpath(path, root).startswith( + "cache/" + ), + ) + ``` + + Returns: + An `Artifact` object if code was logged + """ + if name is None: + if self.settings._jupyter: + notebook_name = None + if self.settings.notebook_name: + notebook_name = self.settings.notebook_name + elif self.settings.x_jupyter_path: + if self.settings.x_jupyter_path.startswith("fileId="): + notebook_name = self.settings.x_jupyter_name + else: + notebook_name = self.settings.x_jupyter_path + name_string = f"{self._settings.project}-{notebook_name}" + else: + name_string = ( + f"{self._settings.project}-{self._settings.program_relpath}" + ) + name = wandb.util.make_artifact_name_safe(f"source-{name_string}") + art = InternalArtifact(name, "code") + files_added = False + if root is not None: + root = os.path.abspath(root) + for file_path in filenames.filtered_dir(root, include_fn, exclude_fn): + files_added = True + save_name = os.path.relpath(file_path, root) + art.add_file(file_path, name=save_name) + # Add any manually staged files such as ipynb notebooks + for dirpath, _, files in os.walk(self._settings._tmp_code_dir): + for fname in files: + file_path = os.path.join(dirpath, fname) + save_name = os.path.relpath(file_path, self._settings._tmp_code_dir) + files_added = True + art.add_file(file_path, name=save_name) + if not files_added: + wandb.termwarn( + "No relevant files were detected in the specified directory. No code will be logged to your run." + ) + return None + + artifact = self._log_artifact(art) + + self._config.update( + {"_wandb": {"code_path": artifact.name}}, + allow_val_change=True, + ) + + return artifact + + @_log_to_run + def get_sweep_url(self) -> str | None: + """This method is deprecated and will be removed in a future release. Use `run.sweep_url` instead. + + The URL of the sweep associated with the run, if there is one. + Offline runs do not have a sweep URL. + + + """ + deprecate.deprecate( + field_name=Deprecated.run__get_sweep_url, + warning_message=( + "The get_sweep_url method is deprecated and will be removed in a" + " future release. Please use `run.sweep_url` instead." + ), + ) + return self.sweep_url + + @property + @_attach + def sweep_url(self) -> str | None: + """URL of the sweep associated with the run, if there is one. + + Offline runs do not have a sweep URL. + """ + if self._settings._offline: + wandb.termwarn("URL not available in offline run") + return None + return self._settings.sweep_url + + @_log_to_run + def get_url(self) -> str | None: + """This method is deprecated and will be removed in a future release. Use `run.url` instead. + + URL of the W&B run, if there is one. Offline runs do not have a URL. + + + """ + deprecate.deprecate( + field_name=Deprecated.run__get_url, + warning_message=( + "The get_url method is deprecated and will be removed in a" + " future release. Please use `run.url` instead." + ), + ) + return self.url + + @property + @_log_to_run + @_attach + def url(self) -> str | None: + """The url for the W&B run, if there is one. + + Offline runs will not have a url. + """ + if self._settings._offline: + wandb.termwarn("URL not available in offline run") + return None + return self._settings.run_url + + @property + @_log_to_run + @_attach + def entity(self) -> str: + """The name of the W&B entity associated with the run. + + Entity can be a username or the name of a team or organization. + """ + return self._settings.entity or "" + + def _label_internal( + self, + code: str | None = None, + repo: str | None = None, + code_version: str | None = None, + ) -> None: + with telemetry.context(run=self) as tel: + if code and RE_LABEL.match(code): + tel.label.code_string = code + if repo and RE_LABEL.match(repo): + tel.label.repo_string = repo + if code_version and RE_LABEL.match(code_version): + tel.label.code_version = code_version + + def _label( + self, + code: str | None = None, + repo: str | None = None, + code_version: str | None = None, + **kwargs: str, + ) -> None: + if self._settings.label_disable: + return + for k, v in (("code", code), ("repo", repo), ("code_version", code_version)): + if v and not RE_LABEL.match(v): + wandb.termwarn( + f"Label added for '{k}' with invalid identifier '{v}' (ignored).", + repeat=False, + ) + for v in kwargs: + wandb.termwarn( + f"Label added for unsupported key {v!r} (ignored).", + repeat=False, + ) + + self._label_internal(code=code, repo=repo, code_version=code_version) + + # update telemetry in the backend immediately for _label() callers + self._telemetry_flush() + + def _label_probe_lines(self, lines: list[str]) -> None: + if not lines: + return + parsed = telemetry._parse_label_lines(lines) + if not parsed: + return + label_dict = {} + code = parsed.get("code") or parsed.get("c") + if code: + label_dict["code"] = code + repo = parsed.get("repo") or parsed.get("r") + if repo: + label_dict["repo"] = repo + code_ver = parsed.get("version") or parsed.get("v") + if code_ver: + label_dict["code_version"] = code_ver + self._label_internal(**label_dict) + + def _label_probe_main(self) -> None: + m = sys.modules.get("__main__") + if not m: + return + doc = getattr(m, "__doc__", None) + if not doc: + return + + doclines = doc.splitlines() + self._label_probe_lines(doclines) + + # TODO: annotate jupyter Notebook class + def _label_probe_notebook(self, notebook: Any) -> None: + logger.info("probe notebook") + lines = None + try: + data = notebook.probe_ipynb() + cell0 = data.get("cells", [])[0] + lines = cell0.get("source") + # kaggle returns a string instead of a list + if isinstance(lines, str): + lines = lines.split() + except Exception as e: + logger.info(f"Unable to probe notebook: {e}") + return + if lines: + self._label_probe_lines(lines) + + @_log_to_run + @_attach + def display(self, height: int = 420, hidden: bool = False) -> bool: + """Display this run in Jupyter.""" + if self._settings.silent: + return False + + if not ipython.in_jupyter(): + return False + + try: + from IPython import display + except ImportError: + wandb.termwarn(".display() only works in jupyter environments") + return False + + display.display(display.HTML(self.to_html(height, hidden))) + return True + + @_log_to_run + @_attach + def to_html(self, height: int = 420, hidden: bool = False) -> str: + """Generate HTML containing an iframe displaying the current run. + + + """ + url = self._settings.run_url + "?jupyter=true" + style = f"border:none;width:100%;height:{height}px;" + prefix = "" + if hidden: + style += "display:none;" + prefix = ipython.toggle_button() + return prefix + f"" + + def _repr_mimebundle_( + self, include: Any | None = None, exclude: Any | None = None + ) -> dict[str, str]: + return {"text/html": self.to_html(hidden=True)} + + @_log_to_run + @_raise_if_finished + def _config_callback( + self, + key: tuple[str, ...] | str | None = None, + val: Any | None = None, + data: dict[str, object] | None = None, + ) -> None: + logger.info(f"config_cb {key} {val} {data}") + if self._backend and self._backend.interface: + self._backend.interface.publish_config(key=key, val=val, data=data) + + @_log_to_run + def _config_artifact_callback( + self, key: str, val: str | Artifact | dict + ) -> Artifact: + # artifacts can look like dicts as they are passed into the run config + # since the run config stores them on the backend as a dict with fields shown + # in wandb.util.artifact_to_json + if _is_artifact_version_weave_dict(val): + assert isinstance(val, dict) + public_api = self._public_api() + artifact = Artifact._from_id(val["id"], public_api.client) + + assert artifact + return self.use_artifact(artifact) + elif _is_artifact_string(val): + # this will never fail, but is required to make mypy happy + assert isinstance(val, str) + artifact_string, base_url, is_id = parse_artifact_string(val) + overrides = {} + if base_url is not None: + overrides = {"base_url": base_url} + public_api = public.Api(overrides) + else: + public_api = self._public_api() + if is_id: + artifact = Artifact._from_id(artifact_string, public_api._client) + else: + artifact = public_api._artifact(name=artifact_string) + # in the future we'll need to support using artifacts from + # different instances of wandb. + + assert artifact + return self.use_artifact(artifact) + elif _is_artifact_object(val): + return self.use_artifact(val) + else: + raise ValueError( + f"Cannot call _config_artifact_callback on type {type(val)}" + ) + + def _set_config_wandb(self, key: str, val: Any) -> None: + self._config_callback(key=("_wandb", key), val=val) + + @_log_to_run + @_raise_if_finished + def _summary_update_callback(self, summary_record: SummaryRecord) -> None: + with telemetry.context(run=self) as tel: + tel.feature.set_summary = True + if self._backend and self._backend.interface: + self._backend.interface.publish_summary(self, summary_record) + + @_log_to_run + def _summary_get_current_summary_callback(self) -> dict[str, Any]: + if self._is_finished: + # TODO: WB-18420: fetch summary from backend and stage it before run is finished + wandb.termwarn("Summary data not available in finished run") + return {} + if not self._backend or not self._backend.interface: + return {} + handle = self._backend.interface.deliver_get_summary() + + try: + result = handle.wait_or(timeout=self._settings.summary_timeout) + except TimeoutError: + return {} + + get_summary_response = result.response.get_summary_response + return proto_util.dict_from_proto_list(get_summary_response.item) + + @_log_to_run + def _metric_callback(self, metric_record: MetricRecord) -> None: + if self._backend and self._backend.interface: + self._backend.interface._publish_metric(metric_record) + + @_log_to_run + def _publish_file(self, fname: str) -> None: + """Mark a run file to be uploaded with the run. + + This is a W&B-internal function: it can be used by other internal + wandb code. + + Args: + fname: The path to the file in the run's files directory, relative + to the run's files directory. + """ + if not self._backend or not self._backend.interface: + return + files: FilesDict = dict(files=[(GlobStr(fname), "now")]) + self._backend.interface.publish_files(files) + + def _pop_all_charts( + self, + data: dict[str, Any], + key_prefix: str | None = None, + ) -> dict[str, Any]: + """Pops all charts from a dictionary including nested charts. + + This function will return a mapping of the charts and a dot-separated + key for each chart. Indicating the path to the chart in the data dictionary. + """ + keys_to_remove = set() + charts: dict[str, Any] = {} + for k, v in data.items(): + key = f"{key_prefix}.{k}" if key_prefix else k + if isinstance(v, Visualize): + keys_to_remove.add(k) + charts[key] = v + elif isinstance(v, CustomChart): + keys_to_remove.add(k) + charts[key] = v + elif isinstance(v, dict): + nested_charts = self._pop_all_charts(v, key) + charts.update(nested_charts) + + for k in keys_to_remove: + data.pop(k) + + return charts + + def _serialize_custom_charts( + self, + data: dict[str, Any], + ) -> dict[str, Any]: + """Process and replace chart objects with their underlying table values. + + This processes the chart objects passed to `wandb.Run.log()`, replacing their entries + in the given dictionary (which is saved to the run's history) and adding them + to the run's config. + + Args: + data: Dictionary containing data that may include plot objects + Plot objects can be nested in dictionaries, which will be processed recursively. + + Returns: + The processed dictionary with custom charts transformed into tables. + """ + if not data: + return data + + charts = self._pop_all_charts(data) + for k, v in charts.items(): + v.set_key(k) + self._config_callback( + val=v.spec.config_value, + key=v.spec.config_key, + ) + + if isinstance(v, CustomChart): + data[v.spec.table_key] = v.table + elif isinstance(v, Visualize): + data[k] = v.table + + return data + + @_log_to_run + def _partial_history_callback( + self, + data: dict[str, Any], + step: int | None = None, + commit: bool | None = None, + ) -> None: + if not (self._backend and self._backend.interface): + return + + data = data.copy() # avoid modifying the original data + + # Serialize custom charts before publishing + data = self._serialize_custom_charts(data) + + not_using_tensorboard = len(wandb.patched["tensorboard"]) == 0 + self._backend.interface.publish_partial_history( + self, + data, + user_step=self._step, + step=step, + flush=commit, + publish_step=not_using_tensorboard, + ) + + @_log_to_run + def _console_callback(self, name: str, data: str) -> None: + # logger.info("console callback: %s, %s", name, data) + if self._backend and self._backend.interface: + self._backend.interface.publish_output(name, data) + + @_log_to_run + @_raise_if_finished + def _console_raw_callback(self, name: str, data: str) -> None: + # logger.info("console callback: %s, %s", name, data) + + # NOTE: console output is only allowed on the process which installed the callback + # this will prevent potential corruption in the socket to the service. Other methods + # are protected by the _attach run decorator, but this callback was installed on the + # write function of stdout and stderr streams. + console_pid = getattr(self, "_attach_pid", 0) + if console_pid != os.getpid(): + return + + if self._backend and self._backend.interface: + self._backend.interface.publish_output_raw(name, data) + + @_log_to_run + def _tensorboard_callback( + self, logdir: str, save: bool = True, root_logdir: str = "" + ) -> None: + logger.info("tensorboard callback: %s, %s", logdir, save) + if self._backend and self._backend.interface: + self._backend.interface.publish_tbdata(logdir, save, root_logdir) + + def _set_library(self, library: _WandbSetup) -> None: + self._wl = library + + def _set_backend(self, backend: wandb.sdk.backend.backend.Backend) -> None: + self._backend = backend + + def _set_internal_run_interface( + self, + interface: wandb.sdk.interface.interface_queue.InterfaceQueue, + ) -> None: + self._internal_run_interface = interface + + def _set_teardown_hooks(self, hooks: list[TeardownHook]) -> None: + self._teardown_hooks = hooks + + def _set_run_obj(self, run_obj: RunRecord) -> None: # noqa: C901 + if run_obj.starting_step: + self._starting_step = run_obj.starting_step + self._step = run_obj.starting_step + + if run_obj.start_time: + self._start_time = run_obj.start_time.ToMicroseconds() / 1e6 + + if run_obj.runtime: + self._start_runtime = run_obj.runtime + + # Grab the config from resuming + if run_obj.config: + c_dict = config_util.dict_no_value_from_proto_list(run_obj.config.update) + # We update the config object here without triggering the callback + self._config._update(c_dict, allow_val_change=True, ignore_locked=True) + # Update the summary, this will trigger an un-needed graphql request :( + if run_obj.summary: + summary_dict = {} + for orig in run_obj.summary.update: + summary_dict[orig.key] = json.loads(orig.value_json) + if summary_dict: + self.summary.update(summary_dict) + + # update settings from run_obj + if run_obj.run_id: + self._settings.run_id = run_obj.run_id + if run_obj.entity: + self._settings.entity = run_obj.entity + if run_obj.project: + self._settings.project = run_obj.project + if run_obj.run_group: + self._settings.run_group = run_obj.run_group + if run_obj.job_type: + self._settings.run_job_type = run_obj.job_type + if run_obj.display_name: + self._settings.run_name = run_obj.display_name + if run_obj.notes: + self._settings.run_notes = run_obj.notes + if run_obj.tags: + self._settings.run_tags = tuple(run_obj.tags) + if run_obj.sweep_id: + self._settings.sweep_id = run_obj.sweep_id + if run_obj.host: + self._settings.host = run_obj.host + if run_obj.resumed: + self._settings.resumed = run_obj.resumed + if run_obj.git: + if run_obj.git.remote_url: + self._settings.git_remote_url = run_obj.git.remote_url + if run_obj.git.commit: + self._settings.git_commit = run_obj.git.commit + + if run_obj.forked: + self._forked = run_obj.forked + + wandb._sentry.configure_scope( + process_context="user", + tags=dict(self._settings), + ) + + def _populate_git_info(self) -> None: + from .lib.gitlib import GitRepo + + # Use user-provided git info if available, otherwise resolve it from the environment + try: + repo = GitRepo( + root=self._settings.git_root, + remote=self._settings.git_remote, + remote_url=self._settings.git_remote_url, + commit=self._settings.git_commit, + lazy=False, + ) + self._settings.git_remote_url = repo.remote_url + self._settings.git_commit = repo.last_commit + except Exception: + wandb.termwarn("Cannot find valid git repo associated with this directory.") + + def _add_singleton( + self, data_type: str, key: str, value: dict[int | str, str] + ) -> None: + """Store a singleton item to wandb config. + + A singleton in this context is a piece of data that is continually + logged with the same value in each history step, but represented + as a single item in the config. + + We do this to avoid filling up history with a lot of repeated unnecessary data + + Add singleton can be called many times in one run, and it will only be + updated when the value changes. The last value logged will be the one + persisted to the server. + """ + value_extra = {"type": data_type, "key": key, "value": value} + + if data_type not in self._config["_wandb"]: + self._config["_wandb"][data_type] = {} + + if data_type in self._config["_wandb"][data_type]: + old_value = self._config["_wandb"][data_type][key] + else: + old_value = None + + if value_extra != old_value: + self._config["_wandb"][data_type][key] = value_extra + self._config.persist() + + def _log( + self, + data: dict[str, Any], + step: int | None = None, + commit: bool | None = None, + ) -> None: + if not isinstance(data, Mapping): + raise TypeError("wandb.log must be passed a dictionary") + + if any(not isinstance(key, str) for key in data.keys()): + raise TypeError("Key values passed to `wandb.log` must be strings.") + + self._partial_history_callback(data, step, commit) + + if step is not None: + if os.getpid() != self._init_pid or self._is_attached: + wandb.termwarn( + "Note that setting step in multiprocessing can result in data loss. " + "Please use `run.define_metric(...)` to define a custom metric " + "to log your step values.", + repeat=False, + ) + # if step is passed in when tensorboard_sync is used we honor the step passed + # to make decisions about how to close out the history record, but will strip + # this history later on in publish_history() + if len(wandb.patched["tensorboard"]) > 0: + wandb.termwarn( + "Step cannot be set when using tensorboard syncing. " + "Please use `run.define_metric(...)` to define a custom metric " + "to log your step values.", + repeat=False, + ) + if step > self._step: + self._step = step + + if (step is None and commit is None) or commit: + self._step += 1 + + @_log_to_run + @_raise_if_finished + @_attach + def log( + self, + data: dict[str, Any], + step: int | None = None, + commit: bool | None = None, + ) -> None: + """Upload run data. + + Use `log` to log data from runs, such as scalars, images, video, + histograms, plots, and tables. See [Log objects and media](https://docs.wandb.ai/guides/track/log) for + code snippets, best practices, and more. + + Basic usage: + + ```python + import wandb + + with wandb.init() as run: + run.log({"train-loss": 0.5, "accuracy": 0.9}) + ``` + + The previous code snippet saves the loss and accuracy to the run's + history and updates the summary values for these metrics. + + Visualize logged data in a workspace at [wandb.ai](https://wandb.ai), + or locally on a [self-hosted instance](https://docs.wandb.ai/guides/hosting) + of the W&B app, or export data to visualize and explore locally, such as in a + Jupyter notebook, with the [Public API](https://docs.wandb.ai/guides/track/public-api-guide). + + Logged values don't have to be scalars. You can log any + [W&B supported Data Type](https://docs.wandb.ai/ref/python/data-types/) + such as images, audio, video, and more. For example, you can use + `wandb.Table` to log structured data. See + [Log tables, visualize and query data](https://docs.wandb.ai/guides/models/tables/tables-walkthrough) + tutorial for more details. + + W&B organizes metrics with a forward slash (`/`) in their name + into sections named using the text before the final slash. For example, + the following results in two sections named "train" and "validate": + + ```python + with wandb.init() as run: + # Log metrics in the "train" section. + run.log( + { + "train/accuracy": 0.9, + "train/loss": 30, + "validate/accuracy": 0.8, + "validate/loss": 20, + } + ) + ``` + + Only one level of nesting is supported; `run.log({"a/b/c": 1})` + produces a section named "a/b". + + `run.log()` is not intended to be called more than a few times per second. + For optimal performance, limit your logging to once every N iterations, + or collect data over multiple iterations and log it in a single step. + + By default, each call to `log` creates a new "step". + The step must always increase, and it is not possible to log + to a previous step. You can use any metric as the X axis in charts. + See [Custom log axes](https://docs.wandb.ai/guides/track/log/customize-logging-axes/) + for more details. + + In many cases, it is better to treat the W&B step like + you'd treat a timestamp rather than a training step. + + ```python + with wandb.init() as run: + # Example: log an "epoch" metric for use as an X axis. + run.log({"epoch": 40, "train-loss": 0.5}) + ``` + + It is possible to use multiple `wandb.Run.log()` invocations to log to + the same step with the `step` and `commit` parameters. + The following are all equivalent: + + ```python + with wandb.init() as run: + # Normal usage: + run.log({"train-loss": 0.5, "accuracy": 0.8}) + run.log({"train-loss": 0.4, "accuracy": 0.9}) + + # Implicit step without auto-incrementing: + run.log({"train-loss": 0.5}, commit=False) + run.log({"accuracy": 0.8}) + run.log({"train-loss": 0.4}, commit=False) + run.log({"accuracy": 0.9}) + + # Explicit step: + run.log({"train-loss": 0.5}, step=current_step) + run.log({"accuracy": 0.8}, step=current_step) + current_step += 1 + run.log({"train-loss": 0.4}, step=current_step) + run.log({"accuracy": 0.9}, step=current_step) + ``` + + Args: + data: A `dict` with `str` keys and values that are serializable + Python objects including: `int`, `float` and `string`; + any of the `wandb.data_types`; lists, tuples and NumPy arrays + of serializable Python objects; other `dict`s of this + structure. + step: The step number to log. If `None`, then an implicit + auto-incrementing step is used. See the notes in + the description. + commit: If true, finalize and upload the step. If false, then + accumulate data for the step. See the notes in the description. + If `step` is `None`, then the default is `commit=True`; + otherwise, the default is `commit=False`. + + Examples: + For more and more detailed examples, see + [our guides to logging](https://docs.wandb.com/guides/track/log). + + Basic usage + + ```python + import wandb + + with wandb.init() as run: + run.log({"train-loss": 0.5, "accuracy": 0.9 + ``` + + Incremental logging + + ```python + import wandb + + with wandb.init() as run: + run.log({"loss": 0.2}, commit=False) + # Somewhere else when I'm ready to report this step: + run.log({"accuracy": 0.8}) + ``` + + Histogram + + ```python + import numpy as np + import wandb + + # sample gradients at random from normal distribution + gradients = np.random.randn(100, 100) + with wandb.init() as run: + run.log({"gradients": wandb.Histogram(gradients)}) + ``` + + Image from NumPy + + ```python + import numpy as np + import wandb + + with wandb.init() as run: + examples = [] + for i in range(3): + pixels = np.random.randint(low=0, high=256, size=(100, 100, 3)) + image = wandb.Image(pixels, caption=f"random field {i}") + examples.append(image) + run.log({"examples": examples}) + ``` + + Image from PIL + + ```python + import numpy as np + from PIL import Image as PILImage + import wandb + + with wandb.init() as run: + examples = [] + for i in range(3): + pixels = np.random.randint( + low=0, + high=256, + size=(100, 100, 3), + dtype=np.uint8, + ) + pil_image = PILImage.fromarray(pixels, mode="RGB") + image = wandb.Image(pil_image, caption=f"random field {i}") + examples.append(image) + run.log({"examples": examples}) + ``` + + Video from NumPy + + ```python + import numpy as np + import wandb + + with wandb.init() as run: + # axes are (time, channel, height, width) + frames = np.random.randint( + low=0, + high=256, + size=(10, 3, 100, 100), + dtype=np.uint8, + ) + run.log({"video": wandb.Video(frames, fps=4)}) + ``` + + Matplotlib plot + + ```python + from matplotlib import pyplot as plt + import numpy as np + import wandb + + with wandb.init() as run: + fig, ax = plt.subplots() + x = np.linspace(0, 10) + y = x * x + ax.plot(x, y) # plot y = x^2 + run.log({"chart": fig}) + ``` + + PR Curve + + ```python + import wandb + + with wandb.init() as run: + run.log({"pr": wandb.plot.pr_curve(y_test, y_probas, labels)}) + ``` + + 3D Object + + ```python + import wandb + + with wandb.init() as run: + run.log( + { + "generated_samples": [ + wandb.Object3D(open("sample.obj")), + wandb.Object3D(open("sample.gltf")), + wandb.Object3D(open("sample.glb")), + ] + } + ) + ``` + + Raises: + wandb.Error: If called before `wandb.init()`. + ValueError: If invalid data is passed. + + """ + if step is not None: + with telemetry.context(run=self) as tel: + tel.feature.set_step_log = True + + if self._settings._shared and step is not None: + wandb.termwarn( + "In shared mode, the use of `wandb.log` with the step argument is not supported " + f"and will be ignored. Please refer to {url_registry.url('define-metric')} " + "on how to customize your x-axis.", + repeat=False, + ) + self._log(data=data, step=step, commit=commit) + + @_log_to_run + @_raise_if_finished + @_attach + def save( + self, + glob_str: str | os.PathLike, + base_path: str | os.PathLike | None = None, + policy: PolicyName = "live", + ) -> bool | list[str]: + """Sync one or more files to W&B. + + Relative paths are relative to the current working directory. + + A Unix glob, such as "myfiles/*", is expanded at the time `save` is + called regardless of the `policy`. In particular, new files are not + picked up automatically. + + A `base_path` may be provided to control the directory structure of + uploaded files. It should be a prefix of `glob_str`, and the directory + structure beneath it is preserved. + + When given an absolute path or glob and no `base_path`, one + directory level is preserved as in the example above. + + 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("/User/username/Documents/run123/*.txt") + # => Saves files in a "run123/" folder in the run. See note below. + + run.save("/User/username/Documents/run123/*.txt", base_path="/User") + # => Saves files in a "username/Documents/run123/" folder in the run. + + run.save("files/*/saveme.txt") + # => Saves each "saveme.txt" file in an appropriate subdirectory + # of "files/". + + # Explicitly finish the run since a context manager is not used. + run.finish() + ``` + """ + if isinstance(glob_str, bytes): + # Preserved for backward compatibility: allow bytes inputs. + glob_str = glob_str.decode("utf-8") + if isinstance(glob_str, str) and (glob_str.startswith(("gs://", "s3://"))): + # Provide a better error message for a common misuse. + wandb.termlog(f"{glob_str} is a cloud storage url, can't save file to W&B.") + return [] + # NOTE: We use PurePath instead of Path because WindowsPath doesn't + # like asterisks and errors out in resolve(). It also makes logical + # sense: globs aren't real paths, they're just path-like strings. + glob_path = pathlib.PurePath(glob_str) + resolved_glob_path = pathlib.PurePath(os.path.abspath(glob_path)) + + if base_path is not None: + base_path = pathlib.Path(base_path) + elif not glob_path.is_absolute(): + base_path = pathlib.Path(".") + else: + # Absolute glob paths with no base path get special handling. + wandb.termwarn( + "Saving files without folders. If you want to preserve " + "subdirectories pass base_path to wandb.save, i.e. " + 'wandb.save("/mnt/folder/file.h5", base_path="/mnt")', + repeat=False, + ) + base_path = resolved_glob_path.parent.parent + + if policy not in ("live", "end", "now"): + raise ValueError( + 'Only "live", "end" and "now" policies are currently supported.' + ) + + resolved_base_path = pathlib.PurePath(os.path.abspath(base_path)) + + return self._save( + resolved_glob_path, + resolved_base_path, + policy, + ) + + def _save( + self, + glob_path: pathlib.PurePath, + base_path: pathlib.PurePath, + policy: PolicyName, + ) -> list[str]: + # Can't use is_relative_to() because that's added in Python 3.9, + # but we support down to Python 3.8. + if not str(glob_path).startswith(str(base_path)): + raise ValueError("Glob may not walk above the base path") + + if glob_path == base_path: + raise ValueError("Glob cannot be the same as the base path") + + relative_glob = glob_path.relative_to(base_path) + if relative_glob.parts[0] == "*": + raise ValueError("Glob may not start with '*' relative to the base path") + relative_glob_str = GlobStr(str(relative_glob)) + + with telemetry.context(run=self) as tel: + tel.feature.save = True + + # Files in the files directory matched by the glob, including old and + # new ones. + globbed_files = set( + pathlib.Path( + self._settings.files_dir, + ).glob(relative_glob_str) + ) + + had_symlinked_files = len(globbed_files) > 0 + is_star_glob = "*" in relative_glob_str + + # The base_path may itself be a glob, so we can't do + # base_path.glob(relative_glob_str) + for path_str in glob.glob(str(base_path / relative_glob_str)): + source_path = pathlib.Path(path_str).absolute() + + # We can't use relative_to() because base_path may be a glob. + relative_path = pathlib.Path(*source_path.parts[len(base_path.parts) :]) + + target_path = pathlib.Path(self._settings.files_dir, relative_path) + globbed_files.add(target_path) + + # If the file is already where it needs to be, don't create a symlink. + if source_path.resolve() == target_path.resolve(): + continue + + target_path.parent.mkdir(parents=True, exist_ok=True) + + # Delete the symlink if it exists. + target_path.unlink(missing_ok=True) + + target_path.symlink_to(source_path) + + # Inform users that new files aren't detected automatically. + if not had_symlinked_files and is_star_glob: + file_str = f"{len(globbed_files)} file" + if len(globbed_files) > 1: + file_str += "s" + wandb.termwarn( + f"Symlinked {file_str} into the W&B run directory, " + "call wandb.save again to sync new files." + ) + + files_dict: FilesDict = { + "files": [ + ( + GlobStr(str(f.relative_to(self._settings.files_dir))), + policy, + ) + for f in globbed_files + ] + } + if self._backend and self._backend.interface: + self._backend.interface.publish_files(files_dict) + + return [str(f) for f in globbed_files] + + @_log_to_run + @_attach + def restore( + self, + name: str, + run_path: str | None = None, + replace: bool = False, + root: str | None = None, + ) -> None | TextIO: + return restore( + name, + run_path or self._get_path(), + replace, + root or self._settings.files_dir, + ) + + @_log_to_run + @_attach + def finish( + self, + exit_code: int | None = None, + quiet: bool | None = None, + ) -> None: + """Finish a run and upload any remaining data. + + Marks the completion of a W&B run and ensures all data is synced to the server. + The run's final state is determined by its exit conditions and sync status. + + Run States: + - Running: Active run that is logging data and/or sending heartbeats. + - Crashed: Run that stopped sending heartbeats unexpectedly. + - Finished: Run completed successfully (`exit_code=0`) with all data synced. + - Failed: Run completed with errors (`exit_code!=0`). + - Killed: Run was forcibly stopped before it could finish. + + Args: + exit_code: Integer indicating the run's exit status. Use 0 for success, + any other value marks the run as failed. + quiet: Deprecated. Configure logging verbosity using `wandb.Settings(quiet=...)`. + """ + if quiet is not None: + deprecate.deprecate( + field_name=Deprecated.run__finish_quiet, + warning_message=( + "The `quiet` argument to `wandb.run.finish()` is deprecated, " + "use `wandb.Settings(quiet=...)` to set this instead." + ), + run=self, + ) + return self._finish(exit_code) + + @_log_to_run + def _finish( + self, + exit_code: int | None = None, + ) -> None: + if self._is_finished: + return + + assert self._wl + + logger.info(f"finishing run {self._get_path()}") + with telemetry.context(run=self) as tel: + tel.feature.finish = True + + # Run hooks that need to happen before the last messages to the + # internal service, like Jupyter hooks. + for hook in self._teardown_hooks: + if hook.stage == TeardownStage.EARLY: + hook.call() + + # Early-stage hooks may use methods that require _is_finished + # to be False, so we set this after running those hooks. + self._is_finished = True + self._wl.remove_active_run(self) + + try: + self._atexit_cleanup(exit_code=exit_code) + + # Run hooks that should happen after the last messages to the + # internal service, like detaching the logger. + for hook in self._teardown_hooks: + if hook.stage == TeardownStage.LATE: + hook.call() + self._teardown_hooks = [] + + # Inform the service that we're done sending messages for this run. + # + # TODO: Why not do this in _atexit_cleanup()? + if self._settings.run_id: + service = self._wl.assert_service() + service.inform_finish(run_id=self._settings.run_id) + + finally: + if wandb.run is self: + module.unset_globals() + wandb._sentry.end_session() + + @_log_to_run + @_raise_if_finished + @_attach + def status( + self, + ) -> RunStatus: + """Get sync info from the internal backend, about the current run's sync status.""" + if not self._backend or not self._backend.interface: + return RunStatus() + + handle_run_status = self._backend.interface.deliver_request_run_status() + result = handle_run_status.wait_or(timeout=None) + sync_data = result.response.run_status_response + + sync_time = None + if sync_data.sync_time.seconds: + sync_time = datetime.fromtimestamp( + sync_data.sync_time.seconds + sync_data.sync_time.nanos / 1e9 + ) + return RunStatus( + sync_items_total=sync_data.sync_items_total, + sync_items_pending=sync_data.sync_items_pending, + sync_time=sync_time, + ) + + def _add_panel( + self, visualize_key: str, panel_type: str, panel_config: dict + ) -> None: + config = { + "panel_type": panel_type, + "panel_config": panel_config, + } + self._config_callback(val=config, key=("_wandb", "visualize", visualize_key)) + + def _redirect( + self, + stdout_slave_fd: int | None, + stderr_slave_fd: int | None, + console: str | None = None, + ) -> None: + if console is None: + console = self._settings.console + # only use raw for service to minimize potential changes + if console == "wrap": + console = "wrap_raw" + logger.info("redirect: %s", console) + + out_redir: redirect.RedirectBase + err_redir: redirect.RedirectBase + + # raw output handles the output_log writing in the internal process + if console in {"redirect", "wrap_emu"}: + output_log_path = os.path.join( + self._settings.files_dir, filenames.OUTPUT_FNAME + ) + # output writer might have been set up, see wrap_fallback case + if not self._output_writer: + self._output_writer = filesystem.CRDedupedFile( + open(output_log_path, "wb") + ) + + if console == "redirect": + logger.info("Redirecting console.") + out_redir = redirect.Redirect( + src="stdout", + cbs=[ + lambda data: self._console_callback("stdout", data), + self._output_writer.write, # type: ignore + ], + flush_periodically=(self._settings.mode == "online"), + ) + err_redir = redirect.Redirect( + src="stderr", + cbs=[ + lambda data: self._console_callback("stderr", data), + self._output_writer.write, # type: ignore + ], + flush_periodically=(self._settings.mode == "online"), + ) + if os.name == "nt": + + def wrap_fallback() -> None: + if self._out_redir: + self._out_redir.uninstall() + if self._err_redir: + self._err_redir.uninstall() + msg = ( + "Tensorflow detected. Stream redirection is not supported " + "on Windows when tensorflow is imported. Falling back to " + "wrapping stdout/err." + ) + wandb.termlog(msg) + self._redirect(None, None, console="wrap") + + add_import_hook("tensorflow", wrap_fallback) + elif console == "wrap_emu": + logger.info("Wrapping output streams.") + out_redir = redirect.StreamWrapper( + src="stdout", + cbs=[ + lambda data: self._console_callback("stdout", data), + self._output_writer.write, # type: ignore + ], + flush_periodically=(self._settings.mode == "online"), + ) + err_redir = redirect.StreamWrapper( + src="stderr", + cbs=[ + lambda data: self._console_callback("stderr", data), + self._output_writer.write, # type: ignore + ], + flush_periodically=(self._settings.mode == "online"), + ) + elif console == "wrap_raw": + logger.info("Wrapping output streams.") + out_redir = redirect.StreamRawWrapper( + src="stdout", + cbs=[ + lambda data: self._console_raw_callback("stdout", data), + ], + ) + err_redir = redirect.StreamRawWrapper( + src="stderr", + cbs=[ + lambda data: self._console_raw_callback("stderr", data), + ], + ) + elif console == "off": + return + else: + raise ValueError("unhandled console") + try: + # save stdout and stderr before installing new write functions + out_redir.install() + err_redir.install() + self._out_redir = out_redir + self._err_redir = err_redir + logger.info("Redirects installed.") + except Exception as e: + wandb.termwarn(f"Failed to redirect: {e}") + logger.exception("Failed to redirect.") + return + + def _restore(self) -> None: + logger.info("restore") + # TODO(jhr): drain and shutdown all threads + if self._out_redir: + self._out_redir.uninstall() + if self._err_redir: + self._err_redir.uninstall() + logger.info("restore done") + + def _atexit_cleanup(self, exit_code: int | None = None) -> None: + if self._backend is None: + logger.warning("process exited without backend configured") + return + if self._atexit_cleanup_called: + return + self._atexit_cleanup_called = True + + exit_code = exit_code or (self._hooks and self._hooks.exit_code) or 0 + self._exit_code = exit_code + logger.info(f"got exitcode: {exit_code}") + + # Delete this run's "resume" file if the run finished successfully. + # + # This is used by the "auto" resume mode, which resumes from the last + # failed (or unfinished/crashed) run. If we reach this line, then this + # run shouldn't be a candidate for "auto" resume. + if exit_code == 0: + if os.path.exists(self._settings.resume_fname): + os.remove(self._settings.resume_fname) + + try: + self._on_finish() + + except KeyboardInterrupt: + if not wandb.wandb_agent._is_running(): # type: ignore + wandb.termerror("Control-C detected -- Run data was not synced") + raise + + except Exception: + self._console_stop() + logger.exception("Problem finishing run") + wandb.termerror("Problem finishing run") + raise + + Run._footer( + sampled_history=self._sampled_history, + final_summary=self._final_summary, + poll_exit_response=self._poll_exit_response, + internal_messages_response=self._internal_messages_response, + settings=self._settings, + printer=self._printer, + ) + + def _console_start(self) -> None: + logger.info("atexit reg") + self._hooks = ExitHooks() + + self._redirect(self._stdout_slave_fd, self._stderr_slave_fd) + + def _console_stop(self) -> None: + self._restore() + if self._output_writer: + self._output_writer.close() + self._output_writer = None + + def _on_start(self) -> None: + self._header() + + if self._settings.save_code and self._settings.code_dir is not None: + self.log_code(self._settings.code_dir) + + if self._settings.x_save_requirements: + if self._backend and self._backend.interface: + from wandb.util import working_set + + logger.debug( + "Saving list of pip packages installed into the current environment" + ) + self._backend.interface.publish_python_packages(working_set()) + + if self._backend and self._backend.interface and not self._settings._offline: + assert self._settings.run_id + self._run_status_checker = RunStatusChecker( + self._settings.run_id, + interface=self._backend.interface, + settings=self._settings, + ) + self._run_status_checker.start() + + self._console_start() + self._on_ready() + + def _on_attach(self) -> None: + """Event triggered when run is attached to another run.""" + with telemetry.context(run=self) as tel: + tel.feature.attach = True + + self._is_attached = True + self._on_ready() + + def _register_telemetry_import_hooks( + self, + ) -> None: + def _telemetry_import_hook( + run: Run, + module: Any, + ) -> None: + with telemetry.context(run=run) as tel: + try: + name = getattr(module, "__name__", None) + if name is not None: + setattr(tel.imports_finish, name, True) + except AttributeError: + return + + import_telemetry_set = telemetry.list_telemetry_imports() + import_hook_fn = functools.partial(_telemetry_import_hook, self) + if not self._settings.run_id: + return + for module_name in import_telemetry_set: + register_post_import_hook( + import_hook_fn, + self._settings.run_id, + module_name, + ) + + def _on_ready(self) -> None: + """Event triggered when run is ready for the user.""" + assert self._wl + self._wl.add_active_run(self) + + self._register_telemetry_import_hooks() + + # start reporting any telemetry changes + self._telemetry_obj_active = True + self._telemetry_flush() + + try: + self._detect_and_apply_job_inputs() + except Exception: + logger.exception("Problem applying launch job inputs") + + # object is about to be returned to the user, don't let them modify it + self._freeze() + + if not self._settings.resume: + if os.path.exists(self._settings.resume_fname): + os.remove(self._settings.resume_fname) + + def _detect_and_apply_job_inputs(self) -> None: + """If the user has staged launch inputs, apply them to the run.""" + from wandb.sdk.launch.inputs.internal import StagedLaunchInputs + + StagedLaunchInputs().apply(self) + + def _make_job_source_reqs(self) -> tuple[list[str], dict[str, Any], dict[str, Any]]: + from wandb.util import working_set + + installed_packages_list = sorted(f"{d.key}=={d.version}" for d in working_set()) + input_types = TypeRegistry.type_of(self.config.as_dict()).to_json() + output_types = TypeRegistry.type_of(self.summary._as_dict()).to_json() + + return installed_packages_list, input_types, output_types + + def _construct_job_artifact( + self, + name: str, + source_dict: JobSourceDict, + installed_packages_list: list[str], + patch_path: os.PathLike | None = None, + ) -> Artifact: + job_artifact = InternalArtifact(name, job_builder.JOB_ARTIFACT_TYPE) + if patch_path and os.path.exists(patch_path): + job_artifact.add_file(FilePathStr(str(patch_path)), "diff.patch") + with job_artifact.new_file("requirements.frozen.txt") as f: + f.write("\n".join(installed_packages_list)) + with job_artifact.new_file("wandb-job.json") as f: + f.write(json.dumps(source_dict)) + + return job_artifact + + def _create_image_job( + self, + input_types: dict[str, Any], + output_types: dict[str, Any], + installed_packages_list: list[str], + docker_image_name: str | None = None, + args: list[str] | None = None, + ) -> Artifact | None: + docker_image_name = docker_image_name or os.getenv("WANDB_DOCKER") + + if not docker_image_name: + return None + + name = wandb.util.make_artifact_name_safe(f"job-{docker_image_name}") + s_args: Sequence[str] = args if args is not None else self._settings._args + source_info: JobSourceDict = { + "_version": "v0", + "source_type": "image", + "source": {"image": docker_image_name, "args": s_args}, + "input_types": input_types, + "output_types": output_types, + "runtime": self._settings._python, + } + job_artifact = self._construct_job_artifact( + name, source_info, installed_packages_list + ) + + return job_artifact + + def _log_job_artifact_with_image( + self, docker_image_name: str, args: list[str] | None = None + ) -> Artifact: + packages, in_types, out_types = self._make_job_source_reqs() + job_artifact = self._create_image_job( + in_types, + out_types, + packages, + args=args, + docker_image_name=docker_image_name, + ) + + assert job_artifact + artifact = self.log_artifact(job_artifact) + + if not artifact: + raise wandb.Error(f"Job Artifact log unsuccessful: {artifact}") + else: + return artifact + + async def _display_finish_stats( + self, + progress_printer: progress.ProgressPrinter, + ) -> None: + last_result: Result | None = None + + async def loop_update_printer() -> None: + while True: + if last_result: + progress_printer.update( + [last_result.response.poll_exit_response], + ) + await asyncio.sleep(0.1) + + async def loop_poll_exit() -> None: + nonlocal last_result + assert self._backend and self._backend.interface + + while True: + handle = self._backend.interface.deliver_poll_exit() + + time_start = time.monotonic() + last_result = await handle.wait_async(timeout=None) + + # Update at most once a second. + time_elapsed = time.monotonic() - time_start + if time_elapsed < 1: + await asyncio.sleep(1 - time_elapsed) + + async with asyncio_compat.open_task_group() as task_group: + task_group.start_soon(loop_update_printer()) + task_group.start_soon(loop_poll_exit()) + + def _on_finish(self) -> None: + trigger.call("on_finished") + + if self._run_status_checker is not None: + self._run_status_checker.stop() + + self._console_stop() # TODO: there's a race here with jupyter console logging + + assert self._backend and self._backend.interface + + if self._settings.x_update_finish_state: + exit_handle = self._backend.interface.deliver_exit(self._exit_code) + else: + exit_handle = self._backend.interface.deliver_finish_without_exit() + + with progress.progress_printer( + self._printer, + default_text="Finishing up...", + ) as progress_printer: + # Wait for the run to complete. + wait_with_progress( + exit_handle, + timeout=None, + progress_after=1, + display_progress=functools.partial( + self._display_finish_stats, + progress_printer, + ), + ) + + poll_exit_handle = self._backend.interface.deliver_poll_exit() + result = poll_exit_handle.wait_or(timeout=None) + self._poll_exit_response = result.response.poll_exit_response + + internal_messages_handle = self._backend.interface.deliver_internal_messages() + result = internal_messages_handle.wait_or(timeout=None) + self._internal_messages_response = result.response.internal_messages_response + + # dispatch all our final requests + + final_summary_handle = self._backend.interface.deliver_get_summary() + sampled_history_handle = ( + self._backend.interface.deliver_request_sampled_history() + ) + + result = sampled_history_handle.wait_or(timeout=None) + self._sampled_history = result.response.sampled_history_response + + result = final_summary_handle.wait_or(timeout=None) + self._final_summary = result.response.get_summary_response + + if self._backend: + self._backend.cleanup() + + if self._run_status_checker: + self._run_status_checker.join() + + if self._settings.run_id: + self._unregister_telemetry_import_hooks(self._settings.run_id) + + @staticmethod + def _unregister_telemetry_import_hooks(run_id: str) -> None: + import_telemetry_set = telemetry.list_telemetry_imports() + for module_name in import_telemetry_set: + unregister_post_import_hook(module_name, run_id) + + @_log_to_run + @_raise_if_finished + @_attach + def define_metric( + self, + name: str, + step_metric: str | wandb_metric.Metric | None = None, + step_sync: bool | None = None, + hidden: bool | None = None, + summary: str | None = None, + goal: str | None = None, + overwrite: bool | None = None, + ) -> wandb_metric.Metric: + """Customize metrics logged with `wandb.Run.log()`. + + Args: + name: The name of the metric to customize. + step_metric: The name of another metric to serve as the X-axis + for this metric in automatically generated charts. + step_sync: Automatically insert the last value of step_metric into + `wandb.Run.log()` if it is not provided explicitly. Defaults to True + if step_metric is specified. + hidden: Hide this metric from automatic plots. + summary: Specify aggregate metrics added to summary. + Supported aggregations include "min", "max", "mean", "last", + "first", "best", "copy" and "none". "none" prevents a summary + from being generated. "best" is used together with the goal + parameter, "best" is deprecated and should not be used, use + "min" or "max" instead. "copy" is deprecated and should not be + used. + goal: Specify how to interpret the "best" summary type. + Supported options are "minimize" and "maximize". "goal" is + deprecated and should not be used, use "min" or "max" instead. + overwrite: If false, then this call is merged with previous + `define_metric` calls for the same metric by using their + values for any unspecified parameters. If true, then + unspecified parameters overwrite values specified by + previous calls. + + Returns: + An object that represents this call but can otherwise be discarded. + """ + if summary and "copy" in summary: + deprecate.deprecate( + Deprecated.run__define_metric_copy, + "define_metric(summary='copy') is deprecated and will be removed.", + self, + ) + + if (summary and "best" in summary) or goal is not None: + deprecate.deprecate( + Deprecated.run__define_metric_best_goal, + "define_metric(summary='best', goal=...) is deprecated and will be removed. " + "Use define_metric(summary='min') or define_metric(summary='max') instead.", + self, + ) + + return self._define_metric( + name, + step_metric, + step_sync, + hidden, + summary, + goal, + overwrite, + ) + + def _define_metric( + self, + name: str, + step_metric: str | wandb_metric.Metric | None = None, + step_sync: bool | None = None, + hidden: bool | None = None, + summary: str | None = None, + goal: str | None = None, + overwrite: bool | None = None, + ) -> wandb_metric.Metric: + if not name: + raise wandb.Error("define_metric() requires non-empty name argument") + if isinstance(step_metric, wandb_metric.Metric): + step_metric = step_metric.name + for arg_name, arg_val, exp_type in ( + ("name", name, str), + ("step_metric", step_metric, str), + ("step_sync", step_sync, bool), + ("hidden", hidden, bool), + ("summary", summary, str), + ("goal", goal, str), + ("overwrite", overwrite, bool), + ): + # NOTE: type checking is broken for isinstance and str + if arg_val is not None and not isinstance(arg_val, exp_type): + arg_type = type(arg_val).__name__ + raise wandb.Error( + f"Unhandled define_metric() arg: {arg_name} type: {arg_type}" + ) + stripped = name[:-1] if name.endswith("*") else name + if "*" in stripped: + raise wandb.Error( + f"Unhandled define_metric() arg: name (glob suffixes only): {name}" + ) + summary_ops: Sequence[str] | None = None + if summary: + summary_items = [s.lower() for s in summary.split(",")] + summary_ops = [] + valid = {"min", "max", "mean", "best", "last", "copy", "none", "first"} + # TODO: deprecate copy and best + for i in summary_items: + if i not in valid: + raise wandb.Error(f"Unhandled define_metric() arg: summary op: {i}") + summary_ops.append(i) + with telemetry.context(run=self) as tel: + tel.feature.metric_summary = True + # TODO: deprecate goal + goal_cleaned: str | None = None + if goal is not None: + goal_cleaned = goal[:3].lower() + valid_goal = {"min", "max"} + if goal_cleaned not in valid_goal: + raise wandb.Error(f"Unhandled define_metric() arg: goal: {goal}") + with telemetry.context(run=self) as tel: + tel.feature.metric_goal = True + if hidden: + with telemetry.context(run=self) as tel: + tel.feature.metric_hidden = True + if step_sync: + with telemetry.context(run=self) as tel: + tel.feature.metric_step_sync = True + + with telemetry.context(run=self) as tel: + tel.feature.metric = True + + m = wandb_metric.Metric( + name=name, + step_metric=step_metric, + step_sync=step_sync, + summary=summary_ops, + hidden=hidden, + goal=goal_cleaned, + overwrite=overwrite, + ) + m._set_callback(self._metric_callback) + m._commit() + return m + + @_log_to_run + @_attach + def watch( + self, + models: torch.nn.Module | Sequence[torch.nn.Module], + criterion: torch.F | None = None, # type: ignore + log: Literal["gradients", "parameters", "all"] | None = "gradients", + log_freq: int = 1000, + idx: int | None = None, + log_graph: bool = False, + ) -> None: + """Hook into given PyTorch model to monitor gradients and the model's computational graph. + + This function can track parameters, gradients, or both during training. + + Args: + models: A single model or a sequence of models to be monitored. + criterion: The loss function being optimized (optional). + log: Specifies whether to log "gradients", "parameters", or "all". + Set to None to disable logging. (default="gradients"). + log_freq: Frequency (in batches) to log gradients and parameters. (default=1000) + idx: Index used when tracking multiple models with `wandb.watch`. (default=None) + log_graph: Whether to log the model's computational graph. (default=False) + + Raises: + ValueError: + If `wandb.init()` has not been called or if any of the models are not instances + of `torch.nn.Module`. + """ + wandb.sdk._watch(self, models, criterion, log, log_freq, idx, log_graph) + + @_log_to_run + @_attach + def unwatch( + self, models: torch.nn.Module | Sequence[torch.nn.Module] | None = None + ) -> None: + """Remove pytorch model topology, gradient and parameter hooks. + + Args: + models: Optional list of pytorch models that have had watch called on them. + """ + wandb.sdk._unwatch(self, models=models) + + @_log_to_run + @_raise_if_finished + @_attach + def link_artifact( + self, + artifact: Artifact, + target_path: str, + aliases: list[str] | None = None, + ) -> Artifact | None: + """Link the given artifact to a portfolio (a promoted collection of artifacts). + + Linked artifacts are visible in the UI for the specified portfolio. + + Args: + artifact: the (public or local) artifact which will be linked + target_path: `str` - takes the following forms: `{portfolio}`, `{project}/{portfolio}`, + or `{entity}/{project}/{portfolio}` + aliases: `List[str]` - optional alias(es) that will only be applied on this linked artifact + inside the portfolio. + The alias "latest" will always be applied to the latest version of an artifact that is linked. + + Returns: + The linked artifact if linking was successful, otherwise None. + + """ + 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.project and is_artifact_registry_project(target.project)): + target = target.with_defaults(prefix=self.entity, project=self.project) + + return artifact.link(target.to_str(), aliases) + + @_log_to_run + @_raise_if_finished + @_attach + def use_artifact( + self, + artifact_or_name: str | Artifact, + type: str | None = None, + aliases: list[str] | None = None, + use_as: str | None = None, + ) -> Artifact: + """Declare an artifact as an input to a run. + + Call `download` or `file` on the returned object to get the contents locally. + + Args: + artifact_or_name: The name of the artifact to use. May be prefixed + with the name of the project the artifact was logged to + ("" or "/"). If no + entity is specified in the name, the Run or API setting's entity is used. + Valid names can be in the following forms + - name:version + - name:alias + type: The type of artifact to use. + aliases: Aliases to apply to this artifact + use_as: This argument is deprecated and does nothing. + + Returns: + An `Artifact` object. + + Examples: + ```python + import wandb + + run = wandb.init(project="") + + # Use an artifact by name and alias + artifact_a = run.use_artifact(artifact_or_name=":") + + # Use an artifact by name and version + artifact_b = run.use_artifact(artifact_or_name=":v") + + # Use an artifact by entity/project/name:alias + artifact_c = run.use_artifact( + artifact_or_name="//:" + ) + + # Use an artifact by entity/project/name:version + artifact_d = run.use_artifact( + artifact_or_name="//:v" + ) + + # Explicitly finish the run since a context manager is not used. + run.finish() + ``` + + """ + if self._settings._offline: + raise TypeError("Cannot use artifact when in offline mode.") + + api = internal.Api( + default_settings={ + "entity": self._settings.entity, + "project": self._settings.project, + } + ) + api.set_current_run_id(self._settings.run_id) + + if use_as is not None: + deprecate.deprecate( + field_name=Deprecated.run__use_artifact_use_as, + warning_message=( + "`use_as` argument is deprecated and does not affect the behaviour of `run.use_artifact`" + ), + ) + + if isinstance(artifact_or_name, str): + name = artifact_or_name + public_api = self._public_api() + artifact = public_api._artifact(type=type, name=name) + if type is not None and type != artifact.type: + raise ValueError( + f"Supplied type {type} does not match type {artifact.type} of artifact {artifact.name}" + ) + api.use_artifact( + artifact.id, + entity_name=self._settings.entity, + project_name=self._settings.project, + artifact_entity_name=artifact.entity, + artifact_project_name=artifact.project, + ) + else: + artifact = artifact_or_name + if aliases is None: + aliases = [] + elif isinstance(aliases, str): + aliases = [aliases] + if isinstance(artifact_or_name, Artifact) and artifact.is_draft(): + if use_as is not None: + wandb.termwarn( + "Indicating use_as is not supported when using a draft artifact" + ) + self._log_artifact( + artifact, + aliases=aliases, + is_user_created=True, + use_after_commit=True, + ) + artifact.wait() + elif isinstance(artifact, Artifact) and not artifact.is_draft(): + api.use_artifact( + artifact.id, + artifact_entity_name=artifact.entity, + artifact_project_name=artifact.project, + ) + else: + raise ValueError( + 'You must pass an artifact name (e.g. "pedestrian-dataset:v1"), ' + "an instance of `wandb.Artifact`, or `wandb.Api().artifact()` to `use_artifact`" + ) + if self._backend and self._backend.interface: + self._backend.interface.publish_use_artifact(artifact) + return artifact + + @_log_to_run + @_raise_if_finished + @_attach + def log_artifact( + self, + artifact_or_path: Artifact | StrPath, + name: str | None = None, + type: str | None = None, + aliases: list[str] | None = None, + tags: list[str] | None = None, + ) -> Artifact: + """Declare an artifact as an output of a run. + + Args: + artifact_or_path: (str or Artifact) A path to the contents of this artifact, + can be in the following forms: + - `/local/directory` + - `/local/directory/file.txt` + - `s3://bucket/path` + You can also pass an Artifact object created by calling + `wandb.Artifact`. + name: (str, optional) An artifact name. Valid names can be in the following forms: + - name:version + - name:alias + - digest + This will default to the basename of the path prepended with the current + run id if not specified. + type: (str) The type of artifact to log, examples include `dataset`, `model` + aliases: (list, optional) Aliases to apply to this artifact, + defaults to `["latest"]` + tags: (list, optional) Tags to apply to this artifact, if any. + + Returns: + An `Artifact` object. + """ + return self._log_artifact( + artifact_or_path, + name=name, + type=type, + aliases=aliases, + tags=tags, + ) + + @_log_to_run + @_raise_if_finished + @_attach + def upsert_artifact( + self, + artifact_or_path: Artifact | str, + name: str | None = None, + type: str | None = None, + aliases: list[str] | None = None, + distributed_id: str | None = None, + ) -> Artifact: + """Declare (or append to) a non-finalized artifact as output of a run. + + Note that you must call run.finish_artifact() to finalize the artifact. + This is useful when distributed jobs need to all contribute to the same artifact. + + Args: + artifact_or_path: A path to the contents of this artifact, + can be in the following forms: + - `/local/directory` + - `/local/directory/file.txt` + - `s3://bucket/path` + name: An artifact name. May be prefixed with "entity/project". Defaults + to the basename of the path prepended with the current run ID + if not specified. Valid names can be in the following forms: + - name:version + - name:alias + - digest + type: The type of artifact to log. Common examples include `dataset`, `model`. + aliases: Aliases to apply to this artifact, defaults to `["latest"]`. + distributed_id: Unique string that all distributed jobs share. If None, + defaults to the run's group name. + + Returns: + An `Artifact` object. + """ + if self._settings.run_group is None and distributed_id is None: + raise TypeError( + "Cannot upsert artifact unless run is in a group or distributed_id is provided" + ) + if distributed_id is None: + distributed_id = self._settings.run_group or "" + return self._log_artifact( + artifact_or_path, + name=name, + type=type, + aliases=aliases, + distributed_id=distributed_id, + finalize=False, + ) + + @_log_to_run + @_raise_if_finished + @_attach + def finish_artifact( + self, + artifact_or_path: Artifact | str, + name: str | None = None, + type: str | None = None, + aliases: list[str] | None = None, + distributed_id: str | None = None, + ) -> Artifact: + """Finishes a non-finalized artifact as output of a run. + + Subsequent "upserts" with the same distributed ID will result in a new version. + + Args: + artifact_or_path: A path to the contents of this artifact, + can be in the following forms: + - `/local/directory` + - `/local/directory/file.txt` + - `s3://bucket/path` + You can also pass an Artifact object created by calling + `wandb.Artifact`. + name: An artifact name. May be prefixed with entity/project. + Valid names can be in the following forms: + - name:version + - name:alias + - digest + This will default to the basename of the path prepended with the current + run id if not specified. + type: The type of artifact to log, examples include `dataset`, `model` + aliases: Aliases to apply to this artifact, + defaults to `["latest"]` + distributed_id: Unique string that all distributed jobs share. If None, + defaults to the run's group name. + + Returns: + An `Artifact` object. + """ + if self._settings.run_group is None and distributed_id is None: + raise TypeError( + "Cannot finish artifact unless run is in a group or distributed_id is provided" + ) + if distributed_id is None: + distributed_id = self._settings.run_group or "" + + return self._log_artifact( + artifact_or_path, + name, + type, + aliases, + distributed_id=distributed_id, + finalize=True, + ) + + def _log_artifact( + self, + artifact_or_path: Artifact | StrPath, + name: str | None = None, + type: str | None = None, + aliases: list[str] | None = None, + tags: list[str] | None = None, + distributed_id: str | None = None, + finalize: bool = True, + is_user_created: bool = False, + use_after_commit: bool = False, + ) -> Artifact: + if self._settings.anonymous in ["allow", "must"]: + wandb.termwarn( + "Artifacts logged anonymously cannot be claimed and expire after 7 days." + ) + + if not finalize and distributed_id is None: + raise TypeError("Must provide distributed_id if artifact is not finalize") + + if aliases is not None: + aliases = validate_aliases(aliases) + + # Check if artifact tags are supported + if tags is not None: + tags = validate_tags(tags) + + artifact, aliases = self._prepare_artifact( + artifact_or_path, name, type, aliases + ) + + if len(artifact.metadata) > MAX_ARTIFACT_METADATA_KEYS: + raise ValueError( + f"Artifact must not have more than {MAX_ARTIFACT_METADATA_KEYS} metadata keys." + ) + + artifact.distributed_id = distributed_id + self._assert_can_log_artifact(artifact) + if self._backend and self._backend.interface: + if not self._settings._offline: + handle = self._backend.interface.deliver_artifact( + self, + artifact, + aliases, + tags, + self.step, + finalize=finalize, + is_user_created=is_user_created, + use_after_commit=use_after_commit, + ) + artifact._set_save_handle(handle, self._public_api().client) + else: + self._backend.interface.publish_artifact( + self, + artifact, + aliases, + tags, + finalize=finalize, + is_user_created=is_user_created, + use_after_commit=use_after_commit, + ) + elif self._internal_run_interface: + self._internal_run_interface.publish_artifact( + self, + artifact, + aliases, + tags, + finalize=finalize, + is_user_created=is_user_created, + use_after_commit=use_after_commit, + ) + return artifact + + def _public_api(self, overrides: dict[str, str] | None = None) -> PublicApi: + overrides = {"run": self._settings.run_id} # type: ignore + if not self._settings._offline: + overrides["entity"] = self._settings.entity or "" + overrides["project"] = self._settings.project or "" + return public.Api(overrides) + + # TODO(jhr): annotate this + def _assert_can_log_artifact(self, artifact) -> None: # type: ignore + if self._settings._offline: + return + try: + public_api = self._public_api() + entity = public_api.settings["entity"] + project = public_api.settings["project"] + expected_type = Artifact._expected_type( + entity, project, artifact.name, public_api.client + ) + except requests.exceptions.RequestException: + # Just return early if there is a network error. This is + # ok, as this function is intended to help catch an invalid + # type early, but not a hard requirement for valid operation. + return + if expected_type is not None and artifact.type != expected_type: + raise ValueError( + f"Artifact {artifact.name} already exists with type '{expected_type}'; " + f"cannot create another with type '{artifact.type}'" + ) + if entity and artifact._source_entity and entity != artifact._source_entity: + raise ValueError( + f"Artifact {artifact.name} is owned by entity " + f"'{artifact._source_entity}'; it can't be moved to '{entity}'" + ) + if project and artifact._source_project and project != artifact._source_project: + raise ValueError( + f"Artifact {artifact.name} exists in project " + f"'{artifact._source_project}'; it can't be moved to '{project}'" + ) + + def _prepare_artifact( + self, + artifact_or_path: Artifact | StrPath, + name: str | None = None, + type: str | None = None, + aliases: list[str] | None = None, + ) -> tuple[Artifact, list[str]]: + if isinstance(artifact_or_path, (str, os.PathLike)): + name = ( + name + or f"run-{self._settings.run_id}-{os.path.basename(artifact_or_path)}" + ) + artifact = Artifact(name, type or "unspecified") + if os.path.isfile(artifact_or_path): + artifact.add_file(str(artifact_or_path)) + elif os.path.isdir(artifact_or_path): + artifact.add_dir(str(artifact_or_path)) + elif "://" in str(artifact_or_path): + artifact.add_reference(str(artifact_or_path)) + else: + raise ValueError( + "path must be a file, directory or external" + "reference like s3://bucket/path" + ) + else: + artifact = artifact_or_path + if not isinstance(artifact, Artifact): + raise TypeError( + "You must pass an instance of wandb.Artifact or a " + "valid file path to log_artifact" + ) + + artifact.finalize() + return artifact, _resolve_aliases(aliases) + + @_log_to_run + @_raise_if_finished + @_attach + def log_model( + self, + path: StrPath, + name: str | None = None, + aliases: list[str] | None = None, + ) -> None: + """Logs a model artifact containing the contents inside the 'path' to a run and marks it as an output to this run. + + The name of model artifact can only contain alphanumeric characters, + underscores, and hyphens. + + Args: + path: (str) A path to the contents of this model, + can be in the following forms: + - `/local/directory` + - `/local/directory/file.txt` + - `s3://bucket/path` + name: A name to assign to the model artifact that + the file contents will be added to. This will default to the + basename of the path prepended with the current run id if + not specified. + aliases: Aliases to apply to the created model artifact, + defaults to `["latest"]` + + Raises: + ValueError: If name has invalid special characters. + + Returns: + None + """ + self._log_artifact( + artifact_or_path=path, name=name, type="model", aliases=aliases + ) + + @_log_to_run + @_raise_if_finished + @_attach + def use_model(self, name: str) -> FilePathStr: + """Download the files logged in a model artifact 'name'. + + Args: + name: A model artifact name. 'name' must match the name of an existing logged + model artifact. May be prefixed with `entity/project/`. Valid names + can be in the following forms + - model_artifact_name:version + - model_artifact_name:alias + + Returns: + path (str): Path to downloaded model artifact file(s). + + Raises: + AssertionError: If model artifact 'name' is of a type that does + not contain the substring 'model'. + """ + if self._settings._offline: + # Downloading artifacts is not supported when offline. + raise RuntimeError("`use_model` not supported in offline mode.") + + artifact = self.use_artifact(artifact_or_name=name) + if "model" not in str(artifact.type.lower()): + raise AssertionError( + "You can only use this method for 'model' artifacts." + " For an artifact to be a 'model' artifact, its type property" + " must contain the substring 'model'." + ) + + path = artifact.download() + + # If returned directory contains only one file, return path to that file + dir_list = os.listdir(path) + if len(dir_list) == 1: + return FilePathStr(os.path.join(path, dir_list[0])) + return path + + @_log_to_run + @_raise_if_finished + @_attach + def link_model( + self, + path: StrPath, + registered_model_name: str, + name: str | None = None, + aliases: list[str] | None = None, + ) -> Artifact | None: + """Log a model artifact version and link it to a registered model in the model registry. + + Linked model versions are visible in the UI for the specified registered model. + + This method will: + - Check if 'name' model artifact has been logged. If so, use the artifact version that matches the files + located at 'path' or log a new version. Otherwise log files under 'path' as a new model artifact, 'name' + of type 'model'. + - Check if registered model with name 'registered_model_name' exists in the 'model-registry' project. + If not, create a new registered model with name 'registered_model_name'. + - Link version of model artifact 'name' to registered model, 'registered_model_name'. + - Attach aliases from 'aliases' list to the newly linked model artifact version. + + Args: + path: (str) A path to the contents of this model, can be in the + following forms: + - `/local/directory` + - `/local/directory/file.txt` + - `s3://bucket/path` + registered_model_name: The name of the registered model that the + model is to be linked to. A registered model is a collection of + model versions linked to the model registry, typically + representing a team's specific ML Task. The entity that this + registered model belongs to will be derived from the run. + name: The name of the model artifact that files in 'path' will be + logged to. This will default to the basename of the path + prepended with the current run id if not specified. + aliases: Aliases that will only be applied on this linked artifact + inside the registered model. The alias "latest" will always be + applied to the latest version of an artifact that is linked. + + Raises: + AssertionError: If registered_model_name is a path or + if model artifact 'name' is of a type that does not contain + the substring 'model'. + ValueError: If name has invalid special characters. + + Returns: + The linked artifact if linking was successful, otherwise `None`. + """ + name_parts = registered_model_name.split("/") + if len(name_parts) != 1: + raise AssertionError( + "Please provide only the name of the registered model." + " Do not append the entity or project name." + ) + + project = "model-registry" + target_path = self.entity + "/" + project + "/" + registered_model_name + + public_api = self._public_api() + try: + artifact = public_api._artifact(name=f"{name}:latest") + if "model" not in str(artifact.type.lower()): + raise AssertionError( + "You can only use this method for 'model' artifacts." + " For an artifact to be a 'model' artifact, its type" + " property must contain the substring 'model'." + ) + + artifact = self._log_artifact( + artifact_or_path=path, name=name, type=artifact.type + ) + except (ValueError, CommError): + artifact = self._log_artifact( + artifact_or_path=path, name=name, type="model" + ) + return self.link_artifact( + artifact=artifact, target_path=target_path, aliases=aliases + ) + + @_log_to_run + @_raise_if_finished + @_attach + def alert( + self, + title: str, + text: str, + level: str | AlertLevel | None = None, + wait_duration: int | float | timedelta | None = None, + ) -> None: + """Create an alert with the given title and text. + + Args: + title: The title of the alert, must be less than 64 characters long. + text: The text body of the alert. + level: The alert level to use, either: `INFO`, `WARN`, or `ERROR`. + wait_duration: The time to wait (in seconds) before sending another + alert with this title. + """ + level = level or AlertLevel.INFO + level_str: str = level.value if isinstance(level, AlertLevel) else level + if level_str not in {lev.value for lev in AlertLevel}: + raise ValueError("level must be one of 'INFO', 'WARN', or 'ERROR'") + + wait_duration = wait_duration or timedelta(minutes=1) + if isinstance(wait_duration, int) or isinstance(wait_duration, float): + wait_duration = timedelta(seconds=wait_duration) + elif not callable(getattr(wait_duration, "total_seconds", None)): + raise TypeError( + "wait_duration must be an int, float, or datetime.timedelta" + ) + wait_duration = int(wait_duration.total_seconds() * 1000) + + if self._backend and self._backend.interface: + self._backend.interface.publish_alert(title, text, level_str, wait_duration) + + def __enter__(self) -> Run: + return self + + def __exit__( + self, + exc_type: type[BaseException], + exc_val: BaseException, + exc_tb: TracebackType, + ) -> bool: + exception_raised = exc_type is not None + if exception_raised: + traceback.print_exception(exc_type, exc_val, exc_tb) + exit_code = 1 if exception_raised else 0 + self._finish(exit_code=exit_code) + return not exception_raised + + @_log_to_run + @_raise_if_finished + @_attach + def mark_preempting(self) -> None: + """Mark this run as preempting. + + Also tells the internal process to immediately report this to server. + """ + if self._backend and self._backend.interface: + self._backend.interface.publish_preempting() + + @property + @_log_to_run + @_raise_if_finished + @_attach + def _system_metrics(self) -> dict[str, list[tuple[datetime, float]]]: + """Returns a dictionary of system metrics. + + Returns: + A dictionary of system metrics. + """ + from wandb.proto import wandb_internal_pb2 + + def pb_to_dict( + system_metrics_pb: wandb_internal_pb2.GetSystemMetricsResponse, + ) -> dict[str, list[tuple[datetime, float]]]: + res = {} + + for metric, records in system_metrics_pb.system_metrics.items(): + measurements = [] + for record in records.record: + # Convert timestamp to datetime + dt = datetime.fromtimestamp( + record.timestamp.seconds, tz=timezone.utc + ) + dt = dt.replace(microsecond=record.timestamp.nanos // 1000) + + measurements.append((dt, record.value)) + + res[metric] = measurements + + return res + + if not self._backend or not self._backend.interface: + return {} + + handle = self._backend.interface.deliver_get_system_metrics() + + try: + result = handle.wait_or(timeout=1) + except TimeoutError: + return {} + else: + try: + response = result.response.get_system_metrics_response + return pb_to_dict(response) if response else {} + except Exception: + logger.exception("Error getting system metrics.") + return {} + + # ------------------------------------------------------------------------------ + # HEADER + # ------------------------------------------------------------------------------ + def _header(self) -> None: + self._header_wandb_version_info() + self._header_sync_info() + self._header_run_info() + + def _header_wandb_version_info(self) -> None: + if self._settings.quiet or self._settings.silent: + return + + # TODO: add this to a higher verbosity level + self._printer.display(f"Tracking run with wandb version {wandb.__version__}") + + def _header_sync_info(self) -> None: + sync_location_msg = f"Run data is saved locally in {self._printer.files(self._settings.sync_dir)}" + + if self._settings._offline: + offline_warning = ( + f"W&B syncing is set to {self._printer.code('`offline`')} " + f"in this directory. Run {self._printer.code('`wandb online`')} " + f"or set {self._printer.code('WANDB_MODE=online')} " + "to enable cloud syncing." + ) + self._printer.display([offline_warning, sync_location_msg]) + else: + messages = [sync_location_msg] + + if not self._printer.supports_html: + disable_sync_msg = ( + f"Run {self._printer.code('`wandb offline`')} to turn off syncing." + ) + messages.append(disable_sync_msg) + + if not self._settings.quiet and not self._settings.silent: + self._printer.display(messages) + + def _header_run_info(self) -> None: + settings, printer = self._settings, self._printer + + if settings._offline or settings.silent: + return + + run_url = settings.run_url + project_url = settings.project_url + sweep_url = settings.sweep_url + + run_state_str = ( + "Resuming run" + if settings.resumed or settings.resume_from + else "Syncing run" + ) + run_name = settings.run_name + if not run_name: + return + + if printer.supports_html: + import wandb.jupyter + + if not wandb.jupyter.display_if_magic_is_used(self): + run_line = f"{printer.link(run_url, run_name)}" + project_line, sweep_line = "", "" + + if not settings.quiet: + doc_html = printer.link(url_registry.url("developer-guide"), "docs") + + project_html = printer.link(project_url, "Weights & Biases") + project_line = f"to {project_html} ({doc_html})" + + if sweep_url: + sweep_line = f"Sweep page: {printer.link(sweep_url, sweep_url)}" + + printer.display( + [f"{run_state_str} {run_line} {project_line}", sweep_line], + ) + + elif run_name: + printer.display(f"{run_state_str} {printer.name(run_name)}") + + if not settings.quiet: + # TODO: add verbosity levels and add this to higher levels + printer.display( + f"{printer.emoji('star')} View project at {printer.link(project_url)}" + ) + if sweep_url: + printer.display( + f"{printer.emoji('broom')} View sweep at {printer.link(sweep_url)}" + ) + printer.display( + f"{printer.emoji('rocket')} View run at {printer.link(run_url)}", + ) + + if run_name and settings.anonymous in ["allow", "must"]: + printer.display( + ( + "Do NOT share these links with anyone." + " They can be used to claim your runs." + ), + level="warn", + ) + + # ------------------------------------------------------------------------------ + # FOOTER + # ------------------------------------------------------------------------------ + # Note: All the footer methods are static methods since we want to share the printing logic + # with the service execution path that doesn't have access to the run instance + @staticmethod + def _footer( + sampled_history: SampledHistoryResponse | None = None, + final_summary: GetSummaryResponse | None = None, + poll_exit_response: PollExitResponse | None = None, + internal_messages_response: InternalMessagesResponse | None = None, + *, + settings: Settings, + printer: printer.Printer, + ) -> None: + Run._footer_history_summary_info( + history=sampled_history, + summary=final_summary, + settings=settings, + printer=printer, + ) + + Run._footer_sync_info( + poll_exit_response=poll_exit_response, + settings=settings, + printer=printer, + ) + Run._footer_log_dir_info(settings=settings, printer=printer) + Run._footer_internal_messages( + internal_messages_response=internal_messages_response, + settings=settings, + printer=printer, + ) + + @staticmethod + def _footer_sync_info( + poll_exit_response: PollExitResponse | None = None, + *, + settings: Settings, + printer: printer.Printer, + ) -> None: + if settings.silent: + return + + if settings._offline: + if not settings.quiet: + printer.display( + [ + "You can sync this run to the cloud by running:", + printer.code(f"wandb sync {settings.sync_dir}"), + ], + ) + return + + info = [] + if settings.run_name and settings.run_url: + info.append( + f"{printer.emoji('rocket')} View run {printer.name(settings.run_name)} at: {printer.link(settings.run_url)}" + ) + if settings.project_url: + info.append( + f"{printer.emoji('star')} View project at: {printer.link(settings.project_url)}" + ) + if poll_exit_response and poll_exit_response.file_counts: + logger.info("logging synced files") + file_counts = poll_exit_response.file_counts + info.append( + f"Synced {file_counts.wandb_count} W&B file(s), {file_counts.media_count} media file(s), " + f"{file_counts.artifact_count} artifact file(s) and {file_counts.other_count} other file(s)", + ) + printer.display(info) + + @staticmethod + def _footer_log_dir_info( + *, + settings: Settings, + printer: printer.Printer, + ) -> None: + if settings.quiet or settings.silent: + return + + log_dir = settings.log_user or settings.log_internal + if log_dir: + log_dir = os.path.dirname(log_dir.replace(os.getcwd(), ".")) + printer.display( + f"Find logs at: {printer.files(log_dir)}", + ) + + @staticmethod + def _footer_history_summary_info( + history: SampledHistoryResponse | None = None, + summary: GetSummaryResponse | None = None, + *, + settings: Settings, + printer: printer.Printer, + ) -> None: + if settings.quiet or settings.silent: + return + + panel = [] + + # Render history if available + if history: + logger.info("rendering history") + + sampled_history = { + item.key: wandb.util.downsample( + item.values_float or item.values_int, 40 + ) + for item in history.item + if not item.key.startswith("_") + } + + history_rows = [] + for key, values in sorted(sampled_history.items()): + if any(not isinstance(value, numbers.Number) for value in values): + continue + sparkline = printer.sparklines(values) + if sparkline: + history_rows.append([key, sparkline]) + if history_rows: + history_grid = printer.grid( + history_rows, + "Run history:", + ) + panel.append(history_grid) + + # Render summary if available + if summary: + final_summary = {} + for item in summary.item: + if item.key.startswith("_") or len(item.nested_key) > 0: + continue + final_summary[item.key] = json.loads(item.value_json) + + logger.info("rendering summary") + summary_rows = [] + for key, value in sorted(final_summary.items()): + # arrays etc. might be too large. for now, we just don't print them + if isinstance(value, str): + value = value[:20] + "..." * (len(value) >= 20) + summary_rows.append([key, value]) + elif isinstance(value, numbers.Number): + value = round(value, 5) if isinstance(value, float) else value + summary_rows.append([key, str(value)]) + else: + continue + + if summary_rows: + summary_grid = printer.grid( + summary_rows, + "Run summary:", + ) + panel.append(summary_grid) + + if panel: + printer.display(printer.panel(panel)) + + @staticmethod + def _footer_internal_messages( + internal_messages_response: InternalMessagesResponse | None = None, + *, + settings: Settings, + printer: printer.Printer, + ) -> None: + if settings.quiet or settings.silent: + return + + if not internal_messages_response: + return + + for message in internal_messages_response.messages.warning: + printer.display(message, level="warn") + + +# We define this outside of the run context to support restoring before init +def restore( + name: str, + run_path: str | None = None, + replace: bool = False, + root: str | None = None, +) -> None | TextIO: + """Download the specified file from cloud storage. + + File is placed into the current directory or run directory. + By default, will only download the file if it doesn't already exist. + + Args: + name: The name of the file. + run_path: Optional path to a run to pull files from, i.e. `username/project_name/run_id` + if wandb.init has not been called, this is required. + replace: Whether to download the file even if it already exists locally + root: The directory to download the file to. Defaults to the current + directory or the run directory if wandb.init was called. + + Returns: + None if it can't find the file, otherwise a file object open for reading. + + Raises: + CommError: If W&B can't connect to the W&B backend. + ValueError: If the file is not found or can't find run_path. + """ + is_disabled = wandb.run is not None and wandb.run.disabled + run = None if is_disabled else wandb.run + if run_path is None: + if run is not None: + run_path = run.path + else: + raise ValueError( + "run_path required when calling wandb.restore before wandb.init" + ) + if root is None: + if run is not None: + root = run.dir + api = public.Api() + api_run = api.run(run_path) + if root is None: + root = os.getcwd() + path = os.path.join(root, name) + if os.path.exists(path) and replace is False: + return open(path) + if is_disabled: + return None + files = api_run.files([name]) + if len(files) == 0: + return None + # if the file does not exist, the file has an md5 of 0 + if files[0].md5 == "0": + raise ValueError(f"File {name} not found in {run_path or root}.") + return files[0].download(root=root, replace=True) + + +# propagate our doc string to the runs restore method +try: + Run.restore.__doc__ = restore.__doc__ +except AttributeError: + pass + + +def finish( + exit_code: int | None = None, + quiet: bool | None = None, +) -> None: + """Finish a run and upload any remaining data. + + Marks the completion of a W&B run and ensures all data is synced to the server. + The run's final state is determined by its exit conditions and sync status. + + Run States: + - Running: Active run that is logging data and/or sending heartbeats. + - Crashed: Run that stopped sending heartbeats unexpectedly. + - Finished: Run completed successfully (`exit_code=0`) with all data synced. + - Failed: Run completed with errors (`exit_code!=0`). + + Args: + exit_code: Integer indicating the run's exit status. Use 0 for success, + any other value marks the run as failed. + quiet: Deprecated. Configure logging verbosity using `wandb.Settings(quiet=...)`. + """ + if wandb.run: + wandb.run.finish(exit_code=exit_code, quiet=quiet) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/wandb_settings.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/wandb_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..debc598f94c3378ea88353c3f97673c3edb35489 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/wandb_settings.py @@ -0,0 +1,2092 @@ +from __future__ import annotations + +import configparser +import json +import logging +import os +import pathlib +import platform +import re +import shutil +import socket +import sys +from datetime import datetime + +# Optional and Union are used for type hinting instead of | because +# the latter is not supported in pydantic<2.6 and Python<3.10. +# Dict, List, and Tuple are used for backwards compatibility +# with pydantic v1 and Python<3.9. +from typing import Any, Callable, Dict, List, Literal, Optional, Sequence, Tuple, Union +from urllib.parse import quote, unquote, urlencode + +from google.protobuf.wrappers_pb2 import BoolValue, DoubleValue, Int32Value, StringValue +from pydantic import BaseModel, ConfigDict, Field +from typing_extensions import Self + +import wandb +from wandb import env, util +from wandb._pydantic import ( + IS_PYDANTIC_V2, + AliasChoices, + computed_field, + field_validator, + model_validator, +) +from wandb.errors import UsageError +from wandb.proto import wandb_settings_pb2 + +from .lib import apikey, credentials, ipython +from .lib.gitlib import GitRepo +from .lib.run_moment import RunMoment + +validate_url: Callable[[str], None] + +if IS_PYDANTIC_V2: + from pydantic_core import SchemaValidator, core_schema + + def validate_url(url: str) -> None: + """Validate a URL string.""" + url_validator = SchemaValidator( + core_schema.url_schema( + allowed_schemes=["http", "https"], + strict=True, + ) + ) + url_validator.validate_python(url) +else: + from pydantic import root_validator + + def validate_url(url: str) -> None: + """Validate the base url of the wandb server. + + param value: URL to validate + + Based on the Django URLValidator, but with a few additional checks. + + Copyright (c) Django Software Foundation and individual contributors. + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of Django nor the names of its contributors may be used + to endorse or promote products derived from this software without + specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + """ + from urllib.parse import urlparse, urlsplit + + if url is None: + return + + ul = "\u00a1-\uffff" # Unicode letters range (must not be a raw string). + + # IP patterns + ipv4_re = ( + r"(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)" + r"(?:\.(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)){3}" + ) + ipv6_re = r"\[[0-9a-f:.]+\]" # (simple regex, validated later) + + # Host patterns + hostname_re = ( + r"[a-z" + ul + r"0-9](?:[a-z" + ul + r"0-9-]{0,61}[a-z" + ul + r"0-9])?" + ) + # Max length for domain name labels is 63 characters per RFC 1034 sec. 3.1 + domain_re = r"(?:\.(?!-)[a-z" + ul + r"0-9-]{1,63}(? 253: + raise ValueError("hostname is invalid") + + +def _path_convert(*args: str) -> str: + """Join path and apply os.path.expanduser to it.""" + return os.path.expanduser(os.path.join(*args)) + + +class Settings(BaseModel, validate_assignment=True): + """Settings for the W&B SDK. + + This class manages configuration settings for the W&B SDK, + ensuring type safety and validation of all settings. Settings are accessible + as attributes and can be initialized programmatically, through environment + variables (`WANDB_ prefix`), and with configuration files. + + The settings are organized into three categories: + 1. Public settings: Core configuration options that users can safely modify to customize + W&B's behavior for their specific needs. + 2. Internal settings: Settings prefixed with 'x_' that handle low-level SDK behavior. + These settings are primarily for internal use and debugging. While they can be modified, + they are not considered part of the public API and may change without notice in future + versions. + 3. Computed settings: Read-only settings that are automatically derived from other settings or + the environment. + """ + + # Pydantic Model configuration. + model_config = ConfigDict( + extra="forbid", # throw an error if extra fields are provided + validate_default=True, # validate default values + use_attribute_docstrings=True, # for field descriptions + revalidate_instances="always", + ) + + # Public settings. + + allow_offline_artifacts: bool = True + """Flag to allow table artifacts to be synced in offline mode. + + To revert to the old behavior, set this to False. + """ + + allow_val_change: bool = False + """Flag to allow modification of `Config` values after they've been set.""" + + anonymous: Optional[Literal["allow", "must", "never"]] = None + """Controls anonymous data logging. + + Possible values are: + - "never": requires you to link your W&B account before + tracking the run, so you don't accidentally create an anonymous + run. + - "allow": lets a logged-in user track runs with their account, but + lets someone who is running the script without a W&B account see + the charts in the UI. + - "must": sends the run to an anonymous account instead of to a + signed-up user account. + """ + + api_key: Optional[str] = None + """The W&B API key.""" + + azure_account_url_to_access_key: Optional[Dict[str, str]] = None + """Mapping of Azure account URLs to their corresponding access keys for Azure integration.""" + + base_url: str = "https://api.wandb.ai" + """The URL of the W&B backend for data synchronization.""" + + code_dir: Optional[str] = None + """Directory containing the code to be tracked by W&B.""" + + config_paths: Optional[Sequence[str]] = None + """Paths to files to load configuration from into the `Config` object.""" + + console: Literal["auto", "off", "wrap", "redirect", "wrap_raw", "wrap_emu"] = Field( + default="auto", + validate_default=True, + ) + """The type of console capture to be applied. + + Possible values are: + "auto" - Automatically selects the console capture method based on the + system environment and settings. + + "off" - Disables console capture. + + "redirect" - Redirects low-level file descriptors for capturing output. + + "wrap" - Overrides the write methods of sys.stdout/sys.stderr. Will be + mapped to either "wrap_raw" or "wrap_emu" based on the state of the system. + + "wrap_raw" - Same as "wrap" but captures raw output directly instead of + through an emulator. Derived from the `wrap` setting and should not be set manually. + + "wrap_emu" - Same as "wrap" but captures output through an emulator. + Derived from the `wrap` setting and should not be set manually. + """ + + console_multipart: bool = False + """Whether to produce multipart console log files.""" + + credentials_file: str = Field( + default_factory=lambda: str(credentials.DEFAULT_WANDB_CREDENTIALS_FILE) + ) + """Path to file for writing temporary access tokens.""" + + disable_code: bool = False + """Whether to disable capturing the code.""" + + disable_git: bool = False + """Whether to disable capturing the git state.""" + + disable_job_creation: bool = True + """Whether to disable the creation of a job artifact for W&B Launch.""" + + docker: Optional[str] = None + """The Docker image used to execute the script.""" + + email: Optional[str] = None + """The email address of the user.""" + + entity: Optional[str] = None + """The W&B entity, such as a user or a team.""" + + organization: Optional[str] = None + """The W&B organization.""" + + force: bool = False + """Whether to pass the `force` flag to `wandb.login()`.""" + + fork_from: Optional[RunMoment] = None + """Specifies a point in a previous execution of a run to fork from. + + The point is defined by the run ID, a metric, and its value. + Currently, only the metric '_step' is supported. + """ + + git_commit: Optional[str] = None + """The git commit hash to associate with the run.""" + + git_remote: str = "origin" + """The git remote to associate with the run.""" + + git_remote_url: Optional[str] = None + """The URL of the git remote repository.""" + + git_root: Optional[str] = None + """Root directory of the git repository.""" + + heartbeat_seconds: int = 30 + """Interval in seconds between heartbeat signals sent to the W&B servers. + + + """ + + host: Optional[str] = None + """Hostname of the machine running the script.""" + + http_proxy: Optional[str] = None + """Custom proxy servers for http requests to W&B.""" + + https_proxy: Optional[str] = None + """Custom proxy servers for https requests to W&B.""" + + identity_token_file: Optional[str] = None + """Path to file containing an identity token (JWT) for authentication.""" + + ignore_globs: Sequence[str] = () + """Unix glob patterns relative to `files_dir` specifying files to exclude from upload.""" + + init_timeout: float = 90.0 + """Time in seconds to wait for the `wandb.init` call to complete before timing out.""" + + insecure_disable_ssl: bool = False + """Whether to insecurely disable SSL verification.""" + + job_name: Optional[str] = None + """Name of the Launch job running the script.""" + + job_source: Optional[Literal["repo", "artifact", "image"]] = None + """Source type for Launch.""" + + label_disable: bool = False + """Whether to disable automatic labeling features.""" + + launch: bool = False + """Flag to indicate if the run is being launched through W&B Launch. + + + """ + + launch_config_path: Optional[str] = None + """Path to the launch configuration file.""" + + login_timeout: Optional[float] = None + """Time in seconds to wait for login operations before timing out.""" + + mode: Literal["online", "offline", "shared", "disabled", "dryrun", "run"] = Field( + default="online", + validate_default=True, + ) + """The operating mode for W&B logging and synchronization.""" + + notebook_name: Optional[str] = None + """Name of the notebook if running in a Jupyter-like environment.""" + + program: Optional[str] = None + """Path to the script that created the run, if available.""" + + program_abspath: Optional[str] = None + """The absolute path from the root repository directory to the script that + created the run. + + Root repository directory is defined as the directory containing the + .git directory, if it exists. Otherwise, it's the current working directory. + """ + + program_relpath: Optional[str] = None + """The relative path to the script that created the run.""" + + project: Optional[str] = None + """The W&B project ID.""" + + quiet: bool = False + """Flag to suppress non-essential output.""" + + reinit: Union[ + Literal[ + "default", + "return_previous", + "finish_previous", + "create_new", + ], + bool, + ] = "default" + """What to do when `wandb.init()` is called while a run is active. + + Options: + - "default": Use "finish_previous" in notebooks and "return_previous" + otherwise. + - "return_previous": Return the most recently created run + that is not yet finished. This does not update `wandb.run`; see + the "create_new" option. + - "finish_previous": Finish all active runs, then return a new run. + - "create_new": Create a new run without modifying other active runs. + Does not update `wandb.run` and top-level functions like `wandb.log`. + Because of this, some older integrations that rely on the global run + will not work. + + Can also be a boolean, but this is deprecated. False is the same as + "return_previous", and True is the same as "finish_previous". + """ + + relogin: bool = False + """Flag to force a new login attempt.""" + + resume: Optional[Literal["allow", "must", "never", "auto"]] = None + """Specifies the resume behavior for the run. + + Options: + - "must": Resumes from an existing run with the same ID. If no such run exists, + it will result in failure. + - "allow": Attempts to resume from an existing run with the same ID. If none is + found, a new run will be created. + - "never": Always starts a new run. If a run with the same ID already exists, + it will result in failure. + - "auto": Automatically resumes from the most recent failed run on the same + machine. + """ + + resume_from: Optional[RunMoment] = None + """Specifies a point in a previous execution of a run to resume from. + + The point is defined by the run ID, a metric, and its value. + Currently, only the metric '_step' is supported. + """ + + resumed: bool = False + """Indication from the server about the state of the run. + + This is different from resume, a user provided flag. + + """ + + root_dir: str = Field(default_factory=lambda: os.path.abspath(os.getcwd())) + """The root directory to use as the base for all run-related paths. + + In particular, this is used to derive the wandb directory and the run directory. + """ + + run_group: Optional[str] = None + """Group identifier for related runs. + + Used for grouping runs in the UI. + """ + + run_id: Optional[str] = None + """The ID of the run.""" + + run_job_type: Optional[str] = None + """Type of job being run (e.g., training, evaluation).""" + + run_name: Optional[str] = None + """Human-readable name for the run.""" + + run_notes: Optional[str] = None + """Additional notes or description for the run.""" + + run_tags: Optional[Tuple[str, ...]] = None + """Tags to associate with the run for organization and filtering.""" + + sagemaker_disable: bool = False + """Flag to disable SageMaker-specific functionality.""" + + save_code: Optional[bool] = None + """Whether to save the code associated with the run.""" + + settings_system: Optional[str] = None + """Path to the system-wide settings file.""" + + show_colors: Optional[bool] = None + """Whether to use colored output in the console. + + + """ + + show_emoji: Optional[bool] = None + """Whether to show emoji in the console output. + + + """ + + show_errors: bool = True + """Whether to display error messages.""" + + show_info: bool = True + """Whether to display informational messages.""" + + show_warnings: bool = True + """Whether to display warning messages.""" + + silent: bool = False + """Flag to suppress all output.""" + + start_method: Optional[str] = None + """Method to use for starting subprocesses. + + This is deprecated and will be removed in a future release. + + """ + + strict: Optional[bool] = None + """Whether to enable strict mode for validation and error checking.""" + + summary_timeout: int = 60 + """Time in seconds to wait for summary operations before timing out.""" + + summary_warnings: int = 5 + """Maximum number of summary warnings to display. + + + """ + + sweep_id: Optional[str] = None + """Identifier of the sweep this run belongs to.""" + + sweep_param_path: Optional[str] = None + """Path to the sweep parameters configuration.""" + + symlink: bool = Field( + default_factory=lambda: False if platform.system() == "Windows" else True + ) + """Whether to use symlinks (True by default except on Windows).""" + + sync_tensorboard: Optional[bool] = None + """Whether to synchronize TensorBoard logs with W&B.""" + + table_raise_on_max_row_limit_exceeded: bool = False + """Whether to raise an exception when table row limits are exceeded.""" + + username: Optional[str] = None + """Username.""" + + # Internal settings. + # + # These are typically not meant to be set by the user and should not be considered + # a part of the public API as they may change or be removed in future versions. + + x_cli_only_mode: bool = False + """Flag to indicate that the SDK is running in CLI-only mode. + + + """ + + x_disable_meta: bool = False + """Flag to disable the collection of system metadata.""" + + x_disable_stats: bool = False + """Flag to disable the collection of system metrics.""" + + x_disable_viewer: bool = False + """Flag to disable the early viewer query. + + + """ + + x_disable_machine_info: bool = False + """Flag to disable automatic machine info collection. + + + """ + + x_executable: Optional[str] = None + """Path to the Python executable. + + + """ + + x_extra_http_headers: Optional[Dict[str, str]] = None + """Additional headers to add to all outgoing HTTP requests.""" + + x_file_stream_max_bytes: Optional[int] = None + """An approximate maximum request size for the filestream API. + + Its purpose is to prevent HTTP requests from failing due to + containing too much data. This number is approximate: + requests will be slightly larger. + + """ + + x_file_stream_max_line_bytes: Optional[int] = None + """Maximum line length for filestream JSONL files. + + + """ + + x_file_stream_transmit_interval: Optional[float] = None + """Interval in seconds between filestream transmissions. + + + """ + + # Filestream retry client configuration. + + x_file_stream_retry_max: Optional[int] = None + """Max number of retries for filestream operations. + + + """ + + x_file_stream_retry_wait_min_seconds: Optional[float] = None + """Minimum wait time between retries for filestream operations. + + + """ + + x_file_stream_retry_wait_max_seconds: Optional[float] = None + """Maximum wait time between retries for filestream operations. + + + """ + + x_file_stream_timeout_seconds: Optional[float] = None + """Timeout in seconds for individual filestream HTTP requests. + + + """ + + # file transfer retry client configuration + + x_file_transfer_retry_max: Optional[int] = None + """Max number of retries for file transfer operations. + + + """ + + x_file_transfer_retry_wait_min_seconds: Optional[float] = None + """Minimum wait time between retries for file transfer operations. + + + """ + + x_file_transfer_retry_wait_max_seconds: Optional[float] = None + """Maximum wait time between retries for file transfer operations. + + + """ + + x_file_transfer_timeout_seconds: Optional[float] = None + """Timeout in seconds for individual file transfer HTTP requests. + + + """ + + x_files_dir: Optional[str] = None + """Override setting for the computed files_dir. + + + """ + + x_flow_control_custom: Optional[bool] = None + """Flag indicating custom flow control for filestream. + + TODO: Not implemented in wandb-core. + + """ + + x_flow_control_disabled: Optional[bool] = None + """Flag indicating flow control is disabled for filestream. + + TODO: Not implemented in wandb-core. + + """ + + # graphql retry client configuration + + x_graphql_retry_max: Optional[int] = None + """Max number of retries for GraphQL operations. + + + """ + + x_graphql_retry_wait_min_seconds: Optional[float] = None + """Minimum wait time between retries for GraphQL operations. + + + """ + + x_graphql_retry_wait_max_seconds: Optional[float] = None + """Maximum wait time between retries for GraphQL operations. + + + """ + + x_graphql_timeout_seconds: Optional[float] = None + """Timeout in seconds for individual GraphQL requests. + + + """ + + x_internal_check_process: float = 8.0 + """Interval for internal process health checks in seconds. + + + """ + + x_jupyter_name: Optional[str] = None + """Name of the Jupyter notebook. + + + """ + + x_jupyter_path: Optional[str] = None + """Path to the Jupyter notebook. + + + """ + + x_jupyter_root: Optional[str] = None + """Root directory of the Jupyter notebook. + + + """ + + x_label: Optional[str] = None + """Label to assign to system metrics and console logs collected for the run. + + This is used to group data by on the frontend and can be used to distinguish data + from different processes in a distributed training job. + """ + + x_live_policy_rate_limit: Optional[int] = None + """Rate limit for live policy updates in seconds. + + + """ + + x_live_policy_wait_time: Optional[int] = None + """Wait time between live policy updates in seconds. + + + """ + + x_log_level: int = logging.INFO + """Logging level for internal operations. + + + """ + + x_network_buffer: Optional[int] = None + """Size of the network buffer used in flow control. + + TODO: Not implemented in wandb-core. + + """ + + x_primary: bool = Field( + default=True, validation_alias=AliasChoices("x_primary", "x_primary_node") + ) + """Determines whether to save internal wandb files and metadata. + + In a distributed setting, this is useful for avoiding file overwrites + from secondary processes when only system metrics and logs are needed, + as the primary process handles the main logging. + """ + + x_proxies: Optional[Dict[str, str]] = None + """Custom proxy servers for requests to W&B. + + This is deprecated and will be removed in a future release. + Please use `http_proxy` and `https_proxy` instead. + + """ + + x_runqueue_item_id: Optional[str] = None + """ID of the Launch run queue item being processed. + + + """ + + x_save_requirements: bool = True + """Flag to save the requirements file.""" + + x_server_side_derived_summary: bool = False + """Flag to delegate automatic computation of summary from history to the server. + + This does not disable user-provided summary updates. + """ + + x_server_side_expand_glob_metrics: bool = True + """Flag to delegate glob matching of metrics in define_metric to the server. + + If the server does not support this, the client will perform the glob matching. + + """ + + x_service_transport: Optional[str] = None + """Transport method for communication with the wandb service. + + + """ + + x_service_wait: float = 30.0 + """Time in seconds to wait for the wandb-core internal service to start.""" + + x_skip_transaction_log: bool = False + """Whether to skip saving the run events to the transaction log. + + This is only relevant for online runs. Can be used to reduce the amount of + data written to disk. + + Should be used with caution, as it removes the gurantees about + recoverability. + """ + + x_start_time: Optional[float] = None + """The start time of the run in seconds since the Unix epoch. + + + """ + + x_stats_pid: int = os.getpid() + """PID of the process that started the wandb-core process to collect system stats for. + + + """ + + x_stats_sampling_interval: float = Field(default=15.0) + """Sampling interval for the system monitor in seconds.""" + + x_stats_neuron_monitor_config_path: Optional[str] = None + """Path to the default config file for the neuron-monitor tool. + + This is used to monitor AWS Trainium devices. + + """ + + x_stats_dcgm_exporter: Optional[str] = None + """Endpoint to extract Nvidia DCGM metrics from. + + Options: + - Extract DCGM-related metrics from a query to the Prometheus `/api/v1/query` endpoint. + It is a common practice to aggregate metrics reported by the instances of the DCGM Exporter + running on different nodes in a cluster using Prometheus. + - TODO: Parse metrics directly from the `/metrics` endpoint of the DCGM Exporter. + + Examples: + - `http://localhost:9400/api/v1/query?query=DCGM_FI_DEV_GPU_TEMP{node="l1337", cluster="globular"}`. + - TODO: `http://192.168.0.1:9400/metrics`. + + """ + + x_stats_open_metrics_endpoints: Optional[Dict[str, str]] = None + """OpenMetrics `/metrics` endpoints to monitor for system metrics.""" + + x_stats_open_metrics_filters: Union[ + Dict[str, Dict[str, str]], Sequence[str], None + ] = None + """Filter to apply to metrics collected from OpenMetrics `/metrics` endpoints. + + Supports two formats: + - {"metric regex pattern, including endpoint name as prefix": {"label": "label value regex pattern"}} + - ("metric regex pattern 1", "metric regex pattern 2", ...) + """ + + x_stats_open_metrics_http_headers: Optional[Dict[str, str]] = None + """HTTP headers to add to OpenMetrics requests.""" + + x_stats_disk_paths: Optional[Sequence[str]] = ("/",) + """System paths to monitor for disk usage.""" + + x_stats_cpu_count: Optional[int] = None + """System CPU count. + + If set, overrides the auto-detected value in the run metadata. + """ + + x_stats_cpu_logical_count: Optional[int] = None + """Logical CPU count. + + If set, overrides the auto-detected value in the run metadata. + """ + + x_stats_gpu_count: Optional[int] = None + """GPU device count. + + If set, overrides the auto-detected value in the run metadata. + """ + + x_stats_gpu_type: Optional[str] = None + """GPU device type. + + If set, overrides the auto-detected value in the run metadata. + """ + + x_stats_gpu_device_ids: Optional[Sequence[int]] = None + """GPU device indices to monitor. + + If not set, the system monitor captures metrics for all GPUs. + Assumes 0-based indexing matching CUDA/ROCm device enumeration. + """ + + x_stats_buffer_size: int = 0 + """Number of system metric samples to buffer in memory in the wandb-core process. + + Can be accessed via run._system_metrics. + + """ + + x_stats_coreweave_metadata_base_url: str = "http://169.254.169.254" + """The scheme and hostname for contacting the CoreWeave metadata server. + + Only accessible from within a CoreWeave cluster. + + """ + + x_stats_coreweave_metadata_endpoint: str = "/api/v2/cloud-init/meta-data" + """The relative path on the CoreWeave metadata server to which to make requests. + + This must not include the schema and hostname prefix. + Only accessible from within a CoreWeave cluster. + + """ + + x_stats_track_process_tree: bool = False + """Monitor the entire process tree for resource usage, starting from `x_stats_pid`. + + When `True`, the system monitor aggregates the RSS, CPU%, and thread count + from the process with PID `x_stats_pid` and all of its descendants. + This can have a performance overhead and is disabled by default. + """ + + x_sync: bool = False + """Flag to indicate whether we are syncing a run from the transaction log. + + + """ + + x_update_finish_state: bool = True + """Flag to indicate whether this process can update the run's final state on the server. + + Set to False in distributed training when only the main process should determine the final state. + """ + + # Model validator to catch legacy settings. + @model_validator(mode="before") + @classmethod + def catch_private_settings(cls, values): + """Check if a private field is provided and assign to the corresponding public one. + + This is a compatibility layer to handle previous versions of the settings. + """ + new_values = {} + for key in values: + # Internal settings are prefixed with "x_" instead of "_" + # as Pydantic does not allow "_" in field names. + if key.startswith("_"): + new_values["x" + key] = values[key] + else: + new_values[key] = values[key] + return new_values + + if IS_PYDANTIC_V2: + + @model_validator(mode="after") + def validate_mutual_exclusion_of_branching_args(self) -> Self: + """Check if `fork_from`, `resume`, and `resume_from` are mutually exclusive. + + + """ + if ( + sum( + o is not None + for o in [self.fork_from, self.resume, self.resume_from] + ) + > 1 + ): + raise ValueError( + "`fork_from`, `resume`, or `resume_from` are mutually exclusive. " + "Please specify only one of them." + ) + return self + + @model_validator(mode="after") + def validate_skip_transaction_log(self): + if self._offline and self.x_skip_transaction_log: + raise ValueError("Cannot skip transaction log in offline mode") + return self + else: + + @root_validator(pre=False) # type: ignore [call-overload] + @classmethod + def validate_mutual_exclusion_of_branching_args(cls, values): + if ( + sum( + values.get(o) is not None + for o in ["fork_from", "resume", "resume_from"] + ) + > 1 + ): + raise ValueError( + "`fork_from`, `resume`, or `resume_from` are mutually exclusive. " + "Please specify only one of them." + ) + return values + + @root_validator(pre=False) # type: ignore [call-overload] + @classmethod + def validate_skip_transaction_log(cls, values): + if values.get("_offline") and values.get("x_skip_transaction_log"): + raise ValueError("Cannot skip transaction log in offline mode") + return values + + # Field validators. + @field_validator("api_key", mode="after") + @classmethod + def validate_api_key(cls, value): + """Validate the API key. + + + """ + if value is not None and (len(value) > len(value.strip())): + raise UsageError("API key cannot start or end with whitespace") + return value + + @field_validator("base_url", mode="after") + @classmethod + def validate_base_url(cls, value): + """Validate the base URL. + + + """ + validate_url(value) + # wandb.ai-specific checks + if re.match(r".*wandb\.ai[^\.]*$", value) and "api." not in value: + # user might guess app.wandb.ai or wandb.ai is the default cloud server + raise ValueError( + f"{value} is not a valid server address, did you mean https://api.wandb.ai?" + ) + elif re.match(r".*wandb\.ai[^\.]*$", value) and not value.startswith("https"): + raise ValueError("http is not secure, please use https://api.wandb.ai") + return value.rstrip("/") + + @field_validator("code_dir", mode="before") + @classmethod + def validate_code_dir(cls, value): + """Validate the code directory. + + + """ + # TODO: add native support for pathlib.Path + if isinstance(value, pathlib.Path): + return str(value) + return value + + @field_validator("console", mode="after") + @classmethod + def validate_console(cls, value, values): + """Validate the console capture method. + + + """ + if value != "auto": + return value + + return "wrap" + + @field_validator("x_executable", mode="before") + @classmethod + def validate_x_executable(cls, value): + """Validate the Python executable path. + + + """ + # TODO: add native support for pathlib.Path + if isinstance(value, pathlib.Path): + return str(value) + return value + + @field_validator("x_extra_http_headers", mode="before") + @classmethod + def validate_x_extra_http_headers(cls, value): + if isinstance(value, str): + return json.loads(value) + return value + + @field_validator("x_file_stream_max_line_bytes", mode="after") + @classmethod + def validate_file_stream_max_line_bytes(cls, value): + """Validate the maximum line length for filestream JSONL files. + + + """ + if value is not None and value < 1: + raise ValueError("File stream max line bytes must be greater than 0") + return value + + @field_validator("x_files_dir", mode="before") + @classmethod + def validate_x_files_dir(cls, value): + """Validate the files directory. + + + """ + # TODO: add native support for pathlib.Path + if isinstance(value, pathlib.Path): + return str(value) + return value + + @field_validator("fork_from", mode="before") + @classmethod + def validate_fork_from(cls, value, values) -> Optional[RunMoment]: + """Validate the fork_from field. + + + """ + run_moment = cls._runmoment_preprocessor(value) + + if hasattr(values, "data"): + # pydantic v2 + values = values.data + else: + # pydantic v1 + values = values + + if ( + run_moment + and values.get("run_id") is not None + and values.get("run_id") == run_moment.run + ): + raise ValueError( + "Provided `run_id` is the same as the run to `fork_from`. " + "Please provide a different `run_id` or remove the `run_id` argument. " + "If you want to rewind the current run, please use `resume_from` instead." + ) + return run_moment + + @field_validator("http_proxy", mode="after") + @classmethod + def validate_http_proxy(cls, value): + """Validate the HTTP proxy. + + + """ + if value is None: + return None + validate_url(value) + return value.rstrip("/") + + @field_validator("https_proxy", mode="after") + @classmethod + def validate_https_proxy(cls, value): + """Validate the HTTPS proxy. + + + """ + if value is None: + return None + validate_url(value) + return value.rstrip("/") + + @field_validator("ignore_globs", mode="after") + @classmethod + def validate_ignore_globs(cls, value): + """Validate the ignore globs. + + + """ + return tuple(value) if not isinstance(value, tuple) else value + + @field_validator("program", mode="before") + @classmethod + def validate_program(cls, value): + """Validate the program path. + + + """ + # TODO: add native support for pathlib.Path + if isinstance(value, pathlib.Path): + return str(value) + return value + + @field_validator("program_abspath", mode="before") + @classmethod + def validate_program_abspath(cls, value): + """Validate the absolute program path. + + + """ + # TODO: add native support for pathlib.Path + if isinstance(value, pathlib.Path): + return str(value) + return value + + @field_validator("program_relpath", mode="before") + @classmethod + def validate_program_relpath(cls, value): + """Validate the relative program path. + + + """ + # TODO: add native support for pathlib.Path + if isinstance(value, pathlib.Path): + return str(value) + return value + + @field_validator("project", mode="after") + @classmethod + def validate_project(cls, value, values): + """Validate the project name. + + + """ + if value is None: + return None + invalid_chars_list = list("/\\#?%:") + if len(value) > 128: + raise UsageError(f"Invalid project name {value!r}: exceeded 128 characters") + invalid_chars = {char for char in invalid_chars_list if char in value} + if invalid_chars: + raise UsageError( + f"Invalid project name {value!r}: " + f"cannot contain characters {','.join(invalid_chars_list)!r}, " + f"found {','.join(invalid_chars)!r}" + ) + return value + + @field_validator("resume", mode="before") + @classmethod + def validate_resume(cls, value): + """Validate the resume behavior. + + + """ + if value is False: + return None + if value is True: + return "auto" + return value + + @field_validator("resume_from", mode="before") + @classmethod + def validate_resume_from(cls, value, values) -> Optional[RunMoment]: + """Validate the resume_from field. + + + """ + run_moment = cls._runmoment_preprocessor(value) + + if hasattr(values, "data"): + # pydantic v2 + values = values.data + else: + # pydantic v1 + values = values + + if ( + run_moment + and values.get("run_id") is not None + and values.get("run_id") != run_moment.run + ): + raise ValueError( + "Both `run_id` and `resume_from` have been specified with different ids." + ) + return run_moment + + @field_validator("root_dir", mode="before") + @classmethod + def validate_root_dir(cls, value): + """Validate the root directory. + + + """ + # TODO: add native support for pathlib.Path + if isinstance(value, pathlib.Path): + return str(value) + return value + + @field_validator("run_id", mode="after") + @classmethod + def validate_run_id(cls, value, values): + """Validate the run ID. + + + """ + if value is None: + return None + + if len(value) == 0: + raise UsageError("Run ID cannot be empty") + if len(value) > len(value.strip()): + raise UsageError("Run ID cannot start or end with whitespace") + if not bool(value.strip()): + raise UsageError("Run ID cannot contain only whitespace") + + # check if the run id contains any reserved characters + reserved_chars = ":;,#?/'" + if any(char in reserved_chars for char in value): + raise UsageError(f"Run ID cannot contain the characters: {reserved_chars}") + return value + + @field_validator("settings_system", mode="after") + @classmethod + def validate_settings_system(cls, value): + """Validate the system settings file path. + + + """ + if value is None: + return None + elif isinstance(value, pathlib.Path): + return str(_path_convert(value)) + else: + return _path_convert(value) + + @field_validator("x_service_wait", mode="after") + @classmethod + def validate_service_wait(cls, value): + """Validate the service wait time. + + + """ + if value < 0: + raise UsageError("Service wait time cannot be negative") + return value + + @field_validator("start_method", mode="after") + @classmethod + def validate_start_method(cls, value): + """Validate the start method for subprocesses. + + + """ + if value is None: + return value + wandb.termwarn( + "`start_method` is deprecated and will be removed in a future version " + "of wandb. This setting is currently non-functional and safely ignored.", + repeat=False, + ) + return value + + @field_validator("x_stats_coreweave_metadata_base_url", mode="after") + @classmethod + def validate_x_stats_coreweave_metadata_base_url(cls, value): + validate_url(value) + return value.rstrip("/") + + @field_validator("x_stats_gpu_device_ids", mode="before") + @classmethod + def validate_x_stats_gpu_device_ids(cls, value): + """Validate the GPU device IDs. + + + """ + if isinstance(value, str): + return json.loads(value) + return value + + @field_validator("x_stats_neuron_monitor_config_path", mode="before") + @classmethod + def validate_x_stats_neuron_monitor_config_path(cls, value): + """Validate the path to the neuron-monitor config file. + + + """ + # TODO: add native support for pathlib.Path + if isinstance(value, pathlib.Path): + return str(value) + return value + + @field_validator("x_stats_open_metrics_endpoints", mode="before") + @classmethod + def validate_stats_open_metrics_endpoints(cls, value): + """Validate the OpenMetrics endpoints. + + + """ + if isinstance(value, str): + return json.loads(value) + return value + + @field_validator("x_stats_open_metrics_filters", mode="before") + @classmethod + def validate_stats_open_metrics_filters(cls, value): + """Validate the OpenMetrics filters. + + + """ + if isinstance(value, str): + return json.loads(value) + return value + + @field_validator("x_stats_open_metrics_http_headers", mode="before") + @classmethod + def validate_stats_open_metrics_http_headers(cls, value): + """Validate the OpenMetrics HTTP headers. + + + """ + if isinstance(value, str): + return json.loads(value) + return value + + @field_validator("x_stats_sampling_interval", mode="after") + @classmethod + def validate_stats_sampling_interval(cls, value): + """Validate the stats sampling interval. + + + """ + if value < 0.1: + raise UsageError("Stats sampling interval cannot be less than 0.1 seconds") + return value + + @field_validator("sweep_id", mode="after") + @classmethod + def validate_sweep_id(cls, value): + """Validate the sweep ID. + + + """ + if value is None: + return None + if len(value) == 0: + raise UsageError("Sweep ID cannot be empty") + if len(value) > len(value.strip()): + raise UsageError("Sweep ID cannot start or end with whitespace") + if not bool(value.strip()): + raise UsageError("Sweep ID cannot contain only whitespace") + return value + + @field_validator("sweep_param_path", mode="before") + @classmethod + def validate_sweep_param_path(cls, value): + """Validate the sweep parameter path. + + + """ + # TODO: add native support for pathlib.Path + if isinstance(value, pathlib.Path): + return str(value) + return value + + # Computed fields. + + @computed_field # type: ignore[prop-decorator] + @property + def _args(self) -> List[str]: + if not self._jupyter: + return sys.argv[1:] + return [] + + @computed_field # type: ignore[prop-decorator] + @property + def _aws_lambda(self) -> bool: + """Check if we are running in a lambda environment.""" + from sentry_sdk.integrations.aws_lambda import ( # type: ignore[import-not-found] + get_lambda_bootstrap, + ) + + lambda_bootstrap = get_lambda_bootstrap() + if not lambda_bootstrap or not hasattr( + lambda_bootstrap, "handle_event_request" + ): + return False + return True + + @computed_field # type: ignore[prop-decorator] + @property + def _code_path_local(self) -> Optional[str]: + """The relative path from the current working directory to the code path. + + For example, if the code path is /home/user/project/example.py, and the + current working directory is /home/user/project, then the code path local + is example.py. + + If couldn't find the relative path, this will be an empty string. + """ + return self._get_program_relpath(self.program) if self.program else None + + @computed_field # type: ignore[prop-decorator] + @property + def _colab(self) -> bool: + return "google.colab" in sys.modules + + @computed_field # type: ignore[prop-decorator] + @property + def _ipython(self) -> bool: + return ipython.in_ipython() + + @computed_field # type: ignore[prop-decorator] + @property + def _jupyter(self) -> bool: + return ipython.in_jupyter() + + @computed_field # type: ignore[prop-decorator] + @property + def _kaggle(self) -> bool: + return util._is_likely_kaggle() + + @computed_field # type: ignore[prop-decorator] + @property + def _noop(self) -> bool: + return self.mode == "disabled" + + @computed_field # type: ignore[prop-decorator] + @property + def _notebook(self) -> bool: + return self._ipython or self._jupyter or self._colab or self._kaggle + + @computed_field # type: ignore[prop-decorator] + @property + def _offline(self) -> bool: + return self.mode in ("offline", "dryrun") + + @computed_field # type: ignore[prop-decorator] + @property + def _os(self) -> str: + """The operating system of the machine running the script.""" + return platform.platform(aliased=True) + + @computed_field # type: ignore[prop-decorator] + @property + def _platform(self) -> str: + return f"{platform.system()}-{platform.machine()}".lower() + + @computed_field # type: ignore[prop-decorator] + @property + def _python(self) -> str: + return f"{platform.python_implementation()} {platform.python_version()}" + + @computed_field # type: ignore[prop-decorator] + @property + def _shared(self) -> bool: + """Whether we are in shared mode. + + In "shared" mode, multiple processes can write to the same run, + for example from different machines. + """ + return self.mode == "shared" + + @computed_field # type: ignore[prop-decorator] + @property + def _start_datetime(self) -> str: + if self.x_start_time is None: + return "" + datetime_now = datetime.fromtimestamp(self.x_start_time) + return datetime_now.strftime("%Y%m%d_%H%M%S") + + @computed_field # type: ignore[prop-decorator] + @property + def _tmp_code_dir(self) -> str: + return _path_convert(self.sync_dir, "tmp", "code") + + @computed_field # type: ignore[prop-decorator] + @property + def _windows(self) -> bool: + return platform.system() == "Windows" + + @computed_field # type: ignore[prop-decorator] + @property + def colab_url(self) -> Optional[str]: + """The URL to the Colab notebook, if running in Colab.""" + if not self._colab: + return None + if self.x_jupyter_path and self.x_jupyter_path.startswith("fileId="): + unescaped = unquote(self.x_jupyter_path) + return "https://colab.research.google.com/notebook#" + unescaped + return None + + @computed_field # type: ignore[prop-decorator] + @property + def deployment(self) -> Literal["local", "cloud"]: + return "local" if self.is_local else "cloud" + + @computed_field # type: ignore[prop-decorator] + @property + def files_dir(self) -> str: + """Absolute path to the local directory where the run's files are stored.""" + return self.x_files_dir or _path_convert(self.sync_dir, "files") + + @computed_field # type: ignore[prop-decorator] + @property + def is_local(self) -> bool: + return str(self.base_url) != "https://api.wandb.ai" + + @computed_field # type: ignore[prop-decorator] + @property + def log_dir(self) -> str: + """The directory for storing log files.""" + return _path_convert(self.sync_dir, "logs") + + @computed_field # type: ignore[prop-decorator] + @property + def log_internal(self) -> str: + """The path to the file to use for internal logs.""" + return _path_convert(self.log_dir, "debug-internal.log") + + @computed_field # type: ignore[prop-decorator] + @property + def log_symlink_internal(self) -> str: + """The path to the symlink to the internal log file of the most recent run.""" + return _path_convert(self.wandb_dir, "debug-internal.log") + + @computed_field # type: ignore[prop-decorator] + @property + def log_symlink_user(self) -> str: + """The path to the symlink to the user-process log file of the most recent run.""" + return _path_convert(self.wandb_dir, "debug.log") + + @computed_field # type: ignore[prop-decorator] + @property + def log_user(self) -> str: + """The path to the file to use for user-process logs.""" + return _path_convert(self.log_dir, "debug.log") + + @computed_field # type: ignore[prop-decorator] + @property + def project_url(self) -> str: + """The W&B URL where the project can be viewed.""" + project_url = self._project_url_base() + if not project_url: + return "" + + query = self._get_url_query_string() + + return f"{project_url}{query}" + + @computed_field # type: ignore[prop-decorator] + @property + def resume_fname(self) -> str: + """The path to the resume file.""" + return _path_convert(self.wandb_dir, "wandb-resume.json") + + @computed_field # type: ignore[prop-decorator] + @property + def run_mode(self) -> Literal["run", "offline-run"]: + """The mode of the run. Can be either "run" or "offline-run".""" + return "run" if not self._offline else "offline-run" + + @computed_field # type: ignore[prop-decorator] + @property + def run_url(self) -> str: + """The W&B URL where the run can be viewed.""" + project_url = self._project_url_base() + if not all([project_url, self.run_id]): + return "" + + query = self._get_url_query_string() + # Exclude specific safe characters from URL encoding to prevent 404 errors + safe_chars = "=+&$@" + return f"{project_url}/runs/{quote(self.run_id or '', safe=safe_chars)}{query}" + + @computed_field # type: ignore[prop-decorator] + @property + def settings_workspace(self) -> str: + """The path to the workspace settings file.""" + return _path_convert(self.wandb_dir, "settings") + + @computed_field # type: ignore[prop-decorator] + @property + def sweep_url(self) -> str: + """The W&B URL where the sweep can be viewed.""" + project_url = self._project_url_base() + if not all([project_url, self.sweep_id]): + return "" + + query = self._get_url_query_string() + return f"{project_url}/sweeps/{quote(self.sweep_id or '')}{query}" + + @computed_field # type: ignore[prop-decorator] + @property + def sync_dir(self) -> str: + """The directory for storing the run's files.""" + return _path_convert( + self.wandb_dir, + f"{self.run_mode}-{self.timespec}-{self.run_id}", + ) + + @computed_field # type: ignore[prop-decorator] + @property + def sync_file(self) -> str: + """Path to the append-only binary transaction log file.""" + return _path_convert(self.sync_dir, f"run-{self.run_id}.wandb") + + @computed_field # type: ignore[prop-decorator] + @property + def sync_symlink_latest(self) -> str: + """Path to the symlink to the most recent run's transaction log file.""" + return _path_convert(self.wandb_dir, "latest-run") + + @computed_field # type: ignore[prop-decorator] + @property + def timespec(self) -> str: + """The time specification for the run.""" + return self._start_datetime + + @computed_field # type: ignore[prop-decorator] + @property + def wandb_dir(self) -> str: + """Full path to the wandb directory.""" + stage_dir = ( + ".wandb" + os.sep + if os.path.exists(os.path.join(self.root_dir, ".wandb")) + else "wandb" + os.sep + ) + path = os.path.join(self.root_dir, stage_dir) + return os.path.expanduser(path) + + # Methods to collect and update settings from different sources. + # + # The Settings class does not track the source of the settings, + # so it is up to the developer to ensure that the settings are applied + # in the correct order. Most of the updates are done in + # wandb/sdk/wandb_setup.py::_WandbSetup._settings_setup. + + def update_from_system_config_file(self): + """Update settings from the system config file.""" + if not self.settings_system or not os.path.exists(self.settings_system): + return + for key, value in self._load_config_file(self.settings_system).items(): + if value is not None: + setattr(self, key, value) + + def update_from_workspace_config_file(self): + """Update settings from the workspace config file.""" + if not self.settings_workspace or not os.path.exists(self.settings_workspace): + return + for key, value in self._load_config_file(self.settings_workspace).items(): + if value is not None: + setattr(self, key, value) + + def update_from_env_vars(self, environ: Dict[str, Any]): + """Update settings from environment variables.""" + env_prefix: str = "WANDB_" + private_env_prefix: str = env_prefix + "_" + special_env_var_names = { + "WANDB_SERVICE_TRANSPORT": "x_service_transport", + "WANDB_DIR": "root_dir", + "WANDB_NAME": "run_name", + "WANDB_NOTES": "run_notes", + "WANDB_TAGS": "run_tags", + "WANDB_JOB_TYPE": "run_job_type", + "WANDB_HTTP_TIMEOUT": "x_graphql_timeout_seconds", + "WANDB_FILE_PUSHER_TIMEOUT": "x_file_transfer_timeout_seconds", + "WANDB_USER_EMAIL": "email", + } + env = dict() + for setting, value in environ.items(): + if not setting.startswith(env_prefix): + continue + + if setting in special_env_var_names: + key = special_env_var_names[setting] + elif setting.startswith(private_env_prefix): + key = "x_" + setting[len(private_env_prefix) :].lower() + else: + # otherwise, strip the prefix and convert to lowercase + key = setting[len(env_prefix) :].lower() + + if key in self.__dict__: + if key in ("ignore_globs", "run_tags"): + value = value.split(",") + env[key] = value + + for key, value in env.items(): + if value is not None: + setattr(self, key, value) + + def update_from_system_environment(self): + """Update settings from the system environment.""" + # For code saving, only allow env var override if value from server is true, or + # if no preference was specified. + if (self.save_code is True or self.save_code is None) and ( + os.getenv(env.SAVE_CODE) is not None + or os.getenv(env.DISABLE_CODE) is not None + ): + self.save_code = env.should_save_code() + + if os.getenv(env.DISABLE_GIT) is not None: + self.disable_git = env.disable_git() + + # Attempt to get notebook information if not already set by the user + if self._jupyter and (self.notebook_name is None or self.notebook_name == ""): + meta = wandb.jupyter.notebook_metadata(self.silent) # type: ignore + self.x_jupyter_path = meta.get("path") + self.x_jupyter_name = meta.get("name") + self.x_jupyter_root = meta.get("root") + elif ( + self._jupyter + and self.notebook_name is not None + and os.path.exists(self.notebook_name) + ): + self.x_jupyter_path = self.notebook_name + self.x_jupyter_name = self.notebook_name + self.x_jupyter_root = os.getcwd() + elif self._jupyter: + wandb.termwarn( + "WANDB_NOTEBOOK_NAME should be a path to a notebook file, " + f"couldn't find {self.notebook_name}.", + ) + + # host is populated by update_from_env_vars if the corresponding env + # vars exist -- but if they don't, we'll fill them in here. + if self.host is None: + self.host = socket.gethostname() # type: ignore + + _executable = ( + self.x_executable + or os.environ.get(env._EXECUTABLE) + or sys.executable + or shutil.which("python3") + or "python3" + ) + self.x_executable = _executable + + if self.docker is None: + self.docker = env.get_docker(util.image_id_from_k8s()) + + # proceed if not in CLI mode + if self.x_cli_only_mode: + return + + program = self.program or self._get_program() + + if program is not None: + try: + root = ( + GitRepo().root or os.getcwd() + if not self.disable_git + else os.getcwd() + ) + except Exception: + # if the git command fails, fall back to the current working directory + root = os.getcwd() + + self.program_relpath = self.program_relpath or self._get_program_relpath( + program, root + ) + program_abspath = os.path.abspath( + os.path.join(root, os.path.relpath(os.getcwd(), root), program) + ) + if os.path.exists(program_abspath): + self.program_abspath = program_abspath + else: + program = "" + + self.program = program + + def update_from_dict(self, settings: Dict[str, Any]) -> None: + """Update settings from a dictionary.""" + for key, value in dict(settings).items(): + if value is not None: + setattr(self, key, value) + + def update_from_settings(self, settings: Settings) -> None: + """Update settings from another instance of `Settings`.""" + d = {field: getattr(settings, field) for field in settings.model_fields_set} + if d: + self.update_from_dict(d) + + # Helper methods. + + def to_proto(self) -> wandb_settings_pb2.Settings: + """Generate a protobuf representation of the settings.""" + settings_proto = wandb_settings_pb2.Settings() + for k, v in self.model_dump(exclude_none=True).items(): + # Client-only settings that don't exist on the protobuf. + if k in ("reinit",): + continue + + # Special case for x_stats_open_metrics_filters. + if k == "x_stats_open_metrics_filters": + if isinstance(v, (list, set, tuple)): + setting = getattr(settings_proto, k) + setting.sequence.value.extend(v) + elif isinstance(v, dict): + setting = getattr(settings_proto, k) + for key, value in v.items(): + for kk, vv in value.items(): + setting.mapping.value[key].value[kk] = vv + else: + raise TypeError(f"Unsupported type {type(v)} for setting {k}") + continue + + # Special case for RunMoment fields. + if k in ("fork_from", "resume_from"): + run_moment = ( + v + if isinstance(v, RunMoment) + else RunMoment( + run=v.get("run"), + value=v.get("value"), + metric=v.get("metric"), + ) + ) + getattr(settings_proto, k).CopyFrom( + wandb_settings_pb2.RunMoment( + run=run_moment.run, + value=run_moment.value, + metric=run_moment.metric, + ) + ) + continue + + if isinstance(v, bool): + getattr(settings_proto, k).CopyFrom(BoolValue(value=v)) + elif isinstance(v, int): + getattr(settings_proto, k).CopyFrom(Int32Value(value=v)) + elif isinstance(v, float): + getattr(settings_proto, k).CopyFrom(DoubleValue(value=v)) + elif isinstance(v, str): + getattr(settings_proto, k).CopyFrom(StringValue(value=v)) + elif isinstance(v, (list, set, tuple)): + # we only support sequences of strings for now + sequence = getattr(settings_proto, k) + sequence.value.extend(v) + elif isinstance(v, dict): + mapping = getattr(settings_proto, k) + for key, value in v.items(): + # we only support dicts with string values for now + mapping.value[key] = value + elif v is None: + # None means that the setting value was not set. + pass + else: + raise TypeError(f"Unsupported type {type(v)} for setting {k}") + + return settings_proto + + def _get_program(self) -> Optional[str]: + """Get the program that started the current process.""" + if self._jupyter: + # If in a notebook, try to get the program from the notebook metadata. + if self.notebook_name: + return self.notebook_name + + if not self.x_jupyter_path: + return self.program + + if self.x_jupyter_path.startswith("fileId="): + return self.x_jupyter_name + + return self.x_jupyter_path + + # If not in a notebook, try to get the program from the environment + # or the __main__ module for scripts run as `python -m ...`. + program = os.getenv(env.PROGRAM) + if program is not None: + return program + + try: + import __main__ + except ImportError: + return None + + try: + if __main__.__spec__ is None: + python_args = __main__.__file__ + else: + python_args = f"-m {__main__.__spec__.name}" + except AttributeError: + return None + + return python_args + + @staticmethod + def _get_program_relpath(program: str, root: Optional[str] = None) -> Optional[str]: + """Get the relative path to the program from the root directory.""" + if not program: + return None + + root = root or os.getcwd() + if not root: + return None + + # For windows if the root and program are on different drives, + # os.path.relpath will raise a ValueError. + if not util.are_paths_on_same_drive(root, program): + return None + + full_path_to_program = os.path.join( + root, os.path.relpath(os.getcwd(), root), program + ) + if os.path.exists(full_path_to_program): + relative_path = os.path.relpath(full_path_to_program, start=root) + if "../" in relative_path: + return None + return relative_path + + return None + + @staticmethod + def _load_config_file(file_name: str, section: str = "default") -> dict: + """Load a config file and return the settings for a given section.""" + parser = configparser.ConfigParser() + parser.add_section(section) + parser.read(file_name) + config: Dict[str, Any] = dict() + for k in parser[section]: + config[k] = parser[section][k] + if k == "ignore_globs": + config[k] = config[k].split(",") + return config + + def _project_url_base(self) -> str: + """Construct the base URL for the project.""" + if not all([self.entity, self.project]): + return "" + + app_url = util.app_url(self.base_url) + return f"{app_url}/{quote(self.entity or '')}/{quote(self.project or '')}" + + def _get_url_query_string(self) -> str: + """Construct the query string for project, run, and sweep URLs.""" + # TODO: remove dependency on Api() + if self.anonymous not in ["allow", "must"]: + return "" + + api_key = apikey.api_key(settings=self) + + return f"?{urlencode({'apiKey': api_key})}" + + @staticmethod + def _runmoment_preprocessor( + val: Union[RunMoment, str, None], + ) -> Optional[RunMoment]: + """Preprocess the setting for forking or resuming a run.""" + if isinstance(val, RunMoment) or val is None: + return val + elif isinstance(val, str): + return RunMoment.from_uri(val) + + if not IS_PYDANTIC_V2: + + def model_copy(self, *args, **kwargs): + return self.copy(*args, **kwargs) + + def model_dump(self, **kwargs): + """Compatibility method for Pydantic v1 to mimic v2's model_dump. + + In v1, this is equivalent to dict() but also includes computed properties. + + Args: + **kwargs: Options passed to the dict method + - exclude_none: Whether to exclude fields with None values + + Returns: + A dictionary of the model's fields and computed properties + """ + # Handle exclude_none separately since it's named differently in v1 + exclude_none = kwargs.pop("exclude_none", False) + + # Start with regular fields from dict() + result = self.dict(**kwargs) + + # Get all computed properties + for name in dir(self.__class__): + attr = getattr(self.__class__, name, None) + if isinstance(attr, property): + try: + # Only include properties that don't raise errors + value = getattr(self, name) + result[name] = value + except (AttributeError, NotImplementedError, TypeError, ValueError): + # Skip properties that can't be accessed or raise errors + pass + elif isinstance(attr, RunMoment): + value = getattr(self, name) + result[name] = value + + # Special Pydantic attributes that should always be excluded + exclude_fields = { + "model_config", + "model_fields", + "model_fields_set", + "__fields__", + "__model_fields_set", + "__pydantic_self__", + "__pydantic_initialised__", + } + + # Remove special Pydantic attributes + for field in exclude_fields: + if field in result: + del result[field] + + if exclude_none: + # Remove None values from the result + return {k: v for k, v in result.items() if v is not None} + + return result + + @property + def model_fields_set(self) -> set: + """Return a set of fields that have been explicitly set. + + This is a compatibility property for Pydantic v1 to mimic v2's model_fields_set. + """ + return getattr(self, "__fields_set__", set()) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/wandb_summary.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/wandb_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..f15c7cc041959115b0cfc0024f5ec2b690209558 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/wandb_summary.py @@ -0,0 +1,150 @@ +import abc +import typing as t + +from .interface.summary_record import SummaryItem, SummaryRecord + + +def _get_dict(d): + if isinstance(d, dict): + return d + # assume argparse Namespace + return vars(d) + + +class SummaryDict(metaclass=abc.ABCMeta): + """dict-like wrapper for the nested dictionaries in a SummarySubDict. + + Triggers self._root._callback on property changes. + """ + + @abc.abstractmethod + def _as_dict(self): + raise NotImplementedError + + @abc.abstractmethod + def _update(self, record: SummaryRecord): + raise NotImplementedError + + def keys(self): + return [k for k in self._as_dict().keys() if k != "_wandb"] + + def get(self, key, default=None): + return self._as_dict().get(key, default) + + def __getitem__(self, key): + item = self._as_dict()[key] + + if isinstance(item, dict): + # this nested dict needs to be wrapped: + wrapped_item = SummarySubDict() + object.__setattr__(wrapped_item, "_items", item) + object.__setattr__(wrapped_item, "_parent", self) + object.__setattr__(wrapped_item, "_parent_key", key) + + return wrapped_item + + # this item isn't a nested dict + return item + + __getattr__ = __getitem__ + + def __setitem__(self, key, val): + self.update({key: val}) + + __setattr__ = __setitem__ + + def __delattr__(self, key): + record = SummaryRecord() + item = SummaryItem() + item.key = (key,) + record.remove = (item,) + self._update(record) + + __delitem__ = __delattr__ + + def update(self, d: t.Dict): + # import ipdb; ipdb.set_trace() + record = SummaryRecord() + for key, value in d.items(): + item = SummaryItem() + item.key = (key,) + item.value = value + record.update.append(item) + + self._update(record) + + +class Summary(SummaryDict): + """Track single values for each metric for each run. + + By default, a metric's summary is the last value of its History. + + For example, `wandb.log({'accuracy': 0.9})` will add a new step to History and + update Summary to the latest value. In some cases, it's more useful to have + the maximum or minimum of a metric instead of the final value. You can set + history manually `(wandb.summary['accuracy'] = best_acc)`. + + In the UI, summary metrics appear in the table to compare across runs. + Summary metrics are also used in visualizations like the scatter plot and + parallel coordinates chart. + + After training has completed, you may want to save evaluation metrics to a + run. Summary can handle numpy arrays and PyTorch/TensorFlow tensors. When + you save one of these types to Summary, we persist the entire tensor in a + binary file and store high level metrics in the summary object, such as min, + mean, variance, and 95th percentile. + + Examples: + ```python + wandb.init(config=args) + + best_accuracy = 0 + for epoch in range(1, args.epochs + 1): + test_loss, test_accuracy = test() + if test_accuracy > best_accuracy: + wandb.run.summary["best_accuracy"] = test_accuracy + best_accuracy = test_accuracy + ``` + """ + + _update_callback: t.Callable + _get_current_summary_callback: t.Callable + + def __init__(self, get_current_summary_callback: t.Callable): + super().__init__() + object.__setattr__(self, "_update_callback", None) + object.__setattr__( + self, "_get_current_summary_callback", get_current_summary_callback + ) + + def _set_update_callback(self, update_callback: t.Callable): + object.__setattr__(self, "_update_callback", update_callback) + + def _as_dict(self): + return self._get_current_summary_callback() + + def _update(self, record: SummaryRecord): + if self._update_callback: # type: ignore + self._update_callback(record) + + +class SummarySubDict(SummaryDict): + """Non-root node of the summary data structure. + + Contains a path to itself from the root. + """ + + _items: t.Dict + _parent: SummaryDict + _parent_key: str + + def __init__(self): + object.__setattr__(self, "_items", dict()) + object.__setattr__(self, "_parent", None) + object.__setattr__(self, "_parent_key", None) + + def _as_dict(self): + return self._items + + def _update(self, record: SummaryRecord): + return self._parent._update(record._add_next_parent(self._parent_key)) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/wandb_sweep.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/wandb_sweep.py new file mode 100644 index 0000000000000000000000000000000000000000..98707a32345dc34a055a34668714cd3d4b7a6008 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sdk/wandb_sweep.py @@ -0,0 +1,120 @@ +import urllib.parse +from typing import TYPE_CHECKING, Callable, Dict, List, Optional, Union + +import wandb +from wandb import env +from wandb.apis import InternalApi +from wandb.sdk.launch.sweeps.utils import handle_sweep_config_violations + +from . import wandb_login + +if TYPE_CHECKING: + from wandb.wandb_controller import _WandbController + + +def _get_sweep_url(api, sweep_id): + """Return sweep url if we can figure it out.""" + if api.api_key: + if api.settings("entity") is None: + viewer = api.viewer() + if viewer.get("entity"): + api.set_setting("entity", viewer["entity"]) + project = api.settings("project") + if not project: + return + if api.settings("entity"): + return "{base}/{entity}/{project}/sweeps/{sweepid}".format( + base=api.app_url, + entity=urllib.parse.quote(api.settings("entity")), + project=urllib.parse.quote(project), + sweepid=urllib.parse.quote(sweep_id), + ) + + +def sweep( + sweep: Union[dict, Callable], + entity: Optional[str] = None, + project: Optional[str] = None, + prior_runs: Optional[List[str]] = None, +) -> str: + """Initialize a hyperparameter sweep. + + Search for hyperparameters that optimizes a cost function + of a machine learning model by testing various combinations. + + Make note the unique identifier, `sweep_id`, that is returned. + At a later step provide the `sweep_id` to a sweep agent. + + See [Sweep configuration structure](https://docs.wandb.ai/guides/sweeps/define-sweep-configuration) + for information on how to define your sweep. + + Args: + sweep: The configuration of a hyperparameter search. + (or configuration generator). + If you provide a callable, ensure that the callable does + not take arguments and that it returns a dictionary that + conforms to the W&B sweep config spec. + entity: The username or team name where you want to send W&B + runs created by the sweep to. Ensure that the entity you + specify already exists. If you don't specify an entity, + the run will be sent to your default entity, + which is usually your username. + project: The name of the project where W&B runs created from + the sweep are sent to. If the project is not specified, the + run is sent to a project labeled 'Uncategorized'. + prior_runs: The run IDs of existing runs to add to this sweep. + + Returns: + str: A unique identifier for the sweep. + """ + if callable(sweep): + sweep = sweep() + """Sweep create for controller api and jupyter (eventually for cli).""" + + # Project may be only found in the sweep config. + if project is None and isinstance(sweep, dict): + project = sweep.get("project", None) + + if entity: + env.set_entity(entity) + if project: + env.set_project(project) + + # Make sure we are logged in + if wandb.run is None: + wandb_login._login(_silent=True) + api = InternalApi() + sweep_id, warnings = api.upsert_sweep(sweep, prior_runs=prior_runs) + handle_sweep_config_violations(warnings) + print("Create sweep with ID:", sweep_id) # noqa: T201 + sweep_url = _get_sweep_url(api, sweep_id) + if sweep_url: + print("Sweep URL:", sweep_url) # noqa: T201 + return sweep_id + + +def controller( + sweep_id_or_config: Optional[Union[str, Dict]] = None, + entity: Optional[str] = None, + project: Optional[str] = None, +) -> "_WandbController": + """Public sweep controller constructor. + + Examples: + ```python + import wandb + + tuner = wandb.controller(...) + print(tuner.sweep_config) + print(tuner.sweep_id) + tuner.configure_search(...) + tuner.configure_stopping(...) + ``` + + """ + from ..wandb_controller import _WandbController + + c = _WandbController( + sweep_id_or_config=sweep_id_or_config, entity=entity, project=project + ) + return c diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sync/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/sync/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..92213239a7fd075123dfe49928241b99640abc0b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/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/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/gql-0.2.0/wandb_gql/__pycache__/client.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/gql-0.2.0/wandb_gql/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e7897207c9fa448089853788522f2a89d296f82 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/gql-0.2.0/wandb_gql/__pycache__/client.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/gql-0.2.0/wandb_gql/transport/__pycache__/local_schema.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/gql-0.2.0/wandb_gql/transport/__pycache__/local_schema.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76e0e4f344b2ee1d74d3b1b7dd225bce53efd7e6 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/gql-0.2.0/wandb_gql/transport/__pycache__/local_schema.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/error/__pycache__/syntax_error.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/error/__pycache__/syntax_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37ffc3071f2b48a887416bb272ea2bd03c12be36 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/error/__pycache__/syntax_error.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/error/base.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/error/base.py new file mode 100644 index 0000000000000000000000000000000000000000..74d644705fbe732c0688f6acec6042c07f84f59e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/error/base.py @@ -0,0 +1,42 @@ +from ..language.location import get_location + + +class GraphQLError(Exception): + __slots__ = 'message', 'nodes', 'stack', 'original_error', '_source', '_positions' + + def __init__(self, message, nodes=None, stack=None, source=None, positions=None): + super(GraphQLError, self).__init__(message) + self.message = message + self.nodes = nodes + self.stack = stack + self._source = source + self._positions = positions + + @property + def source(self): + if self._source: + return self._source + if self.nodes: + node = self.nodes[0] + return node and node.loc and node.loc.source + + @property + def positions(self): + if self._positions: + return self._positions + if self.nodes is not None: + node_positions = [node.loc and node.loc.start for node in self.nodes] + if any(node_positions): + return node_positions + + def reraise(self): + if self.stack: + raise self.with_traceback(self.stack) + else: + raise self + + @property + def locations(self): + source = self.source + if self.positions and source: + return [get_location(source, pos) for pos in self.positions] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..866112679451268bf9137de4fc686a416718a9f5 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/__pycache__/executor.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/__pycache__/executor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6499604bb09dd5e525c27dab781c87061b2a6fa Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/__pycache__/executor.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executor.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executor.py new file mode 100644 index 0000000000000000000000000000000000000000..e8e9fd293cd375cb50c158d9a8e2a1fd9d4cb566 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executor.py @@ -0,0 +1,398 @@ +import collections +from collections.abc import Iterable +import functools +import logging +import sys + +from wandb_promise import Promise, promise_for_dict, is_thenable + +from ..error import GraphQLError, GraphQLLocatedError +from ..pyutils.default_ordered_dict import DefaultOrderedDict +from ..pyutils.ordereddict import OrderedDict +from ..type import (GraphQLEnumType, GraphQLInterfaceType, GraphQLList, + GraphQLNonNull, GraphQLObjectType, GraphQLScalarType, + GraphQLSchema, GraphQLUnionType) +from .base import (ExecutionContext, ExecutionResult, ResolveInfo, Undefined, + collect_fields, default_resolve_fn, get_field_def, + get_operation_root_type) +from .executors.sync import SyncExecutor +from .experimental.executor import execute as experimental_execute +from .middleware import MiddlewareManager + +logger = logging.getLogger(__name__) + + +use_experimental_executor = False + + +def execute(schema, document_ast, root_value=None, context_value=None, + variable_values=None, operation_name=None, executor=None, + return_promise=False, middleware=None): + if use_experimental_executor: + return experimental_execute( + schema, document_ast, root_value, context_value, + variable_values, operation_name, executor, + return_promise, middleware + ) + + assert schema, 'Must provide schema' + assert isinstance(schema, GraphQLSchema), ( + 'Schema must be an instance of GraphQLSchema. Also ensure that there are ' + + 'not multiple versions of GraphQL installed in your node_modules directory.' + ) + if middleware: + if not isinstance(middleware, MiddlewareManager): + middleware = MiddlewareManager(*middleware) + + assert isinstance(middleware, MiddlewareManager), ( + 'middlewares have to be an instance' + ' of MiddlewareManager. Received "{}".'.format(middleware) + ) + + if executor is None: + executor = SyncExecutor() + + context = ExecutionContext( + schema, + document_ast, + root_value, + context_value, + variable_values, + operation_name, + executor, + middleware + ) + + def executor(resolve, reject): + return resolve(execute_operation(context, context.operation, root_value)) + + def on_rejected(error): + context.errors.append(error) + return None + + def on_resolve(data): + if not context.errors: + return ExecutionResult(data=data) + return ExecutionResult(data=data, errors=context.errors) + + promise = Promise(executor).catch(on_rejected).then(on_resolve) + if return_promise: + return promise + context.executor.wait_until_finished() + return promise.get() + + +def execute_operation(exe_context, operation, root_value): + type = get_operation_root_type(exe_context.schema, operation) + fields = collect_fields( + exe_context, + type, + operation.selection_set, + DefaultOrderedDict(list), + set() + ) + + if operation.operation == 'mutation': + return execute_fields_serially(exe_context, type, root_value, fields) + + return execute_fields(exe_context, type, root_value, fields) + + +def execute_fields_serially(exe_context, parent_type, source_value, fields): + def execute_field_callback(results, response_name): + field_asts = fields[response_name] + result = resolve_field( + exe_context, + parent_type, + source_value, + field_asts + ) + if result is Undefined: + return results + + if is_thenable(result): + def collect_result(resolved_result): + results[response_name] = resolved_result + return results + + return result.then(collect_result, None) + + results[response_name] = result + return results + + def execute_field(prev_promise, response_name): + return prev_promise.then(lambda results: execute_field_callback(results, response_name)) + + return functools.reduce(execute_field, fields.keys(), Promise.resolve(collections.OrderedDict())) + + +def execute_fields(exe_context, parent_type, source_value, fields): + contains_promise = False + + final_results = OrderedDict() + + for response_name, field_asts in fields.items(): + result = resolve_field(exe_context, parent_type, source_value, field_asts) + if result is Undefined: + continue + + final_results[response_name] = result + if is_thenable(result): + contains_promise = True + + if not contains_promise: + return final_results + + return promise_for_dict(final_results) + + +def resolve_field(exe_context, parent_type, source, field_asts): + field_ast = field_asts[0] + field_name = field_ast.name.value + + field_def = get_field_def(exe_context.schema, parent_type, field_name) + if not field_def: + return Undefined + + return_type = field_def.type + resolve_fn = field_def.resolver or default_resolve_fn + + # We wrap the resolve_fn from the middleware + resolve_fn_middleware = exe_context.get_field_resolver(resolve_fn) + + # Build a dict of arguments from the field.arguments AST, using the variables scope to + # fulfill any variable references. + args = exe_context.get_argument_values(field_def, field_ast) + + # The resolve function's optional third argument is a context value that + # is provided to every resolve function within an execution. It is commonly + # used to represent an authenticated user, or request-specific caches. + context = exe_context.context_value + + # The resolve function's optional third argument is a collection of + # information about the current execution state. + info = ResolveInfo( + field_name, + field_asts, + return_type, + parent_type, + schema=exe_context.schema, + fragments=exe_context.fragments, + root_value=exe_context.root_value, + operation=exe_context.operation, + variable_values=exe_context.variable_values, + ) + + executor = exe_context.executor + result = resolve_or_error(resolve_fn_middleware, source, args, context, info, executor) + + return complete_value_catching_error( + exe_context, + return_type, + field_asts, + info, + result + ) + + +def resolve_or_error(resolve_fn, source, args, context, info, executor): + try: + return executor.execute(resolve_fn, source, args, context, info) + except Exception as e: + logger.exception("An error occurred while resolving field {}.{}".format( + info.parent_type.name, info.field_name + )) + e.stack = sys.exc_info()[2] + return e + + +def complete_value_catching_error(exe_context, return_type, field_asts, info, result): + # If the field type is non-nullable, then it is resolved without any + # protection from errors. + if isinstance(return_type, GraphQLNonNull): + return complete_value(exe_context, return_type, field_asts, info, result) + + # Otherwise, error protection is applied, logging the error and + # resolving a null value for this field if one is encountered. + try: + completed = complete_value(exe_context, return_type, field_asts, info, result) + if is_thenable(completed): + def handle_error(error): + exe_context.errors.append(error) + return None + + return completed.catch(handle_error) + + return completed + except Exception as e: + exe_context.errors.append(e) + return None + + +def complete_value(exe_context, return_type, field_asts, info, result): + """ + Implements the instructions for completeValue as defined in the + "Field entries" section of the spec. + + If the field type is Non-Null, then this recursively completes the value for the inner type. It throws a field + error if that completion returns null, as per the "Nullability" section of the spec. + + If the field type is a List, then this recursively completes the value for the inner type on each item in the + list. + + If the field type is a Scalar or Enum, ensures the completed value is a legal value of the type by calling the + `serialize` method of GraphQL type definition. + + If the field is an abstract type, determine the runtime type of the value and then complete based on that type. + + Otherwise, the field type expects a sub-selection set, and will complete the value by evaluating all + sub-selections. + """ + # If field type is NonNull, complete for inner type, and throw field error if result is null. + + if is_thenable(result): + return Promise.resolve(result).then( + lambda resolved: complete_value( + exe_context, + return_type, + field_asts, + info, + resolved + ), + lambda error: Promise.rejected(GraphQLLocatedError(field_asts, original_error=error)) + ) + + # print return_type, type(result) + if isinstance(result, Exception): + raise GraphQLLocatedError(field_asts, original_error=result) + + if isinstance(return_type, GraphQLNonNull): + return complete_nonnull_value(exe_context, return_type, field_asts, info, result) + + # If result is null-like, return null. + if result is None: + return None + + # If field type is List, complete each item in the list with the inner type + if isinstance(return_type, GraphQLList): + return complete_list_value(exe_context, return_type, field_asts, info, result) + + # If field type is Scalar or Enum, serialize to a valid value, returning null if coercion is not possible. + if isinstance(return_type, (GraphQLScalarType, GraphQLEnumType)): + return complete_leaf_value(return_type, result) + + if isinstance(return_type, (GraphQLInterfaceType, GraphQLUnionType)): + return complete_abstract_value(exe_context, return_type, field_asts, info, result) + + if isinstance(return_type, GraphQLObjectType): + return complete_object_value(exe_context, return_type, field_asts, info, result) + + assert False, u'Cannot complete value of unexpected type "{}".'.format(return_type) + + +def complete_list_value(exe_context, return_type, field_asts, info, result): + """ + Complete a list value by completing each item in the list with the inner type + """ + assert isinstance(result, Iterable), \ + ('User Error: expected iterable, but did not find one ' + + 'for field {}.{}.').format(info.parent_type, info.field_name) + + item_type = return_type.of_type + completed_results = [] + contains_promise = False + for item in result: + completed_item = complete_value_catching_error(exe_context, item_type, field_asts, info, item) + if not contains_promise and is_thenable(completed_item): + contains_promise = True + + completed_results.append(completed_item) + + return Promise.all(completed_results) if contains_promise else completed_results + + +def complete_leaf_value(return_type, result): + """ + Complete a Scalar or Enum by serializing to a valid value, returning null if serialization is not possible. + """ + # serialize = getattr(return_type, 'serialize', None) + # assert serialize, 'Missing serialize method on type' + + return return_type.serialize(result) + + +def complete_abstract_value(exe_context, return_type, field_asts, info, result): + """ + Complete an value of an abstract type by determining the runtime type of that value, then completing based + on that type. + """ + runtime_type = None + + # Field type must be Object, Interface or Union and expect sub-selections. + if isinstance(return_type, (GraphQLInterfaceType, GraphQLUnionType)): + if return_type.resolve_type: + runtime_type = return_type.resolve_type(result, exe_context.context_value, info) + else: + runtime_type = get_default_resolve_type_fn(result, exe_context.context_value, info, return_type) + + if isinstance(runtime_type, str): + runtime_type = info.schema.get_type(runtime_type) + + if not isinstance(runtime_type, GraphQLObjectType): + raise GraphQLError( + ('Abstract type {} must resolve to an Object type at runtime ' + + 'for field {}.{} with value "{}", received "{}".').format( + return_type, + info.parent_type, + info.field_name, + result, + runtime_type, + ), + field_asts + ) + + if not exe_context.schema.is_possible_type(return_type, runtime_type): + raise GraphQLError( + u'Runtime Object type "{}" is not a possible type for "{}".'.format(runtime_type, return_type), + field_asts + ) + + return complete_object_value(exe_context, runtime_type, field_asts, info, result) + + +def get_default_resolve_type_fn(value, context, info, abstract_type): + possible_types = info.schema.get_possible_types(abstract_type) + for type in possible_types: + if callable(type.is_type_of) and type.is_type_of(value, context, info): + return type + + +def complete_object_value(exe_context, return_type, field_asts, info, result): + """ + Complete an Object value by evaluating all sub-selections. + """ + if return_type.is_type_of and not return_type.is_type_of(result, exe_context.context_value, info): + raise GraphQLError( + u'Expected value of type "{}" but got: {}.'.format(return_type, type(result).__name__), + field_asts + ) + + # Collect sub-fields to execute to complete this value. + subfield_asts = exe_context.get_sub_fields(return_type, field_asts) + return execute_fields(exe_context, return_type, result, subfield_asts) + + +def complete_nonnull_value(exe_context, return_type, field_asts, info, result): + """ + Complete a NonNull value by completing the inner type + """ + completed = complete_value( + exe_context, return_type.of_type, field_asts, info, result + ) + if completed is None: + raise GraphQLError( + 'Cannot return null for non-nullable field {}.{}.'.format(info.parent_type, info.field_name), + field_asts + ) + + return completed diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/__pycache__/asyncio.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/__pycache__/asyncio.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..891809e37d3b40d9cbbd1a7116d79e1564006763 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/__pycache__/asyncio.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/__pycache__/gevent.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/__pycache__/gevent.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51bc24342331f1d27a422a17b772a9a7b36d6ea7 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/__pycache__/gevent.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/__pycache__/thread.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/__pycache__/thread.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c5c4aaa8bbd44afc7f4cb46aba695156e088035 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/__pycache__/thread.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/gevent.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/gevent.py new file mode 100644 index 0000000000000000000000000000000000000000..67395d3f7f359c14899c229ded73f0e6883c79b3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/gevent.py @@ -0,0 +1,22 @@ +from __future__ import absolute_import + +import gevent +from wandb_promise import Promise + +from .utils import process + + +class GeventExecutor(object): + + def __init__(self): + self.jobs = [] + + def wait_until_finished(self): + [j.join() for j in self.jobs] + # gevent.joinall(self.jobs) + + def execute(self, fn, *args, **kwargs): + promise = Promise() + job = gevent.spawn(process, promise, fn, args, kwargs) + self.jobs.append(job) + return promise diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/process.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/process.py new file mode 100644 index 0000000000000000000000000000000000000000..51301c864a5579c6a93df07da92e2ef520264c0c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/process.py @@ -0,0 +1,32 @@ +from multiprocessing import Process, Queue + +from wandb_promise import Promise + +from .utils import process + + +def queue_process(q): + promise, fn, args, kwargs = q.get() + process(promise, fn, args, kwargs) + + +class ProcessExecutor(object): + + def __init__(self): + self.processes = [] + self.q = Queue() + + def wait_until_finished(self): + for _process in self.processes: + _process.join() + self.q.close() + self.q.join_thread() + + def execute(self, fn, *args, **kwargs): + promise = Promise() + + self.q.put([promise, fn, args, kwargs], False) + _process = Process(target=queue_process, args=(self.q)) + _process.start() + self.processes.append(_process) + return promise diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/sync.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/sync.py new file mode 100644 index 0000000000000000000000000000000000000000..85f8471b6a148bf22184b5b0d9ea06bff78c0b2e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/sync.py @@ -0,0 +1,7 @@ +class SyncExecutor(object): + + def wait_until_finished(self): + pass + + def execute(self, fn, *args, **kwargs): + return fn(*args, **kwargs) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4fc44875b8e42a4e08bce82c5826c2979572e389 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/utils.py @@ -0,0 +1,6 @@ +def process(p, f, args, kwargs): + try: + val = f(*args, **kwargs) + p.do_resolve(val) + except Exception as e: + p.do_reject(e) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff6d9de60accc97b5615bbc7a8c8befa6c3de5f8 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/__pycache__/executor.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/__pycache__/executor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d543991753b8f7278b128c27bd1795850de880ce Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/__pycache__/executor.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/__pycache__/fragment.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/__pycache__/fragment.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9544ad039ce155ab0627e922b088c279b350b38e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/__pycache__/fragment.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/__pycache__/resolver.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/__pycache__/resolver.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed96064c18a032901e1cc5c2d8054f14705066c9 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/__pycache__/resolver.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/__pycache__/utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02248b3b63b26ed920d665810c880583834e1911 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/__pycache__/utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/fragment.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/fragment.py new file mode 100644 index 0000000000000000000000000000000000000000..ccef4b405066a3e77a923152e46b9cad4c2dcee1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/fragment.py @@ -0,0 +1,252 @@ +import functools + +from wandb_promise import Promise, is_thenable, promise_for_dict + +from ...pyutils.cached_property import cached_property +from ...pyutils.default_ordered_dict import DefaultOrderedDict +from ...type import (GraphQLInterfaceType, GraphQLList, GraphQLNonNull, + GraphQLObjectType, GraphQLUnionType) +from ..base import ResolveInfo, Undefined, collect_fields, get_field_def +from ..values import get_argument_values +from ...error import GraphQLError +try: + from itertools import izip as zip +except: + pass + + +def get_base_type(type): + if isinstance(type, (GraphQLList, GraphQLNonNull)): + return get_base_type(type.of_type) + return type + + +def get_subfield_asts(context, return_type, field_asts): + subfield_asts = DefaultOrderedDict(list) + visited_fragment_names = set() + for field_ast in field_asts: + selection_set = field_ast.selection_set + if selection_set: + subfield_asts = collect_fields( + context, return_type, selection_set, + subfield_asts, visited_fragment_names + ) + return subfield_asts + + +def get_resolvers(context, type, field_asts): + from .resolver import field_resolver + subfield_asts = get_subfield_asts(context, type, field_asts) + + for response_name, field_asts in subfield_asts.items(): + field_ast = field_asts[0] + field_name = field_ast.name.value + field_def = get_field_def(context and context.schema, type, field_name) + if not field_def: + continue + field_base_type = get_base_type(field_def.type) + field_fragment = None + info = ResolveInfo( + field_name, + field_asts, + field_base_type, + parent_type=type, + schema=context and context.schema, + fragments=context and context.fragments, + root_value=context and context.root_value, + operation=context and context.operation, + variable_values=context and context.variable_values, + ) + if isinstance(field_base_type, GraphQLObjectType): + field_fragment = Fragment( + type=field_base_type, + field_asts=field_asts, + info=info, + context=context + ) + elif isinstance(field_base_type, (GraphQLInterfaceType, GraphQLUnionType)): + field_fragment = AbstractFragment( + abstract_type=field_base_type, + field_asts=field_asts, + info=info, + context=context + ) + resolver = field_resolver(field_def, exe_context=context, info=info, fragment=field_fragment) + args = get_argument_values( + field_def.args, + field_ast.arguments, + context and context.variable_values + ) + yield (response_name, Field(resolver, args, context and context.context_value, info)) + + +class Field(object): + __slots__ = ('fn', 'args', 'context', 'info') + + def __init__(self, fn, args, context, info): + self.fn = fn + self.args = args + self.context = context + self.info = info + + def execute(self, root): + return self.fn(root, self.args, self.context, self.info) + + +class Fragment(object): + + def __init__(self, type, field_asts, context=None, info=None): + self.type = type + self.field_asts = field_asts + self.context = context + self.info = info + + @cached_property + def partial_resolvers(self): + return list(get_resolvers( + self.context, + self.type, + self.field_asts + )) + + @cached_property + def fragment_container(self): + try: + fields = next(zip(*self.partial_resolvers)) + except StopIteration: + fields = tuple() + + class FragmentInstance(dict): + # def __init__(self): + # self.fields = fields + # _fields = ('c','b','a') + set = dict.__setitem__ + # def set(self, name, value): + # self[name] = value + + def __iter__(self): + return iter(fields) + + return FragmentInstance + + def have_type(self, root): + return not self.type.is_type_of or self.type.is_type_of(root, self.context.context_value, self.info) + + def resolve(self, root): + if root and not self.have_type(root): + raise GraphQLError( + u'Expected value of type "{}" but got: {}.'.format(self.type, type(root).__name__), + self.info.field_asts + ) + + contains_promise = False + + final_results = self.fragment_container() + # return OrderedDict( + # ((field_name, field_resolver(root, field_args, context, info)) + # for field_name, field_resolver, field_args, context, info in self.partial_resolvers) + # ) + for response_name, field_resolver in self.partial_resolvers: + + result = field_resolver.execute(root) + if result is Undefined: + continue + + if not contains_promise and is_thenable(result): + contains_promise = True + + final_results[response_name] = result + + if not contains_promise: + return final_results + + return promise_for_dict(final_results) + # return { + # field_name: field_resolver(root, field_args, context, info) + # for field_name, field_resolver, field_args, context, info in self.partial_resolvers + # } + + def resolve_serially(self, root): + def execute_field_callback(results, resolver): + response_name, field_resolver = resolver + + result = field_resolver.execute(root) + + if result is Undefined: + return results + + if is_thenable(result): + def collect_result(resolved_result): + results[response_name] = resolved_result + return results + + return result.then(collect_result) + + results[response_name] = result + return results + + def execute_field(prev_promise, resolver): + return prev_promise.then(lambda results: execute_field_callback(results, resolver)) + + return functools.reduce(execute_field, self.partial_resolvers, Promise.resolve(self.fragment_container())) + + def __eq__(self, other): + return isinstance(other, Fragment) and ( + other.type == self.type and + other.field_asts == self.field_asts and + other.context == self.context and + other.info == self.info + ) + + +class AbstractFragment(object): + + def __init__(self, abstract_type, field_asts, context=None, info=None): + self.abstract_type = abstract_type + self.field_asts = field_asts + self.context = context + self.info = info + self._fragments = {} + + @cached_property + def possible_types(self): + return self.context.schema.get_possible_types(self.abstract_type) + + @cached_property + def possible_types_with_is_type_of(self): + return [ + (type, type.is_type_of) for type in self.possible_types if callable(type.is_type_of) + ] + + def get_fragment(self, type): + if isinstance(type, str): + type = self.context.schema.get_type(type) + + if type not in self._fragments: + assert type in self.possible_types, ( + 'Runtime Object type "{}" is not a possible type for "{}".' + ).format(type, self.abstract_type) + self._fragments[type] = Fragment( + type, + self.field_asts, + self.context, + self.info + ) + + return self._fragments[type] + + def resolve_type(self, result): + return_type = self.abstract_type + context = self.context.context_value + + if return_type.resolve_type: + return return_type.resolve_type(result, context, self.info) + + for type, is_type_of in self.possible_types_with_is_type_of: + if is_type_of(result, context, self.info): + return type + + def resolve(self, root): + _type = self.resolve_type(root) + fragment = self.get_fragment(_type) + return fragment.resolve(root) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/resolver.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..4d39cacd1dc810ec6a4de2fa709077c248760983 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/resolver.py @@ -0,0 +1,151 @@ +import sys +from collections.abc import Iterable +from functools import partial + +from wandb_promise import Promise, is_thenable + +from ...error import GraphQLError, GraphQLLocatedError +from ...type import (GraphQLEnumType, GraphQLInterfaceType, GraphQLList, + GraphQLNonNull, GraphQLObjectType, GraphQLScalarType, + GraphQLUnionType) +from ..base import default_resolve_fn +from ...execution import executor +from .utils import imap, normal_map + + +def on_complete_resolver(on_error, __func, exe_context, info, __resolver, *args, **kwargs): + try: + result = __resolver(*args, **kwargs) + if isinstance(result, Exception): + return on_error(result) + # return Promise.resolve(result).then(__func).catch(on_error) + if is_thenable(result): + # TODO: Remove this, if a promise is resolved with an Exception, + # it should raise by default. This is fixing an old behavior + # in the Promise package + def on_resolve(value): + if isinstance(value, Exception): + return on_error(value) + return value + return result.then(on_resolve).then(__func).catch(on_error) + return __func(result) + except Exception as e: + return on_error(e) + + +def complete_list_value(inner_resolver, exe_context, info, on_error, result): + if result is None: + return None + + assert isinstance(result, Iterable), \ + ('User Error: expected iterable, but did not find one ' + + 'for field {}.{}.').format(info.parent_type, info.field_name) + + completed_results = normal_map(inner_resolver, result) + + if not any(imap(is_thenable, completed_results)): + return completed_results + + return Promise.all(completed_results).catch(on_error) + + +def complete_nonnull_value(exe_context, info, result): + if result is None: + raise GraphQLError( + 'Cannot return null for non-nullable field {}.{}.'.format(info.parent_type, info.field_name), + info.field_asts + ) + return result + + +def complete_leaf_value(serialize, result): + if result is None: + return None + return serialize(result) + + +def complete_object_value(fragment_resolve, exe_context, on_error, result): + if result is None: + return None + + result = fragment_resolve(result) + if is_thenable(result): + return result.catch(on_error) + return result + + +def field_resolver(field, fragment=None, exe_context=None, info=None): + # resolver = exe_context.get_field_resolver(field.resolver or default_resolve_fn) + resolver = field.resolver or default_resolve_fn + if exe_context: + # We decorate the resolver with the middleware + resolver = exe_context.get_field_resolver(resolver) + return type_resolver(field.type, resolver, + fragment, exe_context, info, catch_error=True) + + +def type_resolver(return_type, resolver, fragment=None, exe_context=None, info=None, catch_error=False): + if isinstance(return_type, GraphQLNonNull): + return type_resolver_non_null(return_type, resolver, fragment, exe_context, info) + + if isinstance(return_type, (GraphQLScalarType, GraphQLEnumType)): + return type_resolver_leaf(return_type, resolver, exe_context, info, catch_error) + + if isinstance(return_type, (GraphQLList)): + return type_resolver_list(return_type, resolver, fragment, exe_context, info, catch_error) + + if isinstance(return_type, (GraphQLObjectType)): + assert fragment and fragment.type == return_type, 'Fragment and return_type dont match' + return type_resolver_fragment(return_type, resolver, fragment, exe_context, info, catch_error) + + if isinstance(return_type, (GraphQLInterfaceType, GraphQLUnionType)): + assert fragment, 'You need to pass a fragment to resolve a Interface or Union' + return type_resolver_fragment(return_type, resolver, fragment, exe_context, info, catch_error) + + raise Exception("The resolver have to be created for a fragment") + + +def on_error(exe_context, info, catch_error, e): + error = e + if not isinstance(e, (GraphQLLocatedError, GraphQLError)): + error = GraphQLLocatedError(info.field_asts, original_error=e) + if catch_error: + exe_context.errors.append(error) + executor.logger.exception("An error occurred while resolving field {}.{}".format( + info.parent_type.name, info.field_name + )) + error.stack = sys.exc_info()[2] + return None + raise error + + +def type_resolver_fragment(return_type, resolver, fragment, exe_context, info, catch_error): + on_complete_type_error = partial(on_error, exe_context, info, catch_error) + complete_object_value_resolve = partial( + complete_object_value, + fragment.resolve, + exe_context, + on_complete_type_error) + on_resolve_error = partial(on_error, exe_context, info, catch_error) + return partial(on_complete_resolver, on_resolve_error, complete_object_value_resolve, exe_context, info, resolver) + + +def type_resolver_non_null(return_type, resolver, fragment, exe_context, info): # no catch_error + resolver = type_resolver(return_type.of_type, resolver, fragment, exe_context, info) + nonnull_complete = partial(complete_nonnull_value, exe_context, info) + on_resolve_error = partial(on_error, exe_context, info, False) + return partial(on_complete_resolver, on_resolve_error, nonnull_complete, exe_context, info, resolver) + + +def type_resolver_leaf(return_type, resolver, exe_context, info, catch_error): + leaf_complete = partial(complete_leaf_value, return_type.serialize) + on_resolve_error = partial(on_error, exe_context, info, catch_error) + return partial(on_complete_resolver, on_resolve_error, leaf_complete, exe_context, info, resolver) + + +def type_resolver_list(return_type, resolver, fragment, exe_context, info, catch_error): + item_type = return_type.of_type + inner_resolver = type_resolver(item_type, lambda item: item, fragment, exe_context, info, catch_error=True) + on_resolve_error = partial(on_error, exe_context, info, catch_error) + list_complete = partial(complete_list_value, inner_resolver, exe_context, info, on_resolve_error) + return partial(on_complete_resolver, on_resolve_error, list_complete, exe_context, info, resolver) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__pycache__/ast.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__pycache__/ast.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57f27050cc595643a4d86282c8faa17bef240a53 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__pycache__/ast.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__pycache__/lexer.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__pycache__/lexer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb0bf80c9fb6ab1105d3ad9633a5364fd843316f Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__pycache__/lexer.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__pycache__/location.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__pycache__/location.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e931a26f2fdcdf5f20b7fdac28c76a16c20d217 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__pycache__/location.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__pycache__/parser.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__pycache__/parser.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1f82d0145c9674eef9f543db8ac2c20984a4733 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__pycache__/parser.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__pycache__/printer.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__pycache__/printer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2b16153e293f96dd6a8aa1ba7eb88ccb3b7747d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__pycache__/printer.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__pycache__/source.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__pycache__/source.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef9060be7e42e8e558f39f5b7274b48ce9490164 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__pycache__/source.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__pycache__/visitor_meta.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__pycache__/visitor_meta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7bea59370ee185635fad517ce122ce0d7725f2f6 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/__pycache__/visitor_meta.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/parser.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..d2854a303095d4fcbbaed9f29a9e4dcca5e06db4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/language/parser.py @@ -0,0 +1,779 @@ +from . import ast +from ..error import GraphQLSyntaxError +from .lexer import Lexer, TokenKind, get_token_desc, get_token_kind_desc +from .source import Source + +__all__ = ['parse'] + + +def parse(source, **kwargs): + """Given a GraphQL source, parses it into a Document.""" + options = {'no_location': False, 'no_source': False} + options.update(kwargs) + source_obj = source + + if isinstance(source, str): + source_obj = Source(source) + + parser = Parser(source_obj, options) + return parse_document(parser) + + +def parse_value(source, **kwargs): + options = {'no_location': False, 'no_source': False} + options.update(kwargs) + source_obj = source + + if isinstance(source, str): + source_obj = Source(source) + + parser = Parser(source_obj, options) + return parse_value_literal(parser, False) + + +class Parser(object): + __slots__ = 'lexer', 'source', 'options', 'prev_end', 'token' + + def __init__(self, source, options): + self.lexer = Lexer(source) + self.source = source + self.options = options + self.prev_end = 0 + self.token = self.lexer.next_token() + + +class Loc(object): + __slots__ = 'start', 'end', 'source' + + def __init__(self, start, end, source=None): + self.start = start + self.end = end + self.source = source + + def __repr__(self): + source = ' source={}'.format(self.source) if self.source else '' + return ''.format(self.start, self.end, source) + + def __eq__(self, other): + return ( + isinstance(other, Loc) and + self.start == other.start and + self.end == other.end and + self.source == other.source + ) + + +def loc(parser, start): + """Returns a location object, used to identify the place in + the source that created a given parsed object.""" + if parser.options['no_location']: + return None + + if parser.options['no_source']: + return Loc(start, parser.prev_end) + + return Loc(start, parser.prev_end, parser.source) + + +def advance(parser): + """Moves the internal parser object to the next lexed token.""" + prev_end = parser.token.end + parser.prev_end = prev_end + parser.token = parser.lexer.next_token(prev_end) + + +def peek(parser, kind): + """Determines if the next token is of a given kind""" + return parser.token.kind == kind + + +def skip(parser, kind): + """If the next token is of the given kind, return true after advancing + the parser. Otherwise, do not change the parser state + and throw an error.""" + match = parser.token.kind == kind + if match: + advance(parser) + + return match + + +def expect(parser, kind): + """If the next token is of the given kind, return that token after + advancing the parser. Otherwise, do not change the parser state and + return False.""" + token = parser.token + if token.kind == kind: + advance(parser) + return token + + raise GraphQLSyntaxError( + parser.source, + token.start, + u'Expected {}, found {}'.format( + get_token_kind_desc(kind), + get_token_desc(token) + ) + ) + + +def expect_keyword(parser, value): + """If the next token is a keyword with the given value, return that + token after advancing the parser. Otherwise, do not change the parser + state and return False.""" + token = parser.token + if token.kind == TokenKind.NAME and token.value == value: + advance(parser) + return token + + raise GraphQLSyntaxError( + parser.source, + token.start, + u'Expected "{}", found {}'.format(value, get_token_desc(token)) + ) + + +def unexpected(parser, at_token=None): + """Helper function for creating an error when an unexpected lexed token + is encountered.""" + token = at_token or parser.token + return GraphQLSyntaxError( + parser.source, + token.start, + u'Unexpected {}'.format(get_token_desc(token)) + ) + + +def any(parser, open_kind, parse_fn, close_kind): + """Returns a possibly empty list of parse nodes, determined by + the parse_fn. This list begins with a lex token of openKind + and ends with a lex token of closeKind. Advances the parser + to the next lex token after the closing token.""" + expect(parser, open_kind) + nodes = [] + while not skip(parser, close_kind): + nodes.append(parse_fn(parser)) + + return nodes + + +def many(parser, open_kind, parse_fn, close_kind): + """Returns a non-empty list of parse nodes, determined by + the parse_fn. This list begins with a lex token of openKind + and ends with a lex token of closeKind. Advances the parser + to the next lex token after the closing token.""" + expect(parser, open_kind) + nodes = [parse_fn(parser)] + while not skip(parser, close_kind): + nodes.append(parse_fn(parser)) + + return nodes + + +def parse_name(parser): + """Converts a name lex token into a name parse node.""" + token = expect(parser, TokenKind.NAME) + return ast.Name( + value=token.value, + loc=loc(parser, token.start) + ) + + +# Implements the parsing rules in the Document section. + +def parse_document(parser): + start = parser.token.start + definitions = [] + while True: + definitions.append(parse_definition(parser)) + + if skip(parser, TokenKind.EOF): + break + + return ast.Document( + definitions=definitions, + loc=loc(parser, start) + ) + + +def parse_definition(parser): + if peek(parser, TokenKind.BRACE_L): + return parse_operation_definition(parser) + + if peek(parser, TokenKind.NAME): + name = parser.token.value + + if name in ('query', 'mutation', 'subscription'): + return parse_operation_definition(parser) + elif name == 'fragment': + return parse_fragment_definition(parser) + elif name in ('schema', 'scalar', 'type', 'interface', 'union', 'enum', 'input', 'extend', 'directive'): + return parse_type_system_definition(parser) + + raise unexpected(parser) + + +# Implements the parsing rules in the Operations section. +def parse_operation_definition(parser): + start = parser.token.start + if peek(parser, TokenKind.BRACE_L): + return ast.OperationDefinition( + operation='query', + name=None, + variable_definitions=None, + directives=[], + selection_set=parse_selection_set(parser), + loc=loc(parser, start) + ) + + operation = parse_operation_type(parser) + + name = None + if peek(parser, TokenKind.NAME): + name = parse_name(parser) + + return ast.OperationDefinition( + operation=operation, + name=name, + variable_definitions=parse_variable_definitions(parser), + directives=parse_directives(parser), + selection_set=parse_selection_set(parser), + loc=loc(parser, start) + ) + + +def parse_operation_type(parser): + operation_token = expect(parser, TokenKind.NAME) + operation = operation_token.value + if operation == 'query': + return 'query' + elif operation == 'mutation': + return 'mutation' + elif operation == 'subscription': + return 'subscription' + + raise unexpected(parser, operation_token) + + +def parse_variable_definitions(parser): + if peek(parser, TokenKind.PAREN_L): + return many( + parser, + TokenKind.PAREN_L, + parse_variable_definition, + TokenKind.PAREN_R + ) + + return [] + + +def parse_variable_definition(parser): + start = parser.token.start + + return ast.VariableDefinition( + variable=parse_variable(parser), + type=expect(parser, TokenKind.COLON) and parse_type(parser), + default_value=parse_value_literal(parser, True) if skip(parser, TokenKind.EQUALS) else None, + loc=loc(parser, start) + ) + + +def parse_variable(parser): + start = parser.token.start + expect(parser, TokenKind.DOLLAR) + + return ast.Variable( + name=parse_name(parser), + loc=loc(parser, start) + ) + + +def parse_selection_set(parser): + start = parser.token.start + return ast.SelectionSet( + selections=many(parser, TokenKind.BRACE_L, parse_selection, TokenKind.BRACE_R), + loc=loc(parser, start) + ) + + +def parse_selection(parser): + if peek(parser, TokenKind.SPREAD): + return parse_fragment(parser) + else: + return parse_field(parser) + + +def parse_field(parser): + # Corresponds to both Field and Alias in the spec + start = parser.token.start + + name_or_alias = parse_name(parser) + if skip(parser, TokenKind.COLON): + alias = name_or_alias + name = parse_name(parser) + else: + alias = None + name = name_or_alias + + return ast.Field( + alias=alias, + name=name, + arguments=parse_arguments(parser), + directives=parse_directives(parser), + selection_set=parse_selection_set(parser) if peek(parser, TokenKind.BRACE_L) else None, + loc=loc(parser, start) + ) + + +def parse_arguments(parser): + if peek(parser, TokenKind.PAREN_L): + return many( + parser, TokenKind.PAREN_L, + parse_argument, TokenKind.PAREN_R) + + return [] + + +def parse_argument(parser): + start = parser.token.start + + return ast.Argument( + name=parse_name(parser), + value=expect(parser, TokenKind.COLON) and parse_value_literal(parser, False), + loc=loc(parser, start) + ) + + +# Implements the parsing rules in the Fragments section. + +def parse_fragment(parser): + # Corresponds to both FragmentSpread and InlineFragment in the spec + start = parser.token.start + expect(parser, TokenKind.SPREAD) + + if peek(parser, TokenKind.NAME) and parser.token.value != 'on': + return ast.FragmentSpread( + name=parse_fragment_name(parser), + directives=parse_directives(parser), + loc=loc(parser, start) + ) + + type_condition = None + if parser.token.value == 'on': + advance(parser) + type_condition = parse_named_type(parser) + + return ast.InlineFragment( + type_condition=type_condition, + directives=parse_directives(parser), + selection_set=parse_selection_set(parser), + loc=loc(parser, start) + ) + + +def parse_fragment_definition(parser): + start = parser.token.start + expect_keyword(parser, 'fragment') + + return ast.FragmentDefinition( + name=parse_fragment_name(parser), + type_condition=expect_keyword(parser, 'on') and parse_named_type(parser), + directives=parse_directives(parser), + selection_set=parse_selection_set(parser), + loc=loc(parser, start) + ) + + +def parse_fragment_name(parser): + if parser.token.value == 'on': + raise unexpected(parser) + + return parse_name(parser) + + +def parse_value_literal(parser, is_const): + token = parser.token + if token.kind == TokenKind.BRACKET_L: + return parse_list(parser, is_const) + + elif token.kind == TokenKind.BRACE_L: + return parse_object(parser, is_const) + + elif token.kind == TokenKind.INT: + advance(parser) + return ast.IntValue(value=token.value, loc=loc(parser, token.start)) + + elif token.kind == TokenKind.FLOAT: + advance(parser) + return ast.FloatValue(value=token.value, loc=loc(parser, token.start)) + + elif token.kind == TokenKind.STRING: + advance(parser) + return ast.StringValue(value=token.value, loc=loc(parser, token.start)) + + elif token.kind == TokenKind.NAME: + if token.value in ('true', 'false'): + advance(parser) + return ast.BooleanValue(value=token.value == 'true', loc=loc(parser, token.start)) + + if token.value != 'null': + advance(parser) + return ast.EnumValue(value=token.value, loc=loc(parser, token.start)) + + elif token.kind == TokenKind.DOLLAR: + if not is_const: + return parse_variable(parser) + + raise unexpected(parser) + + +# Implements the parsing rules in the Values section. +def parse_variable_value(parser): + return parse_value_literal(parser, False) + + +def parse_const_value(parser): + return parse_value_literal(parser, True) + + +def parse_list(parser, is_const): + start = parser.token.start + item = parse_const_value if is_const else parse_variable_value + + return ast.ListValue( + values=any( + parser, TokenKind.BRACKET_L, + item, TokenKind.BRACKET_R), + loc=loc(parser, start) + ) + + +def parse_object(parser, is_const): + start = parser.token.start + expect(parser, TokenKind.BRACE_L) + fields = [] + + while not skip(parser, TokenKind.BRACE_R): + fields.append(parse_object_field(parser, is_const)) + + return ast.ObjectValue(fields=fields, loc=loc(parser, start)) + + +def parse_object_field(parser, is_const): + start = parser.token.start + return ast.ObjectField( + name=parse_name(parser), + value=expect(parser, TokenKind.COLON) and parse_value_literal(parser, is_const), + loc=loc(parser, start) + ) + + +# Implements the parsing rules in the Directives section. + +def parse_directives(parser): + directives = [] + while peek(parser, TokenKind.AT): + directives.append(parse_directive(parser)) + return directives + + +def parse_directive(parser): + start = parser.token.start + expect(parser, TokenKind.AT) + + return ast.Directive( + name=parse_name(parser), + arguments=parse_arguments(parser), + loc=loc(parser, start), + ) + + +# Implements the parsing rules in the Types section. +def parse_type(parser): + """Handles the 'Type': TypeName, ListType, and NonNullType + parsing rules.""" + start = parser.token.start + if skip(parser, TokenKind.BRACKET_L): + ast_type = parse_type(parser) + expect(parser, TokenKind.BRACKET_R) + ast_type = ast.ListType(type=ast_type, loc=loc(parser, start)) + + else: + ast_type = parse_named_type(parser) + + if skip(parser, TokenKind.BANG): + return ast.NonNullType(type=ast_type, loc=loc(parser, start)) + + return ast_type + + +def parse_named_type(parser): + start = parser.token.start + return ast.NamedType( + name=parse_name(parser), + loc=loc(parser, start), + ) + + +def parse_type_system_definition(parser): + ''' + TypeSystemDefinition : + - SchemaDefinition + - TypeDefinition + - TypeExtensionDefinition + - DirectiveDefinition + + TypeDefinition : + - ScalarTypeDefinition + - ObjectTypeDefinition + - InterfaceTypeDefinition + - UnionTypeDefinition + - EnumTypeDefinition + - InputObjectTypeDefinition + ''' + if not peek(parser, TokenKind.NAME): + raise unexpected(parser) + + name = parser.token.value + + if name == 'schema': + return parse_schema_definition(parser) + + elif name == 'scalar': + return parse_scalar_type_definition(parser) + + elif name == 'type': + return parse_object_type_definition(parser) + + elif name == 'interface': + return parse_interface_type_definition(parser) + + elif name == 'union': + return parse_union_type_definition(parser) + + elif name == 'enum': + return parse_enum_type_definition(parser) + + elif name == 'input': + return parse_input_object_type_definition(parser) + + elif name == 'extend': + return parse_type_extension_definition(parser) + + elif name == 'directive': + return parse_directive_definition(parser) + + raise unexpected(parser) + + +def parse_schema_definition(parser): + start = parser.token.start + expect_keyword(parser, 'schema') + directives = parse_directives(parser) + operation_types = many( + parser, + TokenKind.BRACE_L, + parse_operation_type_definition, + TokenKind.BRACE_R + ) + + return ast.SchemaDefinition( + directives=directives, + operation_types=operation_types, + loc=loc(parser, start) + ) + + +def parse_operation_type_definition(parser): + start = parser.token.start + operation = parse_operation_type(parser) + expect(parser, TokenKind.COLON) + + return ast.OperationTypeDefinition( + operation=operation, + type=parse_named_type(parser), + loc=loc(parser, start) + ) + + +def parse_scalar_type_definition(parser): + start = parser.token.start + expect_keyword(parser, 'scalar') + + return ast.ScalarTypeDefinition( + name=parse_name(parser), + directives=parse_directives(parser), + loc=loc(parser, start), + ) + + +def parse_object_type_definition(parser): + start = parser.token.start + expect_keyword(parser, 'type') + return ast.ObjectTypeDefinition( + name=parse_name(parser), + interfaces=parse_implements_interfaces(parser), + directives=parse_directives(parser), + fields=any( + parser, + TokenKind.BRACE_L, + parse_field_definition, + TokenKind.BRACE_R + ), + loc=loc(parser, start), + ) + + +def parse_implements_interfaces(parser): + types = [] + if parser.token.value == 'implements': + advance(parser) + + while True: + types.append(parse_named_type(parser)) + + if not peek(parser, TokenKind.NAME): + break + + return types + + +def parse_field_definition(parser): + start = parser.token.start + + return ast.FieldDefinition( + name=parse_name(parser), + arguments=parse_argument_defs(parser), + type=expect(parser, TokenKind.COLON) and parse_type(parser), + directives=parse_directives(parser), + loc=loc(parser, start), + ) + + +def parse_argument_defs(parser): + if not peek(parser, TokenKind.PAREN_L): + return [] + + return many(parser, TokenKind.PAREN_L, parse_input_value_def, TokenKind.PAREN_R) + + +def parse_input_value_def(parser): + start = parser.token.start + + return ast.InputValueDefinition( + name=parse_name(parser), + type=expect(parser, TokenKind.COLON) and parse_type(parser), + default_value=parse_const_value(parser) if skip(parser, TokenKind.EQUALS) else None, + directives=parse_directives(parser), + loc=loc(parser, start), + ) + + +def parse_interface_type_definition(parser): + start = parser.token.start + expect_keyword(parser, 'interface') + + return ast.InterfaceTypeDefinition( + name=parse_name(parser), + directives=parse_directives(parser), + fields=any(parser, TokenKind.BRACE_L, parse_field_definition, TokenKind.BRACE_R), + loc=loc(parser, start), + ) + + +def parse_union_type_definition(parser): + start = parser.token.start + expect_keyword(parser, 'union') + + return ast.UnionTypeDefinition( + name=parse_name(parser), + directives=parse_directives(parser), + types=expect(parser, TokenKind.EQUALS) and parse_union_members(parser), + loc=loc(parser, start), + ) + + +def parse_union_members(parser): + members = [] + + while True: + members.append(parse_named_type(parser)) + + if not skip(parser, TokenKind.PIPE): + break + + return members + + +def parse_enum_type_definition(parser): + start = parser.token.start + expect_keyword(parser, 'enum') + + return ast.EnumTypeDefinition( + name=parse_name(parser), + directives=parse_directives(parser), + values=many(parser, TokenKind.BRACE_L, parse_enum_value_definition, TokenKind.BRACE_R), + loc=loc(parser, start), + ) + + +def parse_enum_value_definition(parser): + start = parser.token.start + + return ast.EnumValueDefinition( + name=parse_name(parser), + directives=parse_directives(parser), + loc=loc(parser, start), + ) + + +def parse_input_object_type_definition(parser): + start = parser.token.start + expect_keyword(parser, 'input') + + return ast.InputObjectTypeDefinition( + name=parse_name(parser), + directives=parse_directives(parser), + fields=any(parser, TokenKind.BRACE_L, parse_input_value_def, TokenKind.BRACE_R), + loc=loc(parser, start), + ) + + +def parse_type_extension_definition(parser): + start = parser.token.start + expect_keyword(parser, 'extend') + + return ast.TypeExtensionDefinition( + definition=parse_object_type_definition(parser), + loc=loc(parser, start) + ) + + +def parse_directive_definition(parser): + start = parser.token.start + expect_keyword(parser, 'directive') + expect(parser, TokenKind.AT) + + name = parse_name(parser) + args = parse_argument_defs(parser) + expect_keyword(parser, 'on') + + locations = parse_directive_locations(parser) + return ast.DirectiveDefinition( + name=name, + locations=locations, + arguments=args, + loc=loc(parser, start) + ) + + +def parse_directive_locations(parser): + locations = [] + + while True: + locations.append(parse_name(parser)) + + if not skip(parser, TokenKind.PIPE): + break + + return locations diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25d7803ddf89b5a7566253f22b68bd6bd0577e0a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__pycache__/cached_property.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__pycache__/cached_property.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abcf8f3e6d13dcd72a871baa8dafcc4f8473d9e3 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__pycache__/cached_property.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__pycache__/default_ordered_dict.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__pycache__/default_ordered_dict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d73a5068b9a2ef3184a32f754824e2b7392e1fd5 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__pycache__/default_ordered_dict.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__pycache__/ordereddict.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__pycache__/ordereddict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71f3c0c98514fe09a4516c06b334120de9c0a851 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__pycache__/ordereddict.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__pycache__/pair_set.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__pycache__/pair_set.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fbedfb54f0b90e9c8161ce610804c2337d0fab18 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__pycache__/pair_set.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__pycache__/version.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__pycache__/version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..698df0e72ec6d774fa05fd82fecedeb7bfb6ce53 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/__pycache__/version.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/ordereddict.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/ordereddict.py new file mode 100644 index 0000000000000000000000000000000000000000..ff341a4c86b8857fabf22fe2ef644b470e9586c6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/ordereddict.py @@ -0,0 +1,8 @@ +try: + # Try to load the Cython performant OrderedDict (C) + # as is more performant than collections.OrderedDict (Python) + from cyordereddict import OrderedDict +except ImportError: + from collections import OrderedDict + +__all__ = ['OrderedDict'] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/pair_set.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/pair_set.py new file mode 100644 index 0000000000000000000000000000000000000000..0af547a9d93aa3a2a6af356bd3d25d56104aa977 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/pair_set.py @@ -0,0 +1,43 @@ +class PairSet(object): + __slots__ = '_data', + + def __init__(self): + self._data = {} + + def __contains__(self, item): + return self.has(item[0], item[1], item[2]) + + def __str__(self): + return str(self._data) + + def __repr__(self): + return str(self._data) + + def has(self, a, b, are_mutually_exclusive): + first = self._data.get(a) + result = first and first.get(b) + if result is None: + return False + + # are_mutually_exclusive being false is a superset of being true, + # hence if we want to know if this PairSet "has" these two with no + # exclusivity, we have to ensure it was added as such. + if not are_mutually_exclusive: + return not result + + return True + + def add(self, a, b, are_mutually_exclusive): + _pair_set_add(self._data, a, b, are_mutually_exclusive) + _pair_set_add(self._data, b, a, are_mutually_exclusive) + return self + + +def _pair_set_add(data, a, b, are_mutually_exclusive): + sub_dict = data.get(a) + + if not sub_dict: + sub_dict = {} + data[a] = sub_dict + + sub_dict[b] = are_mutually_exclusive diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/version.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/version.py new file mode 100644 index 0000000000000000000000000000000000000000..614df9f570dc8c92101cc0126de6ef49c3841615 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/pyutils/version.py @@ -0,0 +1,78 @@ +from __future__ import unicode_literals + +import datetime +import os +import subprocess + + +def get_version(version=None): + "Returns a PEP 440-compliant version number from VERSION." + version = get_complete_version(version) + + # Now build the two parts of the version number: + # main = X.Y[.Z] + # sub = .devN - for pre-alpha releases + # | {a|b|rc}N - for alpha, beta, and rc releases + + main = get_main_version(version) + + sub = '' + if version[3] == 'alpha' and version[4] == 0: + git_changeset = get_git_changeset() + if git_changeset: + sub = '.dev%s' % git_changeset + else: + sub = '.dev' + elif version[3] != 'final': + mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'rc'} + sub = mapping[version[3]] + str(version[4]) + + return str(main + sub) + + +def get_main_version(version=None): + "Returns main version (X.Y[.Z]) from VERSION." + version = get_complete_version(version) + parts = 2 if version[2] == 0 else 3 + return '.'.join(str(x) for x in version[:parts]) + + +def get_complete_version(version=None): + """Returns a tuple of the graphql version. If version argument is non-empty, + then checks for correctness of the tuple provided. + """ + if version is None: + from wandb_graphql import VERSION as version + else: + assert len(version) == 5 + assert version[3] in ('alpha', 'beta', 'rc', 'final') + + return version + + +def get_docs_version(version=None): + version = get_complete_version(version) + if version[3] != 'final': + return 'dev' + else: + return '%d.%d' % version[:2] + + +def get_git_changeset(): + """Returns a numeric identifier of the latest git changeset. + The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format. + This value isn't guaranteed to be unique, but collisions are very unlikely, + so it's sufficient for generating the development version numbers. + """ + repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + try: + git_log = subprocess.Popen( + 'git log --pretty=format:%ct --quiet -1 HEAD', + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + shell=True, cwd=repo_dir, universal_newlines=True, + ) + timestamp = git_log.communicate()[0] + timestamp = datetime.datetime.utcfromtimestamp(int(timestamp)) + except: + return None + return timestamp.strftime('%Y%m%d%H%M%S') diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0fbb51d32a90ad8c7f3157f6078d0dc75fff425e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/__pycache__/definition.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/__pycache__/definition.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8db86aece08a37adfc374b320162deda1928958 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/__pycache__/definition.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/__pycache__/directives.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/__pycache__/directives.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..306d724b25d715c0fbb771fed45d0b68f2820b41 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/__pycache__/directives.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/__pycache__/introspection.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/__pycache__/introspection.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c2596e59b74a7e8910b4028266a633b4c67426b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/__pycache__/introspection.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/__pycache__/scalars.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/__pycache__/scalars.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2769a7ba5be9b628b910651000b16a8f70779df Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/__pycache__/scalars.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/__pycache__/schema.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/__pycache__/schema.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..933fafdb17ee70078211937fa989797bf71b176c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/__pycache__/schema.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/__pycache__/typemap.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/__pycache__/typemap.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..957c823b3df34798c4f679e2f7205ee0be5037f8 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/__pycache__/typemap.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/introspection.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/introspection.py new file mode 100644 index 0000000000000000000000000000000000000000..b2732fc82b0888598e82b06b91ecebc2e16980df --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/introspection.py @@ -0,0 +1,440 @@ +from collections import OrderedDict, namedtuple + +from ..language.printer import print_ast +from ..utils.ast_from_value import ast_from_value +from .definition import (GraphQLArgument, GraphQLEnumType, GraphQLEnumValue, + GraphQLField, GraphQLInputObjectType, + GraphQLInterfaceType, GraphQLList, GraphQLNonNull, + GraphQLObjectType, GraphQLScalarType, + GraphQLUnionType) +from .directives import DirectiveLocation +from .scalars import GraphQLBoolean, GraphQLString + +InputField = namedtuple('InputField', ['name', 'description', 'type', 'default_value']) +Field = namedtuple('Field', ['name', 'type', 'description', 'args', 'deprecation_reason']) + + +def input_fields_to_list(input_fields): + fields = [] + for field_name, field in input_fields.items(): + fields.append(InputField( + name=field_name, + description=field.description, + type=field.type, + default_value=field.default_value)) + return fields + + +__Schema = GraphQLObjectType( + '__Schema', + description='A GraphQL Schema defines the capabilities of a GraphQL server. It ' + 'exposes all available types and directives on the server, as well as ' + 'the entry points for query, mutation and subscription operations.', + fields=lambda: OrderedDict([ + ('types', GraphQLField( + description='A list of all types supported by this server.', + type=GraphQLNonNull(GraphQLList(GraphQLNonNull(__Type))), + resolver=lambda schema, *_: schema.get_type_map().values(), + )), + ('queryType', GraphQLField( + description='The type that query operations will be rooted at.', + type=GraphQLNonNull(__Type), + resolver=lambda schema, *_: schema.get_query_type(), + )), + ('mutationType', GraphQLField( + description='If this server supports mutation, the type that ' + 'mutation operations will be rooted at.', + type=__Type, + resolver=lambda schema, *_: schema.get_mutation_type(), + )), + ('subscriptionType', GraphQLField( + description='If this server support subscription, the type ' + 'that subscription operations will be rooted at.', + type=__Type, + resolver=lambda schema, *_: schema.get_subscription_type(), + )), + ('directives', GraphQLField( + description='A list of all directives supported by this server.', + type=GraphQLNonNull(GraphQLList(GraphQLNonNull(__Directive))), + resolver=lambda schema, *_: schema.get_directives(), + )), + ])) + +_on_operation_locations = set(DirectiveLocation.OPERATION_LOCATIONS) +_on_fragment_locations = set(DirectiveLocation.FRAGMENT_LOCATIONS) +_on_field_locations = set(DirectiveLocation.FIELD_LOCATIONS) + +__Directive = GraphQLObjectType( + '__Directive', + description='A Directive provides a way to describe alternate runtime execution and ' + 'type validation behavior in a GraphQL document.' + '\n\nIn some cases, you need to provide options to alter GraphQL\'s ' + 'execution behavior in ways field arguments will not suffice, such as ' + 'conditionally including or skipping a field. Directives provide this by ' + 'describing additional information to the executor.', + fields=lambda: OrderedDict([ + ('name', GraphQLField(GraphQLNonNull(GraphQLString))), + ('description', GraphQLField(GraphQLString)), + ('locations', GraphQLField( + type=GraphQLNonNull(GraphQLList(GraphQLNonNull(__DirectiveLocation))), + )), + ('args', GraphQLField( + type=GraphQLNonNull(GraphQLList(GraphQLNonNull(__InputValue))), + resolver=lambda directive, *args: input_fields_to_list(directive.args), + )), + ('onOperation', GraphQLField( + type=GraphQLNonNull(GraphQLBoolean), + deprecation_reason='Use `locations`.', + resolver=lambda directive, *args: set(directive.locations) & _on_operation_locations, + )), + ('onFragment', GraphQLField( + type=GraphQLNonNull(GraphQLBoolean), + deprecation_reason='Use `locations`.', + resolver=lambda directive, *args: set(directive.locations) & _on_fragment_locations, + )), + ('onField', GraphQLField( + type=GraphQLNonNull(GraphQLBoolean), + deprecation_reason='Use `locations`.', + resolver=lambda directive, *args: set(directive.locations) & _on_field_locations, + )) + ])) + +__DirectiveLocation = GraphQLEnumType( + '__DirectiveLocation', + description=( + 'A Directive can be adjacent to many parts of the GraphQL language, a ' + + '__DirectiveLocation describes one such possible adjacencies.' + ), + values=OrderedDict([ + ('QUERY', GraphQLEnumValue( + DirectiveLocation.QUERY, + description='Location adjacent to a query operation.' + )), + ('MUTATION', GraphQLEnumValue( + DirectiveLocation.MUTATION, + description='Location adjacent to a mutation operation.' + )), + ('SUBSCRIPTION', GraphQLEnumValue( + DirectiveLocation.SUBSCRIPTION, + description='Location adjacent to a subscription operation.' + )), + ('FIELD', GraphQLEnumValue( + DirectiveLocation.FIELD, + description='Location adjacent to a field.' + )), + ('FRAGMENT_DEFINITION', GraphQLEnumValue( + DirectiveLocation.FRAGMENT_DEFINITION, + description='Location adjacent to a fragment definition.' + )), + ('FRAGMENT_SPREAD', GraphQLEnumValue( + DirectiveLocation.FRAGMENT_SPREAD, + description='Location adjacent to a fragment spread.' + )), + ('INLINE_FRAGMENT', GraphQLEnumValue( + DirectiveLocation.INLINE_FRAGMENT, + description='Location adjacent to an inline fragment.' + )), + ('SCHEMA', GraphQLEnumValue( + DirectiveLocation.SCHEMA, + description='Location adjacent to a schema definition.' + )), + ('SCALAR', GraphQLEnumValue( + DirectiveLocation.SCALAR, + description='Location adjacent to a scalar definition.' + )), + ('OBJECT', GraphQLEnumValue( + DirectiveLocation.OBJECT, + description='Location adjacent to an object definition.' + )), + ('FIELD_DEFINITION', GraphQLEnumValue( + DirectiveLocation.FIELD_DEFINITION, + description='Location adjacent to a field definition.' + )), + ('ARGUMENT_DEFINITION', GraphQLEnumValue( + DirectiveLocation.ARGUMENT_DEFINITION, + description='Location adjacent to an argument definition.' + )), + ('INTERFACE', GraphQLEnumValue( + DirectiveLocation.INTERFACE, + description='Location adjacent to an interface definition.' + )), + ('UNION', GraphQLEnumValue( + DirectiveLocation.UNION, + description='Location adjacent to a union definition.' + )), + ('ENUM', GraphQLEnumValue( + DirectiveLocation.ENUM, + description='Location adjacent to an enum definition.' + )), + ('ENUM_VALUE', GraphQLEnumValue( + DirectiveLocation.ENUM_VALUE, + description='Location adjacent to an enum value definition.' + )), + ('INPUT_OBJECT', GraphQLEnumValue( + DirectiveLocation.INPUT_OBJECT, + description='Location adjacent to an input object definition.' + )), + ('INPUT_FIELD_DEFINITION', GraphQLEnumValue( + DirectiveLocation.INPUT_FIELD_DEFINITION, + description='Location adjacent to an input object field definition.' + )), + ])) + + +class TypeKind(object): + SCALAR = 'SCALAR' + OBJECT = 'OBJECT' + INTERFACE = 'INTERFACE' + UNION = 'UNION' + ENUM = 'ENUM' + INPUT_OBJECT = 'INPUT_OBJECT' + LIST = 'LIST' + NON_NULL = 'NON_NULL' + + +class TypeFieldResolvers(object): + _kinds = ( + (GraphQLScalarType, TypeKind.SCALAR), + (GraphQLObjectType, TypeKind.OBJECT), + (GraphQLInterfaceType, TypeKind.INTERFACE), + (GraphQLUnionType, TypeKind.UNION), + (GraphQLEnumType, TypeKind.ENUM), + (GraphQLInputObjectType, TypeKind.INPUT_OBJECT), + (GraphQLList, TypeKind.LIST), + (GraphQLNonNull, TypeKind.NON_NULL), + ) + + @classmethod + def kind(cls, type, *_): + for klass, kind in cls._kinds: + if isinstance(type, klass): + return kind + + raise Exception('Unknown kind of type: {}'.format(type)) + + @staticmethod + def fields(type, args, *_): + if isinstance(type, (GraphQLObjectType, GraphQLInterfaceType)): + fields = [] + include_deprecated = args.get('includeDeprecated') + for field_name, field in type.fields.items(): + if field.deprecation_reason and not include_deprecated: + continue + fields.append(Field( + name=field_name, + description=field.description, + type=field.type, + args=field.args, + deprecation_reason=field.deprecation_reason + )) + return fields + return None + + @staticmethod + def interfaces(type, *_): + if isinstance(type, GraphQLObjectType): + return type.interfaces + + @staticmethod + def possible_types(type, args, context, info): + if isinstance(type, (GraphQLInterfaceType, GraphQLUnionType)): + return info.schema.get_possible_types(type) + + @staticmethod + def enum_values(type, args, *_): + if isinstance(type, GraphQLEnumType): + values = type.values + if not args.get('includeDeprecated'): + values = [v for v in values if not v.deprecation_reason] + + return values + + @staticmethod + def input_fields(type, *_): + if isinstance(type, GraphQLInputObjectType): + return input_fields_to_list(type.fields) + + +__Type = GraphQLObjectType( + '__Type', + description='The fundamental unit of any GraphQL Schema is the type. There are ' + 'many kinds of types in GraphQL as represented by the `__TypeKind` enum.' + '\n\nDepending on the kind of a type, certain fields describe ' + 'information about that type. Scalar types provide no information ' + 'beyond a name and description, while Enum types provide their values. ' + 'Object and Interface types provide the fields they describe. Abstract ' + 'types, Union and Interface, provide the Object types possible ' + 'at runtime. List and NonNull types compose other types.', + fields=lambda: OrderedDict([ + ('kind', GraphQLField( + type=GraphQLNonNull(__TypeKind), + resolver=TypeFieldResolvers.kind + )), + ('name', GraphQLField(GraphQLString)), + ('description', GraphQLField(GraphQLString)), + ('fields', GraphQLField( + type=GraphQLList(GraphQLNonNull(__Field)), + args={ + 'includeDeprecated': GraphQLArgument( + GraphQLBoolean, + default_value=False + ) + }, + resolver=TypeFieldResolvers.fields + )), + ('interfaces', GraphQLField( + type=GraphQLList(GraphQLNonNull(__Type)), + resolver=TypeFieldResolvers.interfaces + )), + ('possibleTypes', GraphQLField( + type=GraphQLList(GraphQLNonNull(__Type)), + resolver=TypeFieldResolvers.possible_types + )), + ('enumValues', GraphQLField( + type=GraphQLList(GraphQLNonNull(__EnumValue)), + args={ + 'includeDeprecated': GraphQLArgument( + GraphQLBoolean, + default_value=False + ) + }, + resolver=TypeFieldResolvers.enum_values + )), + ('inputFields', GraphQLField( + type=GraphQLList(GraphQLNonNull(__InputValue)), + resolver=TypeFieldResolvers.input_fields + )), + ('ofType', GraphQLField( + type=__Type, + resolver=lambda type, *_: getattr(type, 'of_type', None) + )), + ])) + +__Field = GraphQLObjectType( + '__Field', + description='Object and Interface types are described by a list of Fields, each of ' + 'which has a name, potentially a list of arguments, and a return type.', + fields=lambda: OrderedDict([ + ('name', GraphQLField(GraphQLNonNull(GraphQLString))), + ('description', GraphQLField(GraphQLString)), + ('args', GraphQLField( + type=GraphQLNonNull(GraphQLList(GraphQLNonNull(__InputValue))), + resolver=lambda field, *_: input_fields_to_list(field.args) + )), + ('type', GraphQLField(GraphQLNonNull(__Type))), + ('isDeprecated', GraphQLField( + type=GraphQLNonNull(GraphQLBoolean), + resolver=lambda field, *_: bool(field.deprecation_reason) + )), + ('deprecationReason', GraphQLField( + type=GraphQLString, + resolver=lambda field, *_: field.deprecation_reason + )) + ]) +) + +__InputValue = GraphQLObjectType( + '__InputValue', + description='Arguments provided to Fields or Directives and the input fields of an ' + 'InputObject are represented as Input Values which describe their type ' + 'and optionally a default value.', + fields=lambda: OrderedDict([ + ('name', GraphQLField(GraphQLNonNull(GraphQLString))), + ('description', GraphQLField(GraphQLString)), + ('type', GraphQLField(GraphQLNonNull(__Type))), + ('defaultValue', GraphQLField( + type=GraphQLString, + resolver=lambda input_val, *_: + None if input_val.default_value is None + else print_ast(ast_from_value(input_val.default_value, input_val)) + )) + ])) + +__EnumValue = GraphQLObjectType( + '__EnumValue', + description='One possible value for a given Enum. Enum values are unique values, not ' + 'a placeholder for a string or numeric value. However an Enum value is ' + 'returned in a JSON response as a string.', + fields=lambda: OrderedDict([ + ('name', GraphQLField(GraphQLNonNull(GraphQLString))), + ('description', GraphQLField(GraphQLString)), + ('isDeprecated', GraphQLField( + type=GraphQLNonNull(GraphQLBoolean), + resolver=lambda field, *_: bool(field.deprecation_reason) + )), + ('deprecationReason', GraphQLField( + type=GraphQLString, + resolver=lambda enum_value, *_: enum_value.deprecation_reason, + )) + ])) + +__TypeKind = GraphQLEnumType( + '__TypeKind', + description='An enum describing what kind of type a given `__Type` is', + values=OrderedDict([ + ('SCALAR', GraphQLEnumValue( + TypeKind.SCALAR, + description='Indicates this type is a scalar.' + )), + ('OBJECT', GraphQLEnumValue( + TypeKind.OBJECT, + description='Indicates this type is an object. ' + '`fields` and `interfaces` are valid fields.' + )), + ('INTERFACE', GraphQLEnumValue( + TypeKind.INTERFACE, + description='Indicates this type is an interface. ' + '`fields` and `possibleTypes` are valid fields.' + )), + ('UNION', GraphQLEnumValue( + TypeKind.UNION, + description='Indicates this type is a union. ' + '`possibleTypes` is a valid field.' + )), + ('ENUM', GraphQLEnumValue( + TypeKind.ENUM, + description='Indicates this type is an enum. ' + '`enumValues` is a valid field.' + )), + ('INPUT_OBJECT', GraphQLEnumValue( + TypeKind.INPUT_OBJECT, + description='Indicates this type is an input object. ' + '`inputFields` is a valid field.' + )), + ('LIST', GraphQLEnumValue( + TypeKind.LIST, + description='Indicates this type is a list. ' + '`ofType` is a valid field.' + )), + ('NON_NULL', GraphQLEnumValue( + TypeKind.NON_NULL, + description='Indicates this type is a non-null. ' + '`ofType` is a valid field.' + )), + ])) + +IntrospectionSchema = __Schema + +SchemaMetaFieldDef = GraphQLField( + # name='__schema', + type=GraphQLNonNull(__Schema), + description='Access the current type schema of this server.', + resolver=lambda source, args, context, info: info.schema, + args={} +) + +TypeMetaFieldDef = GraphQLField( + type=__Type, + # name='__type', + description='Request the type information of a single type.', + args={'name': GraphQLArgument(GraphQLNonNull(GraphQLString))}, + resolver=lambda source, args, context, info: info.schema.get_type(args['name']) +) + +TypeNameMetaFieldDef = GraphQLField( + type=GraphQLNonNull(GraphQLString), + # name='__typename', + description='The name of the current Object type at runtime.', + resolver=lambda source, args, context, info: info.parent_type.name, + args={} +) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/typemap.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/typemap.py new file mode 100644 index 0000000000000000000000000000000000000000..12733a661371c44ee63f7edaeca9eb27c04c2a80 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/type/typemap.py @@ -0,0 +1,145 @@ +from collections import OrderedDict, defaultdict +from collections.abc import Sequence +from functools import reduce + +from ..utils.type_comparators import is_equal_type, is_type_sub_type_of +from .definition import (GraphQLArgument, GraphQLField, + GraphQLInputObjectField, GraphQLInputObjectType, + GraphQLInterfaceType, GraphQLList, GraphQLNonNull, + GraphQLObjectType, GraphQLUnionType, is_input_type, + is_output_type) + + +class GraphQLTypeMap(OrderedDict): + + def __init__(self, types): + super(GraphQLTypeMap, self).__init__() + self.update(reduce(self.reducer, types, OrderedDict())) + self._possible_type_map = defaultdict(set) + + # Keep track of all implementations by interface name. + self._implementations = {} + for gql_type in self.values(): + if isinstance(gql_type, GraphQLObjectType): + for interface in gql_type.interfaces: + self._implementations.setdefault(interface.name, []).append(gql_type) + + # Enforce correct interface implementations. + for type in self.values(): + if isinstance(type, GraphQLObjectType): + for interface in type.interfaces: + self.assert_object_implements_interface(self, type, interface) + + def get_possible_types(self, abstract_type): + if isinstance(abstract_type, GraphQLUnionType): + return abstract_type.types + assert isinstance(abstract_type, GraphQLInterfaceType) + return self._implementations.get(abstract_type.name, None) + + def is_possible_type(self, abstract_type, possible_type): + possible_types = self.get_possible_types(abstract_type) + assert isinstance(possible_types, Sequence), ( + 'Could not find possible implementing types for ${} in ' + + 'schema. Check that schema.types is defined and is an array of' + + 'all possible types in the schema.' + ).format(abstract_type) + + if not self._possible_type_map[abstract_type.name]: + self._possible_type_map[abstract_type.name].update([p.name for p in possible_types]) + + return possible_type.name in self._possible_type_map[abstract_type.name] + + @classmethod + def reducer(cls, map, type): + if not type: + return map + + if isinstance(type, GraphQLList) or isinstance(type, GraphQLNonNull): + return cls.reducer(map, type.of_type) + + if type.name in map: + assert map[type.name] == type, ( + 'Schema must contain unique named types but contains multiple types named "{}".' + ).format(type.name) + + return map + + map[type.name] = type + + reduced_map = map + + if isinstance(type, (GraphQLUnionType)): + for t in type.types: + reduced_map = cls.reducer(reduced_map, t) + + if isinstance(type, GraphQLObjectType): + for t in type.interfaces: + reduced_map = cls.reducer(reduced_map, t) + + if isinstance(type, (GraphQLObjectType, GraphQLInterfaceType, GraphQLInputObjectType)): + field_map = type.fields + type_is_input = isinstance(type, GraphQLInputObjectType) + for field_name, field in field_map.items(): + if type_is_input: + assert isinstance(field, GraphQLInputObjectField), ( + '{}.{} must be an instance of GraphQLInputObjectField.'.format(type, field_name) + ) + assert is_input_type(field.type), ( + '{}.{} field type must be Input Type but got: {}.'.format(type, field_name, field.type) + ) + else: + assert isinstance(field, (GraphQLField, GraphQLField)), ( + '{}.{} must be an instance of GraphQLField.'.format(type, field_name) + ) + assert is_output_type(field.type), ( + '{}.{} field type must be Output Type but got: {}.'.format(type, field_name, field.type) + ) + for arg_name, arg in field.args.items(): + assert isinstance(arg, (GraphQLArgument, GraphQLArgument)), ( + '{}.{}({}:) argument must be an instance of GraphQLArgument.'.format(type, field_name, arg_name) + ) + assert is_input_type(arg.type), ( + '{}.{}({}:) argument type must be Input Type but got: {}.'.format(type, field_name, arg_name, + arg.type) + ) + reduced_map = cls.reducer(reduced_map, arg.type) + + reduced_map = cls.reducer(reduced_map, getattr(field, 'type', None)) + + return reduced_map + + @classmethod + def assert_object_implements_interface(cls, schema, object, interface): + object_field_map = object.fields + interface_field_map = interface.fields + + for field_name, interface_field in interface_field_map.items(): + object_field = object_field_map.get(field_name) + + assert object_field, '"{}" expects field "{}" but "{}" does not provide it.'.format( + interface, field_name, object + ) + + assert is_type_sub_type_of(schema, object_field.type, interface_field.type), ( + '{}.{} expects type "{}" but {}.{} provides type "{}".' + ).format(interface, field_name, interface_field.type, object, field_name, object_field.type) + + for arg_name, interface_arg in interface_field.args.items(): + object_arg = object_field.args.get(arg_name) + + assert object_arg, ( + '{}.{} expects argument "{}" but {}.{} does not provide it.' + ).format(interface, field_name, arg_name, object, field_name) + + assert is_equal_type(interface_arg.type, object_arg.type), ( + '{}.{}({}:) expects type "{}" but {}.{}({}:) provides type "{}".' + ).format(interface, field_name, arg_name, interface_arg.type, object, field_name, arg_name, object_arg.type) + + for arg_name, object_arg in object_field.args.items(): + interface_arg = interface_field.args.get(arg_name) + if not interface_arg: + assert not isinstance(object_arg.type, GraphQLNonNull), ( + '{}.{}({}:) is of required type ' + '"{}" but is not also provided by the ' + 'interface {}.{}.' + ).format(object, field_name, arg_name, object_arg.type, interface, field_name) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d993be816499fd83f7a864a3303e0df228eb79a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/ast_from_value.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/ast_from_value.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ba3b9b53d835238109dac22f77487f31e8649c6 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/ast_from_value.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/ast_to_dict.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/ast_to_dict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f76bf2aec61ec32cd4b7e3f1ada7bb292f0fa49f Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/ast_to_dict.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/base.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e32f8cc97bdb3f82a358fc7bd65435498746de9e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/base.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/build_ast_schema.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/build_ast_schema.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..064bbf43371c77d1d5739050ddd16aa88d902cd9 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/build_ast_schema.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/build_client_schema.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/build_client_schema.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b9dbc01f9985fed4036718313c526470ba4480b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/build_client_schema.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/concat_ast.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/concat_ast.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07a34fbe1c5037d544c31041f4cb5df3a29cea5e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/concat_ast.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/extend_schema.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/extend_schema.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..088f24f20cc38b4de43632edb03518237959a31d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/extend_schema.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/get_field_def.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/get_field_def.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bccff59c3837308677f321f8b593c5f55d18d33a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/get_field_def.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/get_operation_ast.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/get_operation_ast.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c604df33459cbd4b0c2330690d1774251e00411 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/get_operation_ast.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/introspection_query.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/introspection_query.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8433727a2699d60e744f5e1f46c4d9c4a179105b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/introspection_query.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/is_valid_literal_value.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/is_valid_literal_value.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22ad73aff5e0585512d0bb73eb31efa7f8fc6fa1 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/is_valid_literal_value.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/is_valid_value.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/is_valid_value.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28d23ac84ee88daa6301db705b70354e4e520682 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/is_valid_value.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/quoted_or_list.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/quoted_or_list.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62651cdc60b90f11dd8bd63fe2024fa6ce2636ad Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/quoted_or_list.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/schema_printer.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/schema_printer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3761bb5cbd0be74870fe6030047cdbabe3737803 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/schema_printer.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/type_comparators.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/type_comparators.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4a1acd0404a5050a24a01a98c370c982ddafb4a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/type_comparators.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/type_from_ast.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/type_from_ast.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1cd775c6a22a57acf8ad2f3a87d407e678338c5b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/type_from_ast.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/type_info.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/type_info.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de00644c3cc21816646bd8ee35fde844d3626ee5 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/type_info.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/value_from_ast.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/value_from_ast.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b285436aca0f7ae2f4195c5601c5fd51b7614a7 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/__pycache__/value_from_ast.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/ast_to_dict.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/ast_to_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..a2b5cac5a134902ef98a7caeea8a4cc802f22cc8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/ast_to_dict.py @@ -0,0 +1,24 @@ +from ..language.ast import Node + + +def ast_to_dict(node, include_loc=False): + if isinstance(node, Node): + d = { + 'kind': node.__class__.__name__ + } + if hasattr(node, '_fields'): + for field in node._fields: + d[field] = ast_to_dict(getattr(node, field), include_loc) + + if include_loc and hasattr(node, 'loc') and node.loc: + d['loc'] = { + 'start': node.loc.start, + 'end': node.loc.end + } + + return d + + elif isinstance(node, list): + return [ast_to_dict(item, include_loc) for item in node] + + return node diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/build_client_schema.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/build_client_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..116b77715eef61327bd5856165ab4f9f67e42627 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/build_client_schema.py @@ -0,0 +1,250 @@ +from ..language.parser import parse_value +from ..pyutils.ordereddict import OrderedDict +from ..type import (GraphQLArgument, GraphQLBoolean, GraphQLEnumType, + GraphQLEnumValue, GraphQLField, GraphQLFloat, GraphQLID, + GraphQLInputObjectField, GraphQLInputObjectType, + GraphQLInt, GraphQLInterfaceType, GraphQLList, + GraphQLNonNull, GraphQLObjectType, GraphQLScalarType, + GraphQLSchema, GraphQLString, GraphQLUnionType, + is_input_type, is_output_type) +from ..type.directives import DirectiveLocation, GraphQLDirective +from ..type.introspection import (TypeKind, __Directive, __DirectiveLocation, + __EnumValue, __Field, __InputValue, __Schema, + __Type, __TypeKind) +from .value_from_ast import value_from_ast + + +def _false(*_): + return False + + +def _none(*_): + return None + + +def no_execution(*args): + raise Exception('Client Schema cannot be used for execution.') + + +def build_client_schema(introspection): + schema_introspection = introspection['__schema'] + + type_introspection_map = {t['name']: t for t in schema_introspection['types']} + + type_def_cache = { + 'String': GraphQLString, + 'Int': GraphQLInt, + 'Float': GraphQLFloat, + 'Boolean': GraphQLBoolean, + 'ID': GraphQLID, + '__Schema': __Schema, + '__Directive': __Directive, + '__DirectiveLocation': __DirectiveLocation, + '__Type': __Type, + '__Field': __Field, + '__InputValue': __InputValue, + '__EnumValue': __EnumValue, + '__TypeKind': __TypeKind, + + } + + def get_type(type_ref): + kind = type_ref.get('kind') + + if kind == TypeKind.LIST: + item_ref = type_ref.get('ofType') + + if not item_ref: + raise Exception('Decorated type deeper than introspection query.') + + return GraphQLList(get_type(item_ref)) + + elif kind == TypeKind.NON_NULL: + nullable_ref = type_ref.get('ofType') + if not nullable_ref: + raise Exception('Decorated type deeper than introspection query.') + + return GraphQLNonNull(get_type(nullable_ref)) + + return get_named_type(type_ref['name']) + + def get_named_type(type_name): + if type_name in type_def_cache: + return type_def_cache[type_name] + + type_introspection = type_introspection_map.get(type_name) + if not type_introspection: + raise Exception( + 'Invalid or incomplete schema, unknown type: {}. Ensure that a full introspection query ' + 'is used in order to build a client schema.'.format(type_name) + ) + + type_def = type_def_cache[type_name] = build_type(type_introspection) + return type_def + + def get_input_type(type_ref): + input_type = get_type(type_ref) + assert is_input_type(input_type), 'Introspection must provide input type for arguments.' + return input_type + + def get_output_type(type_ref): + output_type = get_type(type_ref) + assert is_output_type(output_type), 'Introspection must provide output type for fields.' + return output_type + + def get_object_type(type_ref): + object_type = get_type(type_ref) + assert isinstance(object_type, GraphQLObjectType), 'Introspection must provide object type for possibleTypes.' + return object_type + + def get_interface_type(type_ref): + interface_type = get_type(type_ref) + assert isinstance(interface_type, GraphQLInterfaceType), \ + 'Introspection must provide interface type for interfaces.' + return interface_type + + def build_type(type): + type_kind = type.get('kind') + handler = type_builders.get(type_kind) + if not handler: + raise Exception( + 'Invalid or incomplete schema, unknown kind: {}. Ensure that a full introspection query ' + 'is used in order to build a client schema.'.format(type_kind) + ) + + return handler(type) + + def build_scalar_def(scalar_introspection): + return GraphQLScalarType( + name=scalar_introspection['name'], + description=scalar_introspection.get('description'), + serialize=_none, + parse_value=_false, + parse_literal=_false + ) + + def build_object_def(object_introspection): + return GraphQLObjectType( + name=object_introspection['name'], + description=object_introspection.get('description'), + interfaces=[get_interface_type(i) for i in object_introspection.get('interfaces', [])], + fields=lambda: build_field_def_map(object_introspection) + ) + + def build_interface_def(interface_introspection): + return GraphQLInterfaceType( + name=interface_introspection['name'], + description=interface_introspection.get('description'), + fields=lambda: build_field_def_map(interface_introspection), + resolve_type=no_execution + ) + + def build_union_def(union_introspection): + return GraphQLUnionType( + name=union_introspection['name'], + description=union_introspection.get('description'), + types=[get_object_type(t) for t in union_introspection.get('possibleTypes', [])], + resolve_type=no_execution + ) + + def build_enum_def(enum_introspection): + return GraphQLEnumType( + name=enum_introspection['name'], + description=enum_introspection.get('description'), + values=OrderedDict([(value_introspection['name'], + GraphQLEnumValue(description=value_introspection.get('description'), + deprecation_reason=value_introspection.get('deprecationReason'))) + for value_introspection in enum_introspection.get('enumValues', []) + ]) + ) + + def build_input_object_def(input_object_introspection): + return GraphQLInputObjectType( + name=input_object_introspection['name'], + description=input_object_introspection.get('description'), + fields=lambda: build_input_value_def_map( + input_object_introspection.get('inputFields'), GraphQLInputObjectField + ) + ) + + type_builders = { + TypeKind.SCALAR: build_scalar_def, + TypeKind.OBJECT: build_object_def, + TypeKind.INTERFACE: build_interface_def, + TypeKind.UNION: build_union_def, + TypeKind.ENUM: build_enum_def, + TypeKind.INPUT_OBJECT: build_input_object_def + } + + def build_field_def_map(type_introspection): + return OrderedDict([ + (f['name'], GraphQLField( + type=get_output_type(f['type']), + description=f.get('description'), + resolver=no_execution, + deprecation_reason=f.get('deprecationReason'), + args=build_input_value_def_map(f.get('args'), GraphQLArgument))) + for f in type_introspection.get('fields', []) + ]) + + def build_default_value(f): + default_value = f.get('defaultValue') + if default_value is None: + return None + + return value_from_ast(parse_value(default_value), get_input_type(f['type'])) + + def build_input_value_def_map(input_value_introspection, argument_type): + return OrderedDict([ + (f['name'], build_input_value(f, argument_type)) for f in input_value_introspection + ]) + + def build_input_value(input_value_introspection, argument_type): + input_value = argument_type( + description=input_value_introspection['description'], + type=get_input_type(input_value_introspection['type']), + default_value=build_default_value(input_value_introspection) + ) + return input_value + + def build_directive(directive_introspection): + # Support deprecated `on****` fields for building `locations`, as this + # is used by GraphiQL which may need to support outdated servers. + locations = list(directive_introspection.get('locations', [])) + if not locations: + locations = [] + if directive_introspection.get('onField', False): + locations += list(DirectiveLocation.FIELD_LOCATIONS) + if directive_introspection.get('onOperation', False): + locations += list(DirectiveLocation.OPERATION_LOCATIONS) + if directive_introspection.get('onFragment', False): + locations += list(DirectiveLocation.FRAGMENT_LOCATIONS) + + return GraphQLDirective( + name=directive_introspection['name'], + description=directive_introspection.get('description'), + # TODO: {} ? + args=build_input_value_def_map(directive_introspection.get('args', {}), GraphQLArgument), + locations=locations + ) + + # Iterate through all types, getting the type definition for each, ensuring + # that any type not directly referenced by a field will get created. + types = [get_named_type(type_introspection_name) for type_introspection_name in type_introspection_map.keys()] + + query_type = get_object_type(schema_introspection['queryType']) + mutation_type = get_object_type( + schema_introspection['mutationType']) if schema_introspection.get('mutationType') else None + subscription_type = get_object_type(schema_introspection['subscriptionType']) if \ + schema_introspection.get('subscriptionType') else None + + directives = [build_directive(d) for d in schema_introspection['directives']] \ + if schema_introspection['directives'] else [] + + return GraphQLSchema( + query=query_type, + mutation=mutation_type, + subscription=subscription_type, + directives=directives, + types=types + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/extend_schema.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/extend_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..e1bd3451e6e879a6f1cb192e0a9acbf085cf8706 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/extend_schema.py @@ -0,0 +1,357 @@ +from collections import defaultdict + +from ..error import GraphQLError +from ..language import ast +from ..pyutils.ordereddict import OrderedDict +from ..type.definition import (GraphQLArgument, GraphQLEnumType, + GraphQLEnumValue, GraphQLField, + GraphQLInputObjectField, GraphQLInputObjectType, + GraphQLInterfaceType, GraphQLList, + GraphQLNonNull, GraphQLObjectType, + GraphQLScalarType, GraphQLUnionType) +from ..type.introspection import (__Directive, __DirectiveLocation, + __EnumValue, __Field, __InputValue, __Schema, + __Type, __TypeKind) +from ..type.scalars import (GraphQLBoolean, GraphQLFloat, GraphQLID, + GraphQLInt, GraphQLString) +from ..type.schema import GraphQLSchema +from .value_from_ast import value_from_ast + + +def extend_schema(schema, documentAST=None): + """Produces a new schema given an existing schema and a document which may + contain GraphQL type extensions and definitions. The original schema will + remain unaltered. + + Because a schema represents a graph of references, a schema cannot be + extended without effectively making an entire copy. We do not know until it's + too late if subgraphs remain unchanged. + + This algorithm copies the provided schema, applying extensions while + producing the copy. The original schema remains unaltered.""" + + assert isinstance( + schema, GraphQLSchema), 'Must provide valid GraphQLSchema' + assert documentAST and isinstance( + documentAST, ast.Document), 'Must provide valid Document AST' + + # Collect the type definitions and extensions found in the document. + type_definition_map = {} + type_extensions_map = defaultdict(list) + + for _def in documentAST.definitions: + if isinstance(_def, ( + ast.ObjectTypeDefinition, + ast.InterfaceTypeDefinition, + ast.EnumTypeDefinition, + ast.UnionTypeDefinition, + ast.ScalarTypeDefinition, + ast.InputObjectTypeDefinition, + )): + # Sanity check that none of the defined types conflict with the + # schema's existing types. + type_name = _def.name.value + if schema.get_type(type_name): + raise GraphQLError( + ('Type "{}" already exists in the schema. It cannot also ' + + 'be defined in this type definition.').format(type_name), + [_def] + ) + + type_definition_map[type_name] = _def + elif isinstance(_def, ast.TypeExtensionDefinition): + # Sanity check that this type extension exists within the + # schema's existing types. + extended_type_name = _def.definition.name.value + existing_type = schema.get_type(extended_type_name) + if not existing_type: + raise GraphQLError( + ('Cannot extend type "{}" because it does not ' + + 'exist in the existing schema.').format(extended_type_name), + [_def.definition] + ) + if not isinstance(existing_type, GraphQLObjectType): + raise GraphQLError( + 'Cannot extend non-object type "{}".'.format( + extended_type_name), + [_def.definition] + ) + + type_extensions_map[extended_type_name].append(_def) + + # Below are functions used for producing this schema that have closed over + # this scope and have access to the schema, cache, and newly defined types. + + def get_type_from_def(type_def): + type = _get_named_type(type_def.name) + assert type, 'Invalid schema' + return type + + def get_type_from_AST(astNode): + type = _get_named_type(astNode.name.value) + if not type: + raise GraphQLError( + ('Unknown type: "{}". Ensure that this type exists ' + + 'either in the original schema, or is added in a type definition.').format( + astNode.name.value), + [astNode] + ) + return type + + # Given a name, returns a type from either the existing schema or an + # added type. + def _get_named_type(typeName): + cached_type_def = type_def_cache.get(typeName) + if cached_type_def: + return cached_type_def + + existing_type = schema.get_type(typeName) + if existing_type: + type_def = extend_type(existing_type) + type_def_cache[typeName] = type_def + return type_def + + type_ast = type_definition_map.get(typeName) + if type_ast: + type_def = build_type(type_ast) + type_def_cache[typeName] = type_def + return type_def + + # Given a type's introspection result, construct the correct + # GraphQLType instance. + def extend_type(type): + if isinstance(type, GraphQLObjectType): + return extend_object_type(type) + if isinstance(type, GraphQLInterfaceType): + return extend_interface_type(type) + if isinstance(type, GraphQLUnionType): + return extend_union_type(type) + return type + + def extend_object_type(type): + return GraphQLObjectType( + name=type.name, + description=type.description, + interfaces=lambda: extend_implemented_interfaces(type), + fields=lambda: extend_field_map(type), + ) + + def extend_interface_type(type): + return GraphQLInterfaceType( + name=type.name, + description=type.description, + fields=lambda: extend_field_map(type), + resolve_type=cannot_execute_client_schema, + ) + + def extend_union_type(type): + return GraphQLUnionType( + name=type.name, + description=type.description, + types=list(map(get_type_from_def, type.types)), + resolve_type=cannot_execute_client_schema, + ) + + def extend_implemented_interfaces(type): + interfaces = list(map(get_type_from_def, type.interfaces)) + + # If there are any extensions to the interfaces, apply those here. + extensions = type_extensions_map[type.name] + for extension in extensions: + for namedType in extension.definition.interfaces: + interface_name = namedType.name.value + if any([_def.name == interface_name for _def in interfaces]): + raise GraphQLError( + ('Type "{}" already implements "{}". ' + + 'It cannot also be implemented in this type extension.').format( + type.name, interface_name), + [namedType] + ) + interfaces.append(get_type_from_AST(namedType)) + + return interfaces + + def extend_field_map(type): + new_field_map = OrderedDict() + old_field_map = type.fields + for field_name, field in old_field_map.items(): + new_field_map[field_name] = GraphQLField( + extend_field_type(field.type), + description=field.description, + deprecation_reason=field.deprecation_reason, + args=field.args, + resolver=cannot_execute_client_schema, + ) + + # If there are any extensions to the fields, apply those here. + extensions = type_extensions_map[type.name] + for extension in extensions: + for field in extension.definition.fields: + field_name = field.name.value + if field_name in old_field_map: + raise GraphQLError( + ('Field "{}.{}" already exists in the ' + + 'schema. It cannot also be defined in this type extension.').format( + type.name, field_name), + [field] + ) + new_field_map[field_name] = GraphQLField( + build_field_type(field.type), + args=build_input_values(field.arguments), + resolver=cannot_execute_client_schema, + ) + + return new_field_map + + def extend_field_type(type): + if isinstance(type, GraphQLList): + return GraphQLList(extend_field_type(type.of_type)) + if isinstance(type, GraphQLNonNull): + return GraphQLNonNull(extend_field_type(type.of_type)) + return get_type_from_def(type) + + def build_type(type_ast): + _type_build = { + ast.ObjectTypeDefinition: build_object_type, + ast.InterfaceTypeDefinition: build_interface_type, + ast.UnionTypeDefinition: build_union_type, + ast.ScalarTypeDefinition: build_scalar_type, + ast.EnumTypeDefinition: build_enum_type, + ast.InputObjectTypeDefinition: build_input_object_type + } + func = _type_build.get(type(type_ast)) + if func: + return func(type_ast) + + def build_object_type(type_ast): + return GraphQLObjectType( + type_ast.name.value, + interfaces=lambda: build_implemented_interfaces(type_ast), + fields=lambda: build_field_map(type_ast), + ) + + def build_interface_type(type_ast): + return GraphQLInterfaceType( + type_ast.name.value, + fields=lambda: build_field_map(type_ast), + resolve_type=cannot_execute_client_schema, + ) + + def build_union_type(type_ast): + return GraphQLUnionType( + type_ast.name.value, + types=list(map(get_type_from_AST, type_ast.types)), + resolve_type=cannot_execute_client_schema, + ) + + def build_scalar_type(type_ast): + return GraphQLScalarType( + type_ast.name.value, + serialize=lambda *args, **kwargs: None, + # Note: validation calls the parse functions to determine if a + # literal value is correct. Returning null would cause use of custom + # scalars to always fail validation. Returning false causes them to + # always pass validation. + parse_value=lambda *args, **kwargs: False, + parse_literal=lambda *args, **kwargs: False, + ) + + def build_enum_type(type_ast): + return GraphQLEnumType( + type_ast.name.value, + values={v.name.value: GraphQLEnumValue() for v in type_ast.values}, + ) + + def build_input_object_type(type_ast): + return GraphQLInputObjectType( + type_ast.name.value, + fields=lambda: build_input_values( + type_ast.fields, GraphQLInputObjectField), + ) + + def build_implemented_interfaces(type_ast): + return list(map(get_type_from_AST, type_ast.interfaces)) + + def build_field_map(type_ast): + return { + field.name.value: GraphQLField( + build_field_type(field.type), + args=build_input_values(field.arguments), + resolver=cannot_execute_client_schema, + ) for field in type_ast.fields + } + + def build_input_values(values, input_type=GraphQLArgument): + input_values = OrderedDict() + for value in values: + type = build_field_type(value.type) + input_values[value.name.value] = input_type( + type, + default_value=value_from_ast(value.default_value, type) + ) + return input_values + + def build_field_type(type_ast): + if isinstance(type_ast, ast.ListType): + return GraphQLList(build_field_type(type_ast.type)) + if isinstance(type_ast, ast.NonNullType): + return GraphQLNonNull(build_field_type(type_ast.type)) + return get_type_from_AST(type_ast) + + # If this document contains no new types, then return the same unmodified + # GraphQLSchema instance. + if not type_extensions_map and not type_definition_map: + return schema + + # A cache to use to store the actual GraphQLType definition objects by name. + # Initialize to the GraphQL built in scalars and introspection types. All + # functions below are inline so that this type def cache is within the scope + # of the closure. + + type_def_cache = { + 'String': GraphQLString, + 'Int': GraphQLInt, + 'Float': GraphQLFloat, + 'Boolean': GraphQLBoolean, + 'ID': GraphQLID, + '__Schema': __Schema, + '__Directive': __Directive, + '__DirectiveLocation': __DirectiveLocation, + '__Type': __Type, + '__Field': __Field, + '__InputValue': __InputValue, + '__EnumValue': __EnumValue, + '__TypeKind': __TypeKind, + } + + # Get the root Query, Mutation, and Subscription types. + query_type = get_type_from_def(schema.get_query_type()) + + existing_mutation_type = schema.get_mutation_type() + mutationType = existing_mutation_type and get_type_from_def( + existing_mutation_type) or None + + existing_subscription_type = schema.get_subscription_type() + subscription_type = existing_subscription_type and get_type_from_def( + existing_subscription_type) or None + + # Iterate through all types, getting the type definition for each, ensuring + # that any type not directly referenced by a field will get created. + types = [get_type_from_def(_def) for _def in schema.get_type_map().values()] + + # Do the same with new types, appending to the list of defined types. + types += [get_type_from_AST(_def) for _def in type_definition_map.values()] + + # Then produce and return a Schema with these types. + return GraphQLSchema( + query=query_type, + mutation=mutationType, + subscription=subscription_type, + # Copy directives. + directives=schema.get_directives(), + types=types + ) + + +def cannot_execute_client_schema(*args, **kwargs): + raise Exception('Client Schema cannot be used for execution.') diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_from_ast.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_from_ast.py new file mode 100644 index 0000000000000000000000000000000000000000..8689f27adf0527887a1029d6a3730d42568244df --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/utils/type_from_ast.py @@ -0,0 +1,21 @@ +from ..language import ast +from ..type.definition import GraphQLList, GraphQLNonNull + + +def type_from_ast(schema, input_type_ast): + if isinstance(input_type_ast, ast.ListType): + inner_type = type_from_ast(schema, input_type_ast.type) + if inner_type: + return GraphQLList(inner_type) + else: + return None + + if isinstance(input_type_ast, ast.NonNullType): + inner_type = type_from_ast(schema, input_type_ast.type) + if inner_type: + return GraphQLNonNull(inner_type) + else: + return None + + assert isinstance(input_type_ast, ast.NamedType), 'Must be a type name.' + return schema.get_type(input_type_ast.name.value) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..893af3e790576776013bbd60f9db943d5d4094ba --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/__init__.py @@ -0,0 +1,4 @@ +from .validation import validate +from .rules import specified_rules + +__all__ = ['validate', 'specified_rules'] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b1ebd7d6ad8d9e7e49eaa2232d3050f087e923b9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__init__.py @@ -0,0 +1,79 @@ +from .arguments_of_correct_type import ArgumentsOfCorrectType +from .default_values_of_correct_type import DefaultValuesOfCorrectType +from .fields_on_correct_type import FieldsOnCorrectType +from .fragments_on_composite_types import FragmentsOnCompositeTypes +from .known_argument_names import KnownArgumentNames +from .known_directives import KnownDirectives +from .known_fragment_names import KnownFragmentNames +from .known_type_names import KnownTypeNames +from .lone_anonymous_operation import LoneAnonymousOperation +from .no_fragment_cycles import NoFragmentCycles +from .no_undefined_variables import NoUndefinedVariables +from .no_unused_fragments import NoUnusedFragments +from .no_unused_variables import NoUnusedVariables +from .overlapping_fields_can_be_merged import OverlappingFieldsCanBeMerged +from .possible_fragment_spreads import PossibleFragmentSpreads +from .provided_non_null_arguments import ProvidedNonNullArguments +from .scalar_leafs import ScalarLeafs +from .unique_argument_names import UniqueArgumentNames +from .unique_fragment_names import UniqueFragmentNames +from .unique_input_field_names import UniqueInputFieldNames +from .unique_operation_names import UniqueOperationNames +from .unique_variable_names import UniqueVariableNames +from .variables_are_input_types import VariablesAreInputTypes +from .variables_in_allowed_position import VariablesInAllowedPosition + +specified_rules = [ + UniqueOperationNames, + LoneAnonymousOperation, + KnownTypeNames, + FragmentsOnCompositeTypes, + VariablesAreInputTypes, + ScalarLeafs, + FieldsOnCorrectType, + UniqueFragmentNames, + KnownFragmentNames, + NoUnusedFragments, + PossibleFragmentSpreads, + NoFragmentCycles, + NoUndefinedVariables, + NoUnusedVariables, + KnownDirectives, + KnownArgumentNames, + UniqueArgumentNames, + ArgumentsOfCorrectType, + ProvidedNonNullArguments, + DefaultValuesOfCorrectType, + VariablesInAllowedPosition, + OverlappingFieldsCanBeMerged, + UniqueInputFieldNames, + UniqueVariableNames +] + +__all__ = [ + 'ArgumentsOfCorrectType', + 'DefaultValuesOfCorrectType', + 'FieldsOnCorrectType', + 'FragmentsOnCompositeTypes', + 'KnownArgumentNames', + 'KnownDirectives', + 'KnownFragmentNames', + 'KnownTypeNames', + 'LoneAnonymousOperation', + 'NoFragmentCycles', + 'UniqueVariableNames', + 'NoUndefinedVariables', + 'NoUnusedFragments', + 'NoUnusedVariables', + 'OverlappingFieldsCanBeMerged', + 'PossibleFragmentSpreads', + 'ProvidedNonNullArguments', + 'ScalarLeafs', + 'UniqueArgumentNames', + 'UniqueFragmentNames', + 'UniqueInputFieldNames', + 'UniqueOperationNames', + 'VariablesAreInputTypes', + 'VariablesInAllowedPosition', + 'specified_rules' +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc5cd0f3046f8b296a8dcb94c1c7bb1095ede758 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/arguments_of_correct_type.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/arguments_of_correct_type.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..46fb0886c76a49da9d0ad30fec87fe8e2ba9558c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/arguments_of_correct_type.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/base.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f10aa779cf8e1ad9e385fa66642081c9018bc70 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/base.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/default_values_of_correct_type.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/default_values_of_correct_type.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91c21a7fbba5400be47406f4e6977847e34e5f0d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/default_values_of_correct_type.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/fragments_on_composite_types.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/fragments_on_composite_types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2eb328c9eb11107caa9e61dfe9e0bbbc22d9e8f0 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/fragments_on_composite_types.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/known_argument_names.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/known_argument_names.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79d56f2827952e76b9deb05f752c08c87ea2b9c0 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/known_argument_names.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/known_directives.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/known_directives.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..915c3aa54b65b2879ee45b64cb389e43d79d9df4 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/known_directives.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/known_fragment_names.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/known_fragment_names.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6060b32bd963a91e84d105ff3c950b96d46d1c29 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/known_fragment_names.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/lone_anonymous_operation.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/lone_anonymous_operation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9b49d84692411c66f7e37cf24da5d5e4e1db486 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/lone_anonymous_operation.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/no_undefined_variables.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/no_undefined_variables.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab23fdb2a0caee453d04ec6c6e434bdd2bac2133 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/no_undefined_variables.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/no_unused_variables.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/no_unused_variables.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22b33cb0db7bfe506af606287e1be3159f127a46 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/no_unused_variables.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/overlapping_fields_can_be_merged.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/overlapping_fields_can_be_merged.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ff0d66a1fbd469881ab411283bf099de95558da Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/overlapping_fields_can_be_merged.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/possible_fragment_spreads.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/possible_fragment_spreads.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aec84f30a280eef33c48102470c167237cf05e23 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/possible_fragment_spreads.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/provided_non_null_arguments.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/provided_non_null_arguments.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6eb44c95994bc578d118bb52a2ed8d346ba6ccf2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/provided_non_null_arguments.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/scalar_leafs.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/scalar_leafs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b5b18fbfe1862a4784909c734c5123f09512024 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/scalar_leafs.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/unique_argument_names.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/unique_argument_names.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30fcf0b6f8ed1c0c4805ca6ac29320125cf35e65 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/unique_argument_names.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/unique_fragment_names.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/unique_fragment_names.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4bafb4f0e7ad026f2aeba688160540f51bafcef Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/unique_fragment_names.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/unique_operation_names.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/unique_operation_names.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d52573b56874cbd2705fe271027cfa0e8dd4969 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/unique_operation_names.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/unique_variable_names.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/unique_variable_names.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b056fc4ff26741c77452c9d4fc9e702413a02e9 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/unique_variable_names.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/variables_are_input_types.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/variables_are_input_types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1463bb5c41fb39147b5105af3fc62bfbcb565bfc Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/variables_are_input_types.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/variables_in_allowed_position.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/variables_in_allowed_position.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9df314a79e2697703ae5e41749e04709e4601952 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/__pycache__/variables_in_allowed_position.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/arguments_of_correct_type.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/arguments_of_correct_type.py new file mode 100644 index 0000000000000000000000000000000000000000..011fae79b59d229c156afa812c78d427879a99d6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/arguments_of_correct_type.py @@ -0,0 +1,24 @@ +from ...error import GraphQLError +from ...language.printer import print_ast +from ...utils.is_valid_literal_value import is_valid_literal_value +from .base import ValidationRule + + +class ArgumentsOfCorrectType(ValidationRule): + + def enter_Argument(self, node, key, parent, path, ancestors): + arg_def = self.context.get_argument() + if arg_def: + errors = is_valid_literal_value(arg_def.type, node.value) + if errors: + self.context.report_error(GraphQLError( + self.bad_value_message(node.name.value, arg_def.type, + print_ast(node.value), errors), + [node.value] + )) + return False + + @staticmethod + def bad_value_message(arg_name, type, value, verbose_errors): + message = (u'\n' + u'\n'.join(verbose_errors)) if verbose_errors else '' + return 'Argument "{}" has invalid value {}.{}'.format(arg_name, value, message) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/base.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/base.py new file mode 100644 index 0000000000000000000000000000000000000000..43bb53b7493ad3711fb0d7d99e195e200cfa51c6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/base.py @@ -0,0 +1,8 @@ +from ...language.visitor import Visitor + + +class ValidationRule(Visitor): + __slots__ = 'context', + + def __init__(self, context): + self.context = context diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/default_values_of_correct_type.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/default_values_of_correct_type.py new file mode 100644 index 0000000000000000000000000000000000000000..ad6346b46573289f43040425938cb327007e2393 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/default_values_of_correct_type.py @@ -0,0 +1,44 @@ +from ...error import GraphQLError +from ...language.printer import print_ast +from ...type.definition import GraphQLNonNull +from ...utils.is_valid_literal_value import is_valid_literal_value +from .base import ValidationRule + + +class DefaultValuesOfCorrectType(ValidationRule): + + def enter_VariableDefinition(self, node, key, parent, path, ancestors): + name = node.variable.name.value + default_value = node.default_value + type = self.context.get_input_type() + + if isinstance(type, GraphQLNonNull) and default_value: + self.context.report_error(GraphQLError( + self.default_for_non_null_arg_message(name, type, type.of_type), + [default_value] + )) + + if type and default_value: + errors = is_valid_literal_value(type, default_value) + if errors: + self.context.report_error(GraphQLError( + self.bad_value_for_default_arg_message(name, type, print_ast(default_value), errors), + [default_value] + )) + return False + + def enter_SelectionSet(self, node, key, parent, path, ancestors): + return False + + def enter_FragmentDefinition(self, node, key, parent, path, ancestors): + return False + + @staticmethod + def default_for_non_null_arg_message(var_name, type, guess_type): + return u'Variable "${}" of type "{}" is required and will not use the default value. ' \ + u'Perhaps you meant to use type "{}".'.format(var_name, type, guess_type) + + @staticmethod + def bad_value_for_default_arg_message(var_name, type, value, verbose_errors): + message = (u'\n' + u'\n'.join(verbose_errors)) if verbose_errors else u'' + return u'Variable "${}" of type "{}" has invalid default value: {}.{}'.format(var_name, type, value, message) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/fields_on_correct_type.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/fields_on_correct_type.py new file mode 100644 index 0000000000000000000000000000000000000000..55bb2221c9e4df059215227dcecacf9ec884e6e4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/fields_on_correct_type.py @@ -0,0 +1,113 @@ +from collections import Counter + +from ...error import GraphQLError +from ...pyutils.ordereddict import OrderedDict +from ...type.definition import (GraphQLInterfaceType, GraphQLObjectType, + GraphQLUnionType) +from ...utils.quoted_or_list import quoted_or_list +from ...utils.suggestion_list import suggestion_list +from .base import ValidationRule + +try: + # Python 2 + from itertools import izip +except ImportError: + # Python 3 + izip = zip + + +def _undefined_field_message(field_name, type, suggested_types, + suggested_fields): + message = 'Cannot query field "{}" on type "{}".'.format(field_name, type) + + if suggested_types: + suggestions = quoted_or_list(suggested_types) + message += " Did you mean to use an inline fragment on {}?".format(suggestions) + elif suggested_fields: + suggestions = quoted_or_list(suggested_fields) + message += " Did you mean {}?".format(suggestions) + + return message + + +class OrderedCounter(Counter, OrderedDict): + pass + + +class FieldsOnCorrectType(ValidationRule): + '''Fields on correct type + + A GraphQL document is only valid if all fields selected are defined by the + parent type, or are an allowed meta field such as __typenamme + ''' + + def enter_Field(self, node, key, parent, path, ancestors): + parent_type = self.context.get_parent_type() + if not parent_type: + return + + field_def = self.context.get_field_def() + if not field_def: + # This field doesn't exist, lets look for suggestions. + schema = self.context.get_schema() + field_name = node.name.value + + # First determine if there are any suggested types to condition on. + suggested_type_names = get_suggested_type_names(schema, parent_type, field_name) + # if there are no suggested types perhaps it was a typo? + suggested_field_names = [] if suggested_type_names else get_suggested_field_names(schema, parent_type, field_name) + + # report an error including helpful suggestions. + self.context.report_error(GraphQLError( + _undefined_field_message(field_name, parent_type.name, suggested_type_names, suggested_field_names), + [node] + )) + + +def get_suggested_type_names(schema, output_type, field_name): + '''Go through all of the implementations of type, as well as the interfaces + that they implement. If any of those types include the provided field, + suggest them, sorted by how often the type is referenced, starting + with Interfaces.''' + + if isinstance(output_type, (GraphQLInterfaceType, GraphQLUnionType)): + suggested_object_types = [] + interface_usage_count = OrderedDict() + for possible_type in schema.get_possible_types(output_type): + if not possible_type.fields.get(field_name): + return + + # This object type defines this field. + suggested_object_types.append(possible_type.name) + + for possible_interface in possible_type.interfaces: + if not possible_interface.fields.get(field_name): + continue + + # This interface type defines this field. + interface_usage_count[possible_interface.name] = ( + interface_usage_count.get(possible_interface.name, 0) + 1) + + # Suggest interface types based on how common they are. + suggested_interface_types = sorted(list(interface_usage_count.keys()), key=lambda k: interface_usage_count[k], + reverse=True) + + # Suggest both interface and object types. + suggested_interface_types.extend(suggested_object_types) + return suggested_interface_types + + # Otherwise, must be an Object type, which does not have possible fields. + return [] + + +def get_suggested_field_names(schema, graphql_type, field_name): + '''For the field name provided, determine if there are any similar field names + that may be the result of a typo.''' + + if isinstance(graphql_type, (GraphQLInterfaceType, GraphQLObjectType)): + possible_field_names = list(graphql_type.fields.keys()) + + return suggestion_list(field_name, possible_field_names) + + # Otherwise, must be a Union type, which does not define fields. + return [] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/fragments_on_composite_types.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/fragments_on_composite_types.py new file mode 100644 index 0000000000000000000000000000000000000000..a95e247c08fa14846786520ad9a4720bce0dba32 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/fragments_on_composite_types.py @@ -0,0 +1,33 @@ +from ...error import GraphQLError +from ...language.printer import print_ast +from ...type.definition import is_composite_type +from .base import ValidationRule + + +class FragmentsOnCompositeTypes(ValidationRule): + + def enter_InlineFragment(self, node, key, parent, path, ancestors): + type = self.context.get_type() + + if node.type_condition and type and not is_composite_type(type): + self.context.report_error(GraphQLError( + self.inline_fragment_on_non_composite_error_message(print_ast(node.type_condition)), + [node.type_condition] + )) + + def enter_FragmentDefinition(self, node, key, parent, path, ancestors): + type = self.context.get_type() + + if type and not is_composite_type(type): + self.context.report_error(GraphQLError( + self.fragment_on_non_composite_error_message(node.name.value, print_ast(node.type_condition)), + [node.type_condition] + )) + + @staticmethod + def inline_fragment_on_non_composite_error_message(type): + return 'Fragment cannot condition on non composite type "{}".'.format(type) + + @staticmethod + def fragment_on_non_composite_error_message(frag_name, type): + return 'Fragment "{}" cannot condition on non composite type "{}".'.format(frag_name, type) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_argument_names.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_argument_names.py new file mode 100644 index 0000000000000000000000000000000000000000..2b5860397ec2c58d9f45fee3e3eebdc0358fad80 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_argument_names.py @@ -0,0 +1,70 @@ +from ...error import GraphQLError +from ...language import ast +from ...utils.quoted_or_list import quoted_or_list +from ...utils.suggestion_list import suggestion_list +from .base import ValidationRule + + +def _unknown_arg_message(arg_name, field_name, type, suggested_args): + message = 'Unknown argument "{}" on field "{}" of type "{}".'.format(arg_name, field_name, type) + if suggested_args: + message += ' Did you mean {}?'.format(quoted_or_list(suggested_args)) + + return message + + +def _unknown_directive_arg_message(arg_name, directive_name, suggested_args): + message = 'Unknown argument "{}" on directive "@{}".'.format(arg_name, directive_name) + if suggested_args: + message += ' Did you mean {}?'.format(quoted_or_list(suggested_args)) + + return message + + +class KnownArgumentNames(ValidationRule): + + def enter_Argument(self, node, key, parent, path, ancestors): + argument_of = ancestors[-1] + + if isinstance(argument_of, ast.Field): + field_def = self.context.get_field_def() + if not field_def: + return + + field_arg_def = field_def.args.get(node.name.value) + + if not field_arg_def: + parent_type = self.context.get_parent_type() + assert parent_type + self.context.report_error(GraphQLError( + _unknown_arg_message( + node.name.value, + argument_of.name.value, + parent_type.name, + suggestion_list( + node.name.value, + (arg_name for arg_name in field_def.args.keys()) + ) + ), + [node] + )) + + elif isinstance(argument_of, ast.Directive): + directive = self.context.get_directive() + if not directive: + return + + directive_arg_def = directive.args.get(node.name.value) + + if not directive_arg_def: + self.context.report_error(GraphQLError( + _unknown_directive_arg_message( + node.name.value, + directive.name, + suggestion_list( + node.name.value, + (arg_name for arg_name in directive.args.keys()) + ) + ), + [node] + )) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_directives.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_directives.py new file mode 100644 index 0000000000000000000000000000000000000000..f672105df350babee2dd9b03fb11b5609dded655 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_directives.py @@ -0,0 +1,97 @@ +from ...error import GraphQLError +from ...language import ast +from ...type.directives import DirectiveLocation +from .base import ValidationRule + + +class KnownDirectives(ValidationRule): + + def enter_Directive(self, node, key, parent, path, ancestors): + directive_def = next(( + definition for definition in self.context.get_schema().get_directives() + if definition.name == node.name.value + ), None) + + if not directive_def: + return self.context.report_error(GraphQLError( + self.unknown_directive_message(node.name.value), + [node] + )) + + candidate_location = get_directive_location_for_ast_path(ancestors) + if not candidate_location: + self.context.report_error(GraphQLError( + self.misplaced_directive_message(node.name.value, node.type), + [node] + )) + elif candidate_location not in directive_def.locations: + self.context.report_error(GraphQLError( + self.misplaced_directive_message(node.name.value, candidate_location), + [node] + )) + + @staticmethod + def unknown_directive_message(directive_name): + return 'Unknown directive "{}".'.format(directive_name) + + @staticmethod + def misplaced_directive_message(directive_name, location): + return 'Directive "{}" may not be used on "{}".'.format(directive_name, location) + + +_operation_definition_map = { + 'query': DirectiveLocation.QUERY, + 'mutation': DirectiveLocation.MUTATION, + 'subscription': DirectiveLocation.SUBSCRIPTION, +} + + +def get_directive_location_for_ast_path(ancestors): + applied_to = ancestors[-1] + if isinstance(applied_to, ast.OperationDefinition): + return _operation_definition_map.get(applied_to.operation) + + elif isinstance(applied_to, ast.Field): + return DirectiveLocation.FIELD + + elif isinstance(applied_to, ast.FragmentSpread): + return DirectiveLocation.FRAGMENT_SPREAD + + elif isinstance(applied_to, ast.InlineFragment): + return DirectiveLocation.INLINE_FRAGMENT + + elif isinstance(applied_to, ast.FragmentDefinition): + return DirectiveLocation.FRAGMENT_DEFINITION + + elif isinstance(applied_to, ast.SchemaDefinition): + return DirectiveLocation.SCHEMA + + elif isinstance(applied_to, ast.ScalarTypeDefinition): + return DirectiveLocation.SCALAR + + elif isinstance(applied_to, ast.ObjectTypeDefinition): + return DirectiveLocation.OBJECT + + elif isinstance(applied_to, ast.FieldDefinition): + return DirectiveLocation.FIELD_DEFINITION + + elif isinstance(applied_to, ast.InterfaceTypeDefinition): + return DirectiveLocation.INTERFACE + + elif isinstance(applied_to, ast.UnionTypeDefinition): + return DirectiveLocation.UNION + + elif isinstance(applied_to, ast.EnumTypeDefinition): + return DirectiveLocation.ENUM + + elif isinstance(applied_to, ast.EnumValueDefinition): + return DirectiveLocation.ENUM_VALUE + + elif isinstance(applied_to, ast.InputObjectTypeDefinition): + return DirectiveLocation.INPUT_OBJECT + + elif isinstance(applied_to, ast.InputValueDefinition): + parent_node = ancestors[-3] + return (DirectiveLocation.INPUT_FIELD_DEFINITION + if isinstance(parent_node, ast.InputObjectTypeDefinition) + else DirectiveLocation.ARGUMENT_DEFINITION) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_fragment_names.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_fragment_names.py new file mode 100644 index 0000000000000000000000000000000000000000..6c7375e3c4c9d8b083b3873643114bbf7a8625b3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_fragment_names.py @@ -0,0 +1,19 @@ +from ...error import GraphQLError +from .base import ValidationRule + + +class KnownFragmentNames(ValidationRule): + + def enter_FragmentSpread(self, node, key, parent, path, ancestors): + fragment_name = node.name.value + fragment = self.context.get_fragment(fragment_name) + + if not fragment: + self.context.report_error(GraphQLError( + self.unknown_fragment_message(fragment_name), + [node.name] + )) + + @staticmethod + def unknown_fragment_message(fragment_name): + return 'Unknown fragment "{}".'.format(fragment_name) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_type_names.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_type_names.py new file mode 100644 index 0000000000000000000000000000000000000000..d7d1369933238e797f3efced67c7a38c5dbea689 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_type_names.py @@ -0,0 +1,43 @@ +from ...error import GraphQLError +from ...utils.quoted_or_list import quoted_or_list +from ...utils.suggestion_list import suggestion_list +from .base import ValidationRule + + +def _unknown_type_message(type, suggested_types): + message = 'Unknown type "{}".'.format(type) + if suggested_types: + message += ' Perhaps you meant {}?'.format(quoted_or_list(suggested_types)) + + return message + + +class KnownTypeNames(ValidationRule): + + def enter_ObjectTypeDefinition(self, node, *args): + return False + + def enter_InterfaceTypeDefinition(self, node, *args): + return False + + def enter_UnionTypeDefinition(self, node, *args): + return False + + def enter_InputObjectTypeDefinition(self, node, *args): + return False + + def enter_NamedType(self, node, *args): + schema = self.context.get_schema() + type_name = node.name.value + type = schema.get_type(type_name) + + if not type: + self.context.report_error( + GraphQLError( + _unknown_type_message( + type_name, + suggestion_list(type_name, list(schema.get_type_map().keys())) + ), + [node] + ) + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/lone_anonymous_operation.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/lone_anonymous_operation.py new file mode 100644 index 0000000000000000000000000000000000000000..462a67f31174753baac5b421a0142c0c12c04e08 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/lone_anonymous_operation.py @@ -0,0 +1,23 @@ +from ...error import GraphQLError +from ...language import ast +from .base import ValidationRule + + +class LoneAnonymousOperation(ValidationRule): + __slots__ = 'operation_count', + + def __init__(self, context): + self.operation_count = 0 + super(LoneAnonymousOperation, self).__init__(context) + + def enter_Document(self, node, key, parent, path, ancestors): + self.operation_count = \ + sum(1 for definition in node.definitions if isinstance(definition, ast.OperationDefinition)) + + def enter_OperationDefinition(self, node, key, parent, path, ancestors): + if not node.name and self.operation_count > 1: + self.context.report_error(GraphQLError(self.anonymous_operation_not_alone_message(), [node])) + + @staticmethod + def anonymous_operation_not_alone_message(): + return 'This anonymous operation must be the only defined operation.' diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_fragment_cycles.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_fragment_cycles.py new file mode 100644 index 0000000000000000000000000000000000000000..d2e0d79f0e4bc0130180a44ab40fa6102f8d68b3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_fragment_cycles.py @@ -0,0 +1,59 @@ +from ...error import GraphQLError +from .base import ValidationRule + + +class NoFragmentCycles(ValidationRule): + __slots__ = 'errors', 'visited_frags', 'spread_path', 'spread_path_index_by_name' + + def __init__(self, context): + super(NoFragmentCycles, self).__init__(context) + self.errors = [] + self.visited_frags = set() + self.spread_path = [] + self.spread_path_index_by_name = {} + + def enter_OperationDefinition(self, node, key, parent, path, ancestors): + return False + + def enter_FragmentDefinition(self, node, key, parent, path, ancestors): + if node.name.value not in self.visited_frags: + self.detect_cycle_recursive(node) + return False + + def detect_cycle_recursive(self, fragment): + fragment_name = fragment.name.value + self.visited_frags.add(fragment_name) + + spread_nodes = self.context.get_fragment_spreads(fragment.selection_set) + if not spread_nodes: + return + + self.spread_path_index_by_name[fragment_name] = len(self.spread_path) + + for spread_node in spread_nodes: + spread_name = spread_node.name.value + cycle_index = self.spread_path_index_by_name.get(spread_name) + + if cycle_index is None: + self.spread_path.append(spread_node) + if spread_name not in self.visited_frags: + spread_fragment = self.context.get_fragment(spread_name) + if spread_fragment: + self.detect_cycle_recursive(spread_fragment) + self.spread_path.pop() + else: + cycle_path = self.spread_path[cycle_index:] + self.context.report_error(GraphQLError( + self.cycle_error_message( + spread_name, + [s.name.value for s in cycle_path] + ), + cycle_path + [spread_node] + )) + + self.spread_path_index_by_name[fragment_name] = None + + @staticmethod + def cycle_error_message(fragment_name, spread_names): + via = ' via {}'.format(', '.join(spread_names)) if spread_names else '' + return 'Cannot spread fragment "{}" within itself{}.'.format(fragment_name, via) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_unused_fragments.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_unused_fragments.py new file mode 100644 index 0000000000000000000000000000000000000000..8d35f483612600227fa158ceb39eebd7eb8cdd6f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_unused_fragments.py @@ -0,0 +1,38 @@ +from ...error import GraphQLError +from .base import ValidationRule + + +class NoUnusedFragments(ValidationRule): + __slots__ = 'fragment_definitions', 'operation_definitions', 'fragment_adjacencies', 'spread_names' + + def __init__(self, context): + super(NoUnusedFragments, self).__init__(context) + self.operation_definitions = [] + self.fragment_definitions = [] + + def enter_OperationDefinition(self, node, key, parent, path, ancestors): + self.operation_definitions.append(node) + return False + + def enter_FragmentDefinition(self, node, key, parent, path, ancestors): + self.fragment_definitions.append(node) + return False + + def leave_Document(self, node, key, parent, path, ancestors): + fragment_names_used = set() + + for operation in self.operation_definitions: + fragments = self.context.get_recursively_referenced_fragments(operation) + for fragment in fragments: + fragment_names_used.add(fragment.name.value) + + for fragment_definition in self.fragment_definitions: + if fragment_definition.name.value not in fragment_names_used: + self.context.report_error(GraphQLError( + self.unused_fragment_message(fragment_definition.name.value), + [fragment_definition] + )) + + @staticmethod + def unused_fragment_message(fragment_name): + return 'Fragment "{}" is never used.'.format(fragment_name) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_unused_variables.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_unused_variables.py new file mode 100644 index 0000000000000000000000000000000000000000..a799e826472214019ab8b9037954165f4a299749 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/no_unused_variables.py @@ -0,0 +1,37 @@ +from ...error import GraphQLError +from .base import ValidationRule + + +class NoUnusedVariables(ValidationRule): + __slots__ = 'variable_definitions' + + def __init__(self, context): + self.variable_definitions = [] + super(NoUnusedVariables, self).__init__(context) + + def enter_OperationDefinition(self, node, key, parent, path, ancestors): + self.variable_definitions = [] + + def leave_OperationDefinition(self, operation, key, parent, path, ancestors): + variable_name_used = set() + usages = self.context.get_recursive_variable_usages(operation) + op_name = operation.name and operation.name.value or None + + for variable_usage in usages: + variable_name_used.add(variable_usage.node.name.value) + + for variable_definition in self.variable_definitions: + if variable_definition.variable.name.value not in variable_name_used: + self.context.report_error(GraphQLError( + self.unused_variable_message(variable_definition.variable.name.value, op_name), + [variable_definition] + )) + + def enter_VariableDefinition(self, node, key, parent, path, ancestors): + self.variable_definitions.append(node) + + @staticmethod + def unused_variable_message(variable_name, op_name): + if op_name: + return 'Variable "${}" is never used in operation "{}".'.format(variable_name, op_name) + return 'Variable "${}" is never used.'.format(variable_name) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/possible_fragment_spreads.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/possible_fragment_spreads.py new file mode 100644 index 0000000000000000000000000000000000000000..b9cc4165867f59e042cd6233340dfa40a568a568 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/possible_fragment_spreads.py @@ -0,0 +1,44 @@ +from ...error import GraphQLError +from ...utils.type_comparators import do_types_overlap +from ...utils.type_from_ast import type_from_ast +from .base import ValidationRule + + +class PossibleFragmentSpreads(ValidationRule): + + def enter_InlineFragment(self, node, key, parent, path, ancestors): + frag_type = self.context.get_type() + parent_type = self.context.get_parent_type() + schema = self.context.get_schema() + if frag_type and parent_type and not do_types_overlap(schema, frag_type, parent_type): + self.context.report_error(GraphQLError( + self.type_incompatible_anon_spread_message(parent_type, frag_type), + [node] + )) + + def enter_FragmentSpread(self, node, key, parent, path, ancestors): + frag_name = node.name.value + frag_type = self.get_fragment_type(self.context, frag_name) + parent_type = self.context.get_parent_type() + schema = self.context.get_schema() + if frag_type and parent_type and not do_types_overlap(schema, frag_type, parent_type): + self.context.report_error(GraphQLError( + self.type_incompatible_spread_message(frag_name, parent_type, frag_type), + [node] + )) + + @staticmethod + def get_fragment_type(context, name): + frag = context.get_fragment(name) + return frag and type_from_ast(context.get_schema(), frag.type_condition) + + @staticmethod + def type_incompatible_spread_message(frag_name, parent_type, frag_type): + return 'Fragment {} cannot be spread here as objects of type {} can never be of type {}'.format(frag_name, + parent_type, + frag_type) + + @staticmethod + def type_incompatible_anon_spread_message(parent_type, frag_type): + return 'Fragment cannot be spread here as objects of type {} can never be of type {}'.format(parent_type, + frag_type) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/provided_non_null_arguments.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/provided_non_null_arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..09507277d922740bbc2d16b8e1dbc6401b31fc4b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/provided_non_null_arguments.py @@ -0,0 +1,46 @@ +from ...error import GraphQLError +from ...type.definition import GraphQLNonNull +from .base import ValidationRule + + +class ProvidedNonNullArguments(ValidationRule): + + def leave_Field(self, node, key, parent, path, ancestors): + field_def = self.context.get_field_def() + if not field_def: + return False + + arg_asts = node.arguments or [] + arg_ast_map = {arg.name.value: arg for arg in arg_asts} + + for arg_name, arg_def in field_def.args.items(): + arg_ast = arg_ast_map.get(arg_name, None) + if not arg_ast and isinstance(arg_def.type, GraphQLNonNull): + self.context.report_error(GraphQLError( + self.missing_field_arg_message(node.name.value, arg_name, arg_def.type), + [node] + )) + + def leave_Directive(self, node, key, parent, path, ancestors): + directive_def = self.context.get_directive() + if not directive_def: + return False + + arg_asts = node.arguments or [] + arg_ast_map = {arg.name.value: arg for arg in arg_asts} + + for arg_name, arg_def in directive_def.args.items(): + arg_ast = arg_ast_map.get(arg_name, None) + if not arg_ast and isinstance(arg_def.type, GraphQLNonNull): + self.context.report_error(GraphQLError( + self.missing_directive_arg_message(node.name.value, arg_name, arg_def.type), + [node] + )) + + @staticmethod + def missing_field_arg_message(name, arg_name, type): + return 'Field "{}" argument "{}" of type "{}" is required but not provided.'.format(name, arg_name, type) + + @staticmethod + def missing_directive_arg_message(name, arg_name, type): + return 'Directive "{}" argument "{}" of type "{}" is required but not provided.'.format(name, arg_name, type) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/scalar_leafs.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/scalar_leafs.py new file mode 100644 index 0000000000000000000000000000000000000000..f03efbc7af3ab1116894e589cb52f87ae9813d3e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/scalar_leafs.py @@ -0,0 +1,33 @@ +from ...error import GraphQLError +from ...type.definition import get_named_type, is_leaf_type +from .base import ValidationRule + + +class ScalarLeafs(ValidationRule): + + def enter_Field(self, node, key, parent, path, ancestors): + type = self.context.get_type() + + if not type: + return + + if is_leaf_type(get_named_type(type)): + if node.selection_set: + self.context.report_error(GraphQLError( + self.no_subselection_allowed_message(node.name.value, type), + [node.selection_set] + )) + + elif not node.selection_set: + self.context.report_error(GraphQLError( + self.required_subselection_message(node.name.value, type), + [node] + )) + + @staticmethod + def no_subselection_allowed_message(field, type): + return 'Field "{}" of type "{}" must not have a sub selection.'.format(field, type) + + @staticmethod + def required_subselection_message(field, type): + return 'Field "{}" of type "{}" must have a sub selection.'.format(field, type) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_argument_names.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_argument_names.py new file mode 100644 index 0000000000000000000000000000000000000000..9e25c75c8e5cfbe6e4853f806de68e7f6bbd97a4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_argument_names.py @@ -0,0 +1,32 @@ +from ...error import GraphQLError +from .base import ValidationRule + + +class UniqueArgumentNames(ValidationRule): + __slots__ = 'known_arg_names', + + def __init__(self, context): + super(UniqueArgumentNames, self).__init__(context) + self.known_arg_names = {} + + def enter_Field(self, node, key, parent, path, ancestors): + self.known_arg_names = {} + + def enter_Directive(self, node, key, parent, path, ancestors): + self.known_arg_names = {} + + def enter_Argument(self, node, key, parent, path, ancestors): + arg_name = node.name.value + + if arg_name in self.known_arg_names: + self.context.report_error(GraphQLError( + self.duplicate_arg_message(arg_name), + [self.known_arg_names[arg_name], node.name] + )) + else: + self.known_arg_names[arg_name] = node.name + return False + + @staticmethod + def duplicate_arg_message(field): + return 'There can only be one argument named "{}".'.format(field) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_input_field_names.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_input_field_names.py new file mode 100644 index 0000000000000000000000000000000000000000..6fe18bab577d8b1f81eebda4b60b1181fd9d93a3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_input_field_names.py @@ -0,0 +1,33 @@ +from ...error import GraphQLError +from .base import ValidationRule + + +class UniqueInputFieldNames(ValidationRule): + __slots__ = 'known_names', 'known_names_stack' + + def __init__(self, context): + super(UniqueInputFieldNames, self).__init__(context) + self.known_names = {} + self.known_names_stack = [] + + def enter_ObjectValue(self, node, key, parent, path, ancestors): + self.known_names_stack.append(self.known_names) + self.known_names = {} + + def leave_ObjectValue(self, node, key, parent, path, ancestors): + self.known_names = self.known_names_stack.pop() + + def enter_ObjectField(self, node, key, parent, path, ancestors): + field_name = node.name.value + if field_name in self.known_names: + self.context.report_error(GraphQLError( + self.duplicate_input_field_message(field_name), + [self.known_names[field_name], node.name] + )) + else: + self.known_names[field_name] = node.name + return False + + @staticmethod + def duplicate_input_field_message(field_name): + return 'There can only be one input field named "{}".'.format(field_name) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_operation_names.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_operation_names.py new file mode 100644 index 0000000000000000000000000000000000000000..1fccbb9b2230fb708bed7ee42d5ff96ce4083b20 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_operation_names.py @@ -0,0 +1,31 @@ +from ...error import GraphQLError +from .base import ValidationRule + + +class UniqueOperationNames(ValidationRule): + __slots__ = 'known_operation_names', + + def __init__(self, context): + super(UniqueOperationNames, self).__init__(context) + self.known_operation_names = {} + + def enter_OperationDefinition(self, node, key, parent, path, ancestors): + operation_name = node.name + if not operation_name: + return + + if operation_name.value in self.known_operation_names: + self.context.report_error(GraphQLError( + self.duplicate_operation_name_message(operation_name.value), + [self.known_operation_names[operation_name.value], operation_name] + )) + else: + self.known_operation_names[operation_name.value] = operation_name + return False + + def enter_FragmentDefinition(self, node, key, parent, path, ancestors): + return False + + @staticmethod + def duplicate_operation_name_message(operation_name): + return 'There can only be one operation named "{}".'.format(operation_name) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_variable_names.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_variable_names.py new file mode 100644 index 0000000000000000000000000000000000000000..f471e3464343d8d304e8d62341daba736a2c4ab7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_variable_names.py @@ -0,0 +1,27 @@ +from ...error import GraphQLError +from .base import ValidationRule + + +class UniqueVariableNames(ValidationRule): + __slots__ = 'known_variable_names', + + def __init__(self, context): + super(UniqueVariableNames, self).__init__(context) + self.known_variable_names = {} + + def enter_OperationDefinition(self, node, key, parent, path, ancestors): + self.known_variable_names = {} + + def enter_VariableDefinition(self, node, key, parent, path, ancestors): + variable_name = node.variable.name.value + if variable_name in self.known_variable_names: + self.context.report_error(GraphQLError( + self.duplicate_variable_message(variable_name), + [self.known_variable_names[variable_name], node.variable.name] + )) + else: + self.known_variable_names[variable_name] = node.variable.name + + @staticmethod + def duplicate_variable_message(operation_name): + return 'There can be only one variable named "{}".'.format(operation_name) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/variables_are_input_types.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/variables_are_input_types.py new file mode 100644 index 0000000000000000000000000000000000000000..f510fbba0ad1584ea5101e0869c5133f14dbb708 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/variables_are_input_types.py @@ -0,0 +1,21 @@ +from ...error import GraphQLError +from ...language.printer import print_ast +from ...type.definition import is_input_type +from ...utils.type_from_ast import type_from_ast +from .base import ValidationRule + + +class VariablesAreInputTypes(ValidationRule): + + def enter_VariableDefinition(self, node, key, parent, path, ancestors): + type = type_from_ast(self.context.get_schema(), node.type) + + if type and not is_input_type(type): + self.context.report_error(GraphQLError( + self.non_input_type_on_variable_message(node.variable.name.value, print_ast(node.type)), + [node.type] + )) + + @staticmethod + def non_input_type_on_variable_message(variable_name, type_name): + return 'Variable "${}" cannot be non-input type "{}".'.format(variable_name, type_name) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/variables_in_allowed_position.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/variables_in_allowed_position.py new file mode 100644 index 0000000000000000000000000000000000000000..4117e0f8217f3d7ddee4fc6850d4899a130c0602 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/variables_in_allowed_position.py @@ -0,0 +1,53 @@ +from ...error import GraphQLError +from ...type.definition import GraphQLNonNull +from ...utils.type_comparators import is_type_sub_type_of +from ...utils.type_from_ast import type_from_ast +from .base import ValidationRule + + +class VariablesInAllowedPosition(ValidationRule): + __slots__ = 'var_def_map' + + def __init__(self, context): + super(VariablesInAllowedPosition, self).__init__(context) + self.var_def_map = {} + + def enter_OperationDefinition(self, node, key, parent, path, ancestors): + self.var_def_map = {} + + def leave_OperationDefinition(self, operation, key, parent, path, ancestors): + usages = self.context.get_recursive_variable_usages(operation) + + for usage in usages: + node = usage.node + type = usage.type + var_name = node.name.value + var_def = self.var_def_map.get(var_name) + if var_def and type: + # A var type is allowed if it is the same or more strict (e.g. is + # a subtype of) than the expected type. It can be more strict if + # the variable type is non-null when the expected type is nullable. + # If both are list types, the variable item type can be more strict + # than the expected item type (contravariant). + schema = self.context.get_schema() + var_type = type_from_ast(schema, var_def.type) + if var_type and not is_type_sub_type_of(schema, self.effective_type(var_type, var_def), type): + self.context.report_error(GraphQLError( + self.bad_var_pos_message(var_name, var_type, type), + [var_def, node] + )) + + def enter_VariableDefinition(self, node, key, parent, path, ancestors): + self.var_def_map[node.variable.name.value] = node + + @staticmethod + def effective_type(var_type, var_def): + if not var_def.default_value or isinstance(var_type, GraphQLNonNull): + return var_type + + return GraphQLNonNull(var_type) + + @staticmethod + def bad_var_pos_message(var_name, var_type, expected_type): + return 'Variable "{}" of type "{}" used in position expecting type "{}".'.format(var_name, var_type, + expected_type) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/__pycache__/conftest.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/__pycache__/conftest.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93ea39eefb7c4b92bd8c08bb59b41ca0ba2ea994 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/__pycache__/conftest.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/__pycache__/setup.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/__pycache__/setup.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5506b35deca943508394c2915fb33513dee786e1 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/__pycache__/setup.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..791b28886a3afa464fe6c59fcdb187d078330977 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/__pycache__/conftest.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/__pycache__/conftest.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2cd61467af5958a7bdc39b29dbefec5218a0c8d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/__pycache__/conftest.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/__pycache__/test_awaitable.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/__pycache__/test_awaitable.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7034e06e66d1d93c8a5440c4588d8107d9af4526 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/__pycache__/test_awaitable.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/__pycache__/test_benchmark.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/__pycache__/test_benchmark.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e6e92f7ebf9387f8810041da9111794c4fca51d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/__pycache__/test_benchmark.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/__pycache__/utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c115d03c0315647fa904b3a019844f1df4ffec88 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/__pycache__/utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/test_benchmark.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/test_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..eb30f24e2f587ab7d806013a3fd7af077abc1c2b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/test_benchmark.py @@ -0,0 +1,116 @@ +from pytest import raises +import time +from promise import Promise, promisify, is_thenable + + +def test_benchmark_promise_creation(benchmark): + @benchmark + def create_promise(): # unnecessary function call + p = Promise() + + +def test_benchmark_promise_resolve(benchmark): + def create_promise(): + return Promise.resolve(True) + + result = benchmark(create_promise).get() + assert result == True + + +def test_benchmark_is_thenable_basic_type(benchmark): + def create_promise(): + return is_thenable(True) + + result = benchmark(create_promise) + assert result == False + + +def test_benchmark_is_thenable_custom_type(benchmark): + class MyType(object): + pass + + my_type_instance = MyType() + + def create_promise(): + return is_thenable(my_type_instance) + + result = benchmark(create_promise) + assert result == False + + +def test_benchmark_promise_creation_with_resolve(benchmark): + do_resolve = lambda resolve, reject: resolve(True) + + def create_promise(): # unnecessary function call + p = Promise(do_resolve) + # p._wait() + return p + + result = benchmark(create_promise).get() + assert result == True + + +def test_benchmark_promise_creation_with_reject(benchmark): + do_resolve = lambda resolve, reject: reject(Exception("Error")) + + def create_promise(): # unnecessary function call + p = Promise(do_resolve) + # p._wait() + return p + + with raises(Exception) as exc_info: + result = benchmark(create_promise).get() + + assert str(exc_info.value) == "Error" + + +# def test_benchmark_promisify_promise(benchmark): +# instance = Promise() + +# def create_promise(): # unnecessary function call +# return promisify(instance) + +# result = benchmark(create_promise) + +# assert isinstance(result, Promise) + + +def test_benchmark_promisify_custom_type(benchmark): + class CustomThenable(object): + pass + # def then(self, resolve, reject): + # return resolve(True) + + instance = CustomThenable() + + def create_promise(): # unnecessary function call + return Promise.resolve(instance) + + result = benchmark(create_promise) + + assert isinstance(result, Promise) + assert result.get() == instance + + +def test_benchmark_promise_all(benchmark): + values = range(1000) + + def create_promise(): # unnecessary function call + return Promise.all(values) + + result = benchmark(create_promise) + + assert isinstance(result, Promise) + assert result.get() == list(range(1000)) + + +def test_benchmark_promise_all_promise(benchmark): + values = [Promise.resolve(i) for i in range(100000)] + + def create_promise(): # unnecessary function call + return Promise.all(values) + + result = benchmark(create_promise) + + assert isinstance(result, Promise) + assert result.get() == list(range(100000)) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/test_complex_threads.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/test_complex_threads.py new file mode 100644 index 0000000000000000000000000000000000000000..6cddfaac1e9900c9351c50eeaacbda6f93cef477 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/test_complex_threads.py @@ -0,0 +1,23 @@ +from time import sleep +from concurrent.futures import ThreadPoolExecutor +from promise import Promise +from operator import mul + +executor = ThreadPoolExecutor(max_workers=40000) + + +def promise_factorial(n): + if n < 2: + return 1 + sleep(.02) + a = executor.submit(promise_factorial, n - 1) + + def promise_then(r): + return mul(r, n) + + return Promise.resolve(a).then(promise_then) + + +def test_factorial(): + p = promise_factorial(10) + assert p.get() == 3628800 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/test_dataloader.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/test_dataloader.py new file mode 100644 index 0000000000000000000000000000000000000000..a8352fc6e3d5f7b6c71d949d87a59bb9ecdd79cd --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/test_dataloader.py @@ -0,0 +1,452 @@ +from pytest import raises + +from promise import Promise, async_instance +from promise.dataloader import DataLoader + + +def id_loader(**options): + load_calls = [] + + resolve = options.pop("resolve", Promise.resolve) + + def fn(keys): + load_calls.append(keys) + return resolve(keys) + + identity_loader = DataLoader(fn, **options) + return identity_loader, load_calls + + +def test_build_a_simple_data_loader(): + def call_fn(keys): + return Promise.resolve(keys) + + identity_loader = DataLoader(call_fn) + + promise1 = identity_loader.load(1) + assert isinstance(promise1, Promise) + + value1 = promise1.get() + assert value1 == 1 + + +def test_supports_loading_multiple_keys_in_one_call(): + def call_fn(keys): + return Promise.resolve(keys) + + identity_loader = DataLoader(call_fn) + + promise_all = identity_loader.load_many([1, 2]) + assert isinstance(promise_all, Promise) + + values = promise_all.get() + assert values == [1, 2] + + promise_all = identity_loader.load_many([]) + assert isinstance(promise_all, Promise) + + values = promise_all.get() + assert values == [] + + +def test_batches_multiple_requests(): + @Promise.safe + def do(): + identity_loader, load_calls = id_loader() + + promise1 = identity_loader.load(1) + promise2 = identity_loader.load(2) + + p = Promise.all([promise1, promise2]) + + value1, value2 = p.get() + + assert value1 == 1 + assert value2 == 2 + + assert load_calls == [[1, 2]] + + do().get() + + +def test_batches_multiple_requests_with_max_batch_sizes(): + @Promise.safe + def do(): + identity_loader, load_calls = id_loader(max_batch_size=2) + + promise1 = identity_loader.load(1) + promise2 = identity_loader.load(2) + promise3 = identity_loader.load(3) + + p = Promise.all([promise1, promise2, promise3]) + + value1, value2, value3 = p.get() + + assert value1 == 1 + assert value2 == 2 + assert value3 == 3 + + assert load_calls == [[1, 2], [3]] + + do().get() + + +def test_coalesces_identical_requests(): + @Promise.safe + def do(): + identity_loader, load_calls = id_loader() + + promise1 = identity_loader.load(1) + promise2 = identity_loader.load(1) + + assert promise1 == promise2 + p = Promise.all([promise1, promise2]) + + value1, value2 = p.get() + + assert value1 == 1 + assert value2 == 1 + + assert load_calls == [[1]] + + do().get() + + +def test_caches_repeated_requests(): + @Promise.safe + def do(): + identity_loader, load_calls = id_loader() + + a, b = Promise.all([identity_loader.load("A"), identity_loader.load("B")]).get() + + assert a == "A" + assert b == "B" + + assert load_calls == [["A", "B"]] + + a2, c = Promise.all( + [identity_loader.load("A"), identity_loader.load("C")] + ).get() + + assert a2 == "A" + assert c == "C" + + assert load_calls == [["A", "B"], ["C"]] + + a3, b2, c2 = Promise.all( + [ + identity_loader.load("A"), + identity_loader.load("B"), + identity_loader.load("C"), + ] + ).get() + + assert a3 == "A" + assert b2 == "B" + assert c2 == "C" + + assert load_calls == [["A", "B"], ["C"]] + + do().get() + + +def test_clears_single_value_in_loader(): + @Promise.safe + def do(): + identity_loader, load_calls = id_loader() + + a, b = Promise.all([identity_loader.load("A"), identity_loader.load("B")]).get() + + assert a == "A" + assert b == "B" + + assert load_calls == [["A", "B"]] + + identity_loader.clear("A") + + a2, b2 = Promise.all( + [identity_loader.load("A"), identity_loader.load("B")] + ).get() + + assert a2 == "A" + assert b2 == "B" + + assert load_calls == [["A", "B"], ["A"]] + + do().get() + + +def test_clears_all_values_in_loader(): + @Promise.safe + def do(): + identity_loader, load_calls = id_loader() + + a, b = Promise.all([identity_loader.load("A"), identity_loader.load("B")]).get() + + assert a == "A" + assert b == "B" + + assert load_calls == [["A", "B"]] + + identity_loader.clear_all() + + a2, b2 = Promise.all( + [identity_loader.load("A"), identity_loader.load("B")] + ).get() + + assert a2 == "A" + assert b2 == "B" + + assert load_calls == [["A", "B"], ["A", "B"]] + + do().get() + + +def test_does_not_replace_cache_map(): + @Promise.safe + def do(): + identity_loader, _ = id_loader() + a, b = Promise.all([identity_loader.load("A"), identity_loader.load("B")]).get() + + assert a == "A" + assert b == "B" + + cache_map = identity_loader._promise_cache + + identity_loader.clear_all() + + assert id(identity_loader._promise_cache) == id(cache_map) + + do().get() + + +def test_allows_priming_the_cache(): + @Promise.safe + def do(): + identity_loader, load_calls = id_loader() + + identity_loader.prime("A", "A") + + a, b = Promise.all([identity_loader.load("A"), identity_loader.load("B")]).get() + + assert a == "A" + assert b == "B" + + assert load_calls == [["B"]] + + do().get() + + +def test_does_not_prime_keys_that_already_exist(): + @Promise.safe + def do(): + identity_loader, load_calls = id_loader() + + identity_loader.prime("A", "X") + + a1 = identity_loader.load("A").get() + b1 = identity_loader.load("B").get() + + assert a1 == "X" + assert b1 == "B" + + identity_loader.prime("A", "Y") + identity_loader.prime("B", "Y") + + a2 = identity_loader.load("A").get() + b2 = identity_loader.load("B").get() + + assert a2 == "X" + assert b2 == "B" + + assert load_calls == [["B"]] + + do().get() + + +# Represents Errors + + +def test_resolves_to_error_to_indicate_failure(): + @Promise.safe + def do(): + def resolve(keys): + mapped_keys = [ + key if key % 2 == 0 else Exception("Odd: {}".format(key)) + for key in keys + ] + return Promise.resolve(mapped_keys) + + even_loader, load_calls = id_loader(resolve=resolve) + + with raises(Exception) as exc_info: + even_loader.load(1).get() + + assert str(exc_info.value) == "Odd: 1" + + value2 = even_loader.load(2).get() + assert value2 == 2 + assert load_calls == [[1], [2]] + + do().get() + + +def test_can_represent_failures_and_successes_simultaneously(): + @Promise.safe + def do(): + def resolve(keys): + mapped_keys = [ + key if key % 2 == 0 else Exception("Odd: {}".format(key)) + for key in keys + ] + return Promise.resolve(mapped_keys) + + even_loader, load_calls = id_loader(resolve=resolve) + + promise1 = even_loader.load(1) + promise2 = even_loader.load(2) + + with raises(Exception) as exc_info: + promise1.get() + + assert str(exc_info.value) == "Odd: 1" + value2 = promise2.get() + assert value2 == 2 + assert load_calls == [[1, 2]] + + do().get() + + +def test_caches_failed_fetches(): + @Promise.safe + def do(): + def resolve(keys): + mapped_keys = [Exception("Error: {}".format(key)) for key in keys] + return Promise.resolve(mapped_keys) + + error_loader, load_calls = id_loader(resolve=resolve) + + with raises(Exception) as exc_info: + error_loader.load(1).get() + + assert str(exc_info.value) == "Error: 1" + + with raises(Exception) as exc_info: + error_loader.load(1).get() + + assert str(exc_info.value) == "Error: 1" + + assert load_calls == [[1]] + + do().get() + + +def test_caches_failed_fetches(): + @Promise.safe + def do(): + identity_loader, load_calls = id_loader() + + identity_loader.prime(1, Exception("Error: 1")) + + with raises(Exception) as exc_info: + identity_loader.load(1).get() + + assert load_calls == [] + + do().get() + + +# It is resilient to job queue ordering +# def test_batches_loads_occuring_within_promises(): +# @Promise.safe +# def do(): +# identity_loader, load_calls = id_loader() +# values = Promise.all([ +# identity_loader.load('A'), +# Promise.resolve(None).then(lambda v: Promise.resolve(None)).then( +# lambda v: identity_loader.load('B') +# ) +# ]).get() + +# assert values == ['A', 'B'] +# assert load_calls == [['A', 'B']] + +# do().get() + + +def test_catches_error_if_loader_resolver_fails(): + @Promise.safe + def do(): + def do_resolve(x): + raise Exception("AOH!") + + a_loader, a_load_calls = id_loader(resolve=do_resolve) + + with raises(Exception) as exc_info: + a_loader.load("A1").get() + + assert str(exc_info.value) == "AOH!" + + do().get() + + +def test_can_call_a_loader_from_a_loader(): + @Promise.safe + def do(): + deep_loader, deep_load_calls = id_loader() + a_loader, a_load_calls = id_loader( + resolve=lambda keys: deep_loader.load(tuple(keys)) + ) + b_loader, b_load_calls = id_loader( + resolve=lambda keys: deep_loader.load(tuple(keys)) + ) + + a1, b1, a2, b2 = Promise.all( + [ + a_loader.load("A1"), + b_loader.load("B1"), + a_loader.load("A2"), + b_loader.load("B2"), + ] + ).get() + + assert a1 == "A1" + assert b1 == "B1" + assert a2 == "A2" + assert b2 == "B2" + + assert a_load_calls == [["A1", "A2"]] + assert b_load_calls == [["B1", "B2"]] + assert deep_load_calls == [[("A1", "A2"), ("B1", "B2")]] + + do().get() + + +def test_dataloader_clear_with_missing_key_works(): + @Promise.safe + def do(): + def do_resolve(x): + return x + + a_loader, a_load_calls = id_loader(resolve=do_resolve) + assert a_loader.clear("A1") == a_loader + + do().get() + + +def test_wrong_loader_return_type_does_not_block_async_instance(): + @Promise.safe + def do(): + def do_resolve(x): + return x + + a_loader, a_load_calls = id_loader(resolve=do_resolve) + + with raises(Exception): + a_loader.load("A1").get() + assert async_instance.have_drained_queues + with raises(Exception): + a_loader.load("A2").get() + assert async_instance.have_drained_queues + + do().get() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/test_dataloader_extra.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/test_dataloader_extra.py new file mode 100644 index 0000000000000000000000000000000000000000..f24fc18a954e020afa6f8bc0dcc7e9219c76af02 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/test_dataloader_extra.py @@ -0,0 +1,65 @@ +# from promise import Promise +# from promise.dataloader import DataLoader + + +# def id_loader(**options): +# load_calls = [] + +# def fn(keys): +# load_calls.append(keys) +# return Promise.resolve(keys) + +# identity_loader = DataLoader(fn, **options) +# return identity_loader, load_calls + + +# def test_batches_multiple_requests(): +# identity_loader, load_calls = id_loader() + +# @Promise.safe +# def safe(): +# promise1 = identity_loader.load(1) +# promise2 = identity_loader.load(2) +# return promise1, promise2 + +# promise1, promise2 = safe() +# value1, value2 = Promise.all([promise1, promise2]).get() +# assert value1 == 1 +# assert value2 == 2 + +# assert load_calls == [[1, 2]] + + +# def test_batches_multiple_requests_two(): +# identity_loader, load_calls = id_loader() + +# @Promise.safe +# def safe(): +# promise1 = identity_loader.load(1) +# promise2 = identity_loader.load(2) +# return Promise.all([promise1, promise2]) + +# p = safe() +# value1, value2 = p.get() + +# assert value1 == 1 +# assert value2 == 2 + +# assert load_calls == [[1, 2]] + + +# @Promise.safe +# def test_batches_multiple_requests_safe(): +# identity_loader, load_calls = id_loader() + +# promise1 = identity_loader.load(1) +# promise2 = identity_loader.load(2) + +# p = Promise.all([promise1, promise2]) + +# value1, value2 = p.get() + +# assert value1 == 1 +# assert value2 == 2 + +# assert load_calls == [[1, 2]] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/test_extra.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/test_extra.py new file mode 100644 index 0000000000000000000000000000000000000000..4a083718d134ede122d5a761c592318a9fa5748e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/test_extra.py @@ -0,0 +1,670 @@ +# This exercises some capabilities above and beyond +# the Promises/A+ test suite +from time import sleep +from pytest import raises, fixture + +from threading import Event +from promise import ( + Promise, + is_thenable, + promisify, + promise_for_dict as free_promise_for_dict, +) +from concurrent.futures import Future +from threading import Thread + +from .utils import assert_exception + + +class DelayedFulfill(Thread): + def __init__(self, d, p, v): + self.delay = d + self.promise = p + self.value = v + Thread.__init__(self) + + def run(self): + sleep(self.delay) + self.promise.do_resolve(self.value) + + +class DelayedRejection(Thread): + def __init__(self, d, p, r): + self.delay = d + self.promise = p + self.reason = r + Thread.__init__(self) + + def run(self): + sleep(self.delay) + self.promise.do_reject(self.reason) + + +class FakeThenPromise: + def __init__(self, raises=True): + self.raises = raises + + def then(self, s=None, f=None): + if self.raises: + raise Exception("FakeThenPromise raises in 'then'") + + +def df(value, dtime): + p = Promise() + t = DelayedFulfill(dtime, p, value) + t.start() + + return p + + +def dr(reason, dtime): + p = Promise() + t = DelayedRejection(dtime, p, reason) + t.start() + + return p + + +# Static methods +def test_fulfilled(): + p = Promise.fulfilled(4) + assert p.is_fulfilled + assert p.get() == 4 + + +def test_rejected(): + p = Promise.rejected(Exception("Static rejected")) + assert p.is_rejected + with raises(Exception) as exc_info: + p.get() + assert str(exc_info.value) == "Static rejected" + + +# Fulfill +def test_fulfill_self(): + p = Promise() + with raises(TypeError) as excinfo: + p.do_resolve(p) + p.get() + + +# Exceptions +def test_exceptions(): + def throws(v): + assert False + + p1 = Promise() + p1.then(throws) + p1.do_resolve(5) + + p2 = Promise() + p2.catch(throws) + p2.do_reject(Exception()) + + with raises(Exception) as excinfo: + p2.get() + + +def test_thrown_exceptions_have_stacktrace(): + def throws(v): + assert False + + p3 = Promise.resolve("a").then(throws) + with raises(AssertionError) as assert_exc: + p3.get() + + assert assert_exc.traceback[-1].path.strpath == __file__ + + +def test_thrown_exceptions_preserve_stacktrace(): + def throws(v): + assert False + + def after_throws(v): + pass + + p3 = Promise.resolve("a").then(throws).then(after_throws) + with raises(AssertionError) as assert_exc: + p3.get() + + assert assert_exc.traceback[-1].path.strpath == __file__ + + +# WAIT +# def test_wait_when(): +# p1 = df(5, 0.01) +# assert p1.is_pending +# p1._wait() +# assert p1.is_fulfilled + + +def test_wait_if(): + p1 = Promise() + p1.do_resolve(5) + p1._wait() + assert p1.is_fulfilled + + +# def test_wait_timeout(): +# p1 = df(5, 0.1) +# assert p1.is_pending +# with raises(Exception) as exc_info: +# p1._wait(timeout=0.05) +# assert str(exc_info.value) == "Timeout" +# assert p1.is_pending +# p1._wait() +# assert p1.is_fulfilled + + +# # GET +# def test_get_when(): +# p1 = df(5, 0.01) +# assert p1.is_pending +# v = p1.get() +# assert p1.is_fulfilled +# assert 5 == v + + +def test_get_if(): + p1 = Promise() + p1.do_resolve(5) + v = p1.get() + assert p1.is_fulfilled + assert 5 == v + + +# def test_get_timeout(): +# p1 = df(5, 0.1) +# assert p1.is_pending +# with raises(Exception) as exc_info: +# p1._wait(timeout=0.05) +# assert str(exc_info.value) == "Timeout" +# assert p1.is_pending +# v = p1.get() +# assert p1.is_fulfilled +# assert 5 == v + + +# Promise.all +def test_promise_all_when(): + p1 = Promise() + p2 = Promise() + pl = Promise.all([p1, p2]) + assert p1.is_pending + assert p2.is_pending + assert pl.is_pending + p1.do_resolve(5) + p1._wait() + assert p1.is_fulfilled + assert p2.is_pending + assert pl.is_pending + p2.do_resolve(10) + p2._wait() + pl._wait() + assert p1.is_fulfilled + assert p2.is_fulfilled + assert pl.is_fulfilled + assert 5 == p1.get() + assert 10 == p2.get() + assert 5 == pl.get()[0] + assert 10 == pl.get()[1] + + +def test_promise_all_when_mixed_promises(): + p1 = Promise() + p2 = Promise() + pl = Promise.all([p1, 32, p2, False, True]) + assert p1.is_pending + assert p2.is_pending + assert pl.is_pending + p1.do_resolve(5) + p1._wait() + assert p1.is_fulfilled + assert p2.is_pending + assert pl.is_pending + p2.do_resolve(10) + p2._wait() + pl._wait() + assert p1.is_fulfilled + assert p2.is_fulfilled + assert pl.is_fulfilled + assert 5 == p1.get() + assert 10 == p2.get() + assert pl.get() == [5, 32, 10, False, True] + + +def test_promise_all_when_if_no_promises(): + pl = Promise.all([10, 32, False, True]) + assert pl.get() == [10, 32, False, True] + + +def test_promise_all_if(): + p1 = Promise() + p2 = Promise() + pd1 = Promise.all([p1, p2]) + pd2 = Promise.all([p1]) + pd3 = Promise.all([]) + pd3._wait() + assert p1.is_pending + assert p2.is_pending + assert pd1.is_pending + assert pd2.is_pending + assert pd3.is_fulfilled + p1.do_resolve(5) + p1._wait() + pd2._wait() + assert p1.is_fulfilled + assert p2.is_pending + assert pd1.is_pending + assert pd2.is_fulfilled + p2.do_resolve(10) + p2._wait() + pd1._wait() + pd2._wait() + assert p1.is_fulfilled + assert p2.is_fulfilled + assert pd1.is_fulfilled + assert pd2.is_fulfilled + assert 5 == p1.get() + assert 10 == p2.get() + assert 5 == pd1.get()[0] + assert 5 == pd2.get()[0] + assert 10 == pd1.get()[1] + assert [] == pd3.get() + + +# promise_for_dict +@fixture(params=[Promise.for_dict, free_promise_for_dict]) +def promise_for_dict(request): + return request.param + + +def test_dict_promise_when(promise_for_dict): + p1 = Promise() + p2 = Promise() + d = {"a": p1, "b": p2} + pd1 = promise_for_dict(d) + pd2 = promise_for_dict({"a": p1}) + pd3 = promise_for_dict({}) + assert p1.is_pending + assert p2.is_pending + assert pd1.is_pending + assert pd2.is_pending + pd3._wait() + assert pd3.is_fulfilled + p1.do_resolve(5) + p1._wait() + pd2._wait() + assert p1.is_fulfilled + assert p2.is_pending + assert pd1.is_pending + assert pd2.is_fulfilled + p2.do_resolve(10) + p2._wait() + pd1._wait() + assert p1.is_fulfilled + assert p2.is_fulfilled + assert pd1.is_fulfilled + assert pd2.is_fulfilled + assert 5 == p1.get() + assert 10 == p2.get() + assert 5 == pd1.get()["a"] + assert 5 == pd2.get()["a"] + assert 10 == pd1.get()["b"] + assert {} == pd3.get() + + +def test_dict_promise_if(promise_for_dict): + p1 = Promise() + p2 = Promise() + d = {"a": p1, "b": p2} + pd = promise_for_dict(d) + assert p1.is_pending + assert p2.is_pending + assert pd.is_pending + p1.do_resolve(5) + p1._wait() + assert p1.is_fulfilled + assert p2.is_pending + assert pd.is_pending + p2.do_resolve(10) + p2._wait() + assert p1.is_fulfilled + assert p2.is_fulfilled + # pd._wait() + # assert pd.is_fulfilled + # assert 5 == p1.get() + # assert 10 == p2.get() + # assert 5 == pd.get()["a"] + # assert 10 == pd.get()["b"] + + +def test_done(): + counter = [0] + r = Promise() + + def inc(_): + counter[0] += 1 + + def dec(_): + counter[0] -= 1 + + def end(_): + r.do_resolve(None) + + p = Promise() + p.done(inc, dec) + p.done(inc, dec) + p.done(end) + p.do_resolve(4) + + Promise.wait(r) + assert counter[0] == 2 + + r = Promise() + + counter = [0] + p = Promise() + p.done(inc, dec) + p.done(inc, dec) + p.done(None, end) + p.do_reject(Exception()) + + Promise.wait(r) + assert counter[0] == -2 + + +def test_done_all(): + counter = [0] + + def inc(_): + counter[0] += 1 + + def dec(_): + counter[0] -= 1 + + p = Promise() + r = Promise() + p.done_all() + p.done_all([(inc, dec)]) + p.done_all( + [ + (inc, dec), + (inc, dec), + {"success": inc, "failure": dec}, + lambda _: r.do_resolve(None), + ] + ) + p.do_resolve(4) + Promise.wait(r) + assert counter[0] == 4 + + p = Promise() + r = Promise() + p.done_all() + p.done_all([inc]) + p.done_all([(inc, dec)]) + p.done_all( + [ + (inc, dec), + {"success": inc, "failure": dec}, + (None, lambda _: r.do_resolve(None)), + ] + ) + p.do_reject(Exception("Uh oh!")) + Promise.wait(r) + assert counter[0] == 1 + + +def test_then_all(): + p = Promise() + + handlers = [ + ((lambda x: x * x), (lambda r: 1)), + {"success": (lambda x: x + x), "failure": (lambda r: 2)}, + ] + + results = ( + p.then_all() + + p.then_all([lambda x: x]) + + p.then_all([(lambda x: x * x, lambda r: 1)]) + + p.then_all(handlers) + ) + + p.do_resolve(4) + + assert [r.get() for r in results] == [4, 16, 16, 8] + + p = Promise() + + handlers = [ + ((lambda x: x * x), (lambda r: 1)), + {"success": (lambda x: x + x), "failure": (lambda r: 2)}, + ] + + results = ( + p.then_all() + + p.then_all([(lambda x: x * x, lambda r: 1)]) + + p.then_all(handlers) + ) + + p.do_reject(Exception()) + + assert [r.get() for r in results] == [1, 1, 2] + + +def test_do_resolve(): + p1 = Promise(lambda resolve, reject: resolve(0)) + assert p1.get() == 0 + assert p1.is_fulfilled + + +def test_do_resolve_fail_on_call(): + def raises(resolve, reject): + raise Exception("Fails") + + p1 = Promise(raises) + assert not p1.is_fulfilled + assert str(p1.reason) == "Fails" + + +def test_catch(): + p1 = Promise(lambda resolve, reject: resolve(0)) + p2 = p1.then(lambda value: 1 / value).catch(lambda e: e).then(lambda e: type(e)) + assert p2.get() == ZeroDivisionError + assert p2.is_fulfilled + + +def test_is_thenable_promise(): + promise = Promise() + assert is_thenable(promise) + + +def test_is_thenable_then_object(): + promise = FakeThenPromise() + assert not is_thenable(promise) + + +def test_is_thenable_future(): + promise = Future() + assert is_thenable(promise) + + +def test_is_thenable_simple_object(): + assert not is_thenable(object()) + + +@fixture(params=[Promise.resolve]) +def resolve(request): + return request.param + + +def test_resolve_promise(resolve): + promise = Promise() + assert resolve(promise) == promise + + +def test_resolve_then_object(resolve): + promise = FakeThenPromise(raises=False) + p = resolve(promise) + assert isinstance(p, Promise) + + +def test_resolve_future(resolve): + future = Future() + promise = resolve(future) + assert promise.is_pending + future.set_result(1) + assert promise.get() == 1 + assert promise.is_fulfilled + + +def test_resolve_future_rejected(resolve): + future = Future() + promise = resolve(future) + assert promise.is_pending + future.set_exception(Exception("Future rejected")) + assert promise.is_rejected + assert_exception(promise.reason, Exception, "Future rejected") + + +def test_resolve_object(resolve): + val = object() + promised = resolve(val) + assert isinstance(promised, Promise) + assert promised.get() == val + + +def test_resolve_promise_subclass(): + class MyPromise(Promise): + pass + + p = Promise() + p.do_resolve(10) + m_p = MyPromise.resolve(p) + + assert isinstance(m_p, MyPromise) + assert m_p.get() == p.get() + + +def test_promise_repr_pending(): + promise = Promise() + assert repr(promise) == "".format(hex(id(promise))) + + +def test_promise_repr_pending(): + val = {1: 2} + promise = Promise.fulfilled(val) + promise._wait() + assert repr(promise) == "".format( + hex(id(promise)), repr(val) + ) + + +def test_promise_repr_fulfilled(): + val = {1: 2} + promise = Promise.fulfilled(val) + promise._wait() + assert repr(promise) == "".format( + hex(id(promise)), repr(val) + ) + + +def test_promise_repr_rejected(): + err = Exception("Error!") + promise = Promise.rejected(err) + promise._wait() + assert repr(promise) == "".format( + hex(id(promise)), repr(err) + ) + + +def test_promise_loop(): + def by_two(result): + return result * 2 + + def executor(resolve, reject): + resolve(Promise.resolve(1).then(lambda v: Promise.resolve(v).then(by_two))) + + p = Promise(executor) + assert p.get(.1) == 2 + + +def test_resolve_future_like(resolve): + class CustomThenable(object): + def add_done_callback(self, f): + f(True) + + def done(self): + return True + + def exception(self): + pass + + def result(self): + return True + + instance = CustomThenable() + + promise = resolve(instance) + assert promise.get() == True + + +def sum_function(a, b): + return a + b + + +def test_promisify_function_resolved(resolve): + promisified_func = promisify(sum_function) + + result = promisified_func(1, 2) + assert isinstance(result, Promise) + assert result.get() == 3 + + +def test_promisify_function_rejected(resolve): + promisified_func = promisify(sum_function) + + result = promisified_func(None, None) + assert isinstance(result, Promise) + with raises(Exception) as exc_info_promise: + result.get() + + with raises(Exception) as exc_info: + sum_function(None, None) + + assert str(exc_info_promise.value) == str(exc_info.value) + + +def test_promises_with_only_then(): + context = {"success": False} + error = RuntimeError("Ooops!") + promise1 = Promise( + lambda resolve, reject: context.update({"promise1_reject": reject}) + ) + promise2 = promise1.then(lambda x: None) + promise3 = promise1.then(lambda x: None) + context["promise1_reject"](error) + + promise2._wait() + promise3._wait() + assert promise2.reason == error + assert promise3.reason == error + + +def test_promises_promisify_still_works_but_deprecated_for_non_callables(): + x = promisify(1) + assert isinstance(x, Promise) + assert x.get() == 1 + + +# def test_promise_loop(): +# values = Promise.resolve([1, None, 2]) +# def on_error(error): +# error + +# def executor(resolve, reject): +# resolve(Promise.resolve(values).then(lambda values: Promise.all([Promise.resolve(values[0])]).catch(on_error))) + +# p = Promise(executor) +# assert p.get(.1) == 2 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/test_promise_list.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/test_promise_list.py new file mode 100644 index 0000000000000000000000000000000000000000..e8dc35a99a92f083ce92552d6bc395f197475e93 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/test_promise_list.py @@ -0,0 +1,70 @@ +from pytest import raises + +from promise import Promise +from promise.promise_list import PromiseList + + +def all(promises): + return PromiseList(promises, Promise).promise + + +def test_empty_promises(): + all_promises = all([]) + assert all_promises.get() == [] + + +def test_bad_promises(): + all_promises = all(None) + + with raises(Exception) as exc_info: + all_promises.get() + + assert str(exc_info.value) == "PromiseList requires an iterable. Received None." + + +def test_promise_basic(): + all_promises = all([1, 2]) + assert all_promises.get() == [1, 2] + + +def test_promise_mixed(): + all_promises = all([1, 2, Promise.resolve(3)]) + assert all_promises.get() == [1, 2, 3] + + +def test_promise_rejected(): + e = Exception("Error") + all_promises = all([1, 2, Promise.reject(e)]) + + with raises(Exception) as exc_info: + all_promises.get() + + assert str(exc_info.value) == "Error" + + +def test_promise_reject_skip_all_other_values(): + e1 = Exception("Error1") + e2 = Exception("Error2") + p = Promise() + all_promises = all([1, Promise.reject(e1), Promise.reject(e2)]) + + with raises(Exception) as exc_info: + all_promises.get() + + assert str(exc_info.value) == "Error1" + + +def test_promise_lazy_promise(): + p = Promise() + all_promises = all([1, 2, p]) + assert not all_promises.is_fulfilled + p.do_resolve(3) + assert all_promises.get() == [1, 2, 3] + + +def test_promise_contained_promise(): + p = Promise() + all_promises = all([1, 2, Promise.resolve(None).then(lambda v: p)]) + assert not all_promises.is_fulfilled + p.do_resolve(3) + assert all_promises.get() == [1, 2, 3] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/test_thread_safety.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/test_thread_safety.py new file mode 100644 index 0000000000000000000000000000000000000000..ed55a84ff70b71f4a3b465a9c2cc5c9646f7c210 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/test_thread_safety.py @@ -0,0 +1,115 @@ +from promise import Promise +from promise.dataloader import DataLoader +import threading + + + +def test_promise_thread_safety(): + """ + Promise tasks should never be executed in a different thread from the one they are scheduled from, + unless the ThreadPoolExecutor is used. + + Here we assert that the pending promise tasks on thread 1 are not executed on thread 2 as thread 2 + resolves its own promise tasks. + """ + event_1 = threading.Event() + event_2 = threading.Event() + + assert_object = {'is_same_thread': True} + + def task_1(): + thread_name = threading.current_thread().getName() + + def then_1(value): + # Enqueue tasks to run later. + # This relies on the fact that `then` does not execute the function synchronously when called from + # within another `then` callback function. + promise = Promise.resolve(None).then(then_2) + assert promise.is_pending + event_1.set() # Unblock main thread + event_2.wait() # Wait for thread 2 + + def then_2(value): + assert_object['is_same_thread'] = (thread_name == threading.current_thread().getName()) + + promise = Promise.resolve(None).then(then_1) + + def task_2(): + promise = Promise.resolve(None).then(lambda v: None) + promise.get() # Drain task queue + event_2.set() # Unblock thread 1 + + thread_1 = threading.Thread(target=task_1) + thread_1.start() + + event_1.wait() # Wait for Thread 1 to enqueue promise tasks + + thread_2 = threading.Thread(target=task_2) + thread_2.start() + + for thread in (thread_1, thread_2): + thread.join() + + assert assert_object['is_same_thread'] + + +def test_dataloader_thread_safety(): + """ + Dataloader should only batch `load` calls that happened on the same thread. + + Here we assert that `load` calls on thread 2 are not batched on thread 1 as + thread 1 batches its own `load` calls. + """ + def load_many(keys): + thead_name = threading.current_thread().getName() + return Promise.resolve([thead_name for key in keys]) + + thread_name_loader = DataLoader(load_many) + + event_1 = threading.Event() + event_2 = threading.Event() + event_3 = threading.Event() + + assert_object = { + 'is_same_thread_1': True, + 'is_same_thread_2': True, + } + + def task_1(): + @Promise.safe + def do(): + promise = thread_name_loader.load(1) + event_1.set() + event_2.wait() # Wait for thread 2 to call `load` + assert_object['is_same_thread_1'] = ( + promise.get() == threading.current_thread().getName() + ) + event_3.set() # Unblock thread 2 + + do().get() + + def task_2(): + @Promise.safe + def do(): + promise = thread_name_loader.load(2) + event_2.set() + event_3.wait() # Wait for thread 1 to run `dispatch_queue_batch` + assert_object['is_same_thread_2'] = ( + promise.get() == threading.current_thread().getName() + ) + + do().get() + + thread_1 = threading.Thread(target=task_1) + thread_1.start() + + event_1.wait() # Wait for thread 1 to call `load` + + thread_2 = threading.Thread(target=task_2) + thread_2.start() + + for thread in (thread_1, thread_2): + thread.join() + + assert assert_object['is_same_thread_1'] + assert assert_object['is_same_thread_2'] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..73dd1619c250ecb2b42680afffad6884ae97282f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/tests/utils.py @@ -0,0 +1,3 @@ +def assert_exception(exception, expected_exception_cls, expected_message): + assert isinstance(exception, expected_exception_cls) + assert str(exception) == expected_message diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ed495d0fda9acc8ed0cb6a94ec93485d68781b9e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/__init__.py @@ -0,0 +1,38 @@ +from .pyutils.version import get_version + + +try: + # This variable is injected in the __builtins__ by the build + # process. It used to enable importing subpackages when + # the required packages are not installed + __SETUP__ # type: ignore +except NameError: + __SETUP__ = False + + +VERSION = (2, 3, 0, "final", 0) + +__version__ = get_version(VERSION) + +if not __SETUP__: + from .promise import ( + Promise, + promise_for_dict, + promisify, + is_thenable, + async_instance, + get_default_scheduler, + set_default_scheduler, + ) + from .schedulers.immediate import ImmediateScheduler + + __all__ = [ + "Promise", + "promise_for_dict", + "promisify", + "is_thenable", + "async_instance", + "get_default_scheduler", + "set_default_scheduler", + "ImmediateScheduler", + ] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a92fe94c293adb2e6b720418c08d0bfc449d2d69 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/__pycache__/async_.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/__pycache__/async_.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84ce591459e4ed18fbe6a359f541ccbb200d7ad2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/__pycache__/async_.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/__pycache__/dataloader.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/__pycache__/dataloader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b613cee658f1a4f26668cfca341568741aeb18c2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/__pycache__/dataloader.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/__pycache__/iterate_promise.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/__pycache__/iterate_promise.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfca25edd9329039d48830dcb93f23745c95ba24 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/__pycache__/iterate_promise.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/__pycache__/promise_list.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/__pycache__/promise_list.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b39f0c412b4fe6cb8c9f0f65e015782f5bbbf47 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/__pycache__/promise_list.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/async_.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/async_.py new file mode 100644 index 0000000000000000000000000000000000000000..21ac6e2ce6e6cd855921ed8accd3c4e9e0291fdf --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/async_.py @@ -0,0 +1,135 @@ +# Based on https://github.com/petkaantonov/bluebird/blob/master/src/promise.js +from collections import deque +from threading import local + +if False: + from .promise import Promise + from typing import Any, Callable, Optional, Union # flake8: noqa + + +class Async(local): + def __init__(self, trampoline_enabled=True): + self.is_tick_used = False + self.late_queue = deque() # type: ignore + self.normal_queue = deque() # type: ignore + self.have_drained_queues = False + self.trampoline_enabled = trampoline_enabled + + def enable_trampoline(self): + self.trampoline_enabled = True + + def disable_trampoline(self): + self.trampoline_enabled = False + + def have_items_queued(self): + return self.is_tick_used or self.have_drained_queues + + def _async_invoke_later(self, fn, scheduler): + self.late_queue.append(fn) + self.queue_tick(scheduler) + + def _async_invoke(self, fn, scheduler): + # type: (Callable, Any) -> None + self.normal_queue.append(fn) + self.queue_tick(scheduler) + + def _async_settle_promise(self, promise): + # type: (Promise) -> None + self.normal_queue.append(promise) + self.queue_tick(promise.scheduler) + + def invoke_later(self, fn): + if self.trampoline_enabled: + self._async_invoke_later(fn, scheduler) + else: + scheduler.call_later(0.1, fn) + + def invoke(self, fn, scheduler): + # type: (Callable, Any) -> None + if self.trampoline_enabled: + self._async_invoke(fn, scheduler) + else: + scheduler.call(fn) + + def settle_promises(self, promise): + # type: (Promise) -> None + if self.trampoline_enabled: + self._async_settle_promise(promise) + else: + promise.scheduler.call(promise._settle_promises) + + def throw_later(self, reason, scheduler): + # type: (Exception, Any) -> None + def fn(): + # type: () -> None + raise reason + + scheduler.call(fn) + + fatal_error = throw_later + + def drain_queue(self, queue): + # type: (deque) -> None + from .promise import Promise + + while queue: + fn = queue.popleft() + if isinstance(fn, Promise): + fn._settle_promises() + continue + fn() + + def drain_queue_until_resolved(self, promise): + # type: (Promise) -> None + from .promise import Promise + + queue = self.normal_queue + while queue: + if not promise.is_pending: + return + fn = queue.popleft() + if isinstance(fn, Promise): + fn._settle_promises() + continue + fn() + + self.reset() + self.have_drained_queues = True + self.drain_queue(self.late_queue) + + def wait(self, promise, timeout=None): + # type: (Promise, Optional[float]) -> None + if not promise.is_pending: + # We return if the promise is already + # fulfilled or rejected + return + + target = promise._target() + + if self.trampoline_enabled: + if self.is_tick_used: + self.drain_queue_until_resolved(target) + + if not promise.is_pending: + # We return if the promise is already + # fulfilled or rejected + return + target.scheduler.wait(target, timeout) + + def drain_queues(self): + # type: () -> None + assert self.is_tick_used + self.drain_queue(self.normal_queue) + self.reset() + self.have_drained_queues = True + self.drain_queue(self.late_queue) + + def queue_tick(self, scheduler): + # type: (Any) -> None + if not self.is_tick_used: + self.is_tick_used = True + scheduler.call(self.drain_queues) + + def reset(self): + # type: () -> None + self.is_tick_used = False diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/compat.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..21b091989858e0588a4dc5e1ad10baa677cd7e0b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/compat.py @@ -0,0 +1,32 @@ +try: + from inspect import iscoroutine +except ImportError: + + def iscoroutine(obj): # type: ignore + return False + + +try: + from asyncio import Future, ensure_future # type: ignore +except ImportError: + + class Future: # type: ignore + def __init__(self): + raise Exception("You need asyncio for using Futures") + + def set_result(self): + raise Exception("You need asyncio for using Futures") + + def set_exception(self): + raise Exception("You need asyncio for using Futures") + + def ensure_future(): # type: ignore + raise Exception("ensure_future needs asyncio for executing") + + +try: + from .iterate_promise import iterate_promise +except (SyntaxError, ImportError): + + def iterate_promise(promise): # type: ignore + raise Exception('You need "yield from" syntax for iterate in a Promise.') diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/dataloader.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/dataloader.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1dd0dd472671749cd26c15bc2fa82cd6facb73 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/dataloader.py @@ -0,0 +1,326 @@ +from collections import namedtuple +try: + from collections.abc import Iterable +except ImportError: + from collections import Iterable +from functools import partial +from threading import local + +from .promise import Promise, async_instance, get_default_scheduler + +if False: + from typing import ( + Any, + List, + Sized, + Callable, + Optional, + Tuple, + Union, + Iterator, + Hashable, + ) # flake8: noqa + + +def get_chunks(iterable_obj, chunk_size=1): + # type: (List[Loader], int) -> Iterator + chunk_size = max(1, chunk_size) + return ( + iterable_obj[i : i + chunk_size] + for i in range(0, len(iterable_obj), chunk_size) + ) + + +Loader = namedtuple("Loader", "key,resolve,reject") + + +class DataLoader(local): + + batch = True + max_batch_size = None # type: int + cache = True + + def __init__( + self, + batch_load_fn=None, # type: Callable + batch=None, # type: Optional[Any] + max_batch_size=None, # type: Optional[int] + cache=None, # type: Optional[Any] + get_cache_key=None, # type: Optional[Any] + cache_map=None, # type: Optional[Any] + scheduler=None, # type: Optional[Any] + ): + # type: (...) -> None + + if batch_load_fn is not None: + self.batch_load_fn = batch_load_fn + + if not callable(self.batch_load_fn): + raise TypeError( + ( + "DataLoader must be have a batch_load_fn which accepts " + "List and returns Promise>, but got: {}." + ).format(batch_load_fn) + ) + + if batch is not None: + self.batch = batch + + if max_batch_size is not None: + self.max_batch_size = max_batch_size + + if cache is not None: + self.cache = cache + + self.get_cache_key = get_cache_key or (lambda x: x) + self._promise_cache = cache_map or {} + self._queue = [] # type: List[Loader] + self._scheduler = scheduler + + def load(self, key=None): + # type: (Hashable) -> Promise + """ + Loads a key, returning a `Promise` for the value represented by that key. + """ + if key is None: + raise TypeError( + ( + "The loader.load() function must be called with a value," + + "but got: {}." + ).format(key) + ) + + cache_key = self.get_cache_key(key) + + # If caching and there is a cache-hit, return cached Promise. + if self.cache: + cached_promise = self._promise_cache.get(cache_key) + if cached_promise: + return cached_promise + + # Otherwise, produce a new Promise for this value. + + promise = Promise(partial(self.do_resolve_reject, key)) # type: ignore + + # If caching, cache this promise. + if self.cache: + self._promise_cache[cache_key] = promise + + return promise + + def do_resolve_reject(self, key, resolve, reject): + # type: (Hashable, Callable, Callable) -> None + # Enqueue this Promise to be dispatched. + self._queue.append(Loader(key=key, resolve=resolve, reject=reject)) + # Determine if a dispatch of this queue should be scheduled. + # A single dispatch should be scheduled per queue at the time when the + # queue changes from "empty" to "full". + if len(self._queue) == 1: + if self.batch: + # If batching, schedule a task to dispatch the queue. + enqueue_post_promise_job(partial(dispatch_queue, self), self._scheduler) + else: + # Otherwise dispatch the (queue of one) immediately. + dispatch_queue(self) + + def load_many(self, keys): + # type: (Iterable[Hashable]) -> Promise + """ + Loads multiple keys, promising an array of values + + >>> a, b = await my_loader.load_many([ 'a', 'b' ]) + + This is equivalent to the more verbose: + + >>> a, b = await Promise.all([ + >>> my_loader.load('a'), + >>> my_loader.load('b') + >>> ]) + """ + if not isinstance(keys, Iterable): + raise TypeError( + ( + "The loader.loadMany() function must be called with Array " + + "but got: {}." + ).format(keys) + ) + + return Promise.all([self.load(key) for key in keys]) + + def clear(self, key): + # type: (Hashable) -> DataLoader + """ + Clears the value at `key` from the cache, if it exists. Returns itself for + method chaining. + """ + cache_key = self.get_cache_key(key) + self._promise_cache.pop(cache_key, None) + return self + + def clear_all(self): + # type: () -> DataLoader + """ + Clears the entire cache. To be used when some event results in unknown + invalidations across this particular `DataLoader`. Returns itself for + method chaining. + """ + self._promise_cache.clear() + return self + + def prime(self, key, value): + # type: (Hashable, Any) -> DataLoader + """ + Adds the provied key and value to the cache. If the key already exists, no + change is made. Returns itself for method chaining. + """ + cache_key = self.get_cache_key(key) + + # Only add the key if it does not already exist. + if cache_key not in self._promise_cache: + # Cache a rejected promise if the value is an Error, in order to match + # the behavior of load(key). + if isinstance(value, Exception): + promise = Promise.reject(value) + else: + promise = Promise.resolve(value) + + self._promise_cache[cache_key] = promise + + return self + + +# Private: Enqueue a Job to be executed after all "PromiseJobs" Jobs. +# +# ES6 JavaScript uses the concepts Job and JobQueue to schedule work to occur +# after the current execution context has completed: +# http://www.ecma-international.org/ecma-262/6.0/#sec-jobs-and-job-queues +# +# Node.js uses the `process.nextTick` mechanism to implement the concept of a +# Job, maintaining a global FIFO JobQueue for all Jobs, which is flushed after +# the current call stack ends. +# +# When calling `then` on a Promise, it enqueues a Job on a specific +# "PromiseJobs" JobQueue which is flushed in Node as a single Job on the +# global JobQueue. +# +# DataLoader batches all loads which occur in a single frame of execution, but +# should include in the batch all loads which occur during the flushing of the +# "PromiseJobs" JobQueue after that same execution frame. +# +# In order to avoid the DataLoader dispatch Job occuring before "PromiseJobs", +# A Promise Job is created with the sole purpose of enqueuing a global Job, +# ensuring that it always occurs after "PromiseJobs" ends. + +# Private: cached resolved Promise instance +cache = local() + +def enqueue_post_promise_job(fn, scheduler): + # type: (Callable, Any) -> None + global cache + if not hasattr(cache, 'resolved_promise'): + cache.resolved_promise = Promise.resolve(None) + if not scheduler: + scheduler = get_default_scheduler() + + def on_promise_resolve(v): + # type: (Any) -> None + async_instance.invoke(fn, scheduler) + + cache.resolved_promise.then(on_promise_resolve) + + +def dispatch_queue(loader): + # type: (DataLoader) -> None + """ + Given the current state of a Loader instance, perform a batch load + from its current queue. + """ + # Take the current loader queue, replacing it with an empty queue. + queue = loader._queue + loader._queue = [] + + # If a maxBatchSize was provided and the queue is longer, then segment the + # queue into multiple batches, otherwise treat the queue as a single batch. + max_batch_size = loader.max_batch_size + + if max_batch_size and max_batch_size < len(queue): + chunks = get_chunks(queue, max_batch_size) + for chunk in chunks: + dispatch_queue_batch(loader, chunk) + else: + dispatch_queue_batch(loader, queue) + + +def dispatch_queue_batch(loader, queue): + # type: (DataLoader, List[Loader]) -> None + # Collect all keys to be loaded in this dispatch + keys = [l.key for l in queue] + + # Call the provided batch_load_fn for this loader with the loader queue's keys. + try: + batch_promise = loader.batch_load_fn(keys) + except Exception as e: + failed_dispatch(loader, queue, e) + return None + + # Assert the expected response from batch_load_fn + if not batch_promise or not isinstance(batch_promise, Promise): + failed_dispatch( + loader, + queue, + TypeError( + ( + "DataLoader must be constructed with a function which accepts " + "Array and returns Promise>, but the function did " + "not return a Promise: {}." + ).format(batch_promise) + ), + ) + return None + + def batch_promise_resolved(values): + # type: (Sized) -> None + # Assert the expected resolution from batchLoadFn. + if not isinstance(values, Iterable): + raise TypeError( + ( + "DataLoader must be constructed with a function which accepts " + "Array and returns Promise>, but the function did " + "not return a Promise of an Array: {}." + ).format(values) + ) + + if len(values) != len(keys): + raise TypeError( + ( + "DataLoader must be constructed with a function which accepts " + "Array and returns Promise>, but the function did " + "not return a Promise of an Array of the same length as the Array " + "of keys." + "\n\nKeys:\n{}" + "\n\nValues:\n{}" + ).format(keys, values) + ) + + # Step through the values, resolving or rejecting each Promise in the + # loaded queue. + for l, value in zip(queue, values): + if isinstance(value, Exception): + l.reject(value) + else: + l.resolve(value) + + batch_promise.then(batch_promise_resolved).catch( + partial(failed_dispatch, loader, queue) + ) + + +def failed_dispatch(loader, queue, error): + # type: (DataLoader, Iterable[Loader], Exception) -> None + """ + Do not cache individual loads if the entire batch dispatch fails, + but still reject each request so they do not hang. + """ + for l in queue: + loader.clear(l.key) + l.reject(error) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/iterate_promise.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/iterate_promise.py new file mode 100644 index 0000000000000000000000000000000000000000..ba64f9c02fb23d0fc2196825a478360e7ab3d941 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/iterate_promise.py @@ -0,0 +1,12 @@ +# flake8: noqa +if False: + from .promise import Promise + from typing import Iterator + + +def iterate_promise(promise): + # type: (Promise) -> Iterator + if not promise.is_fulfilled: + yield from promise.future # type: ignore + assert promise.is_fulfilled + return promise.get() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/promise.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/promise.py new file mode 100644 index 0000000000000000000000000000000000000000..5a8a7b3645e696212d1afaf5908f11fb3e6901de --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/promise.py @@ -0,0 +1,848 @@ +from collections import namedtuple +from functools import partial, wraps +from sys import version_info, exc_info +from threading import RLock +from types import TracebackType +from weakref import WeakKeyDictionary + +from .async_ import Async +from .compat import ( + Future, + ensure_future, + iscoroutine, # type: ignore + iterate_promise, +) # type: ignore +from .utils import deprecated, integer_types, string_types, text_type, binary_type, warn +from .promise_list import PromiseList +from .schedulers.immediate import ImmediateScheduler +from typing import TypeVar, Generic + +# from .schedulers.gevent import GeventScheduler +# from .schedulers.asyncio import AsyncioScheduler +# from .schedulers.thread import ThreadScheduler + +if False: + from typing import ( + Type, + List, + Any, + Callable, + Dict, + Iterator, + Optional, # flake8: noqa + Tuple, + Union, + Generic, + Hashable, + MutableMapping, + ) + + +default_scheduler = ImmediateScheduler() + +async_instance = Async() + + +def get_default_scheduler(): + # type: () -> ImmediateScheduler + return default_scheduler + + +def set_default_scheduler(scheduler): + global default_scheduler + default_scheduler = scheduler + + +IS_PYTHON2 = version_info[0] == 2 +DEFAULT_TIMEOUT = None # type: Optional[float] + +MAX_LENGTH = 0xFFFF | 0 +CALLBACK_SIZE = 3 + +CALLBACK_FULFILL_OFFSET = 0 +CALLBACK_REJECT_OFFSET = 1 +CALLBACK_PROMISE_OFFSET = 2 + +BASE_TYPES = set( + integer_types + + string_types + + (bool, float, complex, tuple, list, dict, text_type, binary_type) +) + +# These are the potential states of a promise +STATE_PENDING = -1 +STATE_REJECTED = 0 +STATE_FULFILLED = 1 + + +def make_self_resolution_error(): + # type: () -> TypeError + return TypeError("Promise is self") + + +def try_catch(handler, *args, **kwargs): + # type: (Callable, Any, Any) -> Union[Tuple[Any, None], Tuple[None, Tuple[Exception, Optional[TracebackType]]]] + try: + return (handler(*args, **kwargs), None) + except Exception as e: + tb = exc_info()[2] + return (None, (e, tb)) + + +T = TypeVar("T") +S = TypeVar("S", contravariant=True) + + +class Promise(Generic[T]): + """ + This is the Promise class that complies + Promises/A+ specification. + """ + + # __slots__ = ('_state', '_is_final', '_is_bound', '_is_following', '_is_async_guaranteed', + # '_length', '_handlers', '_fulfillment_handler0', '_rejection_handler0', '_promise0', + # '_is_waiting', '_future', '_trace', '_event_instance' + # ) + + _state = STATE_PENDING # type: int + _is_final = False + _is_bound = False + _is_following = False + _is_async_guaranteed = False + _length = 0 + _handlers = None # type: Dict[int, Union[Callable, Promise, None]] + _fulfillment_handler0 = None # type: Any + _rejection_handler0 = None # type: Any + _promise0 = None # type: Optional[Promise] + _future = None # type: Future + _traceback = None # type: Optional[TracebackType] + # _trace = None + _is_waiting = False + _scheduler = None + + def __init__(self, executor=None, scheduler=None): + # type: (Optional[Callable[[Callable[[T], None], Callable[[Exception], None]], None]], Any) -> None + """ + Initialize the Promise into a pending state. + """ + # self._state = STATE_PENDING # type: int + # self._is_final = False + # self._is_bound = False + # self._is_following = False + # self._is_async_guaranteed = False + # self._length = 0 + # self._handlers = None # type: Dict[int, Union[Callable, None]] + # self._fulfillment_handler0 = None # type: Union[Callable, partial] + # self._rejection_handler0 = None # type: Union[Callable, partial] + # self._promise0 = None # type: Promise + # self._future = None # type: Future + # self._event_instance = None # type: Event + + # self._is_waiting = False + self._scheduler = scheduler + + if executor is not None: + self._resolve_from_executor(executor) + + # For compatibility reasons + # self.reject = self._deprecated_reject + # self.resolve = self._deprecated_resolve + + @property + def scheduler(self): + # type: () -> ImmediateScheduler + return self._scheduler or default_scheduler + + @property + def future(self): + # type: (Promise) -> Future + if not self._future: + self._future = Future() # type: ignore + self._then( # type: ignore + self._future.set_result, self._future.set_exception + ) + return self._future + + def __iter__(self): + # type: () -> Iterator + return iterate_promise(self._target()) # type: ignore + + __await__ = __iter__ + + @deprecated( + "Rejecting directly in a Promise instance is deprecated, as Promise.reject() is now a class method. " + "Please use promise.do_reject() instead.", + name="reject", + ) + def _deprecated_reject(self, e): + self.do_reject(e) + + @deprecated( + "Resolving directly in a Promise instance is deprecated, as Promise.resolve() is now a class method. " + "Please use promise.do_resolve() instead.", + name="resolve", + ) + def _deprecated_resolve(self, value): + self.do_resolve(value) + + def _resolve_callback(self, value): + # type: (T) -> None + if value is self: + return self._reject_callback(make_self_resolution_error(), False) + + if not self.is_thenable(value): + return self._fulfill(value) + + promise = self._try_convert_to_promise(value)._target() + if promise == self: + self._reject(make_self_resolution_error()) + return + + if promise._state == STATE_PENDING: + len = self._length + if len > 0: + promise._migrate_callback0(self) + for i in range(1, len): + promise._migrate_callback_at(self, i) + + self._is_following = True + self._length = 0 + self._set_followee(promise) + elif promise._state == STATE_FULFILLED: + self._fulfill(promise._value()) + elif promise._state == STATE_REJECTED: + self._reject(promise._reason(), promise._target()._traceback) + + def _settled_value(self, _raise=False): + # type: (bool) -> Any + assert not self._is_following + + if self._state == STATE_FULFILLED: + return self._rejection_handler0 + elif self._state == STATE_REJECTED: + if _raise: + raise_val = self._fulfillment_handler0 + raise raise_val.with_traceback(self._traceback) + return self._fulfillment_handler0 + + def _fulfill(self, value): + # type: (T) -> None + if value is self: + err = make_self_resolution_error() + # self._attach_extratrace(err) + return self._reject(err) + self._state = STATE_FULFILLED + self._rejection_handler0 = value + + if self._length > 0: + if self._is_async_guaranteed: + self._settle_promises() + else: + async_instance.settle_promises(self) + + def _reject(self, reason, traceback=None): + # type: (Exception, Optional[TracebackType]) -> None + self._state = STATE_REJECTED + self._fulfillment_handler0 = reason + self._traceback = traceback + + if self._is_final: + assert self._length == 0 + async_instance.fatal_error(reason, self.scheduler) + return + + if self._length > 0: + async_instance.settle_promises(self) + else: + self._ensure_possible_rejection_handled() + + if self._is_async_guaranteed: + self._settle_promises() + else: + async_instance.settle_promises(self) + + def _ensure_possible_rejection_handled(self): + # type: () -> None + # self._rejection_is_unhandled = True + # async_instance.invoke_later(self._notify_unhandled_rejection, self) + pass + + def _reject_callback(self, reason, synchronous=False, traceback=None): + # type: (Exception, bool, Optional[TracebackType]) -> None + assert isinstance( + reason, Exception + ), "A promise was rejected with a non-error: {}".format(reason) + # trace = ensure_error_object(reason) + # has_stack = trace is reason + # self._attach_extratrace(trace, synchronous and has_stack) + self._reject(reason, traceback) + + def _clear_callback_data_index_at(self, index): + # type: (int) -> None + assert not self._is_following + assert index > 0 + base = index * CALLBACK_SIZE - CALLBACK_SIZE + self._handlers[base + CALLBACK_PROMISE_OFFSET] = None + self._handlers[base + CALLBACK_FULFILL_OFFSET] = None + self._handlers[base + CALLBACK_REJECT_OFFSET] = None + + def _fulfill_promises(self, length, value): + # type: (int, T) -> None + for i in range(1, length): + handler = self._fulfillment_handler_at(i) + promise = self._promise_at(i) + self._clear_callback_data_index_at(i) + self._settle_promise(promise, handler, value, None) + + def _reject_promises(self, length, reason): + # type: (int, Exception) -> None + for i in range(1, length): + handler = self._rejection_handler_at(i) + promise = self._promise_at(i) + self._clear_callback_data_index_at(i) + self._settle_promise(promise, handler, reason, None) + + def _settle_promise( + self, + promise, # type: Optional[Promise] + handler, # type: Optional[Callable] + value, # type: Union[T, Exception] + traceback, # type: Optional[TracebackType] + ): + # type: (...) -> None + assert not self._is_following + is_promise = isinstance(promise, self.__class__) + async_guaranteed = self._is_async_guaranteed + if callable(handler): + if not is_promise: + handler(value) # , promise + else: + if async_guaranteed: + promise._is_async_guaranteed = True # type: ignore + self._settle_promise_from_handler( # type: ignore + handler, value, promise # type: ignore + ) # type: ignore + elif is_promise: + if async_guaranteed: + promise._is_async_guaranteed = True # type: ignore + if self._state == STATE_FULFILLED: + promise._fulfill(value) # type: ignore + else: + promise._reject(value, self._traceback) # type: ignore + + def _settle_promise0( + self, + handler, # type: Optional[Callable] + value, # type: Any + traceback, # type: Optional[TracebackType] + ): + # type: (...) -> None + promise = self._promise0 + self._promise0 = None + self._settle_promise(promise, handler, value, traceback) # type: ignore + + def _settle_promise_from_handler(self, handler, value, promise): + # type: (Callable, Any, Promise) -> None + value, error_with_tb = try_catch(handler, value) # , promise + + if error_with_tb: + error, tb = error_with_tb + promise._reject_callback(error, False, tb) + else: + promise._resolve_callback(value) + + def _promise_at(self, index): + # type: (int) -> Optional[Promise] + assert index > 0 + assert not self._is_following + return self._handlers.get( # type: ignore + index * CALLBACK_SIZE - CALLBACK_SIZE + CALLBACK_PROMISE_OFFSET + ) + + def _fulfillment_handler_at(self, index): + # type: (int) -> Optional[Callable] + assert not self._is_following + assert index > 0 + return self._handlers.get( # type: ignore + index * CALLBACK_SIZE - CALLBACK_SIZE + CALLBACK_FULFILL_OFFSET + ) + + def _rejection_handler_at(self, index): + # type: (int) -> Optional[Callable] + assert not self._is_following + assert index > 0 + return self._handlers.get( # type: ignore + index * CALLBACK_SIZE - CALLBACK_SIZE + CALLBACK_REJECT_OFFSET + ) + + def _migrate_callback0(self, follower): + # type: (Promise) -> None + self._add_callbacks( + follower._fulfillment_handler0, + follower._rejection_handler0, + follower._promise0, + ) + + def _migrate_callback_at(self, follower, index): + self._add_callbacks( + follower._fulfillment_handler_at(index), + follower._rejection_handler_at(index), + follower._promise_at(index), + ) + + def _add_callbacks( + self, + fulfill, # type: Optional[Callable] + reject, # type: Optional[Callable] + promise, # type: Optional[Promise] + ): + # type: (...) -> int + assert not self._is_following + + if self._handlers is None: + self._handlers = {} + + index = self._length + if index > MAX_LENGTH - CALLBACK_SIZE: + index = 0 + self._length = 0 + + if index == 0: + assert not self._promise0 + assert not self._fulfillment_handler0 + assert not self._rejection_handler0 + + self._promise0 = promise + if callable(fulfill): + self._fulfillment_handler0 = fulfill + if callable(reject): + self._rejection_handler0 = reject + + else: + base = index * CALLBACK_SIZE - CALLBACK_SIZE + + assert (base + CALLBACK_PROMISE_OFFSET) not in self._handlers + assert (base + CALLBACK_FULFILL_OFFSET) not in self._handlers + assert (base + CALLBACK_REJECT_OFFSET) not in self._handlers + + self._handlers[base + CALLBACK_PROMISE_OFFSET] = promise + if callable(fulfill): + self._handlers[base + CALLBACK_FULFILL_OFFSET] = fulfill + if callable(reject): + self._handlers[base + CALLBACK_REJECT_OFFSET] = reject + + self._length = index + 1 + return index + + def _target(self): + # type: () -> Promise + ret = self + while ret._is_following: + ret = ret._followee() + return ret + + def _followee(self): + # type: () -> Promise + assert self._is_following + assert isinstance(self._rejection_handler0, Promise) + return self._rejection_handler0 + + def _set_followee(self, promise): + # type: (Promise) -> None + assert self._is_following + assert not isinstance(self._rejection_handler0, Promise) + self._rejection_handler0 = promise + + def _settle_promises(self): + # type: () -> None + length = self._length + if length > 0: + if self._state == STATE_REJECTED: + reason = self._fulfillment_handler0 + traceback = self._traceback + self._settle_promise0(self._rejection_handler0, reason, traceback) + self._reject_promises(length, reason) + else: + value = self._rejection_handler0 + self._settle_promise0(self._fulfillment_handler0, value, None) + self._fulfill_promises(length, value) + + self._length = 0 + + def _resolve_from_executor(self, executor): + # type: (Callable[[Callable[[T], None], Callable[[Exception], None]], None]) -> None + # self._capture_stacktrace() + synchronous = True + + def resolve(value): + # type: (T) -> None + self._resolve_callback(value) + + def reject(reason, traceback=None): + # type: (Exception, TracebackType) -> None + self._reject_callback(reason, synchronous, traceback) + + error = None + traceback = None + try: + executor(resolve, reject) + except Exception as e: + traceback = exc_info()[2] + error = e + + synchronous = False + + if error is not None: + self._reject_callback(error, True, traceback) + + @classmethod + def wait(cls, promise, timeout=None): + # type: (Promise, Optional[float]) -> None + async_instance.wait(promise, timeout) + + def _wait(self, timeout=None): + # type: (Optional[float]) -> None + self.wait(self, timeout) + + def get(self, timeout=None): + # type: (Optional[float]) -> T + target = self._target() + self._wait(timeout or DEFAULT_TIMEOUT) + return self._target_settled_value(_raise=True) + + def _target_settled_value(self, _raise=False): + # type: (bool) -> Any + return self._target()._settled_value(_raise) + + _value = _reason = _target_settled_value + value = reason = property(_target_settled_value) + + def __repr__(self): + # type: () -> str + hex_id = hex(id(self)) + if self._is_following: + return "".format(hex_id, self._target()) + state = self._state + if state == STATE_PENDING: + return "".format(hex_id) + elif state == STATE_FULFILLED: + return "".format( + hex_id, repr(self._rejection_handler0) + ) + elif state == STATE_REJECTED: + return "".format( + hex_id, repr(self._fulfillment_handler0) + ) + + return "" + + @property + def is_pending(self): + # type: (Promise) -> bool + """Indicate whether the Promise is still pending. Could be wrong the moment the function returns.""" + return self._target()._state == STATE_PENDING + + @property + def is_fulfilled(self): + # type: (Promise) -> bool + """Indicate whether the Promise has been fulfilled. Could be wrong the moment the function returns.""" + return self._target()._state == STATE_FULFILLED + + @property + def is_rejected(self): + # type: (Promise) -> bool + """Indicate whether the Promise has been rejected. Could be wrong the moment the function returns.""" + return self._target()._state == STATE_REJECTED + + def catch(self, on_rejection): + # type: (Promise, Callable[[Exception], Any]) -> Promise + """ + This method returns a Promise and deals with rejected cases only. + It behaves the same as calling Promise.then(None, on_rejection). + """ + return self.then(None, on_rejection) + + def _then( + self, + did_fulfill=None, # type: Optional[Callable[[T], S]] + did_reject=None, # type: Optional[Callable[[Exception], S]] + ): + # type: (...) -> Promise[S] + promise = self.__class__() # type: Promise + target = self._target() + + state = target._state + if state == STATE_PENDING: + target._add_callbacks(did_fulfill, did_reject, promise) + else: + traceback = None + if state == STATE_FULFILLED: + value = target._rejection_handler0 + handler = did_fulfill + elif state == STATE_REJECTED: + value = target._fulfillment_handler0 + traceback = target._traceback + handler = did_reject # type: ignore + # target._rejection_is_unhandled = False + async_instance.invoke( + partial(target._settle_promise, promise, handler, value, traceback), + promise.scheduler + # target._settle_promise instead? + # settler, + # target, + ) + + return promise + + fulfill = _resolve_callback + do_resolve = _resolve_callback + do_reject = _reject_callback + + def then(self, did_fulfill=None, did_reject=None): + # type: (Promise, Callable[[T], S], Optional[Callable[[Exception], S]]) -> Promise[S] + """ + This method takes two optional arguments. The first argument + is used if the "self promise" is fulfilled and the other is + used if the "self promise" is rejected. In either case, this + method returns another promise that effectively represents + the result of either the first of the second argument (in the + case that the "self promise" is fulfilled or rejected, + respectively). + Each argument can be either: + * None - Meaning no action is taken + * A function - which will be called with either the value + of the "self promise" or the reason for rejection of + the "self promise". The function may return: + * A value - which will be used to fulfill the promise + returned by this method. + * A promise - which, when fulfilled or rejected, will + cascade its value or reason to the promise returned + by this method. + * A value - which will be assigned as either the value + or the reason for the promise returned by this method + when the "self promise" is either fulfilled or rejected, + respectively. + :type success: (Any) -> object + :type failure: (Any) -> object + :rtype : Promise + """ + return self._then(did_fulfill, did_reject) + + def done(self, did_fulfill=None, did_reject=None): + # type: (Optional[Callable], Optional[Callable]) -> None + promise = self._then(did_fulfill, did_reject) + promise._is_final = True + + def done_all(self, handlers=None): + # type: (Promise, Optional[List[Union[Dict[str, Optional[Callable]], Tuple[Callable, Callable], Callable]]]) -> None + """ + :type handlers: list[(Any) -> object] | list[((Any) -> object, (Any) -> object)] + """ + if not handlers: + return + + for handler in handlers: + if isinstance(handler, tuple): + s, f = handler + self.done(s, f) + elif isinstance(handler, dict): + s = handler.get("success") # type: ignore + f = handler.get("failure") # type: ignore + + self.done(s, f) + else: + self.done(handler) + + def then_all(self, handlers=None): + # type: (Promise, List[Callable]) -> List[Promise] + """ + Utility function which calls 'then' for each handler provided. Handler can either + be a function in which case it is used as success handler, or a tuple containing + the success and the failure handler, where each of them could be None. + :type handlers: list[(Any) -> object] | list[((Any) -> object, (Any) -> object)] + :param handlers + :rtype : list[Promise] + """ + if not handlers: + return [] + + promises = [] # type: List[Promise] + + for handler in handlers: + if isinstance(handler, tuple): + s, f = handler + + promises.append(self.then(s, f)) + elif isinstance(handler, dict): + s = handler.get("success") + f = handler.get("failure") + + promises.append(self.then(s, f)) + else: + promises.append(self.then(handler)) + + return promises + + @classmethod + def _try_convert_to_promise(cls, obj): + # type: (Any) -> Promise + _type = obj.__class__ + if issubclass(_type, Promise): + if cls is not Promise: + return cls(obj.then, obj._scheduler) + return obj + + if iscoroutine(obj): # type: ignore + obj = ensure_future(obj) # type: ignore + _type = obj.__class__ + + if is_future_like(_type): + + def executor(resolve, reject): + # type: (Callable, Callable) -> None + if obj.done(): + _process_future_result(resolve, reject)(obj) + else: + obj.add_done_callback(_process_future_result(resolve, reject)) + # _process_future_result(resolve, reject)(obj) + + promise = cls(executor) # type: Promise + promise._future = obj + return promise + + return obj + + @classmethod + def reject(cls, reason): + # type: (Exception) -> Promise + ret = cls() # type: Promise + # ret._capture_stacktrace(); + # ret._rejectCallback(reason, true); + ret._reject_callback(reason, True) + return ret + + rejected = reject + + @classmethod + def resolve(cls, obj): + # type: (T) -> Promise[T] + if not cls.is_thenable(obj): + ret = cls() # type: Promise + # ret._capture_stacktrace() + ret._state = STATE_FULFILLED + ret._rejection_handler0 = obj + return ret + + return cls._try_convert_to_promise(obj) + + cast = resolve + fulfilled = cast + + @classmethod + def promisify(cls, f): + # type: (Callable) -> Callable[..., Promise] + if not callable(f): + warn( + "Promise.promisify is now a function decorator, please use Promise.resolve instead." + ) + return cls.resolve(f) + + @wraps(f) + def wrapper(*args, **kwargs): + # type: (*Any, **Any) -> Promise + def executor(resolve, reject): + # type: (Callable, Callable) -> Optional[Any] + return resolve(f(*args, **kwargs)) + + return cls(executor) + + return wrapper + + _safe_resolved_promise = None # type: Promise + + @classmethod + def safe(cls, fn): + # type: (Callable) -> Callable + from functools import wraps + + if not cls._safe_resolved_promise: + cls._safe_resolved_promise = Promise.resolve(None) + + @wraps(fn) + def wrapper(*args, **kwargs): + # type: (*Any, **Any) -> Promise + return cls._safe_resolved_promise.then(lambda v: fn(*args, **kwargs)) + + return wrapper + + @classmethod + def all(cls, promises): + # type: (Any) -> Promise + return PromiseList(promises, promise_class=cls).promise + + @classmethod + def for_dict(cls, m): + # type: (Dict[Hashable, Promise[S]]) -> Promise[Dict[Hashable, S]] + """ + A special function that takes a dictionary of promises + and turns them into a promise for a dictionary of values. + In other words, this turns an dictionary of promises for values + into a promise for a dictionary of values. + """ + dict_type = type(m) # type: Type[Dict] + + if not m: + return cls.resolve(dict_type()) # type: ignore + + def handle_success(resolved_values): + # type: (List[S]) -> Dict[Hashable, S] + return dict_type(zip(m.keys(), resolved_values)) + + return cls.all(m.values()).then(handle_success) + + @classmethod + def is_thenable(cls, obj): + # type: (Any) -> bool + """ + A utility function to determine if the specified + object is a promise using "duck typing". + """ + _type = obj.__class__ + if obj is None or _type in BASE_TYPES: + return False + + return ( + issubclass(_type, Promise) + or iscoroutine(obj) # type: ignore + or is_future_like(_type) + ) + + +_type_done_callbacks = WeakKeyDictionary() # type: MutableMapping[type, bool] + + +def is_future_like(_type): + # type: (type) -> bool + if _type not in _type_done_callbacks: + _type_done_callbacks[_type] = callable( + getattr(_type, "add_done_callback", None) + ) + return _type_done_callbacks[_type] + + +promisify = Promise.promisify +promise_for_dict = Promise.for_dict +is_thenable = Promise.is_thenable + + +def _process_future_result(resolve, reject): + # type: (Callable, Callable) -> Callable + def handle_future_result(future): + # type: (Any) -> None + try: + resolve(future.result()) + except Exception as e: + tb = exc_info()[2] + reject(e, tb) + + return handle_future_result diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/pyutils/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/pyutils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/pyutils/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/pyutils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10d48ed1977281d599ea8e9411a80ddd1e4bc3e4 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/pyutils/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/pyutils/version.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/pyutils/version.py new file mode 100644 index 0000000000000000000000000000000000000000..47d439145ed903c0cf8f207c96cf2300917860a4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/pyutils/version.py @@ -0,0 +1,83 @@ +from __future__ import unicode_literals + +import datetime +import os +import subprocess + + +def get_version(version=None): + "Returns a PEP 440-compliant version number from VERSION." + version = get_complete_version(version) + + # Now build the two parts of the version number: + # main = X.Y[.Z] + # sub = .devN - for pre-alpha releases + # | {a|b|rc}N - for alpha, beta, and rc releases + + main = get_main_version(version) + + sub = "" + if version[3] == "alpha" and version[4] == 0: + git_changeset = get_git_changeset() + if git_changeset: + sub = ".dev%s" % git_changeset + else: + sub = ".dev" + elif version[3] != "final": + mapping = {"alpha": "a", "beta": "b", "rc": "rc"} + sub = mapping[version[3]] + str(version[4]) + + return str(main + sub) + + +def get_main_version(version=None): + "Returns main version (X.Y[.Z]) from VERSION." + version = get_complete_version(version) + parts = 2 if version[2] == 0 else 3 + return ".".join(str(x) for x in version[:parts]) + + +def get_complete_version(version=None): + """Returns a tuple of the promise version. If version argument is non-empty, + then checks for correctness of the tuple provided. + """ + if version is None: + from promise import VERSION + + return VERSION + else: + assert len(version) == 5 + assert version[3] in ("alpha", "beta", "rc", "final") + + return version + + +def get_docs_version(version=None): + version = get_complete_version(version) + if version[3] != "final": + return "dev" + else: + return "%d.%d" % version[:2] + + +def get_git_changeset(): + """Returns a numeric identifier of the latest git changeset. + The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format. + This value isn't guaranteed to be unique, but collisions are very unlikely, + so it's sufficient for generating the development version numbers. + """ + repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + try: + git_log = subprocess.Popen( + "git log --pretty=format:%ct --quiet -1 HEAD", + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + shell=True, + cwd=repo_dir, + universal_newlines=True, + ) + timestamp = git_log.communicate()[0] + timestamp = datetime.datetime.utcfromtimestamp(int(timestamp)) + except Exception: + return None + return timestamp.strftime("%Y%m%d%H%M%S") diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/schedulers/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/schedulers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/schedulers/thread.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/schedulers/thread.py new file mode 100644 index 0000000000000000000000000000000000000000..a83f9a0a41f95fc0ed2066cee42d224f1aab8100 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/promise-2.3.0/wandb_promise/schedulers/thread.py @@ -0,0 +1,18 @@ +from threading import Thread, Event + + +class ThreadScheduler(object): + def call(self, fn): + thread = Thread(target=fn) + thread.start() + + def wait(self, promise, timeout=None): + e = Event() + + def on_resolve_or_reject(_): + e.set() + + promise._then(on_resolve_or_reject, on_resolve_or_reject) + waited = e.wait(timeout) + if not waited: + raise Exception("Timeout") diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/pygments/__pycache__/formatter.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/pygments/__pycache__/formatter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef805367f07efd101051e449fa07049ddfeb3760 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/pygments/__pycache__/formatter.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/pygments/__pycache__/modeline.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/pygments/__pycache__/modeline.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6dcd81b55bda486215e4a7502bca91ebcd8b8c2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/pygments/__pycache__/modeline.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/pygments/__pycache__/style.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/pygments/__pycache__/style.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5414515116b05e186897fcb01f8acd1b389610b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/pygments/__pycache__/style.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/pygments/__pycache__/token.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/pygments/__pycache__/token.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..280144b7ed490a9256dcb9800301418f760402ec Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/pygments/__pycache__/token.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/pygments/filters/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/pygments/filters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..45f9608c0afb7c19147f77bc864f2f896edb8a21 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/pygments/filters/__init__.py @@ -0,0 +1,350 @@ +# -*- coding: utf-8 -*- +""" + pygments.filters + ~~~~~~~~~~~~~~~~ + + Module containing filter lookup functions and default + filters. + + :copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import re + +from pygments.token import String, Comment, Keyword, Name, Error, Whitespace, \ + string_to_tokentype +from pygments.filter import Filter +from pygments.util import get_list_opt, get_int_opt, get_bool_opt, \ + get_choice_opt, ClassNotFound, OptionError, text_type, string_types +from pygments.plugin import find_plugin_filters + + +def find_filter_class(filtername): + """Lookup a filter by name. Return None if not found.""" + if filtername in FILTERS: + return FILTERS[filtername] + for name, cls in find_plugin_filters(): + if name == filtername: + return cls + return None + + +def get_filter_by_name(filtername, **options): + """Return an instantiated filter. + + Options are passed to the filter initializer if wanted. + Raise a ClassNotFound if not found. + """ + cls = find_filter_class(filtername) + if cls: + return cls(**options) + else: + raise ClassNotFound('filter %r not found' % filtername) + + +def get_all_filters(): + """Return a generator of all filter names.""" + for name in FILTERS: + yield name + for name, _ in find_plugin_filters(): + yield name + + +def _replace_special(ttype, value, regex, specialttype, + replacefunc=lambda x: x): + last = 0 + for match in regex.finditer(value): + start, end = match.start(), match.end() + if start != last: + yield ttype, value[last:start] + yield specialttype, replacefunc(value[start:end]) + last = end + if last != len(value): + yield ttype, value[last:] + + +class CodeTagFilter(Filter): + """Highlight special code tags in comments and docstrings. + + Options accepted: + + `codetags` : list of strings + A list of strings that are flagged as code tags. The default is to + highlight ``XXX``, ``TODO``, ``BUG`` and ``NOTE``. + """ + + def __init__(self, **options): + Filter.__init__(self, **options) + tags = get_list_opt(options, 'codetags', + ['XXX', 'TODO', 'BUG', 'NOTE']) + self.tag_re = re.compile(r'\b(%s)\b' % '|'.join([ + re.escape(tag) for tag in tags if tag + ])) + + def filter(self, lexer, stream): + regex = self.tag_re + for ttype, value in stream: + if ttype in String.Doc or \ + ttype in Comment and \ + ttype not in Comment.Preproc: + for sttype, svalue in _replace_special(ttype, value, regex, + Comment.Special): + yield sttype, svalue + else: + yield ttype, value + + +class KeywordCaseFilter(Filter): + """Convert keywords to lowercase or uppercase or capitalize them, which + means first letter uppercase, rest lowercase. + + This can be useful e.g. if you highlight Pascal code and want to adapt the + code to your styleguide. + + Options accepted: + + `case` : string + The casing to convert keywords to. Must be one of ``'lower'``, + ``'upper'`` or ``'capitalize'``. The default is ``'lower'``. + """ + + def __init__(self, **options): + Filter.__init__(self, **options) + case = get_choice_opt(options, 'case', + ['lower', 'upper', 'capitalize'], 'lower') + self.convert = getattr(text_type, case) + + def filter(self, lexer, stream): + for ttype, value in stream: + if ttype in Keyword: + yield ttype, self.convert(value) + else: + yield ttype, value + + +class NameHighlightFilter(Filter): + """Highlight a normal Name (and Name.*) token with a different token type. + + Example:: + + filter = NameHighlightFilter( + names=['foo', 'bar', 'baz'], + tokentype=Name.Function, + ) + + This would highlight the names "foo", "bar" and "baz" + as functions. `Name.Function` is the default token type. + + Options accepted: + + `names` : list of strings + A list of names that should be given the different token type. + There is no default. + `tokentype` : TokenType or string + A token type or a string containing a token type name that is + used for highlighting the strings in `names`. The default is + `Name.Function`. + """ + + def __init__(self, **options): + Filter.__init__(self, **options) + self.names = set(get_list_opt(options, 'names', [])) + tokentype = options.get('tokentype') + if tokentype: + self.tokentype = string_to_tokentype(tokentype) + else: + self.tokentype = Name.Function + + def filter(self, lexer, stream): + for ttype, value in stream: + if ttype in Name and value in self.names: + yield self.tokentype, value + else: + yield ttype, value + + +class ErrorToken(Exception): + pass + + +class RaiseOnErrorTokenFilter(Filter): + """Raise an exception when the lexer generates an error token. + + Options accepted: + + `excclass` : Exception class + The exception class to raise. + The default is `pygments.filters.ErrorToken`. + + .. versionadded:: 0.8 + """ + + def __init__(self, **options): + Filter.__init__(self, **options) + self.exception = options.get('excclass', ErrorToken) + try: + # issubclass() will raise TypeError if first argument is not a class + if not issubclass(self.exception, Exception): + raise TypeError + except TypeError: + raise OptionError('excclass option is not an exception class') + + def filter(self, lexer, stream): + for ttype, value in stream: + if ttype is Error: + raise self.exception(value) + yield ttype, value + + +class VisibleWhitespaceFilter(Filter): + """Convert tabs, newlines and/or spaces to visible characters. + + Options accepted: + + `spaces` : string or bool + If this is a one-character string, spaces will be replaces by this string. + If it is another true value, spaces will be replaced by ``·`` (unicode + MIDDLE DOT). If it is a false value, spaces will not be replaced. The + default is ``False``. + `tabs` : string or bool + The same as for `spaces`, but the default replacement character is ``»`` + (unicode RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK). The default value + is ``False``. Note: this will not work if the `tabsize` option for the + lexer is nonzero, as tabs will already have been expanded then. + `tabsize` : int + If tabs are to be replaced by this filter (see the `tabs` option), this + is the total number of characters that a tab should be expanded to. + The default is ``8``. + `newlines` : string or bool + The same as for `spaces`, but the default replacement character is ``¶`` + (unicode PILCROW SIGN). The default value is ``False``. + `wstokentype` : bool + If true, give whitespace the special `Whitespace` token type. This allows + styling the visible whitespace differently (e.g. greyed out), but it can + disrupt background colors. The default is ``True``. + + .. versionadded:: 0.8 + """ + + def __init__(self, **options): + Filter.__init__(self, **options) + for name, default in [('spaces', u'·'), + ('tabs', u'»'), + ('newlines', u'¶')]: + opt = options.get(name, False) + if isinstance(opt, string_types) and len(opt) == 1: + setattr(self, name, opt) + else: + setattr(self, name, (opt and default or '')) + tabsize = get_int_opt(options, 'tabsize', 8) + if self.tabs: + self.tabs += ' ' * (tabsize - 1) + if self.newlines: + self.newlines += '\n' + self.wstt = get_bool_opt(options, 'wstokentype', True) + + def filter(self, lexer, stream): + if self.wstt: + spaces = self.spaces or u' ' + tabs = self.tabs or u'\t' + newlines = self.newlines or u'\n' + regex = re.compile(r'\s') + def replacefunc(wschar): + if wschar == ' ': + return spaces + elif wschar == '\t': + return tabs + elif wschar == '\n': + return newlines + return wschar + + for ttype, value in stream: + for sttype, svalue in _replace_special(ttype, value, regex, + Whitespace, replacefunc): + yield sttype, svalue + else: + spaces, tabs, newlines = self.spaces, self.tabs, self.newlines + # simpler processing + for ttype, value in stream: + if spaces: + value = value.replace(' ', spaces) + if tabs: + value = value.replace('\t', tabs) + if newlines: + value = value.replace('\n', newlines) + yield ttype, value + + +class GobbleFilter(Filter): + """Gobbles source code lines (eats initial characters). + + This filter drops the first ``n`` characters off every line of code. This + may be useful when the source code fed to the lexer is indented by a fixed + amount of space that isn't desired in the output. + + Options accepted: + + `n` : int + The number of characters to gobble. + + .. versionadded:: 1.2 + """ + def __init__(self, **options): + Filter.__init__(self, **options) + self.n = get_int_opt(options, 'n', 0) + + def gobble(self, value, left): + if left < len(value): + return value[left:], 0 + else: + return u'', left - len(value) + + def filter(self, lexer, stream): + n = self.n + left = n # How many characters left to gobble. + for ttype, value in stream: + # Remove ``left`` tokens from first line, ``n`` from all others. + parts = value.split('\n') + (parts[0], left) = self.gobble(parts[0], left) + for i in range(1, len(parts)): + (parts[i], left) = self.gobble(parts[i], n) + value = u'\n'.join(parts) + + if value != '': + yield ttype, value + + +class TokenMergeFilter(Filter): + """Merges consecutive tokens with the same token type in the output + stream of a lexer. + + .. versionadded:: 1.2 + """ + def __init__(self, **options): + Filter.__init__(self, **options) + + def filter(self, lexer, stream): + current_type = None + current_value = None + for ttype, value in stream: + if ttype is current_type: + current_value += value + else: + if current_type is not None: + yield current_type, current_value + current_type = ttype + current_value = value + if current_type is not None: + yield current_type, current_value + + +FILTERS = { + 'codetagify': CodeTagFilter, + 'keywordcase': KeywordCaseFilter, + 'highlight': NameHighlightFilter, + 'raiseonerror': RaiseOnErrorTokenFilter, + 'whitespace': VisibleWhitespaceFilter, + 'gobble': GobbleFilter, + 'tokenmerge': TokenMergeFilter, +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/pygments/formatters/html.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/pygments/formatters/html.py new file mode 100644 index 0000000000000000000000000000000000000000..2969d5026381e3d0acc21dae985ee24ef56223eb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/wandb/vendor/pygments/formatters/html.py @@ -0,0 +1,851 @@ +# -*- coding: utf-8 -*- +""" + pygments.formatters.html + ~~~~~~~~~~~~~~~~~~~~~~~~ + + Formatter for HTML output. + + :copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from __future__ import print_function + +import os +import sys +import os.path + +from pygments.formatter import Formatter +from pygments.token import Token, Text, STANDARD_TYPES +from pygments.util import get_bool_opt, get_int_opt, get_list_opt, \ + StringIO, string_types, iteritems + +try: + import ctags +except ImportError: + ctags = None + +__all__ = ['HtmlFormatter'] + + +_escape_html_table = { + ord('&'): u'&', + ord('<'): u'<', + ord('>'): u'>', + ord('"'): u'"', + ord("'"): u''', +} + + +def escape_html(text, table=_escape_html_table): + """Escape &, <, > as well as single and double quotes for HTML.""" + return text.translate(table) + + +def _get_ttype_class(ttype): + fname = STANDARD_TYPES.get(ttype) + if fname: + return fname + aname = '' + while fname is None: + aname = '-' + ttype[-1] + aname + ttype = ttype.parent + fname = STANDARD_TYPES.get(ttype) + return fname + aname + + +CSSFILE_TEMPLATE = '''\ +td.linenos { background-color: #f0f0f0; padding-right: 10px; } +span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; } +pre { line-height: 125%%; } +%(styledefs)s +''' + +DOC_HEADER = '''\ + + + + + %(title)s + + + + +

%(title)s

+ +''' + +DOC_HEADER_EXTERNALCSS = '''\ + + + + + %(title)s + + + + +

%(title)s

+ +''' + +DOC_FOOTER = '''\ + + +''' + + +class HtmlFormatter(Formatter): + r""" + Format tokens as HTML 4 ```` tags within a ``
`` tag, wrapped
+    in a ``
`` tag. The ``
``'s CSS class can be set by the `cssclass` + option. + + If the `linenos` option is set to ``"table"``, the ``
`` is
+    additionally wrapped inside a ``
`` which has one row and two + cells: one containing the line numbers and one containing the code. + Example: + + .. sourcecode:: html + +
+
+ + +
+
1
+            2
+
+
def foo(bar):
+              pass
+            
+
+ + (whitespace added to improve clarity). + + Wrapping can be disabled using the `nowrap` option. + + A list of lines can be specified using the `hl_lines` option to make these + lines highlighted (as of Pygments 0.11). + + With the `full` option, a complete HTML 4 document is output, including + the style definitions inside a ``