diff --git a/CMakeLists.txt b/CMakeLists.txt index e7bfd464..fd73a36c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.21) # VERSION is what /version reports and what a client checks compatibility against. It is NOT the # ABI version -- that lives in abi/rad_abi.h and is read out of the header below, because # a plugin contract and a server release do not move together. -project(radiance VERSION 1.0.4 LANGUAGES C CXX) +project(radiance VERSION 1.0.5 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/core/build/rad_build.h b/core/build/rad_build.h index 17cdb5a4..47580d37 100644 --- a/core/build/rad_build.h +++ b/core/build/rad_build.h @@ -165,6 +165,14 @@ public: * laid over the real ones. */ void set_reference(const Program* ref) { ref_ = ref; } + /* WITHOUT INSTANCES: finish() selects every kernel and initialises none. For a caller that + * launches nothing -- rad-convert plans a container's stored form, which is the kernels' + * layouts and not their setup. A kernel's init is about the process it runs in (a ring, a + * peer's buffers) and the conversion is often not that process: libavx's n-gram gather + * refuses a process that may not make an io_uring ring, and a sandbox that forbids one still + * has to be able to convert the model. */ + void set_instances(bool on) { instances_ = on; } + Program& program() { return prog_; } const Program& program() const { return prog_; } @@ -195,6 +203,7 @@ private: Registry& reg_; Program prog_; const Program* ref_ = nullptr; + bool instances_ = true; std::vector errors_; int status_ = RAD_OK; diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index 3232ba26..bec46cbb 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -1498,7 +1498,7 @@ int Builder::finish() { w.source.c_str(), rad_dtype_name(w.decl.dtype)); } - finish_instances(); + if (instances_) finish_instances(); finish_weight_uses(); finish_layouts(); finish_kv_groups(); diff --git a/core/build/startup.cpp b/core/build/startup.cpp index 180dd6fd..7477c013 100644 --- a/core/build/startup.cpp +++ b/core/build/startup.cpp @@ -319,7 +319,7 @@ std::vector CheckpointSources::refused() const { int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const RadBuildCtx& ctx, Program* out, const std::function& also, - const Program* ref, const WeightSourceFn& sources) { + const Program* ref, const WeightSourceFn& sources, bool instances) { if (!out) return RAD_E_INVAL; Registry& r = rad_tools_registry(); @@ -334,6 +334,7 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R Builder b(r, meta, ctx); if (ref) b.set_reference(ref); if (sources) b.set_sources(sources); + b.set_instances(instances); int s = ap->arch_declare(&b, &meta, &ctx); if (s < 0) { diff --git a/core/build/startup.h b/core/build/startup.h index d761f38c..453f239f 100644 --- a/core/build/startup.h +++ b/core/build/startup.h @@ -88,10 +88,13 @@ const RadChatFormat* rad_tools_chat_format(const LoadedPlugins& plugins, const R * or initialised. The Program that comes back is for its buffers and nothing else. */ /* `sources` answers rad_weight_encoding (Builder::set_sources): a container's entries, a * checkpoint's tensors, or a recipe. Empty, every weight is read as plain in its declared dtype. */ +/* `instances` false selects every kernel and initialises none (Builder::set_instances): for a + * caller that launches nothing, such as rad-convert planning a container's stored form. */ int rad_tools_declare(const LoadedPlugins& plugins, const RadModelMeta& meta, const RadBuildCtx& ctx, Program* out, const std::function& also = {}, - const Program* ref = nullptr, const WeightSourceFn& sources = {}); + const Program* ref = nullptr, const WeightSourceFn& sources = {}, + bool instances = true); /* A container's entries as the source of every declaration's encoding. `f` must outlive the * declare. */ diff --git a/core/config.cpp b/core/config.cpp index 38d02612..80c4e34f 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -127,7 +127,7 @@ static const Flag g_flags[] = { { "--dry-sequence-breakers", "JSON", "default dry_sequence_breakers, a JSON array of at most 16 strings" }, { "--xtc-probability", "F", "default xtc_probability, [0, 1]" }, { "--xtc-threshold", "F", "default xtc_threshold, [0, 1]" }, - { "--default-max-tokens", "N", "max_tokens for requests that do not set one (default 512). `auto` is\n" + { "--default-max-tokens", "N", "max_tokens for requests that do not set one: N, or `auto` (default),\n" " whatever the context leaves after the prompt" }, { "--max-tokens-cap", "N", "the most any request may generate. A larger max_tokens is cut to it rather\n" " than refused, and the reply ends with finish_reason \"length\". 0 is none\n" diff --git a/core/engine.cpp b/core/engine.cpp index 6ccb7a99..e240e797 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -383,7 +383,7 @@ void Engine::phase_mark(int p) { int Engine::fail_loop(int st) { stopping_.store(true, std::memory_order_release); if (barrier_) barrier_->abort(); - sched_.shutdown("the engine stopped on an error and is not serving"); + sched_.shutdown("the engine stopped on an error and is not serving", st < 0 ? st : RAD_E_STATE); loop_status_.store(st < 0 ? st : RAD_E_STATE, std::memory_order_release); return st; } @@ -2027,12 +2027,13 @@ int Engine::run_server() { o.default_reasoning_effort = cfg_.reasoning_effort; o.default_sampling = resolve_sampling_defaults(meta_, file_ != nullptr, cfg_); o.default_dry_breakers_set = cfg_.sample_dry_seq_breakers.has_value(); - /* -1 leaves ServerOptions' own default. `auto` (0) is resolved per request against the - * context, so it needs one to resolve against. */ + /* -1 leaves ServerOptions' own default, which is `auto` (0). That is resolved per request + * against the context, so it needs one to resolve against. */ if (cfg_.default_max_tokens >= 0) o.default_max_tokens = cfg_.default_max_tokens; if (o.default_max_tokens == 0 && o.max_ctx <= 0) { - RAD_ERR("--default-max-tokens auto is what the context leaves, and this model states no " - "context; pass --max-model-len"); + RAD_ERR("a request that names no max_tokens gets what the context leaves after its prompt " + "(--default-max-tokens auto), and this model states no context; pass " + "--max-model-len, or --default-max-tokens N"); return RAD_E_INVAL; } o.max_tokens_cap = cfg_.max_tokens_cap; diff --git a/core/rad_core.h b/core/rad_core.h index 541a350b..22984c1c 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -687,8 +687,9 @@ struct Config { sample_dry_penalty_last_n; std::optional> sample_dry_seq_breakers; - /* --default-max-tokens: what a request that names no max_tokens may generate. -1 is unset - * (the server's 512), 0 is `auto` (whatever the context leaves after the prompt). */ + /* --default-max-tokens: what a request that names no max_tokens may generate. -1 is unset, + * which is the server's default, `auto`; 0 is `auto` stated (whatever the context leaves after + * the prompt). */ int64_t default_max_tokens = -1; /* --max-tokens-cap: the most any request may generate. A larger max_tokens is clamped to it, * the way the context clamps one, and the reply ends with finish_reason "length". 0 is none. */ diff --git a/core/rad_internal.h b/core/rad_internal.h index 09390b9d..8151ce0b 100644 --- a/core/rad_internal.h +++ b/core/rad_internal.h @@ -100,40 +100,46 @@ class Geometry { public: Geometry() = default; - /* The cached RadParam view holds char* into THIS object's own strings. An implicit copy would - * carry those pointers into the copy along with dirty_ = false, so the copy would hand a - * kernel pointers that dangle the moment the source dies -- and every Resolved holds a - * Geometry while every Band holds two, so this type is copied constantly. A copy therefore - * takes the storage and NOT the view, and rebuilds on first use. + /* THE RadParam VIEW IS KEPT CURRENT BY EVERY WRITE, never built on first read. It holds char* + * into this object's own strings, and a view rebuilt lazily from a const reader is a write + * that two readers can make at once: the sizing declares of one rank all read the real + * program's geometries side by side (Engine::probe_arena_levels), and one clearing the view + * while another filled it is the heap corruption that crashed startup. So params() writes + * nothing, and a Geometry nobody is writing can be read from any number of threads. * - * The move is the same rule for a different reason: a moved-from vector's buffer may be - * stolen, so the view's pointers stop meaning anything even though nothing was destroyed. */ + * A copy takes the storage and builds its own view, because the source's points into the + * source. A move takes the view along with the storage: the vectors hand over their arrays, + * so every string stays where it was and every pointer stays good. The moved-from object is + * emptied, view included, so it is a valid empty geometry rather than one whose view names + * strings it no longer owns. */ Geometry(const Geometry& o) - : keys_(o.keys_), svals_(o.svals_), ivals_(o.ivals_), dvals_(o.dvals_), kinds_(o.kinds_) {} + : keys_(o.keys_), svals_(o.svals_), ivals_(o.ivals_), dvals_(o.dvals_), kinds_(o.kinds_) { + rebuild(); + } Geometry& operator=(const Geometry& o) { if (this != &o) { keys_ = o.keys_; svals_ = o.svals_; ivals_ = o.ivals_; dvals_ = o.dvals_; kinds_ = o.kinds_; - view_.clear(); dirty_ = true; + rebuild(); } return *this; } Geometry(Geometry&& o) noexcept : keys_(std::move(o.keys_)), svals_(std::move(o.svals_)), - ivals_(std::move(o.ivals_)), dvals_(std::move(o.dvals_)), - kinds_(std::move(o.kinds_)) { - o.view_.clear(); o.dirty_ = true; + view_(std::move(o.view_)), ivals_(std::move(o.ivals_)), + dvals_(std::move(o.dvals_)), kinds_(std::move(o.kinds_)) { + o.clear(); } Geometry& operator=(Geometry&& o) noexcept { if (this != &o) { keys_ = std::move(o.keys_); svals_ = std::move(o.svals_); + view_ = std::move(o.view_); ivals_ = std::move(o.ivals_); dvals_ = std::move(o.dvals_); kinds_ = std::move(o.kinds_); - view_.clear(); dirty_ = true; - o.view_.clear(); o.dirty_ = true; + o.clear(); } return *this; } @@ -149,17 +155,20 @@ public: const char* get_s(std::string_view k) const; bool has(std::string_view k) const; - /* A view suitable for RadArgs.p. Valid while this object lives. */ - const RadParam* params() const; - int n_params() const; + /* A view suitable for RadArgs.p. Valid while this object lives and is not written. */ + const RadParam* params() const { return view_.data(); } + int n_params() const { return (int)view_.size(); } std::string str() const; /* "M=64 N=8192 K=5120 dtype=w4a8", for diagnostics */ private: std::vector keys_, svals_; std::vector view_; - mutable bool dirty_ = true; - void rebuild() const; + void rebuild(); + void clear() noexcept { + keys_.clear(); svals_.clear(); view_.clear(); ivals_.clear(); dvals_.clear(); + kinds_.clear(); + } std::vector ivals_; std::vector dvals_; std::vector kinds_; diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index 5776b9b6..04834a01 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -98,6 +98,7 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac ctx_limit_ = builder_.max_ctx(); n_deferred_ = 0; closed_ = false; + closed_status_ = RAD_E_STATE; /* Everything the step path touches is reserved here. A vector that grows during a step is an * allocator call on the path this whole component exists to keep clear. */ @@ -152,7 +153,7 @@ int Scheduler::add_locked(std::unique_ptr r) { * listening to -- and the refusal says why. */ if (closed_) { RAD_WARN("request %llu refused: %s", (unsigned long long)r->id, closed_reason_); - server::sink_fail(r->sink, RAD_E_STATE); + server::sink_fail(r->sink, closed_status_, closed_reason_); return RAD_E_STATE; } @@ -312,7 +313,7 @@ void Scheduler::trim_prefix_cache() { } void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool defer_free, - bool publish) { + bool publish, int status, const char* why) { /* PUBLISH BEFORE FREEING. This is the only moment the sequence's whole prefix is both * computed and still owned, and it is what makes the cache a cache rather than a permanently * empty lookup: insert() takes its own KV references, so the blocks survive the free below. @@ -359,7 +360,8 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool /* Terminal, and idempotent on the sink's side: the first call wins, so a cancel racing a * natural stop does not produce two finish reasons. This is the last thing the producer does * to the sink, and the HTTP thread is waiting on exactly it. */ - server::sink_finish(s.req->sink, finish_of(st, s.req->finish_reason)); + if (st == ReqState::Failed && status < 0) server::sink_fail(s.req->sink, status, why); + else server::sink_finish(s.req->sink, finish_of(st, s.req->finish_reason)); } int Scheduler::cancel(uint64_t id) { @@ -467,10 +469,11 @@ void Scheduler::release_deferred() { sweep_deferred(); } -void Scheduler::shutdown(const char* reason) { +void Scheduler::shutdown(const char* reason, int status) { std::lock_guard lk(mu_); closed_ = true; closed_reason_ = reason ? reason : "the engine has stopped"; + closed_status_ = status < 0 ? status : RAD_E_STATE; /* Copied first: close_request erases from both queues. */ std::vector live(running_); live.insert(live.end(), waiting_.begin(), waiting_.end()); @@ -478,7 +481,7 @@ void Scheduler::shutdown(const char* reason) { SchedReq& s = *reqs_[(size_t)slot]; if (!s.req) continue; close_request(s, ReqState::Failed, closed_reason_, /*defer_free=*/false, - /*publish=*/false); + /*publish=*/false, closed_status_, closed_reason_); ++m_.failed; completed_.push_back(s.req->id); } @@ -944,7 +947,8 @@ const RadBatch* Scheduler::step() { kv_->can_ever_fit(r.n_computed + want) ? " and nothing lower-priority is left to preempt" : " at any occupancy"); - close_request(s, ReqState::Failed, "kv_exhausted"); + close_request(s, ReqState::Failed, "kv_exhausted", false, true, RAD_E_FULL, + "the KV pool cannot hold it"); ++m_.failed; completed_.push_back(r.id); failed = true; @@ -1035,7 +1039,8 @@ const RadBatch* Scheduler::step() { RAD_WARN("request %llu failed: %lld tokens leave no room in a %lld-token context", (unsigned long long)s.req->id, (long long)s.seq_len(), (long long)ctx_limit_); - close_request(s, ReqState::Failed, "context_length_exceeded"); + close_request(s, ReqState::Failed, "context_length_exceeded", false, true, + RAD_E_FULL, "it leaves no room in the context"); ++m_.failed; completed_.push_back(s.req->id); continue; diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h index e07f4b24..9f59ada4 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -238,8 +238,9 @@ public: /* THE ENGINE HAS STOPPED AND WILL RUN NO MORE STEPS. Every request still queued or running is * failed with `reason` so its connection is answered rather than left waiting on a step that - * will never come, and any request submitted afterwards is refused the same way. */ - void shutdown(const char* reason); + * will never come, and any request submitted afterwards is refused the same way. `status` is + * what stopped it, and what each of those requests reports. */ + void shutdown(const char* reason, int status = RAD_E_STATE); /* The waiting queue in SERVICE order, by request id -- what the live view shows and what a * test asserts a preempted request re-entered at the front of. Returns how many were written. */ @@ -522,6 +523,7 @@ private: /* Set by shutdown(); add() refuses from then on. */ bool closed_ = false; const char* closed_reason_ = ""; + int closed_status_ = RAD_E_STATE; /* THE LONGEST SEQUENCE THIS DEPLOYMENT CAN ADDRESS, prompt and output together. The batch * builder sizes its block tables for it and the rotary tables are this long, so no position @@ -631,9 +633,13 @@ private: /* lifecycle */ /* `publish` is false only when the engine is shutting down: a sequence the device may have - * left half-computed is not worth indexing, and nothing will ever hit it. */ + * left half-computed is not worth indexing, and nothing will ever hit it. + * + * A FAILED REQUEST SAYS WHAT FAILED: its sink is failed with `status` and `why`, which the + * server puts in the error the client gets. RAD_OK leaves a sink that has failed already (an + * overflow) as it is. */ void close_request(SchedReq& s, ReqState st, const char* reason, bool defer_free = false, - bool publish = true); + bool publish = true, int status = RAD_OK, const char* why = nullptr); /* What reap() does once nothing points at the slot any more: give the blocks back, forget the * id, destroy the Request and return the slot. Called by reap() directly, or by the sweep in * commit() for a request whose reap arrived while something still pointed at it. */ diff --git a/core/server/oai.h b/core/server/oai.h index a9893655..ca054040 100644 --- a/core/server/oai.h +++ b/core/server/oai.h @@ -109,8 +109,13 @@ struct OaiLimits { std::string model_id = "radiance"; int64_t max_ctx = 0; /* 0 = unknown, no length check */ /* What a request that names no max_tokens may generate. 0 is "whatever the context leaves", - * resolved against the prompt in clamp_max_tokens. */ - int64_t default_max_tokens = 512; + * resolved against the prompt in clamp_max_tokens, which needs max_ctx to resolve against. + * + * 0 BY DEFAULT, as vLLM's is: many clients send no max_tokens, and a reasoning model spends + * the first thousands of tokens of an answer thinking. A fixed default of 512 ended those + * answers inside the reasoning, with finish_reason "length" that a chat client does not show, + * so they read as a model that stops at random. */ + int64_t default_max_tokens = 0; /* The most any request may generate; a larger max_tokens is clamped, not refused. 0 = none. */ int64_t max_tokens_cap = 0; int max_n = 8; diff --git a/core/server/server.cpp b/core/server/server.cpp index 6bd5bf3f..da3c7685 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -412,6 +412,16 @@ bool Server::pump(std::vector& gens, const OaiRequest& r) { /* ------------------------------------------------------------------ metrics bookkeeping */ +/* WHAT FAILED, for the client: the sentence the failing component gave, and the status. A failed + * request always carries a status -- an engine that stopped carries the one that stopped it -- so + * this never reads "ok". */ +static std::string engine_failure(const Sink& s) { + const int st = s.status() < 0 ? s.status() : RAD_E_STATE; + const char* why = s.why(); + return why ? fmt("the engine failed this request: %s (%s)", why, rad_strerror(st)) + : fmt("the engine failed this request: %s", rad_strerror(st)); +} + static SuccessReason to_reason(Finish f) { switch (f) { case Finish::Length: return SuccessReason::Length; @@ -536,14 +546,14 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r) /* An engine-side failure is not a 200 with an empty answer. */ for (auto& g : gens) { if (g.finish == Finish::Error) { - int st = g.sink->status(); + const std::string why = engine_failure(*g.sink); retire(gens); release(r.n_choices()); record(r, gens, Finish::Error); ApiError e; e.status = 500; e.type = "internal_server_error"; - e.message = std::string("the engine failed this request: ") + rad_strerror(st); + e.message = why; return error_response(e); } } @@ -689,8 +699,7 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r) ApiError e; e.status = 500; e.type = "internal_server_error"; - e.message = std::string("the engine failed this request: ") + - rad_strerror(g.sink->status()); + e.message = engine_failure(*g.sink); out += sse_error(e); } } diff --git a/core/server/server.h b/core/server/server.h index fded2f99..8a357a6d 100644 --- a/core/server/server.h +++ b/core/server/server.h @@ -66,7 +66,7 @@ struct ServerOptions { int retry_after_s = 1; int64_t max_ctx = 0; - int64_t default_max_tokens = 512; /* 0: what the context leaves (OaiLimits) */ + int64_t default_max_tokens = 0; /* 0: what the context leaves (OaiLimits) */ int64_t max_tokens_cap = 0; /* 0: none */ int max_n = 8; int64_t max_stops = 64; diff --git a/core/server/sink.cpp b/core/server/sink.cpp index d32a7ef4..54017be0 100644 --- a/core/server/sink.cpp +++ b/core/server/sink.cpp @@ -89,8 +89,9 @@ void Sink::finish(Finish f) { } } -void Sink::fail(int rad_status) { +void Sink::fail(int rad_status, const char* why) { status_.store(rad_status, std::memory_order_release); + why_.store(why, std::memory_order_release); finish(Finish::Error); } diff --git a/core/server/sink.h b/core/server/sink.h index 2abd295b..7e5a704c 100644 --- a/core/server/sink.h +++ b/core/server/sink.h @@ -79,7 +79,9 @@ public: /* Terminal. Idempotent -- the first call wins, so a cancel racing a natural stop does not * produce two finish reasons. */ void finish(Finish f); - void fail(int rad_status); + /* `why` says what failed, in a sentence a client can read; a string that outlives the sink + * (a literal), or null. */ + void fail(int rad_status, const char* why = nullptr); /* The scheduler polls this to learn that the client hung up, and frees the blocks (spec §14). * It is also told by IScheduler::cancel(); this is the cheap path that needs no lookup. */ @@ -100,6 +102,7 @@ public: bool done() const { return finish_.load(std::memory_order_acquire) != (int)Finish::None; } Finish finish_reason() const { return (Finish)finish_.load(std::memory_order_acquire); } int status() const { return status_.load(std::memory_order_acquire); } + const char* why() const { return why_.load(std::memory_order_acquire); } bool overflowed() const { return overflow_.load(std::memory_order_acquire); } /* The HTTP thread calls this when the peer disappears. It does NOT free anything itself -- @@ -135,6 +138,7 @@ private: std::atomic finish_{(int)Finish::None}; std::atomic status_{RAD_OK}; + std::atomic why_{nullptr}; std::atomic overflow_{false}; std::atomic cancel_{false}; std::atomic quiesced_{false}; /* the producer will not touch this object again */ @@ -159,8 +163,8 @@ inline bool sink_push(void* s, int32_t token, float logprob = 0.0f) { inline void sink_finish(void* s, Finish f) { if (s) static_cast(s)->finish(f); } -inline void sink_fail(void* s, int rad_status) { - if (s) static_cast(s)->fail(rad_status); +inline void sink_fail(void* s, int rad_status, const char* why = nullptr) { + if (s) static_cast(s)->fail(rad_status, why); } inline bool sink_cancelled(const void* s) { return s && static_cast(s)->cancel_requested(); diff --git a/core/util/rad_util.cpp b/core/util/rad_util.cpp index aa53fef8..8496a1de 100644 --- a/core/util/rad_util.cpp +++ b/core/util/rad_util.cpp @@ -156,35 +156,35 @@ std::vector split_ws(std::string_view s) { * touches this at declare, not per step. A hash map here would be slower and less predictable. */ void Geometry::set_i(std::string_view k, long long v) { for (size_t i = 0; i < keys_.size(); ++i) - if (keys_[i] == k) { kinds_[i] = RAD_P_INT; ivals_[i] = v; dirty_ = true; return; } + if (keys_[i] == k) { kinds_[i] = RAD_P_INT; ivals_[i] = v; rebuild(); return; } keys_.emplace_back(k); svals_.emplace_back(); ivals_.push_back(v); dvals_.push_back(0.0); kinds_.push_back(RAD_P_INT); - dirty_ = true; + rebuild(); } void Geometry::set_f(std::string_view k, double v) { for (size_t i = 0; i < keys_.size(); ++i) - if (keys_[i] == k) { kinds_[i] = RAD_P_F64; dvals_[i] = v; dirty_ = true; return; } + if (keys_[i] == k) { kinds_[i] = RAD_P_F64; dvals_[i] = v; rebuild(); return; } keys_.emplace_back(k); svals_.emplace_back(); ivals_.push_back(0); dvals_.push_back(v); kinds_.push_back(RAD_P_F64); - dirty_ = true; + rebuild(); } void Geometry::set_s(std::string_view k, std::string_view v) { for (size_t i = 0; i < keys_.size(); ++i) - if (keys_[i] == k) { kinds_[i] = RAD_P_STR; svals_[i] = std::string(v); dirty_ = true; return; } + if (keys_[i] == k) { kinds_[i] = RAD_P_STR; svals_[i] = std::string(v); rebuild(); return; } keys_.emplace_back(k); svals_.emplace_back(v); ivals_.push_back(0); dvals_.push_back(0.0); kinds_.push_back(RAD_P_STR); - dirty_ = true; + rebuild(); } bool Geometry::get_i(std::string_view k, long long* out) const { @@ -210,10 +210,12 @@ bool Geometry::has(std::string_view k) const { return false; } -void Geometry::rebuild() const { - auto* self = const_cast(this); - self->view_.clear(); - self->view_.reserve(keys_.size()); +/* Every key and every string value may have moved: an append can reallocate keys_ and svals_, and + * a short string lives inside its element. So the whole view is redone, which is the same handful + * of entries the setter's scan already walked. */ +void Geometry::rebuild() { + view_.clear(); + view_.reserve(keys_.size()); for (size_t i = 0; i < keys_.size(); ++i) { RadParam p{}; p.key = keys_[i].c_str(); @@ -221,14 +223,10 @@ void Geometry::rebuild() const { p.ival = ivals_[i]; p.dval = dvals_[i]; p.sval = kinds_[i] == RAD_P_STR ? svals_[i].c_str() : nullptr; - self->view_.push_back(p); + view_.push_back(p); } - dirty_ = false; } -const RadParam* Geometry::params() const { if (dirty_) rebuild(); return view_.data(); } -int Geometry::n_params() const { if (dirty_) rebuild(); return (int)view_.size(); } - std::string Geometry::str() const { std::string s; for (size_t i = 0; i < keys_.size(); ++i) { diff --git a/docs/GUIDE.md b/docs/GUIDE.md index ab35924c..ac343426 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -739,8 +739,11 @@ radiance --model m.rad --presence-penalty 1.5 --repetition-penalty 1.05 **How much a request may generate.** -- `--default-max-tokens N` sets `max_tokens` for a request that sends none. The default is 512. - `auto` means whatever the context leaves after the prompt. +- `--default-max-tokens N` sets `max_tokens` for a request that sends none. The default, `auto`, + is whatever the context leaves after the prompt, as in vLLM. Many clients send no `max_tokens`, + and a reasoning model can think for thousands of tokens before it answers: a small default ends + those answers inside the reasoning, with a `finish_reason: "length"` that chat clients do not + show. - `--max-tokens-cap N` is the most any request may generate. A larger `max_tokens` is cut to it rather than refused, and the reply ends with `finish_reason: "length"`, the same as the context bound (§5.8). @@ -887,7 +890,7 @@ that names the field wins. | `--dry-multiplier F`, `--dry-base F`, `--dry-allowed-length N`, `--dry-penalty-last-n N` | 0, 1.75, 2, -1 | DRY; a multiplier of 0 is off | | `--dry-sequence-breakers JSON` | `["\n", ":", "\"", "*"]` | a JSON array of at most 16 strings | | `--xtc-probability F`, `--xtc-threshold F` | 0, 0.1 | [0, 1] | -| `--default-max-tokens N` | 512 | `max_tokens` for a request that sends none; `auto` is what the context leaves | +| `--default-max-tokens N` | `auto` | `max_tokens` for a request that sends none; `auto` is what the context leaves | | `--max-tokens-cap N` | none | the most any request may generate; a larger `max_tokens` is cut to it, not refused | | `--max-n N` | the larger of 8 and `--max-num-seqs` | the largest `n` a request may ask for | | `--max-stop-strings N`, `--max-stop-bytes N` | 64, 4096 | how many stop strings a request may send, and how long each may be | @@ -1092,7 +1095,7 @@ curl -s http://localhost:8000/detokenize -H 'Content-Type: application/json' \ |---|---| | `model` | accepted and not enforced — one server serves one model | | `messages` / `prompt` / `input` | chat / completion / embedding | -| `max_tokens`, `max_completion_tokens` | default 512 (`--default-max-tokens`). Clamped to what the context leaves, and to `--max-tokens-cap`, rather than refused — see §5.8 | +| `max_tokens`, `max_completion_tokens` | default: what the context leaves after the prompt (`--default-max-tokens`). Clamped to what the context leaves, and to `--max-tokens-cap`, rather than refused — see §5.8 | | `temperature` | [0, 2] | | `top_p` | (0, 1] | | `top_k` | ≥ 0, 0 disables | diff --git a/libavx/avx_check.cpp b/libavx/avx_check.cpp index 5fedf026..5a2f6b80 100644 --- a/libavx/avx_check.cpp +++ b/libavx/avx_check.cpp @@ -802,6 +802,8 @@ static bool schema_same(const RadOpSchema& a, const RadOpSchema& b, std::string* /* embed_lookup_q over a file-backed table, two ranks and the reader racing (avx_check_rows.cpp). */ bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool verbose, bool bf16); +/* embed_lookup_q's init, where io_uring is refused and here (avx_check_rows.cpp). */ +bool ngram_init_case(const Lib& avx); int main(int argc, char** argv) { std::string ref_path = "libref.so", avx_path = "libavx.so", only_op; @@ -885,6 +887,12 @@ int main(int argc, char** argv) { } int rc = missing ? 1 : 0; + /* Before anything runs a gather: the case forks, and a child is cleanest taken from a process + * that has started none of the gather's threads. */ + if (only_op.empty() || only_op == "embed_lookup_q") { + std::printf("\n"); + if (!ngram_init_case(avx)) rc = 1; + } const int lo = only_level >= 0 ? only_level : 0; const int hi = only_level >= 0 ? only_level : AVX_N_LEVELS - 1; std::vector declined_ops; diff --git a/libavx/avx_check_rows.cpp b/libavx/avx_check_rows.cpp index 9d62e2bf..535c216d 100644 --- a/libavx/avx_check_rows.cpp +++ b/libavx/avx_check_rows.cpp @@ -28,13 +28,104 @@ #include #include +#include + #include +#include #include +#include #include +#include #include #include +#include #include +/* EMBED_LOOKUP_Q'S INIT REFUSES A PROCESS THAT MAY NOT MAKE AN io_uring RING, and says why: Docker's + * default seccomp profile answers EPERM to io_uring_setup, and a server started that way used to + * load the whole model and then fail every request as "unsupported". A child process installs the + * same refusal as a seccomp filter and asks the kernel's init, which must refuse a gather into + * bf16 -- the one that reads through the ring -- name the Docker option on stderr, and accept a + * gather into f32, which reads the table as memory. Then this process asks: it must accept where a + * ring can be made and refuse where it cannot, as in a build sandbox. */ +bool ngram_init_case(const Lib& avx) { + const char* what = "embed_lookup_q's init"; + const RadKernelInfo* r = avx.row("embed_lookup_q"); + if (!r || !r->init) { + std::printf(" %s: the row has no init\n", what); + return false; + } + RadParam bf16[2]{}, f32[2]{}; + bf16[0].key = f32[0].key = "n_embd"; + bf16[0].kind = f32[0].kind = RAD_P_INT; + bf16[0].ival = f32[0].ival = 160; + bf16[1].key = f32[1].key = "dtype"; + bf16[1].kind = f32[1].kind = RAD_P_STR; + bf16[1].sval = "bf16"; + f32[1].sval = "f32"; + + int out[2]; + if (::pipe(out) != 0) { + std::printf(" %s: pipe: %s\n", what, std::strerror(errno)); + return false; + } + std::fflush(nullptr); + const pid_t pid = ::fork(); + if (pid == 0) { + ::dup2(out[1], 2); + ::close(out[0]); + sock_filter f[] = { + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(seccomp_data, nr)), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_io_uring_setup, 0, 1), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | (EPERM & SECCOMP_RET_DATA)), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW), + }; + sock_fprog prog{ (unsigned short)(sizeof f / sizeof f[0]), f }; + if (::prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0 || + ::prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog) != 0) + ::_exit(3); + void* inst = nullptr; + const int a = r->init(bf16, 2, 0, 1, &inst); + const int b = r->init(f32, 2, 0, 1, &inst); + std::fflush(nullptr); + ::_exit(a == RAD_E_UNSUPPORTED && b == RAD_OK ? 0 : 1); + } + ::close(out[1]); + std::string said; + char buf[512]; + for (ssize_t k; (k = ::read(out[0], buf, sizeof buf)) > 0;) said.append(buf, (size_t)k); + ::close(out[0]); + int ws = 0; + if (pid < 0 || ::waitpid(pid, &ws, 0) != pid || !WIFEXITED(ws)) { + std::printf(" %s: the child did not run to the end\n", what); + return false; + } + bool ok = true; + if (WEXITSTATUS(ws) == 3) { + std::printf(" %s, where io_uring is refused: SKIPPED -- no seccomp filter can be installed " + "here\n", what); + } else if (WEXITSTATUS(ws) != 0 || + said.find("--security-opt seccomp=unconfined") == std::string::npos) { + std::printf(" %s, where io_uring is refused: FAIL -- %s; it said: %s\n", what, + WEXITSTATUS(ws) ? "the statuses were wrong" : "the reason was not named", + said.c_str()); + ok = false; + } else { + std::printf(" %s, where io_uring is refused: refused, naming the Docker option\n", what); + } + + io_uring_params p{}; + const long ring = syscall(__NR_io_uring_setup, 1, &p); + const bool here = ring >= 0; + if (here) ::close((int)ring); + void* inst = nullptr; + const int st = r->init(bf16, 2, 0, 1, &inst); + const bool right = here ? st == RAD_OK : st == RAD_E_UNSUPPORTED; + std::printf(" %s, in this process (io_uring %s): %s\n", what, here ? "available" : "refused", + right ? (here ? "accepted" : "refused") : "FAIL"); + return ok && right; +} + bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool verbose, bool bf16) { const RadKernelInfo* r = avx.row("embed_lookup_q"); diff --git a/libavx/avx_ngram.cpp b/libavx/avx_ngram.cpp index cd248c2b..c300553d 100644 --- a/libavx/avx_ngram.cpp +++ b/libavx/avx_ngram.cpp @@ -439,6 +439,7 @@ struct ReadRing { io_uring_cqe *cqes = nullptr; void *sq_ring = nullptr, *cq_ring = nullptr; size_t sq_sz = 0, cq_sz = 0, sqe_sz = 0; + int err = 0; /* the errno that stopped init(), for ring_refusal() */ /* One thread submits and reaps (SINGLE_ISSUER), and completions are run when it asks for them * rather than by interrupting it (DEFER_TASKRUN): the ring is thread-local and the thread only @@ -448,7 +449,7 @@ struct ReadRing { std::memset(&p, 0, sizeof p); p.flags = IORING_SETUP_SINGLE_ISSUER | IORING_SETUP_DEFER_TASKRUN; const long r = syscall(__NR_io_uring_setup, kEntries, &p); - if (r < 0) return false; + if (r < 0) { err = errno; return false; } fd = (int)r; entries = p.sq_entries; sq_sz = p.sq_off.array + (size_t)p.sq_entries * sizeof(unsigned); @@ -459,16 +460,16 @@ struct ReadRing { } sq_ring = mmap(nullptr, sq_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd, IORING_OFF_SQ_RING); - if (sq_ring == MAP_FAILED) { sq_ring = nullptr; shut(); return false; } + if (sq_ring == MAP_FAILED) { err = errno; sq_ring = nullptr; shut(); return false; } cq_ring = (p.features & IORING_FEAT_SINGLE_MMAP) ? sq_ring : mmap(nullptr, cq_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd, IORING_OFF_CQ_RING); - if (cq_ring == MAP_FAILED) { cq_ring = nullptr; shut(); return false; } + if (cq_ring == MAP_FAILED) { err = errno; cq_ring = nullptr; shut(); return false; } sqe_sz = (size_t)p.sq_entries * sizeof(io_uring_sqe); sqes = (io_uring_sqe*)mmap(nullptr, sqe_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd, IORING_OFF_SQES); - if (sqes == MAP_FAILED) { sqes = nullptr; shut(); return false; } + if (sqes == MAP_FAILED) { err = errno; sqes = nullptr; shut(); return false; } sq_tail = (unsigned*)((char*)sq_ring + p.sq_off.tail); sq_mask = (unsigned*)((char*)sq_ring + p.sq_off.ring_mask); sq_array = (unsigned*)((char*)sq_ring + p.sq_off.array); @@ -532,17 +533,51 @@ struct ReadRing { /* Thread-local: each rank thread issues its own step, so each gets its own ring and the two never * contend. Built on that thread's first gather over a file and torn down when the thread exits. */ -inline ReadRing* read_ring() { +/* This thread's ring, made on its first gather. Null if it could not be made, with the errno in + * `*why`. */ +inline ReadRing* read_ring(int* why) { static thread_local bool tried = false; + static thread_local int err = 0; static thread_local std::unique_ptr r; if (!tried) { tried = true; std::unique_ptr p(new ReadRing()); if (p->init()) r = std::move(p); + else err = p->err ? p->err : EIO; } + if (!r && why) *why = err; return r.get(); } +/* WHY THIS PROCESS CANNOT MAKE A RING, said in terms of what to change. Docker's default seccomp + * profile is by far the commonest: it answers EPERM to io_uring_setup, and so does the + * kernel.io_uring_disabled sysctl. A kernel too old for SINGLE_ISSUER and DEFER_TASKRUN answers + * EINVAL. */ +std::string ring_refusal(int e) { + std::string s = "libavx: the n-gram table is read through io_uring, and this process cannot " + "make a ring (" + std::string(std::strerror(e)) + "). "; + if (e == EPERM || e == EACCES) + s += "Docker's default seccomp profile refuses io_uring: run the container with " + "--security-opt seccomp=unconfined (docs/DOCKER.md). Outside a container, the " + "kernel.io_uring_disabled sysctl refuses it the same way."; + else if (e == ENOSYS) + s += "This kernel is built without io_uring."; + else if (e == EINVAL) + s += "The ring needs IORING_SETUP_SINGLE_ISSUER and IORING_SETUP_DEFER_TASKRUN, which " + "Linux 6.1 added."; + return s; +} + +/* Whether this process can make the ring every gathering thread makes: 0, or the errno that + * stopped it. Asked once, by making one and closing it. */ +int ring_errno() { + static const int e = [] { + ReadRing r; + return r.init() ? 0 : (r.err ? r.err : EIO); + }(); + return e; +} + /* Read `reads` through the ring, a batch at a time: a row with a slot is copied into the cache and * published READY; a row without one is decoded straight into its output row. On a failed read, * every claim not yet published is given up (its word back to EMPTY) so no other thread waits on @@ -711,7 +746,7 @@ struct AheadReader { void run() { Gather& g = gather_state(); - ReadRing* rr = read_ring(); + ReadRing* rr = read_ring(nullptr); const uint64_t me = owner_tag(); for (;;) { AheadJob j; @@ -861,9 +896,15 @@ int avx::row_gather(const RowGather& q, RowDecode decode) { if (!tfile) return ferr; #if defined(__linux__) if (tfile->fd >= 0) { - ReadRing* rr = read_ring(); + int why = 0; + ReadRing* rr = read_ring(&why); + if (!rr) { + static std::once_flag said; + std::call_once(said, [why] { std::fprintf(stderr, "%s\n", ring_refusal(why).c_str()); }); + return RAD_E_UNSUPPORTED; + } RowCache* rc = row_cache(tfile, q.row_bytes); - if (!rr || !rc) return RAD_E_UNSUPPORTED; + if (!rc) return RAD_E_NOMEM; const long long ws = q.world_size > 1 ? q.world_size : 1; const long long first = q.rank > 0 && q.rank < ws ? q.M * q.rank / ws : 0; const int rs = gather_rows(*tfile, *rc, *rr, q, first, decode, lut); @@ -943,3 +984,30 @@ extern "C" int avx_layout_ngram(const RadParam* p, int n_p, int operand, const R if (pl[0].rank != 2 || pl[0].shape[0] != r || pl[0].shape[1] != c) return RAD_E_SHAPE; return RAD_E_UNSUPPORTED; } + +/* ============================== THE INSTANCE: CAN THIS PROCESS READ THE TABLE ============================== + * + * Every miss of the gather into bf16 is an io_uring read, and a process that may not make a ring + * fails every step that gathers: the first request fails, after the whole model has loaded, and + * the engine stops. So the instance asks at declare, before a byte is loaded, and refuses with + * the reason. A gather into any other dtype takes the general path, which reads the table as + * memory and makes no ring. rad-convert declares without instances -- it launches nothing -- so a + * sandbox that forbids io_uring still converts the model. */ +extern "C" int avx_init_ngram(const RadParam* p, int n_p, int rank, int world_size, void** out) { + (void)rank; + (void)world_size; + if (out) *out = nullptr; +#if defined(__linux__) + const char* dt = rad_param_gets(p, n_p, "dtype", nullptr); + if (!dt || std::strcmp(dt, "bf16") != 0) return RAD_OK; + if (const int e = ring_errno()) { + static std::once_flag said; + std::call_once(said, [e] { std::fprintf(stderr, "%s\n", ring_refusal(e).c_str()); }); + return RAD_E_UNSUPPORTED; + } +#else + (void)p; + (void)n_p; +#endif + return RAD_OK; +} diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 5f628cce..17d687eb 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -725,14 +725,16 @@ SIMPLE("avx_all_gather", "all_gather", "ar", "gather every rank's shard; world_s SIMPLE("avx_embed_lookup", "embed_lookup", "vocab", "embedding gather", DT_FLOAT, L(embed_lookup)), /* THE ONE ROW WITH A LAYOUT HOOK, and it only checks: the table is read as it is stored, and the * hook refuses a table encoded any other way (avx_ngram.cpp). An E4M3 table into bf16 goes through - * the row cache; every other dtype pair takes the general gather. */ + * the row cache; every other dtype pair takes the general gather. Its init refuses a process that + * may not make the io_uring ring the cache's misses are read through, at declare and not at the + * first request. */ { "avx_embed_lookup_q", "embed_lookup_q", "vocab", "embedding gather, one scale for the table: an E4M3 table into bf16 through a shared row cache " "and direct reads of the container, a later call's rows read ahead", SHAPE_ANY, DT_ANY, RAD_DOMAIN_HOST, 0, nullptr, 0, nullptr, 0, nullptr, - /* init, fini, LAUNCH, scratch, layout, relayout, opd_shape, unrelayout */ - nullptr, nullptr, L(embed_lookup_q), nullptr, avx_layout_ngram, nullptr, nullptr, nullptr, + /* INIT, fini, LAUNCH, scratch, layout, relayout, opd_shape, unrelayout */ + avx_init_ngram, nullptr, L(embed_lookup_q), nullptr, avx_layout_ngram, nullptr, nullptr, nullptr, nullptr, nullptr }, SIMPLE("avx_logits_gemm", "logits_gemm", "vocab", "the lm_head projection", DT_FLOAT, L(logits_gemm)), diff --git a/libavx/avx_rows.h b/libavx/avx_rows.h index c4203ae8..d54ccb42 100644 --- a/libavx/avx_rows.h +++ b/libavx/avx_rows.h @@ -52,4 +52,8 @@ int row_gather(const RowGather& g, RowDecode decode); extern "C" int avx_layout_ngram(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, RadLayout*); +/* Whether this process can read the table's rows: refused, with the reason on stderr, where it may + * not make an io_uring ring (avx_ngram.cpp). */ +extern "C" int avx_init_ngram(const RadParam*, int, int, int, void**); + #endif /* RAD_AVX_ROWS_H */ diff --git a/tests/chatparse_test.cpp b/tests/chatparse_test.cpp index 3d4d8923..b86f0fae 100644 --- a/tests/chatparse_test.cpp +++ b/tests/chatparse_test.cpp @@ -1228,7 +1228,7 @@ static double seconds_to(const std::function& f, int reps = 3) { } static double stream_bytes(const ReplyParser& p, const std::string& text, size_t piece, - std::vector* per_call = nullptr) { + std::vector* per_call = nullptr, int reps = 3) { return seconds_to([&] { std::unique_ptr s = p.open(); std::vector ev; @@ -1240,7 +1240,7 @@ static double stream_bytes(const ReplyParser& p, const std::string& text, size_t ev.clear(); } s->finish(&ev); - }, per_call ? 1 : 3); + }, per_call ? 1 : reps); } TEST(a_long_reply_streamed_byte_by_byte_costs_a_constant_factor_of_parsing_it_once) { @@ -1264,16 +1264,25 @@ TEST(a_long_reply_streamed_byte_by_byte_costs_a_constant_factor_of_parsing_it_on } } -TEST(twice_the_reply_costs_twice_the_time) { +/* FOUR TIMES THE REPLY COSTS FOUR TIMES THE TIME, and a quadratic path sixteen: the bound of 8 sits + * a factor of two from each. The two sizes are timed in turns, best of five each, so a burst of load + * from whatever else the machine runs lands on both: timed one size after the other, best of three, + * a 2x step read x3.9 beside three other test binaries and a server, against the 4 a quadratic + * path gives. */ +TEST(four_times_the_reply_costs_four_times_the_time) { for (const Model& m : models()) { Bench* b = bench(m, ChatRequest{}); if (!b) continue; - const std::string a = long_reply(m, 200 * 1024), c = long_reply(m, 400 * 1024); - const double ta = stream_bytes(b->parser(), a, 1), tc = stream_bytes(b->parser(), c, 1); + const std::string a = long_reply(m, 100 * 1024), c = long_reply(m, 400 * 1024); + double ta = 1e30, tc = 1e30; + for (int rep = 0; rep < 5; ++rep) { + ta = std::min(ta, stream_bytes(b->parser(), a, 1, nullptr, 1)); + tc = std::min(tc, stream_bytes(b->parser(), c, 1, nullptr, 1)); + } const double ratio = tc / ta; fprintf(stderr, " %s: %zu -> %zu bytes byte by byte: %.3f -> %.3f ms (x%.2f)\n", m.name.c_str(), a.size(), c.size(), ta * 1e3, tc * 1e3, ratio); - CHECK(ratio < 3.0); + CHECK(ratio < 8.0); } } diff --git a/tests/oot_plugins.sh b/tests/oot_plugins.sh index 6ffad876..519bcdf6 100644 --- a/tests/oot_plugins.sh +++ b/tests/oot_plugins.sh @@ -119,10 +119,17 @@ say "4. the installed rad-kbench replays the fixture from the out-of-tree home: # 5. The device library's machine code, against the tree's, object by object. A code object also # carries its compilation unit's ID, which clang hashes from the command line and the output path, # so two builds of one source never agree byte for byte; their instructions (.text) and kernel -# descriptors (.rodata) do, unless the flags that reach the device compiler differ. +# descriptors do, unless the flags that reach the device compiler differ. +# +# THE DESCRIPTORS ARE COMPARED BY NAME, NOT AS .rodata's BYTES. The compiler lays them out in an +# order that changes from one run of the same command to the next -- ROCm 7's clang does it to the +# eight instances of the template in r4d_gdn_chunk_scan_k128_v128_c64_bf16.hip -- and each holds +# its kernel's entry as an offset from itself, so the section's bytes differ while every kernel and +# every descriptor is the same. Each descriptor is read by its symbol, its entry resolved to the +# address in .text it names, and the rest of .rodata is compared with the descriptors blanked. if [ -n "$HIPC" ]; then L=$(dirname "$HIPC") - for t in llvm-objcopy clang-offload-bundler; do + for t in llvm-objcopy llvm-readelf clang-offload-bundler; do [ -x "$L/$t" ] || fail "no $t beside $HIPC" done td="$B/libr4d/CMakeFiles/libr4d.dir" @@ -131,15 +138,34 @@ if [ -n "$HIPC" ]; then fatbin() { # fatbin OBJ -- its fat binary into $W/co/fb; false for a source with no kernels "$L/llvm-objcopy" --dump-section .hip_fatbin="$W/co/fb" "$1" /dev/null 2>/dev/null } - code() { # code OBJ TARGET -- checksums of that target's instructions and kernel descriptors + descriptors() { # descriptors CO RODATA -- each descriptor by name; blanks it in RODATA + set -- "$1" "$2" $("$L/llvm-readelf" -SW "$1" | + awk '{ for (i = 1; i < NF; ++i) if ($i == ".rodata") print $(i + 2), $(i + 3) }') + [ $# -eq 4 ] || return 0 + base=$((0x$3)); foff=$((0x$4)) + "$L/llvm-readelf" -sW "$1" | awk '$4 == "OBJECT" && $8 ~ /\.kd$/ { print $2, $3, $8 }' | + sort -u -k3 | + while read -r val size name; do + a=$((0x$val)); o=$((foff + a - base)) + e=$(od -An -t d8 -j $((o + 16)) -N 8 "$1" | tr -d ' ') + printf '%s %s entry=%x %s %s\n' "$name" "$size" $((a + e)) \ + "$(od -An -v -t x1 -j "$o" -N 16 "$1" | tr -d ' \n')" \ + "$(od -An -v -t x1 -j $((o + 24)) -N $((size - 24)) "$1" | tr -d ' \n')" + dd if=/dev/zero of="$2" bs=1 seek=$((a - base)) count="$size" conv=notrunc 2>/dev/null + done + } + code() { # code OBJ TARGET -- checksums of that target's instructions, its descriptors by + # name, and the rest of its read-only data fatbin "$1" "$L/clang-offload-bundler" --type=o --input="$W/co/fb" --unbundle --targets="$2" \ --output="$W/co/co" for sec in .text .rodata; do - "$L/llvm-objcopy" --dump-section "$sec=$W/co/sec" "$W/co/co" /dev/null 2>/dev/null || - : > "$W/co/sec" - cksum < "$W/co/sec" + "$L/llvm-objcopy" --dump-section "$sec=$W/co/$sec" "$W/co/co" /dev/null 2>/dev/null || + : > "$W/co/$sec" done + cksum < "$W/co/.text" + descriptors "$W/co/co" "$W/co/.rodata" | cksum + cksum < "$W/co/.rodata" } [ "$(ls "$td"/*.hip.o | wc -l)" = "$(ls "$od"/*.hip.o | wc -l)" ] || fail "libr4d compiles a different set of HIP sources out of tree" diff --git a/tests/sched_test.cpp b/tests/sched_test.cpp index cc6e5cd5..b7d87a10 100644 --- a/tests/sched_test.cpp +++ b/tests/sched_test.cpp @@ -10,6 +10,7 @@ #include "sched/scheduler.h" #include "sched/derive.h" +#include "server/sink.h" #include #include @@ -546,6 +547,19 @@ struct Fixture { return id; } + /* The same, with the server's sink attached, for what a request tells its client. */ + uint64_t submit_to(server::Sink* sink, int n_prompt, int max_tokens) { + auto r = std::make_unique(); + r->id = next_id++; + r->max_tokens = max_tokens; + r->sink = sink; + r->prompt.resize((size_t)n_prompt); + for (int i = 0; i < n_prompt; ++i) r->prompt[(size_t)i] = 1000 + i; + uint64_t id = r->id; + if (sch.add(std::move(r)) < 0) return 0; + return id; + } + /* Commit a step in which every sequence produced one token and none ended. */ void commit_plain(int32_t token = 7) { const StepPlan& p = sch.plan(); @@ -2039,4 +2053,27 @@ TEST(shutdown_fails_what_is_queued_and_refuses_what_follows) { CHECK(f.sch.step() == nullptr); } +/* AND EACH OF THOSE REQUESTS SAYS WHAT STOPPED IT. The sink carries the status and the sentence + * the server puts in the 500: without them a client read "the engine failed this request: ok" + * after a step failed as unsupported. */ +TEST(shutdown_fails_each_sink_with_the_status_that_stopped_the_engine) { + server::Sink running, waiting, late; + Fixture f; + f.build(/*blocks=*/20, /*states=*/64); + CHECK_OK(f.start()); + + CHECK(f.submit_to(&running, 160, 64) != 0); + CHECK(f.sch.step() != nullptr); + CHECK(f.submit_to(&waiting, 160, 64) != 0); + + f.sch.shutdown("the engine stopped", RAD_E_UNSUPPORTED); + CHECK(f.submit_to(&late, 8, 8) == 0); + for (server::Sink* s : { &running, &waiting, &late }) { + CHECK(s->done()); + CHECK_EQ((int)s->finish_reason(), (int)server::Finish::Error); + CHECK_EQ(s->status(), (int)RAD_E_UNSUPPORTED); + CHECK_EQ(std::string(s->why() ? s->why() : ""), std::string("the engine stopped")); + } +} + RAD_TEST_MAIN() diff --git a/tests/server_test.cpp b/tests/server_test.cpp index d35d4efb..0fdab7f2 100644 --- a/tests/server_test.cpp +++ b/tests/server_test.cpp @@ -226,6 +226,10 @@ struct FakeMultimodal : IMultimodal { struct FakeScheduler : IScheduler { std::string reply = "hello"; bool hang = false; + /* Nonzero: after the reply, the request is failed with this status and reason, as the engine + * fails every request it holds when a step fails. */ + int fail_status = 0; + const char* fail_why = nullptr; SchedMetrics m; std::mutex mu; @@ -251,9 +255,11 @@ struct FakeScheduler : IScheduler { int32_t cap = r.max_tokens; std::string text = reply; bool h = hang; + const int fst = fail_status; + const char* fwhy = fail_why; /* Under the lock: over a real socket, submits arrive from several HTTP workers at once. */ std::lock_guard lk(mu); - workers.emplace_back([sink, cap, text, h] { + workers.emplace_back([sink, cap, text, h, fst, fwhy] { sink_prompt_stats(sink, 8, 4); int32_t n = 0; for (char c : text) { @@ -271,6 +277,7 @@ struct FakeScheduler : IScheduler { sink_finish(sink, Finish::Length); return; } + if (fst) { sink_fail(sink, fst, fwhy); return; } sink_finish(sink, n >= cap ? Finish::Length : Finish::Stop); }); return id; @@ -1055,6 +1062,17 @@ TEST(the_max_tokens_default_and_cap_bound_a_request_like_the_context) { CHECK_EQ(chat_with(f, lim, R"("max_tokens":9999)").max_tokens, 10); CHECK_EQ(chat_with(f, lim, R"("max_tokens":5)").max_tokens, 5); + /* AND `auto` IS THE DEFAULT: limits built with nothing said about max_tokens give a request + * that names none what the context leaves. 512 ended a reasoning model's answers inside its + * reasoning, with a finish_reason "length" a chat client does not show. */ + { + OaiLimits d; + d.model_id = lim.model_id; + d.max_ctx = 64; + OaiRequest a = chat_with(f, d, ""); + CHECK_EQ((int64_t)a.prompts[0].tokens.size() + a.max_tokens, d.max_ctx); + } + /* The cap holds where no context is declared, and on /v1/completions. */ lim.max_ctx = 0; lim.default_max_tokens = 512; @@ -1239,7 +1257,7 @@ TEST(server_info_reports_what_a_request_that_leaves_a_field_out_gets) { ServerOptions o; Server srv(d, o); const json j = json::parse(srv.router().call("GET", "/server_info").body); - CHECK_EQ(j["server"]["default_max_tokens"].get(), 512); + CHECK(j["server"]["default_max_tokens"].is_null()); /* auto */ CHECK(j["server"]["max_tokens_cap"].is_null()); CHECK_EQ(j["server"]["max_stop_strings"].get(), 64); const json& r = j["request_defaults"]; @@ -1442,6 +1460,43 @@ TEST(streaming_completions_use_the_text_completion_chunk_shape) { CHECK_EQ(text, std::string("pq")); } +/* A REQUEST THE ENGINE FAILED SAYS WHAT FAILED, in the 500 and in a stream's error event: the + * reason and the status the engine stopped on. It read "the engine failed this request: ok" when + * a step failed, because nothing carried the status to the request. */ +TEST(a_request_the_engine_failed_says_what_failed) { + Fixture f; + f.sched.reply = "he"; + f.sched.fail_status = RAD_E_UNSUPPORTED; + f.sched.fail_why = "the engine stopped on an error and is not serving"; + const std::string want = "the engine failed this request: the engine stopped on an error and " + "is not serving (unsupported)"; + + HttpResponse r = f.post("/v1/chat/completions", + R"({"messages":[{"role":"user","content":"hi"}]})"); + CHECK_EQ(r.status, 500); + CHECK_EQ(json::parse(r.body)["error"]["message"].get(), want); + + HttpResponse s = f.post("/v1/completions", R"({"prompt":"hi","stream":true})"); + CHECK_EQ(s.status, 200); + int bad = 0, errors = 0; + for (const std::string& p : sse_payloads(drain(s), &bad)) { + if (p == "[DONE]") continue; + json j = json::parse(p); + if (!j.contains("error")) continue; + ++errors; + CHECK_EQ(j["error"]["message"].get(), want); + } + CHECK_EQ(bad, 0); + CHECK_EQ(errors, 1); + + /* With no reason given, the status alone -- and never "ok". */ + f.sched.fail_why = nullptr; + HttpResponse t = f.post("/v1/chat/completions", + R"({"messages":[{"role":"user","content":"hi"}]})"); + CHECK_EQ(json::parse(t.body)["error"]["message"].get(), + std::string("the engine failed this request: unsupported")); +} + TEST(a_streamed_tool_call_is_named_before_its_arguments_flow) { Fixture f; f.sched.reply = "TOOL:lookup:{\"q\":\"x\"}"; diff --git a/tests/tokenizer_perf_test.cpp b/tests/tokenizer_perf_test.cpp index cee5c124..022cc93d 100644 --- a/tests/tokenizer_perf_test.cpp +++ b/tests/tokenizer_perf_test.cpp @@ -7,8 +7,8 @@ * - throughput on prose-and-code text, against an absolute floor and against the reference * encoder (tools/tokref) on the same text -- the ratio holds on a loaded machine where an * absolute number would not; - * - LINEAR SCALING: twice the text takes about twice the time, on ordinary text and on the - * inputs a pre-tokeniser is quadratic on when it goes wrong (one enormous word, one + * - LINEAR SCALING: four times the text takes about four times the time, on ordinary text and + * on the inputs a pre-tokeniser is quadratic on when it goes wrong (one enormous word, one * enormous run of whitespace, digits, alternating classes); * - the segment cache: the last turn of a long conversation costs a fraction of encoding it. * @@ -82,6 +82,18 @@ double encode_seconds(const Tokenizer& t, const std::string& text, int runs = 5) return best_of(runs, [&] { ids.clear(); t.encode(text, ids, false, true); }); } +/* TWO TEXTS TIMED IN TURNS, best of five each, so a burst of load from whatever else the machine + * runs lands on both: timed one after the other, a parallel ctest beside a server read a linear + * input as x3.6 for twice the text, past the bound a quadratic one is held to. */ +void encode_both(const Tokenizer& t, const std::string& small, const std::string& big, + double* ts, double* tb) { + *ts = *tb = 1e30; + for (int i = 0; i < 5; ++i) { + *ts = std::min(*ts, encode_seconds(t, small, 1)); + *tb = std::min(*tb, encode_seconds(t, big, 1)); + } +} + } /* namespace */ TEST(throughput_has_a_floor_and_beats_the_reference) { @@ -100,20 +112,23 @@ TEST(throughput_has_a_floor_and_beats_the_reference) { CHECK(r / s > 4.0); } -/* TWICE THE TEXT, ABOUT TWICE THE TIME. The texts differ, so a cache that remembered one would - * not help the other; the ratio is allowed well past 2 because the larger one also walks more of - * memory. */ +/* FOUR TIMES THE TEXT, ABOUT FOUR TIMES THE TIME. The texts differ, so a cache that remembered one + * would not help the other; the ratio is allowed well past 4 because the larger one also walks + * more of memory. A quarter and a whole megabyte: the cost of a byte steps up by about half + * between one and two megabytes on the machine these were measured on, where the working set + * leaves the core's cache, and a step across that reads as growth the encoder does not have. */ TEST(encoding_time_is_linear_in_the_text) { auto v = vocab(); REQUIRE(v != nullptr); Tokenizer t; t.init(v); t.set_segment_cache(false); - const std::string one = document(3, 1 << 20), two = document(4, 2 << 20); - const double a = encode_seconds(t, one), b = encode_seconds(t, two); - std::fprintf(stderr, " 1 MB %.2f ms, 2 MB %.2f ms, ratio %.2f\n", a * 1e3, b * 1e3, b / a); - CHECK(b / a > 1.3); - CHECK(b / a < 2.8); + const std::string one = document(3, 256 << 10), four = document(4, 1 << 20); + double a, b; + encode_both(t, one, four, &a, &b); + std::fprintf(stderr, " 256 KB %.2f ms, 1 MB %.2f ms, ratio %.2f\n", a * 1e3, b * 1e3, b / a); + CHECK(b / a > 2.6); + CHECK(b / a < 6.0); } /* THE INPUTS A SPLITTER GOES QUADRATIC ON. A backtracking `\s+(?!\S)` rescans a whitespace run @@ -133,14 +148,16 @@ TEST(pathological_inputs_stay_linear) { { "alternating", [](size_t n) { std::string s; while (s.size() < n) s += "a1!"; return s; } }, { "apostrophes", [](size_t n) { std::string s; while (s.size() < n) s += "''s"; return s; } }, }; - /* A megabyte and two, best of five: at a few hundred kilobytes one of these runs in a couple of - * milliseconds, which one preemption under a parallel ctest turns into a false quadratic. */ + /* 125 and 500 KB: linear is 4, quadratic 16, and the bound of 8 sits a factor of two from + * each. Both stay below the size where a byte's cost steps up (see above); a run of whitespace + * costs a little more a byte as it grows, about x4.8 here, and that is not what this holds. */ for (const auto& in : inputs) { - const std::string one = in.make(1000000), two = in.make(2000000); - const double a = encode_seconds(t, one, 5), b = encode_seconds(t, two, 5); - std::fprintf(stderr, " %-17s 1 MB %7.2f ms, 2 MB %7.2f ms, ratio %.2f\n", in.name, + const std::string one = in.make(125000), four = in.make(500000); + double a, b; + encode_both(t, one, four, &a, &b); + std::fprintf(stderr, " %-17s 125 KB %7.2f ms, 500 KB %7.2f ms, ratio %.2f\n", in.name, a * 1e3, b * 1e3, b / a); - CHECK(b / a < 3.0); + CHECK(b / a < 8.0); } } diff --git a/tests/util_test.cpp b/tests/util_test.cpp index 7437c21c..aa90f884 100644 --- a/tests/util_test.cpp +++ b/tests/util_test.cpp @@ -14,7 +14,10 @@ #include "rad_internal.h" +#include #include +#include +#include using namespace rad; @@ -162,8 +165,8 @@ TEST(the_param_view_is_rebuilt_after_a_mutation) { CHECK_EQ(g.n_params(), 1); CHECK_EQ(g.params()[0].ival, 8ll); - /* The view is cached, so the question is whether the cache is invalidated. A stale view hands - * a kernel the geometry it was resolved against rather than the one it is being run on. */ + /* The view is built by the writes, so the question is whether every write rebuilds it. A stale + * view hands a kernel the geometry it was resolved against rather than the one it is run on. */ g.set_i("M", 9); CHECK_EQ(g.params()[0].ival, 9ll); g.set_i("N", 4096); @@ -186,15 +189,15 @@ TEST(the_param_view_is_rebuilt_after_a_mutation) { CHECK_EQ(seen, 1); } -/* THE COPY MUST OWN ITS OWN STRINGS, and the header says why at length: the cached view holds - * char* into the object's own storage, so a copy that took the view along with the storage would +/* THE COPY MUST OWN ITS OWN STRINGS, and the header says why at length: the view holds char* + * into the object's own storage, so a copy that took the view along with the storage would * hand a kernel pointers into the source -- which dies first about as often as not, since every * Resolved holds a Geometry and every Band holds two. */ TEST(a_copied_geometry_points_into_itself_and_not_at_the_source) { Geometry a; a.set_s("dtype", "w4a8"); a.set_i("M", 64); - const char* a_key = a.params()[0].key; /* force the source to build its view */ + const char* a_key = a.params()[0].key; Geometry b = a; CHECK_EQ(b.n_params(), 2); @@ -202,6 +205,7 @@ TEST(a_copied_geometry_points_into_itself_and_not_at_the_source) { CHECK(b.params()[0].key != a_key); /* a different object's storage */ CHECK(b.params()[0].sval != a.params()[0].sval); CHECK_EQ(std::string(b.params()[0].sval), std::string("w4a8")); + CHECK(b.params()[0].sval == b.get_s("dtype")); /* and into the copy's own string */ /* And the two are independent afterwards, in both directions. */ a.set_i("M", 1); @@ -225,11 +229,12 @@ TEST(a_moved_geometry_does_not_leave_the_view_pointing_at_a_stolen_buffer) { Geometry a; a.set_s("dtype", "fp8"); a.set_i("K", 5120); - (void)a.params(); /* build the view, then move out from under it */ Geometry b = std::move(a); CHECK_EQ(b.n_params(), 2); CHECK_EQ(std::string(b.params()[0].sval), std::string("fp8")); + CHECK(b.params()[0].sval == b.get_s("dtype")); /* the view went with the strings it names */ + CHECK_EQ(std::string(b.params()[0].key), std::string("dtype")); /* The moved-from object is empty rather than holding a view of a buffer it no longer owns. */ CHECK_EQ(a.n_params(), 0); @@ -241,6 +246,49 @@ TEST(a_moved_geometry_does_not_leave_the_view_pointing_at_a_stolen_buffer) { CHECK_EQ(b.n_params(), 0); } +/* READING A GEOMETRY WRITES NOTHING, so one that nobody is writing can be read from any number of + * threads. The sizing declares of one rank run side by side and every one of them reads the real + * program's op geometries (Engine::probe_arena_levels); a view built lazily on first read was a + * write each of them made, and two threads clearing and filling one vector corrupted the heap at + * startup. Each round reads a fresh geometry -- a moved one, as every OpInfo's is -- from eight + * threads released together, and every reader must see the whole view and the same one. */ +TEST(a_geometry_read_from_many_threads_at_once_is_not_written) { + constexpr int kThreads = 8, kRounds = 400; + int bad = 0; + for (int round = 0; round < kRounds && bad == 0; ++round) { + Geometry src; + src.set_s("dtype", "fp8_e4m3_with_a_name_past_the_short_string_buffer"); + for (int k = 0; k < 12; ++k) src.set_i(fmt("key_%d", k), k * 1000 + round); + const Geometry g = std::move(src); + + std::atomic ready{0}; + std::atomic go{false}; + std::vector seen(kThreads, nullptr); + std::vector ok(kThreads, 0); + std::vector th; + for (int t = 0; t < kThreads; ++t) + th.emplace_back([&, t] { + ready.fetch_add(1); + while (!go.load()) {} + const RadParam* p = g.params(); + const int n = g.n_params(); + bool good = n == 13 && std::string(p[0].key) == "dtype" && p[0].sval && + std::string(p[0].sval).rfind("fp8_e4m3", 0) == 0; + for (int k = 0; good && k < 12; ++k) + good = p[k + 1].kind == RAD_P_INT && p[k + 1].ival == k * 1000 + round && + std::string(p[k + 1].key) == fmt("key_%d", k); + seen[t] = p; + ok[t] = good; + }); + while (ready.load() < kThreads) {} + go.store(true); + for (auto& x : th) x.join(); + for (int t = 0; t < kThreads; ++t) + if (!ok[t] || seen[t] != seen[0]) ++bad; + } + CHECK_EQ(bad, 0); +} + TEST(geometry_str_prints_every_kind_in_declaration_order) { Geometry g; g.set_i("M", 64); diff --git a/tools/rad_convert.cpp b/tools/rad_convert.cpp index d001c86e..c22d0411 100644 --- a/tools/rad_convert.cpp +++ b/tools/rad_convert.cpp @@ -566,7 +566,8 @@ int main(int argc, char** argv) { for (size_t k = 0; k < widths.size(); ++k) { Program trial; ctx.kv_dtype = widths[k]; - if (rad_tools_declare(plugins, meta.m, ctx, &trial, {}, nullptr, provide) < 0) { + if (rad_tools_declare(plugins, meta.m, ctx, &trial, {}, nullptr, provide, + /*instances=*/false) < 0) { if (planning_errors()) RAD_ERR("the weights above could not be planned, and declare saw each of them as " "the plain dtype it was declared at -- fix those first");