| 95 | } |
| 96 | |
| 97 | bool make_cache_complement_plan( |
| 98 | int64_t n_layers, int64_t n_expert, const std::vector<uint64_t>& layer_blob_bytes, |
| 99 | const std::vector<std::pair<int32_t, int32_t>>& primary_gpu_pairs, |
| 100 | const std::vector<std::pair<int32_t, int32_t>>& additional_gpu_pairs, |
| 101 | std::vector<uint64_t>& offsets, uint64_t& bytes, std::string& err) { |
| 102 | offsets.clear(); |
| 103 | bytes = 0; |
| 104 | err.clear(); |
| 105 | if (n_layers <= 0 || n_expert <= 0 || layer_blob_bytes.size() != (size_t) n_layers) { |
| 106 | err = "FileExpertSource: invalid geometry for the cache complement plan"; |
| 107 | return false; |
| 108 | } |
| 109 | if ((uint64_t) n_layers > (uint64_t) std::numeric_limits<size_t>::max() / (uint64_t) n_expert) { |
| 110 | err = "FileExpertSource: cache complement index table is too large"; |
| 111 | return false; |
| 112 | } |
| 113 | const size_t count = (size_t) n_layers * (size_t) n_expert; |
| 114 | std::vector<uint8_t> omitted(count, 0); |
| 115 | auto mark_pairs = [&](const std::vector<std::pair<int32_t, int32_t>>& pairs, uint8_t bit, |
| 116 | const char* label) -> bool { |
| 117 | for (const auto& pair : pairs) { |
| 118 | if (pair.first < 0 || pair.second < 0 || pair.first >= n_layers || pair.second >= n_expert) { |
| 119 | err = std::string("FileExpertSource: ") + label + " pair is outside the expert geometry"; |
| 120 | return false; |
| 121 | } |
| 122 | const size_t index = (size_t) pair.first * (size_t) n_expert + (size_t) pair.second; |
| 123 | if ((omitted[index] & bit) != 0) { |
| 124 | err = std::string("FileExpertSource: duplicate ") + label + " pair in the cache complement plan"; |
| 125 | return false; |
| 126 | } |
| 127 | if (bit == 2 && (omitted[index] & 1) != 0) { |
| 128 | err = "FileExpertSource: the primary and additional GPU expert tiers overlap"; |
| 129 | return false; |
| 130 | } |
| 131 | omitted[index] |= bit; |
| 132 | } |
| 133 | return true; |
| 134 | }; |
| 135 | if (!mark_pairs(primary_gpu_pairs, 1, "primary GPU") || |
| 136 | !mark_pairs(additional_gpu_pairs, 2, "additional GPU")) return false; |
| 137 | for (uint64_t blob_bytes : layer_blob_bytes) { |
| 138 | if (blob_bytes == 0) { |
| 139 | err = "FileExpertSource: cache complement layer has zero-sized expert blobs"; |
| 140 | return false; |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | offsets.assign(count, kNoCacheComplement); |
| 145 | for (int64_t layer = 0; layer < n_layers; ++layer) { |
| 146 | const uint64_t blob_bytes = layer_blob_bytes[(size_t) layer]; |
| 147 | for (int64_t expert = 0; expert < n_expert; ++expert) { |
| 148 | const size_t index = (size_t) layer * (size_t) n_expert + (size_t) expert; |
| 149 | if (omitted[index] != 0) continue; |
| 150 | if (bytes > std::numeric_limits<uint64_t>::max() - blob_bytes) { |
| 151 | offsets.clear(); |
| 152 | bytes = 0; |
| 153 | err = "FileExpertSource: cache complement size overflows"; |
| 154 | return false; |