| 363 | } |
| 364 | |
| 365 | bool NativeHead::gather_rows(const int32_t* vocab_host, int64_t n_rows, int dst_dev, uint8_t* dst, std::string& err) const { |
| 366 | if (!is_split() || vocab_host == nullptr || n_rows <= 0 || dst == nullptr) { |
| 367 | err = "native head gather_rows: split head not active or invalid arguments"; |
| 368 | return false; |
| 369 | } |
| 370 | const size_t rb = row_bytes(); |
| 371 | std::vector<int32_t> id0, id1; |
| 372 | std::vector<int64_t> pos0, pos1; |
| 373 | id0.reserve((size_t) n_rows); |
| 374 | id1.reserve((size_t) n_rows); |
| 375 | pos0.reserve((size_t) n_rows); |
| 376 | pos1.reserve((size_t) n_rows); |
| 377 | for (int64_t i = 0; i < n_rows; ++i) { |
| 378 | const int32_t id = vocab_host[i]; |
| 379 | if (id < 0 || id >= n_out_) { |
| 380 | err = "native head gather_rows: vocabulary id out of range"; |
| 381 | return false; |
| 382 | } |
| 383 | if (id < split_rows0_) { |
| 384 | id0.push_back(id); |
| 385 | pos0.push_back(i); |
| 386 | } else { |
| 387 | id1.push_back(id - split_rows0_); |
| 388 | pos1.push_back(i); |
| 389 | } |
| 390 | } |
| 391 | auto gather_half = [&](int dev, const void* wsrc, const std::vector<int32_t>& ids, const std::vector<int64_t>& pos, |
| 392 | std::vector<uint8_t>& h_dst) -> bool { |
| 393 | if (ids.empty()) return true; |
| 394 | ScopedDev on_dev(dev); |
| 395 | int32_t* dv = nullptr; |
| 396 | uint8_t* tmp = nullptr; |
| 397 | const size_t bytes = ids.size() * rb; |
| 398 | if (cudaMalloc((void**) &dv, ids.size() * sizeof(int32_t)) != cudaSuccess || |
| 399 | cudaMalloc((void**) &tmp, bytes) != cudaSuccess) { |
| 400 | if (dv) cudaFree(dv); |
| 401 | if (tmp) cudaFree(tmp); |
| 402 | (void) cudaGetLastError(); |
| 403 | err = "native head gather_rows: device temporary allocation failed"; |
| 404 | return false; |
| 405 | } |
| 406 | std::vector<uint8_t> h_tmp(bytes); |
| 407 | const bool ok = cudaMemcpy(dv, ids.data(), ids.size() * sizeof(int32_t), cudaMemcpyHostToDevice) == cudaSuccess; |
| 408 | if (ok) { |
| 409 | strata::kernels::gather_rows((const uint8_t*) wsrc, (int64_t) rb, dv, (int64_t) ids.size(), tmp, nullptr); |
| 410 | } |
| 411 | const bool ok2 = ok && cudaDeviceSynchronize() == cudaSuccess && |
| 412 | cudaMemcpy(h_tmp.data(), tmp, bytes, cudaMemcpyDeviceToHost) == cudaSuccess; |
| 413 | cudaFree(dv); |
| 414 | cudaFree(tmp); |
| 415 | if (!ok2) { |
| 416 | (void) cudaGetLastError(); |
| 417 | err = "native head gather_rows: device gather failed"; |
| 418 | return false; |
| 419 | } |
| 420 | for (size_t k = 0; k < ids.size(); ++k) |
| 421 | std::memcpy(h_dst.data() + (size_t) pos[k] * rb, h_tmp.data() + k * rb, rb); |
| 422 | return true; |
no test coverage detected