| 219 | } |
| 220 | |
| 221 | bool make_cache_complement_plan( |
| 222 | int64_t n_layers, int64_t n_expert, const std::vector<uint64_t>& layer_blob_bytes, |
| 223 | const std::vector<std::pair<int32_t, int32_t>>& primary_gpu_pairs, |
| 224 | const std::vector<std::pair<int32_t, int32_t>>& additional_gpu_pairs, |
| 225 | std::vector<uint64_t>& offsets, uint64_t& bytes, std::string& err) { |
| 226 | offsets.clear(); |
| 227 | bytes = 0; |
| 228 | err.clear(); |
| 229 | if (n_layers <= 0 || n_expert <= 0 || layer_blob_bytes.size() != (size_t) n_layers) { |
| 230 | err = "FileExpertSource: invalid geometry for the cache complement plan"; |
| 231 | return false; |
| 232 | } |
| 233 | if ((uint64_t) n_layers > (uint64_t) std::numeric_limits<size_t>::max() / (uint64_t) n_expert) { |
| 234 | err = "FileExpertSource: cache complement index table is too large"; |
| 235 | return false; |
| 236 | } |
| 237 | const size_t count = (size_t) n_layers * (size_t) n_expert; |
| 238 | std::vector<uint8_t> omitted(count, 0); |
| 239 | auto mark_pairs = [&](const std::vector<std::pair<int32_t, int32_t>>& pairs, uint8_t bit, |
| 240 | const char* label) -> bool { |
| 241 | for (const auto& pair : pairs) { |
| 242 | if (pair.first < 0 || pair.second < 0 || pair.first >= n_layers || pair.second >= n_expert) { |
| 243 | err = std::string("FileExpertSource: ") + label + " pair is outside the expert geometry"; |
| 244 | return false; |
| 245 | } |
| 246 | const size_t index = (size_t) pair.first * (size_t) n_expert + (size_t) pair.second; |
| 247 | if ((omitted[index] & bit) != 0) { |
| 248 | err = std::string("FileExpertSource: duplicate ") + label + " pair in the cache complement plan"; |
| 249 | return false; |
| 250 | } |
| 251 | if (bit == 2 && (omitted[index] & 1) != 0) { |
| 252 | err = "FileExpertSource: the primary and additional GPU expert tiers overlap"; |
| 253 | return false; |
| 254 | } |
| 255 | omitted[index] |= bit; |
| 256 | } |
| 257 | return true; |
| 258 | }; |
| 259 | if (!mark_pairs(primary_gpu_pairs, 1, "primary GPU") || |
| 260 | !mark_pairs(additional_gpu_pairs, 2, "additional GPU")) return false; |
| 261 | for (uint64_t blob_bytes : layer_blob_bytes) { |
| 262 | if (blob_bytes == 0) { |
| 263 | err = "FileExpertSource: cache complement layer has zero-sized expert blobs"; |
| 264 | return false; |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | offsets.assign(count, kNoCacheComplement); |
| 269 | for (int64_t layer = 0; layer < n_layers; ++layer) { |
| 270 | const uint64_t blob_bytes = layer_blob_bytes[(size_t) layer]; |
| 271 | for (int64_t expert = 0; expert < n_expert; ++expert) { |
| 272 | const size_t index = (size_t) layer * (size_t) n_expert + (size_t) expert; |
| 273 | if (omitted[index] != 0) continue; |
| 274 | if (bytes > std::numeric_limits<uint64_t>::max() - blob_bytes) { |
| 275 | offsets.clear(); |
| 276 | bytes = 0; |
| 277 | err = "FileExpertSource: cache complement size overflows"; |
| 278 | return false; |