diff --git a/libopenbuenos/src/ob_buffer_pool.cpp b/libopenbuenos/src/ob_buffer_pool.cpp index 921b2350..5cc8055c 100644 --- a/libopenbuenos/src/ob_buffer_pool.cpp +++ b/libopenbuenos/src/ob_buffer_pool.cpp @@ -57,6 +57,9 @@ size_t compute_slab_size(size_t requested) { while (s < requested) s <<= 1u; return s; } + // Page-align without wrapping. requested > SIZE_MAX-4095 makes the old + // (requested+4095) sum collapse to a 0-byte slab that posix_memalign accepts. + if (requested > (SIZE_MAX - 4095u)) return 0u; return (requested + 4095u) & ~static_cast(4095u); } @@ -311,6 +314,10 @@ ob_status_t ob_buffer_alloc(ob_context_t* ctx, *out_buf = nullptr; const size_t slab_size = ob::compute_slab_size(size_bytes); + if (slab_size < size_bytes) { + ob::set_last_error(ctx, "buffer size overflow during slab rounding"); + return OB_ERR_OVERFLOW; + } // Always map bidirectional when pooled so any future caller can reuse the slab safely. const uint32_t map_flags = (flags & OB_BUF_NO_POOL) diff --git a/libopenbuenos/src/ob_dgc0.cpp b/libopenbuenos/src/ob_dgc0.cpp index 32dcd6c4..01abc9f6 100644 --- a/libopenbuenos/src/ob_dgc0.cpp +++ b/libopenbuenos/src/ob_dgc0.cpp @@ -215,8 +215,20 @@ ob_status_t parse_dgc0_buffer(const uint8_t* data, size_t size, dws.i32_vector_field(tp, 0, &dims); uint8_t dt = dws.field_u8(tp, 1, 2); uint64_t bytes = darwinn_dtype_bytes(dt); + bool scratch_overflow = false; for (int32_t d : dims) { - if (d > 0) bytes *= static_cast(d); + if (d <= 0) continue; + const uint64_t factor = static_cast(d); + if (factor != 0u && bytes > (UINT64_MAX / factor)) { + scratch_overflow = true; + break; + } + bytes *= factor; + } + if (scratch_overflow) { + out->dive_scratch_size = 0u; + if (err) *err = "DGC0 scratchpad dimension product overflows"; + return OB_ERR_OVERFLOW; } if (bytes > out->dive_scratch_size) out->dive_scratch_size = bytes; } diff --git a/libopenbuenos/src/ob_worker_pool.cpp b/libopenbuenos/src/ob_worker_pool.cpp index e566fa2a..8bd76a83 100644 --- a/libopenbuenos/src/ob_worker_pool.cpp +++ b/libopenbuenos/src/ob_worker_pool.cpp @@ -74,6 +74,34 @@ inline void cpu_yield_hint() { #endif } +uint32_t ceil_div_u32(uint32_t n, uint32_t d) { + if (d == 0u) return 0u; + const uint32_t q = n / d; + if ((n % d) == 0u || q == UINT32_MAX) return q; + return q + 1u; +} + +// Publish the next unclaimed index without wrapping next_item back into [0, total). +// fetch_add(step) on a uint32 cursor does that once s+step exceeds 2^32, and the +// following worker then reissues ranges that already ran. +uint32_t claim_work_start(std::atomic& next_item, uint32_t step, uint32_t total) { + uint32_t s = next_item.load(std::memory_order_relaxed); + for (;;) { + if (s >= total) return s; + const uint32_t n = (step == 0u || step >= total || s > total - step) ? total : (s + step); + if (next_item.compare_exchange_weak(s, n, std::memory_order_relaxed, + std::memory_order_relaxed)) { + return s; + } + } +} + +uint32_t claim_work_end(uint32_t s, uint32_t step, uint32_t total) { + if (s >= total) return s; + if (step == 0u || step >= total || s > total - step) return total; + return s + step; +} + struct WorkerLaunchArg { WorkerPool* pool = nullptr; uint32_t worker_idx = 0u; @@ -115,10 +143,9 @@ void* worker_thread_main(void* raw) { if (fn != nullptr) { for (;;) { - const uint32_t s = p->next_item.fetch_add(step, std::memory_order_relaxed); + const uint32_t s = claim_work_start(p->next_item, step, total); if (s >= total) break; - const uint32_t e = (s + step < total) ? (s + step) : total; - fn(arg, s, e, tid); + fn(arg, s, claim_work_end(s, step, total), tid); } if (p->workers_remaining.fetch_sub(1u, std::memory_order_acq_rel) == 1u) { pthread_mutex_lock(&p->mu); @@ -196,7 +223,7 @@ void WorkerPool::parallel_for(uint32_t total, uint32_t min_chunk, TaskFn fn, voi } } - const uint32_t max_useful = (total + min_chunk - 1u) / min_chunk; + const uint32_t max_useful = ceil_div_u32(total, min_chunk); const uint32_t active_threads = std::min(num_threads, max_useful); if (active_threads <= 1u) { fn(arg, 0u, total, 0u); @@ -206,7 +233,7 @@ void WorkerPool::parallel_for(uint32_t total, uint32_t min_chunk, TaskFn fn, voi const uint32_t active_workers = active_threads - 1u; // Work-stealing granularity (~4 chunks/thread) balances heterogeneous ARM64 big+mid cores. const uint32_t target_chunks = active_threads * 4u; - const uint32_t step = std::max(min_chunk, (total + target_chunks - 1u) / target_chunks); + const uint32_t step = std::max(min_chunk, ceil_div_u32(total, target_chunks)); pthread_mutex_lock(&mu); cur_fn = fn; @@ -222,10 +249,9 @@ void WorkerPool::parallel_for(uint32_t total, uint32_t min_chunk, TaskFn fn, voi // Main thread participates as tid=0 for (;;) { - const uint32_t s = next_item.fetch_add(step, std::memory_order_relaxed); + const uint32_t s = claim_work_start(next_item, step, total); if (s >= total) break; - const uint32_t e = (s + step < total) ? (s + step) : total; - fn(arg, s, e, 0u); + fn(arg, s, claim_work_end(s, step, total), 0u); } // Brief bounded yield spin (~25 us) before sleeping on done_cv to avoid futex wakeup jitter diff --git a/libopenbuenos/tests/openbuenos_pool_guards_test.cpp b/libopenbuenos/tests/openbuenos_pool_guards_test.cpp new file mode 100644 index 00000000..bfc754b9 --- /dev/null +++ b/libopenbuenos/tests/openbuenos_pool_guards_test.cpp @@ -0,0 +1,346 @@ +// Host-only guards for buffer-pool slab rounding, worker-pool range claims, +// and DGC0 scratchpad dimension products. No device access. + +#include "ob_internal.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +int g_fails = 0; + +void check(bool cond, const char* expr, int line) { + if (!cond) { + std::fprintf(stderr, "FAIL %s:%d %s\n", "openbuenos_pool_guards_test.cpp", line, expr); + ++g_fails; + } +} + +#define CHECK(cond) check(static_cast(cond), #cond, __LINE__) + +// Back-to-front FlatBuffer writer sufficient to build a minimal DGC0/DWS0 nest. +class MiniFb { + public: + uint32_t pos() const { return static_cast(buf_.size()); } + + void pad(size_t n) { buf_.insert(buf_.end(), n, 0u); } + + void prep(size_t align, size_t additional_bytes = 0u) { + if (align > minalign_) minalign_ = align; + const size_t align_size = (~(buf_.size() + additional_bytes) + 1u) & (align - 1u); + pad(align_size); + } + + void push_bytes_rev(const void* data, size_t len) { + const auto* p = static_cast(data); + for (size_t i = len; i > 0u; --i) buf_.push_back(p[i - 1u]); + } + + void push_u8(uint8_t v) { + prep(1u); + buf_.push_back(v); + } + + void push_u32(uint32_t v) { + prep(4u); + push_bytes_rev(&v, sizeof(v)); + } + + void push_i32(int32_t v) { + prep(4u); + push_bytes_rev(&v, sizeof(v)); + } + + void push_u64(uint64_t v) { + prep(8u); + push_bytes_rev(&v, sizeof(v)); + } + + void push_uoffset(uint32_t target_off) { + prep(4u); + const uint32_t rel = pos() - target_off + 4u; + push_bytes_rev(&rel, sizeof(rel)); + } + + uint32_t create_vector_bytes(const uint8_t* data, size_t len) { + prep(4u, len); + if (len > 0u && data) push_bytes_rev(data, len); + push_u32(static_cast(len)); + return pos(); + } + + uint32_t create_vector_i32(const int32_t* vals, size_t count) { + prep(4u, count * 4u); + for (size_t i = count; i > 0u; --i) push_i32(vals[i - 1u]); + push_u32(static_cast(count)); + return pos(); + } + + uint32_t create_vector_uoffsets(const uint32_t* offs, size_t count) { + prep(4u, count * 4u); + for (size_t i = count; i > 0u; --i) push_uoffset(offs[i - 1u]); + push_u32(static_cast(count)); + return pos(); + } + + void start_table() { + cur_fields_.clear(); + table_start_ = pos(); + } + + void add_u8(uint16_t slot, uint8_t v) { + push_u8(v); + cur_fields_.push_back({slot, pos()}); + } + + void add_u64(uint16_t slot, uint64_t v, uint32_t* from_end) { + push_u64(v); + const uint32_t p = pos(); + cur_fields_.push_back({slot, p}); + if (from_end) *from_end = p; + } + + void add_uoffset(uint16_t slot, uint32_t off) { + if (off == 0u) return; + push_uoffset(off); + cur_fields_.push_back({slot, pos()}); + } + + uint32_t end_table() { + push_i32(0); + const uint32_t table_off = pos(); + int32_t max_slot = -1; + for (const auto& f : cur_fields_) { + if (static_cast(f.first) > max_slot) max_slot = static_cast(f.first); + } + const size_t nslots = (max_slot >= 0) ? static_cast(max_slot + 1) : 0u; + const uint16_t obj_size = static_cast(table_off - table_start_); + const uint16_t vt_size = static_cast(4u + 2u * nslots); + std::vector vt_bytes(vt_size, 0u); + std::memcpy(vt_bytes.data(), &vt_size, 2u); + std::memcpy(vt_bytes.data() + 2u, &obj_size, 2u); + for (const auto& f : cur_fields_) { + const uint16_t rel = static_cast(table_off - f.second); + std::memcpy(vt_bytes.data() + 4u + static_cast(f.first) * 2u, &rel, 2u); + } + prep(2u, vt_bytes.size()); + push_bytes_rev(vt_bytes.data(), vt_bytes.size()); + const uint32_t vt_off = pos(); + const int32_t soff = static_cast(vt_off) - static_cast(table_off); + const auto* sp = reinterpret_cast(&soff); + buf_[table_off - 4u] = sp[3]; + buf_[table_off - 3u] = sp[2]; + buf_[table_off - 2u] = sp[1]; + buf_[table_off - 1u] = sp[0]; + return table_off; + } + + std::vector finish(uint32_t root_off, const char* file_id_4) { + if (file_id_4) { + prep(minalign_, 8u); + push_bytes_rev(file_id_4, 4u); + push_uoffset(root_off); + } else { + prep(minalign_, 4u); + push_uoffset(root_off); + } + std::vector out(buf_.size()); + for (size_t i = 0; i < buf_.size(); ++i) out[i] = buf_[buf_.size() - 1u - i]; + return out; + } + + private: + std::vector buf_; + size_t minalign_ = 1u; + std::vector> cur_fields_; + uint32_t table_start_ = 0u; +}; + +std::vector make_mexec() { + MiniFb fb; + auto layer = [&](uint64_t sz) { + fb.start_table(); + fb.add_u64(3u, sz, nullptr); + return fb.end_table(); + }; + const uint32_t in_layer = layer(16u); + const uint32_t out_layer = layer(16u); + const uint32_t ins = fb.create_vector_uoffsets(&in_layer, 1u); + const uint32_t outs = fb.create_vector_uoffsets(&out_layer, 1u); + fb.start_table(); + fb.add_uoffset(4u, outs); + fb.add_uoffset(3u, ins); + const uint32_t exec = fb.end_table(); + const uint32_t execs = fb.create_vector_uoffsets(&exec, 1u); + fb.start_table(); + fb.add_uoffset(1u, execs); + return fb.finish(fb.end_table(), nullptr); +} + +std::vector make_dws0(const int32_t* dims, size_t ndims) { + const std::vector mexec = make_mexec(); + MiniFb fb; + const uint32_t d_off = fb.create_vector_i32(dims, ndims); + fb.start_table(); + fb.add_u8(5u, 3u); + fb.add_u8(1u, 1u); + fb.add_uoffset(0u, d_off); + const uint32_t tensor = fb.end_table(); + const uint32_t tensors = fb.create_vector_uoffsets(&tensor, 1u); + + const uint32_t me_vec = fb.create_vector_bytes(mexec.data(), mexec.size()); + fb.start_table(); + fb.add_uoffset(0u, me_vec); + const uint32_t detail = fb.end_table(); + + fb.start_table(); + fb.add_uoffset(1u, detail); + fb.add_u8(0u, 2u); + const uint32_t op = fb.end_table(); + const uint32_t ops = fb.create_vector_uoffsets(&op, 1u); + + fb.start_table(); + fb.add_uoffset(3u, ops); + fb.add_uoffset(0u, tensors); + const uint32_t sg = fb.end_table(); + const uint32_t sgs = fb.create_vector_uoffsets(&sg, 1u); + + fb.start_table(); + fb.add_uoffset(3u, sgs); + return fb.finish(fb.end_table(), "DWS0"); +} + +std::vector make_dgc0(const int32_t* dims, size_t ndims) { + const std::vector dws = make_dws0(dims, ndims); + MiniFb fb; + const uint32_t dws_vec = fb.create_vector_bytes(dws.data(), dws.size()); + uint32_t from_end[2] = {}; + uint32_t eb[2] = {}; + for (size_t i = 0; i < 2u; ++i) { + fb.start_table(); + fb.add_u64(1u, 32u, nullptr); + fb.add_u64(0u, 0u, &from_end[i]); + eb[i] = fb.end_table(); + } + const uint32_t ebs = fb.create_vector_uoffsets(eb, 2u); + fb.start_table(); + fb.add_uoffset(7u, ebs); + fb.add_uoffset(0u, dws_vec); + std::vector hdr = fb.finish(fb.end_table(), "DGC0"); + const uint64_t payload_off = hdr.size(); + for (size_t i = 0; i < 2u; ++i) { + const size_t pos = hdr.size() - static_cast(from_end[i]); + std::memcpy(hdr.data() + pos, &payload_off, sizeof(payload_off)); + } + hdr.insert(hdr.end(), 32u, 0u); + return hdr; +} + +bool ranges_cover_once(std::vector> ranges, uint32_t total) { + std::sort(ranges.begin(), ranges.end()); + uint64_t cursor = 0u; + for (const auto& r : ranges) { + if (static_cast(r.first) != cursor || r.second < r.first) return false; + cursor = r.second; + } + return cursor == total && !ranges.empty(); +} + +void test_worker_pool_claim_does_not_reissue() { + ob::WorkerPool pool; + pool.init(2u); + struct Rec { + std::mutex mu; + std::vector> ranges; + } rec; + constexpr uint32_t kTotal = 4000000000u; + pool.parallel_for_fn(kTotal, 1u, [&](uint32_t s, uint32_t e, uint32_t) { + std::lock_guard lk(rec.mu); + rec.ranges.emplace_back(s, e); + }); + CHECK(ranges_cover_once(rec.ranges, kTotal)); + + rec.ranges.clear(); + constexpr uint32_t kSmall = 1027u; + pool.parallel_for_fn(kSmall, 7u, [&](uint32_t s, uint32_t e, uint32_t) { + std::lock_guard lk(rec.mu); + rec.ranges.emplace_back(s, e); + }); + CHECK(ranges_cover_once(rec.ranges, kSmall)); + pool.shutdown(); +} + +void test_slab_round_up_rejects_wrap() { + auto* ctx = new (std::nothrow) ob_context(); + CHECK(ctx != nullptr); + if (!ctx) return; + ctx->mock_mode = true; + + ob_buffer_t* huge = nullptr; + const ob_status_t st = ob_buffer_alloc(ctx, SIZE_MAX - 100u, OB_BUF_NO_POOL, &huge); + if (huge) ob_buffer_free(huge); + CHECK(st == OB_ERR_OVERFLOW); + CHECK(huge == nullptr); + + ob_buffer_t* a = nullptr; + ob_buffer_t* b = nullptr; + CHECK(ob_buffer_alloc(ctx, 100u, OB_BUF_NO_POOL, &a) == OB_OK); + CHECK(ob_buffer_alloc(ctx, 8192u, OB_BUF_NO_POOL, &b) == OB_OK); + CHECK(a && b); + if (a && b) { + CHECK(ob_buffer_size(a) == 100u); + CHECK(ob_buffer_size(b) == 8192u); + CHECK(a->slab.alloc_size >= a->requested_size); + CHECK(b->slab.alloc_size >= b->requested_size); + CHECK(a->slab.iova != b->slab.iova); + std::memset(ob_buffer_data(a), 0x5a, ob_buffer_size(a)); + std::memset(ob_buffer_data(b), 0xa5, 64u); + } + if (a) ob_buffer_free(a); + if (b) ob_buffer_free(b); + delete ctx; +} + +void test_scratchpad_product_overflow() { + const int32_t ok_dims[2] = {4, 5}; + const std::vector ok = make_dgc0(ok_dims, 2u); + ob::ParsedDgc0 parsed; + std::string err; + ob_status_t st = ob::parse_dgc0_buffer(ok.data(), ok.size(), &parsed, &err); + if (st != OB_OK) { + std::fprintf(stderr, "valid dgc0 parse failed: %s\n", err.c_str()); + } + CHECK(st == OB_OK); + CHECK(parsed.dive_scratch_size == 20u); + CHECK(parsed.input_sizes.size() == 1u && parsed.input_sizes[0] == 16u); + CHECK(parsed.output_sizes.size() == 1u && parsed.output_sizes[0] == 16u); + + const int32_t boom[4] = {65536, 65536, 65536, 65536}; + const std::vector bad = make_dgc0(boom, 4u); + parsed = ob::ParsedDgc0{}; + err.clear(); + st = ob::parse_dgc0_buffer(bad.data(), bad.size(), &parsed, &err); + CHECK(st == OB_ERR_OVERFLOW); + CHECK(parsed.dive_scratch_size == 0u); +} + +} // namespace + +int main() { + test_worker_pool_claim_does_not_reissue(); + test_slab_round_up_rejects_wrap(); + test_scratchpad_product_overflow(); + if (g_fails != 0) { + std::fprintf(stderr, "%d check(s) failed\n", g_fails); + return 1; + } + std::printf("openbuenos_pool_guards_test: ok\n"); + return 0; +} diff --git a/llama-cpp-cloudtpu/pjrt_runtime.cpp b/llama-cpp-cloudtpu/pjrt_runtime.cpp index 142baa81..e79d722b 100644 --- a/llama-cpp-cloudtpu/pjrt_runtime.cpp +++ b/llama-cpp-cloudtpu/pjrt_runtime.cpp @@ -298,7 +298,12 @@ size_t pjrt_dtype_nbytes(PjrtDType dt, size_t num_elements) { if (bits == 0 || num_elements == 0) { return 0; } - return (num_elements / 8) * bits + ((num_elements % 8) * bits + 7) / 8; + // ceil(num_elements * bits / 8), rejecting a product that cannot fit in size_t. + if (num_elements > (SIZE_MAX / bits)) { + throw std::overflow_error("pjrt_dtype_nbytes: element count overflows host byte size"); + } + const size_t total_bits = num_elements * bits; + return total_bits / 8u + ((total_bits % 8u) != 0u ? 1u : 0u); } size_t pjrt_host_nbytes(PjrtDType dt, size_t num_elements) { @@ -308,6 +313,9 @@ size_t pjrt_host_nbytes(PjrtDType dt, size_t num_elements) { } // OpenXLA PJRT BufferFromHostBuffer(byte_strides=nullptr) reads 1 byte per element for S4/U4. const size_t host_elem_bytes = (bits < 8) ? 1 : (bits / 8); + if (host_elem_bytes != 0u && num_elements > (SIZE_MAX / host_elem_bytes)) { + throw std::overflow_error("pjrt_host_nbytes: element count overflows host byte size"); + } return num_elements * host_elem_bytes; } @@ -582,10 +590,29 @@ void PjrtEventDeleter::operator()(PJRT_Event* ev) const noexcept { } } -size_t PjrtBuffer::num_elements() const { +static bool shape_num_elements(const int64_t* dims, size_t n_dims, size_t* out) { size_t n = 1; - for (int64_t d : dims) { - n *= static_cast(d); + for (size_t i = 0; i < n_dims; ++i) { + const int64_t dim = dims[i]; + if (dim < 0) { + return false; + } + const size_t factor = static_cast(dim); + if (factor != 0u && n > (SIZE_MAX / factor)) { + return false; + } + n *= factor; + } + if (out != nullptr) { + *out = n; + } + return true; +} + +size_t PjrtBuffer::num_elements() const { + size_t n = 0; + if (!shape_num_elements(dims.data(), dims.size(), &n)) { + throw std::overflow_error("PjrtBuffer shape overflows"); } return n; } @@ -821,9 +848,9 @@ struct MockTensor { std::vector bytes; size_t num_elements() const { - size_t n = 1; - for (int64_t d : dims) { - n *= static_cast(d); + size_t n = 0; + if (!shape_num_elements(dims.data(), dims.size(), &n)) { + throw std::overflow_error("MockPJRT: tensor shape overflows"); } return n; } @@ -2595,12 +2622,22 @@ struct MockBuffer { std::shared_ptr> allocated_bytes; int device_id = 0; }; +struct StagedOutput { + MockBuffer* buf = nullptr; + bool charged = false; +}; +struct DeviceByteCounter { + int device_id = -1; + std::shared_ptr> bytes; +}; struct MockExecutable { MockProgram program; }; struct MockLoadedExecutable { MockExecutable exec; - std::vector>> device_allocated_bytes; + // Hardware id paired with that device's counter. Enumeration order is not + // the hardware id when the mock client scrambles chiplet order. + std::vector device_byte_counters; std::vector assigned_device_ids; }; @@ -2856,27 +2893,42 @@ static PJRT_Error* mock_buffer_from_host(PJRT_Client_BufferFromHostBuffer_Args* if (dt == PjrtDType::INVALID) { return mock_error("MockPJRT: unsupported PJRT_Buffer_Type"); } + if (args->num_dims > 0 && args->dims == nullptr) { + return mock_error("MockPJRT: missing buffer dimensions"); + } std::vector shape(args->dims, args->dims + args->num_dims); auto* mb = new MockBuffer(); - mb->allocated_bytes = d ? d->allocated_bytes : nullptr; - mb->device_id = d ? d->id : 0; - mb->tensor.allocate(dt, std::move(shape)); - if (!mb->tensor.bytes.empty() && args->data) { - const size_t nelems = mb->tensor.num_elements(); - if (dt == PjrtDType::S4) { - pack_s4_from_i8(static_cast(args->data), nelems, mb->tensor.bytes.data()); - } else if (dt == PjrtDType::U4) { - pack_u4_from_u8(static_cast(args->data), nelems, mb->tensor.bytes.data()); - } else { - std::memcpy(mb->tensor.bytes.data(), args->data, mb->tensor.bytes.size()); + bool charged = false; + try { + mb->allocated_bytes = d ? d->allocated_bytes : nullptr; + mb->device_id = d ? d->id : 0; + mb->tensor.allocate(dt, std::move(shape)); + if (!mb->tensor.bytes.empty() && args->data) { + const size_t nelems = mb->tensor.num_elements(); + if (dt == PjrtDType::S4) { + pack_s4_from_i8(static_cast(args->data), nelems, mb->tensor.bytes.data()); + } else if (dt == PjrtDType::U4) { + pack_u4_from_u8(static_cast(args->data), nelems, mb->tensor.bytes.data()); + } else { + std::memcpy(mb->tensor.bytes.data(), args->data, mb->tensor.bytes.size()); + } } + if (mb->allocated_bytes) { + mb->allocated_bytes->fetch_add(static_cast(mb->tensor.bytes.size()), + std::memory_order_relaxed); + charged = true; + } + args->done_with_host_buffer = reinterpret_cast(new MockEvent()); + args->buffer = reinterpret_cast(mb); + return nullptr; + } catch (const std::exception& e) { + if (charged && mb->allocated_bytes) { + mb->allocated_bytes->fetch_sub(static_cast(mb->tensor.bytes.size()), + std::memory_order_relaxed); + } + delete mb; + return mock_error(std::string("MockPJRT: ") + e.what()); } - if (mb->allocated_bytes) { - mb->allocated_bytes->fetch_add(static_cast(mb->tensor.bytes.size()), std::memory_order_relaxed); - } - args->done_with_host_buffer = reinterpret_cast(new MockEvent()); - args->buffer = reinterpret_cast(mb); - return nullptr; } static PJRT_Error* mock_buffer_destroy(PJRT_Buffer_Destroy_Args* args) { auto* mb = reinterpret_cast(args->buffer); @@ -2940,9 +2992,9 @@ static PJRT_Error* mock_client_compile(PJRT_Client_Compile_Args* args) { auto* le = new MockLoadedExecutable(); le->exec.program = parse_stablehlo_mlir(code); if (c) { - le->device_allocated_bytes.reserve(c->devices.size()); + le->device_byte_counters.reserve(c->devices.size()); for (const auto& d : c->devices) { - le->device_allocated_bytes.push_back(d->allocated_bytes); + le->device_byte_counters.push_back(DeviceByteCounter{d->id, d->allocated_bytes}); } } le->assigned_device_ids = @@ -2973,6 +3025,26 @@ static PJRT_Error* mock_exec_num_outputs(PJRT_Executable_NumOutputs_Args* args) return nullptr; } static PJRT_Error* mock_loaded_exec_execute(PJRT_LoadedExecutable_Execute_Args* args) { + std::vector staged; + std::vector staged_events; + auto discard_staged = [&]() { + for (PJRT_Event* ev : staged_events) { + delete reinterpret_cast(ev); + } + staged_events.clear(); + for (StagedOutput& s : staged) { + if (s.buf == nullptr) { + continue; + } + if (s.charged && s.buf->allocated_bytes) { + s.buf->allocated_bytes->fetch_sub(static_cast(s.buf->tensor.bytes.size()), + std::memory_order_relaxed); + } + delete s.buf; + s.buf = nullptr; + } + staged.clear(); + }; try { auto* le = reinterpret_cast(args->executable); const size_t n_devs = std::max(1, args->num_devices); @@ -2998,9 +3070,11 @@ static PJRT_Error* mock_loaded_exec_execute(PJRT_LoadedExecutable_Execute_Args* std::vector>> alloc_bytes(n_devs); for (size_t d = 0; d < n_devs; ++d) { const int expected_dev_id = le->assigned_device_ids[d]; - if (expected_dev_id >= 0 && - static_cast(expected_dev_id) < le->device_allocated_bytes.size()) { - alloc_bytes[d] = le->device_allocated_bytes[static_cast(expected_dev_id)]; + for (const DeviceByteCounter& slot : le->device_byte_counters) { + if (slot.device_id == expected_dev_id) { + alloc_bytes[d] = slot.bytes; + break; + } } for (size_t i = 0; i < args->num_args; ++i) { auto* mb = reinterpret_cast(args->argument_lists[d][i]); @@ -3049,26 +3123,45 @@ static PJRT_Error* mock_loaded_exec_execute(PJRT_LoadedExecutable_Execute_Args* } } } + staged.reserve(n_devs * prog.return_names.size()); for (size_t d = 0; d < n_devs; ++d) { const int dev_id = le->assigned_device_ids[d]; for (size_t oi = 0; oi < prog.return_names.size(); ++oi) { auto* out_mb = new MockBuffer(); + staged.push_back(StagedOutput{out_mb, false}); out_mb->allocated_bytes = alloc_bytes[d]; out_mb->device_id = dev_id; // Copy rather than move so repeated SSA values in return_names stay valid. + // .at throws before the copy when a return name was never defined. out_mb->tensor = envs[d].at(prog.return_names[oi]); if (out_mb->allocated_bytes) { out_mb->allocated_bytes->fetch_add( static_cast(out_mb->tensor.bytes.size()), std::memory_order_relaxed); + staged.back().charged = true; } - args->output_lists[d][oi] = reinterpret_cast(out_mb); + } + } + if (args->device_complete_events) { + staged_events.reserve(n_devs); + for (size_t d = 0; d < n_devs; ++d) { + staged_events.push_back(reinterpret_cast(new MockEvent())); + } + } + size_t staged_i = 0; + for (size_t d = 0; d < n_devs; ++d) { + for (size_t oi = 0; oi < prog.return_names.size(); ++oi) { + args->output_lists[d][oi] = reinterpret_cast(staged[staged_i].buf); + ++staged_i; } if (args->device_complete_events) { - args->device_complete_events[d] = reinterpret_cast(new MockEvent()); + args->device_complete_events[d] = staged_events[d]; } } + staged.clear(); + staged_events.clear(); return nullptr; } catch (const std::exception& e) { + discard_staged(); return mock_error(e.what()); } } @@ -3702,8 +3795,8 @@ void PjrtRuntime::buffer_to_host(PJRT_Buffer* buf, void* dst, size_t dst_size) { dim_args.struct_size = PJRT_Buffer_Dimensions_Args_STRUCT_SIZE; dim_args.buffer = buf; check_error(api_->PJRT_Buffer_Dimensions(&dim_args), "PJRT_Buffer_Dimensions"); - for (size_t i = 0; i < dim_args.num_dims; ++i) { - nelems *= static_cast(dim_args.dims[i]); + if (!shape_num_elements(dim_args.dims, dim_args.num_dims, &nelems)) { + throw std::overflow_error("buffer_to_host: tensor shape overflows"); } if (dim_args.num_dims > 1) { minor_to_major.resize(dim_args.num_dims); diff --git a/llama-cpp-cloudtpu/tests/pjrt_runtime_guards_test.cpp b/llama-cpp-cloudtpu/tests/pjrt_runtime_guards_test.cpp new file mode 100644 index 00000000..ef57c6b3 --- /dev/null +++ b/llama-cpp-cloudtpu/tests/pjrt_runtime_guards_test.cpp @@ -0,0 +1,197 @@ +// Host-only checks for mock PJRT shape overflow, device-local HBM accounting, +// and execute failure cleanup. No device access. +#include "pjrt_runtime.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +int g_fails = 0; + +void check(bool cond, const char* expr, int line) { + if (!cond) { + std::fprintf(stderr, "FAIL %s:%d %s\n", "pjrt_runtime_guards_test.cpp", line, expr); + ++g_fails; + } +} + +#define CHECK(cond) check(static_cast(cond), #cond, __LINE__) + +cloudtpu::RuntimeConfig mock_cfg(cloudtpu::MockTopologyProfile profile, bool scramble) { + cloudtpu::RuntimeConfig cfg; + cfg.mock_mode = true; + cfg.mock_profile = profile; + cfg.mock_scramble_device_order = scramble; + return cfg; +} + +size_t free_bytes(cloudtpu::PjrtRuntime& rt, int device) { + size_t free_b = 0; + CHECK(rt.query_memory_stats(device, &free_b, nullptr)); + return free_b; +} + +void test_shape_overflow_rejects() { + cloudtpu::PjrtBuffer wide; + wide.dtype = cloudtpu::PjrtDType::F32; + wide.dims = {4, 5}; + CHECK(wide.num_elements() == 20u); + CHECK(wide.num_bytes() == 80u); + + bool elems_threw = false; + cloudtpu::PjrtBuffer wrapped; + wrapped.dtype = cloudtpu::PjrtDType::F32; + wrapped.dims = {int64_t{1} << 40, int64_t{1} << 40}; + try { + const size_t n = wrapped.num_elements(); + std::fprintf(stderr, "wrapped element count returned %zu\n", n); + } catch (const std::overflow_error&) { + elems_threw = true; + } catch (const std::exception& ex) { + std::fprintf(stderr, "wrapped elements threw %s\n", ex.what()); + } + CHECK(elems_threw); + + bool bytes_threw = false; + try { + const size_t n = cloudtpu::pjrt_dtype_nbytes(cloudtpu::PjrtDType::F32, (size_t{1} << 62) + 1u); + std::fprintf(stderr, "dtype nbytes returned %zu\n", n); + } catch (const std::overflow_error&) { + bytes_threw = true; + } catch (const std::exception& ex) { + std::fprintf(stderr, "dtype nbytes threw %s\n", ex.what()); + } + CHECK(bytes_threw); + + bool host_threw = false; + try { + const size_t n = cloudtpu::pjrt_host_nbytes(cloudtpu::PjrtDType::F32, (size_t{1} << 62) + 1u); + std::fprintf(stderr, "host nbytes returned %zu\n", n); + } catch (const std::overflow_error&) { + host_threw = true; + } catch (const std::exception& ex) { + std::fprintf(stderr, "host nbytes threw %s\n", ex.what()); + } + CHECK(host_threw); + + cloudtpu::PjrtRuntime rt; + rt.init(mock_cfg(cloudtpu::MockTopologyProfile::V5E_1, false)); + const size_t before = free_bytes(rt, 0); + const float src[2] = {1.0f, 2.0f}; + + bool huge_pjrt = false; + try { + auto buf = rt.buffer_from_host(0, src, cloudtpu::PjrtDType::F32, {(int64_t{1} << 62) + 1}); + std::fprintf(stderr, "huge buffer_from_host succeeded bytes=%zu dim=%lld\n", + buf->num_bytes(), static_cast(buf->dims[0])); + } catch (const cloudtpu::PjrtError&) { + huge_pjrt = true; + } catch (const std::exception& ex) { + std::fprintf(stderr, "huge buffer_from_host threw %s\n", ex.what()); + } + CHECK(huge_pjrt); + CHECK(free_bytes(rt, 0) == before); + + bool neg_pjrt = false; + try { + rt.buffer_from_host(0, src, cloudtpu::PjrtDType::F32, {-1}); + } catch (const cloudtpu::PjrtError&) { + neg_pjrt = true; + } catch (const std::bad_alloc&) { + std::fprintf(stderr, "negative dim threw std::bad_alloc\n"); + } catch (const std::exception& ex) { + std::fprintf(stderr, "negative dim threw %s\n", ex.what()); + } + CHECK(neg_pjrt); + CHECK(free_bytes(rt, 0) == before); + + auto ok = rt.buffer_from_host(0, src, cloudtpu::PjrtDType::F32, {2}); + CHECK(ok->num_elements() == 2u); + CHECK(ok->num_bytes() == 8u); + float dst[2] = {}; + rt.buffer_to_host(ok->handle.get(), dst, sizeof(dst)); + CHECK(dst[0] == 1.0f && dst[1] == 2.0f); + ok.reset(); + CHECK(free_bytes(rt, 0) == before); + rt.shutdown(); +} + +void test_scrambled_output_charges_assigned_device() { + cloudtpu::PjrtRuntime rt; + rt.init(mock_cfg(cloudtpu::MockTopologyProfile::TPU7X_1T, true)); + CHECK(rt.device_count() == 2); + CHECK(rt.device_info(0).id == 0); + CHECK(rt.device_info(1).id == 1); + const size_t free0 = free_bytes(rt, 0); + const size_t free1 = free_bytes(rt, 1); + CHECK(free0 == free1); + + const char* mlir = + "func.func @main() -> tensor<4xf32> {\n" + " %v0 = stablehlo.constant dense<1.0> : tensor<4xf32>\n" + " return %v0 : tensor<4xf32>\n" + "}\n"; + const auto opts = rt.make_spmd_compile_options(1, 0); + auto exec = rt.compile_or_get("guard-const4", mlir, 0, opts); + std::vector outputs; + rt.execute(exec, 0, nullptr, 0, outputs, {cloudtpu::PjrtDType::F32}, {{4}}, true); + CHECK(outputs.size() == 1u); + const size_t used0 = free_bytes(rt, 0); + const size_t used1 = free_bytes(rt, 1); + CHECK(used0 + 16u == free0); + CHECK(used1 == free1); + outputs.clear(); + exec.reset(); + CHECK(free_bytes(rt, 0) == free0); + CHECK(free_bytes(rt, 1) == free1); + rt.shutdown(); +} + +void test_execute_error_releases_published_output() { + cloudtpu::PjrtRuntime rt; + rt.init(mock_cfg(cloudtpu::MockTopologyProfile::V5E_1, false)); + const size_t before = free_bytes(rt, 0); + const char* mlir = + "func.func @main() -> (tensor<4xf32>, tensor<4xf32>) {\n" + " %v0 = stablehlo.constant dense<1.0> : tensor<4xf32>\n" + " return %v0, %missing : tensor<4xf32>, tensor<4xf32>\n" + "}\n"; + auto exec = rt.compile_or_get("guard-missing-return", mlir, 0, {}); + std::vector outputs; + bool threw = false; + try { + rt.execute(exec, 0, nullptr, 0, outputs, + {cloudtpu::PjrtDType::F32, cloudtpu::PjrtDType::F32}, {{4}, {4}}, true); + std::fprintf(stderr, "missing return execute produced %zu outputs\n", outputs.size()); + } catch (const cloudtpu::PjrtError&) { + threw = true; + } catch (const std::exception& ex) { + std::fprintf(stderr, "missing return execute threw %s\n", ex.what()); + } + CHECK(threw); + CHECK(outputs.empty()); + outputs.clear(); + exec.reset(); + CHECK(free_bytes(rt, 0) == before); + rt.shutdown(); +} + +} // namespace + +int main() { + test_shape_overflow_rejects(); + test_scrambled_output_charges_assigned_device(); + test_execute_error_releases_published_output(); + if (g_fails != 0) { + std::fprintf(stderr, "pjrt_runtime_guards_test: %d check(s) failed\n", g_fails); + return 1; + } + std::printf("pjrt_runtime_guards_test: ok\n"); + return 0; +}