diff --git a/CMakeLists.txt b/CMakeLists.txt index fd73a36c..35d7521a 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.5 LANGUAGES C CXX) +project(radiance VERSION 1.0.6 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/README.md b/README.md index 037f3481..f88b4648 100644 --- a/README.md +++ b/README.md @@ -36,11 +36,13 @@ curl -LC - -O https://huggingface.co/StillDeadcode/minicpm5-2b-fp8/resolve/main/ The host needs Docker and an `amdgpu` driver that supports ROCm 7.2; it does not need ROCm. The image is [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), with its -kernels built for `gfx1201`. Pull it, then start a model from its compose file: +kernels built for `gfx1201`. Pull it, clone this repository for its compose files, then start a +model from one of them: ```sh docker pull stilldeadcode/radiance -cp -r deploy/compose ~/radiance-compose && cd ~/radiance-compose +git clone https://codeberg.org/StillDeadcode/radiance.git +cp -r radiance/deploy/compose ~/radiance-compose && cd ~/radiance-compose cp .env.example .env # set RADIANCE_MODELS, RADIANCE_STATE, RADIANCE_API_KEY, the GIDs docker compose -f minicpm5-2b.yaml up -d # or any file from the table docker compose -f minicpm5-2b.yaml logs -f @@ -51,15 +53,16 @@ Every model uses both cards and the same port, so run one at a time. Running wit the reason for each `docker run` option, is in [`docs/DOCKER.md`](docs/DOCKER.md). To build the image yourself, for example for other cards, run `docker/build.sh -t 'gfx1200;gfx1201'` -(it needs `docker buildx` and tests the build as it goes). Then set `RADIANCE_IMAGE=radiance:latest` -in `.env`. +in the clone (it needs `docker buildx` and tests the build as it goes). Then set +`RADIANCE_IMAGE=radiance:latest` in `.env`. ## Build from source -You need Linux, a C++20 compiler, CMake 3.21+ and Ninja. For the device kernels you also need ROCm -7.2 (`hipcc`; set `ROCM_PATH` if it is not `/opt/rocm`). +You need Linux, git, a C++20 compiler, CMake 3.21+ and Ninja. For the device kernels you also need +ROCm 7.2 (`hipcc`; set `ROCM_PATH` if it is not `/opt/rocm`). Clone the repository and build in it: ```sh +git clone https://codeberg.org/StillDeadcode/radiance.git && cd radiance ./build.sh # configure, build for the cards present, run the tests ./build.sh --no-hip # host backend only cmake -S . -B build -G Ninja -DRAD_GPU_TARGETS='gfx1201' # build for cards this machine lacks diff --git a/core/engine.cpp b/core/engine.cpp index e240e797..6dc3ed20 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -1525,6 +1525,10 @@ int Engine::serve() { for (auto& rk : ranks_) rio.push_back({ rk->device, rk->ctx.stream(), &rk->program }); RAD_TRY(sched_.init(ranks_[0]->program, cfg_, kv_iface_.get(), pc_iface_.get(), rio, &geo_)); + /* The step staging the budget kept room for exists now, so a checkpoint slot backed from here + * on leaves the headroom and only what is still to be built on first use. */ + set_checkpoint_floors(std::max(cfg_.gpu_headroom_mib, 0) * (1ll << 20) + + late_lazy_bytes_); for (auto& r : ranks_) r->sampler.attach_vocab(vocab_view_.get()); diff --git a/core/engine.h b/core/engine.h index b4296eb2..971cd92a 100644 --- a/core/engine.h +++ b/core/engine.h @@ -310,6 +310,15 @@ private: * one part of the KV pool still backed on demand. Measured once at the end of bringup; it is * not something the API promises. */ bool release_frees_card_ = true; + /* WHAT THE VRAM BUDGET KEPT FOR ALLOCATIONS MADE AFTER start(), on top of --gpu-headroom-mib: + * the step batch's staging, which serve() allocates, and what is built on first use, if + * ever -- the KV tiers' copy staging and the second compute lane's queue. The checkpoint + * slots backed at the end of bringup leave both free, and the bringup's closing reading is + * checked against both. */ + int64_t late_step_bytes_ = 0; + int64_t late_lazy_bytes_ = 0; + /* Every rank's checkpoint floor: a slot is backed only while the card keeps `keep` free. */ + void set_checkpoint_floors(int64_t keep); int run_server(); /* THE KL MODE (core/kld.h), in place of run_server: the corpus's documents submitted as * scoring requests, and every step's scored rows copied to the host and handed to `kld_`. diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 7e9d88d1..66ce0f6f 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -652,12 +652,27 @@ int Engine::plan() { { std::vector facts; facts.reserve(ranks_.size()); + late_step_bytes_ = late_lazy_bytes_ = 0; const int64_t ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train; for (auto& r : ranks_) { RAD_TRY(rad_dev_set(r->device)); + VramFacts f{}; + /* ONE HARDWARE QUEUE'S VRAM, MEASURED BY MAKING TWO. The engine's compute stream, + * its mover's and a second compute lane are all made after this reading, and the + * driver backs each queue with VRAM the ring alone does not account for. The second + * queue is the unit, so a runtime that sets itself up on its first queue charges that + * once and to `already held`, which is read after both are gone. */ + { + RadStream q[2] = { nullptr, nullptr }; + RadDeviceProps a{}, b{}; + if (rad_stream_create(&q[0], 0) >= 0 && rad_dev_props(r->device, &a) >= 0 && + rad_stream_create(&q[1], 0) >= 0 && rad_dev_props(r->device, &b) >= 0) + f.queue_bytes = std::max(a.vram_free - b.vram_free, 0); + for (RadStream s : q) if (s) rad_stream_destroy(s); + } + f.n_queues = 2 + (r->program.scratch_regions > 1 ? 1 : 0); RadDeviceProps props{}; rad_dev_props(r->device, &props); - VramFacts f{}; f.capacity = props.vram_bytes; f.free = props.vram_free; /* AN EIGHTH OF THE HOST'S MEMORY STAYS THE HOST'S on integrated graphics. The card's @@ -702,6 +717,26 @@ int Engine::plan() { } f.staging = BatchBuilder::device_bytes(r->program, cfg_, kg); if (f.staging < 0) return RAD_E_INVAL; + late_step_bytes_ = std::max(late_step_bytes_, f.staging); + int64_t lazy = r->program.scratch_regions > 1 ? f.queue_bytes : 0; + /* AND THE KV TIERS' COPY STAGING, which TierExec::device_init builds on the first + * copy out. Which groups the prefix cache indexes is settled after this split, so + * every paged group is counted: the entry it sizes can only be smaller. */ + if (cfg_.prefix_cache_host_mib > 0 || cfg_.prefix_cache_disk_mib > 0) { + int64_t entry = 0, bs = 0; + int ng = 0; + for (size_t g = 0; g < r->program.kv_groups.size(); ++g) { + const KVGroupPlan* p = probe.plan((int32_t)g); + if (!p || !p->paged() || p->bytes_per_block <= 0) continue; + entry += p->bytes_per_block; + bs = bs > 0 ? std::min(bs, p->block_size) : p->block_size; + ++ng; + } + const int64_t tier = TierExec::device_bytes(entry, ng, TierExec::sizes(entry, ctx, bs)); + f.staging += tier; + lazy += tier; + } + late_lazy_bytes_ = std::max(late_lazy_bytes_, lazy); facts.push_back(f); } VramBudget vb; @@ -2150,20 +2185,19 @@ int Engine::configure_kv() { * and 0.02 ms a step of the VRAM it costs. The batch is one gather per (group, * layer) however many entries are in it, so the launches are the same either * way -- this buys the copies, which are what there are thousands of. */ - const int max_batch = (int)std::min( - 4096, std::max(64, (16ll << 20) / entry_bytes)); /* A COPY OUT IS FOUR STAGING BATCHES, about 64 MiB a rank. It shares the transfer * stream with the expert mover, so what it queues is what a promotion issued * behind it waits for -- a few milliseconds of link at this size -- and the next * copy goes out on the tick after this one lands, so a long conversation still * leaves at the rate the link carries it. * - * A RESTORE IS A WHOLE CHAIN, as long as the longest context this server takes. */ - const int64_t max_copy = 4ll * max_batch; - const int64_t bs = std::max(1, ranks_[0]->prefix.block_size()); - const int64_t max_chain = - (std::max(1, cfg_.max_ctx > 0 ? cfg_.max_ctx : meta_.n_ctx_train) - + bs - 1) / bs + 1; + * A RESTORE IS A WHOLE CHAIN, as long as the longest context this server takes. + * TierExec::sizes holds the arithmetic, which the VRAM budget reserves from. */ + const TierExec::Sizes tz = TierExec::sizes( + entry_bytes, cfg_.max_ctx > 0 ? cfg_.max_ctx : meta_.n_ctx_train, + ranks_[0]->prefix.block_size()); + const int max_batch = tz.max_batch; + const int64_t max_copy = tz.max_copy, max_chain = tz.max_chain; bool all = true; for (auto& r : ranks_) { /* ON THAT RANK'S DEVICE. rad_dev_alloc takes the CURRENT device, and the @@ -2345,6 +2379,18 @@ static void bind_kv_pools(const Program& p, const KVManager& kv, std::vectordevice; + r->kv.set_checkpoint_floor([dev](int64_t* free_now) -> int { + RadDeviceProps p{}; + RAD_TRY(rad_dev_props(dev, &p)); + *free_now = p.vram_free; + return RAD_OK; + }, keep); + } +} + int Engine::start() { std::vector devs; std::string inventory; @@ -2650,18 +2696,14 @@ int Engine::start() { * HEADROOM. Rank 0's free list hands the ids out and every rank writes its shard of a snapshot * into the same slot of its own pool; backing a slot on one card and meeting a refusal on the * other at the snapshot copy would stop the engine mid-serve. See - * KVManager::set_checkpoint_floor for why the floor is the headroom. */ + * KVManager::set_checkpoint_floor for why the floor is the headroom. + * + * AND NOT INTO WHAT THE BUDGET KEPT FOR LATER either: the step staging serve() allocates, and + * what is built on first use. serve() lowers the floor once the staging exists. */ + const int64_t headroom = std::max(cfg_.gpu_headroom_mib, 0) * (1ll << 20); + const int64_t keep_now = headroom + late_step_bytes_ + late_lazy_bytes_; if (!ranks_.empty()) { - const int64_t keep = std::max(cfg_.gpu_headroom_mib, 0) * (1ll << 20); - for (auto& r : ranks_) { - const int dev = r->device; - r->kv.set_checkpoint_floor([dev](int64_t* free_now) -> int { - RadDeviceProps p{}; - RAD_TRY(rad_dev_props(dev, &p)); - *free_now = p.vram_free; - return RAD_OK; - }, keep); - } + set_checkpoint_floors(keep_now); std::vector peers; for (size_t i = 1; i < ranks_.size(); ++i) peers.push_back(&ranks_[i]->kv); ranks_[0]->kv.set_checkpoint_peers(std::move(peers)); @@ -2679,21 +2721,22 @@ int Engine::start() { RAD_TRY(lead.back_free_checkpoints(&gone)); if (gone > 0) { const int64_t stride = lead.checkpoint_stride(); - const int64_t keep = std::max(cfg_.gpu_headroom_mib, 0) * (1ll << 20); int64_t short_by = 0; for (auto& r : ranks_) { RadDeviceProps p{}; if (rad_dev_props(r->device, &p) < 0) continue; - short_by = std::max(short_by, gone * stride - (p.vram_free - keep)); + short_by = std::max(short_by, gone * stride - (p.vram_free - keep_now)); } RAD_WARN("checkpoint slots: %lld of %lld backed (%s each), %lld withdrawn -- one more " - "would take a card under the %s --gpu-headroom-mib, the room a kernel's first " - "launch allocates from. The prefix cache holds %lld linear-state snapshots on " - "the card and its retention policy decides which. The budget counted all " - "%lld; the card is %s short of them, which is allocations made after the " - "budget was resolved.", + "would take a card under the %s it has to keep free: the %s " + "--gpu-headroom-mib, the room a kernel's first launch allocates from, and %s " + "the budget kept for the step staging and for what is built on first use. " + "The prefix cache holds %lld linear-state snapshots on the card and its " + "retention policy decides which. The budget counted all %lld; the card is %s " + "short of them, which is allocations made after the budget was resolved.", (long long)(asked - gone), (long long)asked, humanb(stride).c_str(), - (long long)gone, humanb(keep).c_str(), (long long)(asked - gone), + (long long)gone, humanb(keep_now).c_str(), humanb(headroom).c_str(), + humanb(late_step_bytes_ + late_lazy_bytes_).c_str(), (long long)(asked - gone), (long long)asked, humanb(short_by).c_str()); } } @@ -2703,20 +2746,29 @@ int Engine::start() { RadDeviceProps props{}; if (rad_dev_props(r->device, &props) < 0 || props.vram_bytes <= 0) continue; + /* AGAINST THE HEADROOM AND WHAT THE BUDGET KEPT FOR LATER, because both are still free + * here: the step staging is allocated by serve(), and the KV tiers' staging and a second + * compute lane are built on first use. A card at exactly the headroom now would be under + * it once those exist. */ const int64_t MiB = 1024 * 1024; - const int64_t want = std::max(cfg_.gpu_headroom_mib, 0) * MiB; + const int64_t late = late_step_bytes_ + late_lazy_bytes_; + const int64_t want = headroom + late; const int64_t got = props.vram_free; + const std::string asked = + late > 0 ? fmt("%s (the %s --gpu-headroom-mib and %s kept for the step staging and " + "for what is built on first use)", humanb(want).c_str(), + humanb(headroom).c_str(), humanb(late).c_str()) + : fmt("%s --gpu-headroom-mib", humanb(want).c_str()); if (got < want) { /* WHAT THIS SHORTFALL THREATENS is whatever allocates after startup: a kernel's code * object, loaded on its FIRST launch, and a spilling kernel's scratch, sized on its * first launch by the whole grid. Neither is knowable when the budget is resolved, and * running out for either is a fault inside the HIP runtime rather than an error. */ - RAD_WARN("card %d settled at %s free against the %s --gpu-headroom-mib asked to keep. " - "The difference is allocations made after the budget was resolved, and it is " - "the room a kernel's first launch allocates from. Raise --gpu-headroom-mib by " - "at least %s so the budget is resolved against the right number.", - r->device, humanb(got).c_str(), humanb(want).c_str(), - humanb(want - got).c_str()); + RAD_WARN("card %d settled at %s free against %s. The difference is allocations " + "made after the budget was resolved, and it comes out of the room a kernel's " + "first launch allocates from. Raise --gpu-headroom-mib by at least %s so the " + "budget is resolved against the right number.", + r->device, humanb(got).c_str(), asked.c_str(), humanb(want - got).c_str()); } else if (got > want + 256 * MiB) { /* AND "TOO MUCH" IS ONLY A FAULT WHERE SOMEBODY STATED THE BUDGET. Where the resolver @@ -2726,20 +2778,19 @@ int Engine::start() { * Warning here would contradict that receipt and send the reader looking for a flag * to set. */ if (cfg_.vram_budget_derived) - RAD_INFO("card %d settled at %s free against the %s --gpu-headroom-mib asked to " - "keep. The split accounted for it: neither pool could address another " - "byte, which is the `unusable` line of the VRAM budget above.", - r->device, humanb(got).c_str(), humanb(want).c_str()); + RAD_INFO("card %d settled at %s free against %s. The split accounted for it: " + "neither pool could address another byte, which is the `unusable` line of " + "the VRAM budget above.", + r->device, humanb(got).c_str(), asked.c_str()); else - RAD_WARN("card %d settled at %s free against the %s --gpu-headroom-mib asked to " - "keep, so %s is unused. On a model that does not fit in VRAM every unused " - "GiB is weight that has to be moved instead of read, and that is decode " - "step time.", - r->device, humanb(got).c_str(), humanb(want).c_str(), + RAD_WARN("card %d settled at %s free against %s, so %s is unused. On a model that " + "does not fit in VRAM every unused GiB is weight that has to be moved " + "instead of read, and that is decode step time.", + r->device, humanb(got).c_str(), asked.c_str(), humanb(got - want).c_str()); } else - RAD_INFO("card %d settled at %s free, against the %s --gpu-headroom-mib asked to keep", - r->device, humanb(got).c_str(), humanb(want).c_str()); + RAD_INFO("card %d settled at %s free, against %s", + r->device, humanb(got).c_str(), asked.c_str()); } return RAD_OK; } diff --git a/core/mem/vram_budget.cpp b/core/mem/vram_budget.cpp index 685a621b..7c67e403 100644 --- a/core/mem/vram_budget.cpp +++ b/core/mem/vram_budget.cpp @@ -49,6 +49,11 @@ int vram_budget_resolve(Config& cfg, const std::vector& per_rank, Vra freeb = std::min(freeb, f.free); b.arena = std::max(b.arena, f.arena); b.staging = std::max(b.staging, f.staging); + if ((int64_t)f.n_queues * f.queue_bytes > b.queues) { + b.queues = (int64_t)f.n_queues * f.queue_bytes; + b.n_queues = f.n_queues; + b.queue_bytes = f.queue_bytes; + } b.kv_ceiling = std::max(b.kv_ceiling, f.kv_ceiling); b.kv_fixed = std::max(b.kv_fixed, f.kv_fixed); b.statics = std::max(b.statics, f.statics); @@ -83,7 +88,7 @@ int vram_budget_resolve(Config& cfg, const std::vector& per_rank, Vra b.derived_kv = want_kv; /* What is left after the terms nobody gets to spend. */ - int64_t fixed = b.already_held + b.headroom + b.arena + b.staging; + int64_t fixed = b.already_held + b.headroom + b.arena + b.staging + b.queues; if (!want_w) fixed += cfg.vram_weights_mib * kMiB; /* a stated pool is fixed too */ if (!want_kv) fixed += cfg.vram_kv_mib * kMiB; b.claimable = b.capacity - fixed; @@ -95,7 +100,8 @@ int vram_budget_resolve(Config& cfg, const std::vector& per_rank, Vra " already held %10s (driver context, code objects, anything else on the card)\n" " --gpu-headroom-mib %10s\n" " activation arena %10s (buffer plan + kernel scratch)\n" - " step staging %10s (block tables + media staging)\n" + " step staging %10s (block tables, media and KV tier staging)\n" + " hardware queues %10s (%d at %s each, measured)\n" "%s%s" " ------------------------------\n" " SHORT BY %10s\n" @@ -103,6 +109,7 @@ int vram_budget_resolve(Config& cfg, const std::vector& per_rank, Vra "or free the card.\n", humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.headroom).c_str(), humanb(b.arena).c_str(), humanb(b.staging).c_str(), + humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(), want_w ? "" : fmt(" --vram-weights-mib %10s (stated)\n", humanb(cfg.vram_weights_mib * kMiB).c_str()).c_str(), want_kv ? "" : fmt(" --vram-kv-mib %10s (stated)\n", @@ -252,14 +259,17 @@ int vram_budget_resolve(Config& cfg, const std::vector& per_rank, Vra * line is not padding: to_mib truncates, and what it drops is real VRAM that ends up beside * the headroom. */ const int64_t granted = cfg.vram_weights_mib * kMiB + cfg.vram_kv_mib * kMiB; - const int64_t unclaimed = b.capacity - b.already_held - b.arena - b.staging - b.stage - granted; + const int64_t unclaimed = b.capacity - b.already_held - b.arena - b.staging - b.queues - b.stage - + granted; const double ela = b.elastic > 0 ? (double)b.elastic : 1.0; b.report = fmt( "VRAM budget, per card:\n" " card total %10s\n" " already held %10s measured: driver context, code objects, anything else resident\n" " activation arena %10s computed from the buffer plan\n" - " step staging %10s the step batch's block tables and media staging\n" + " step staging %10s the step batch's block tables and media staging, and the\n" + " KV tiers' copy staging\n" + " hardware queues %10s %d a card at %s each, measured: the engine's streams\n" " %-18s %10s %s\n" " ------------------------------\n" " claimable %10s\n" @@ -277,6 +287,7 @@ int vram_budget_resolve(Config& cfg, const std::vector& per_rank, Vra " could not place\n", humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.arena).c_str(), humanb(b.staging).c_str(), + humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(), shared ? "left to the host" : "--gpu-headroom-mib", humanb(b.headroom).c_str(), shared ? "integrated graphics: this memory is the host's; --vram-kv-mib states a pool " "outright" diff --git a/core/mem/vram_budget.h b/core/mem/vram_budget.h index 0da3ca7e..150a9dd1 100644 --- a/core/mem/vram_budget.h +++ b/core/mem/vram_budget.h @@ -60,7 +60,15 @@ struct VramFacts { int64_t capacity = 0; /* RadDeviceProps::vram_bytes -- totalGlobalMem */ int64_t free = 0; /* RadDeviceProps::vram_free, measured now */ int64_t arena = 0; /* arena_plan_bytes() for this rank's program, total incl. scratch */ - int64_t staging = 0; /* BatchBuilder::device_bytes(): the step slab and the media staging */ + int64_t staging = 0; /* BatchBuilder::device_bytes(): the step slab and the media staging, + * and TierExec::device_bytes() when a KV tier is configured */ + /* THE HARDWARE QUEUES this rank creates after `free` was read -- its compute stream, the expert + * mover's, and the second compute lane where the program declares one -- at `queue_bytes` + * each. MEASURED, by making one: a queue's kernel-argument ring is the engine's, and the + * driver backs every queue with VRAM of its own beside it (33 MiB a queue on an R9700, eight + * times the ring). */ + int n_queues = 0; + int64_t queue_bytes = 0; int64_t kv_ceiling = 0; /* KVManager::ceiling(max_ctx) for this rank's declared groups */ int64_t kv_fixed = 0; /* KVManager::fixed_bytes(): the part of the ceiling that is state */ /* weight_footprint() for this rank, which under tensor parallel is already this card's even @@ -78,6 +86,9 @@ struct VramFacts { * operator stated the budgets -- the placement report and the pool report both want the totals. */ struct VramBudget { int64_t capacity = 0, already_held = 0, headroom = 0, arena = 0, staging = 0; + int64_t queues = 0; /* n_queues * queue_bytes, from the rank that needs most */ + int n_queues = 0; + int64_t queue_bytes = 0; int64_t claimable = 0; /* after the fixed terms above */ int64_t statics = 0; /* off the top, before the ratio sees anything */ int64_t elastic = 0; /* claimable - statics: what the ratio divides */ diff --git a/core/runtime/tierexec.cpp b/core/runtime/tierexec.cpp index 72c1903d..326788f6 100644 --- a/core/runtime/tierexec.cpp +++ b/core/runtime/tierexec.cpp @@ -86,6 +86,28 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier* return RAD_OK; } +TierExec::Sizes TierExec::sizes(int64_t entry_bytes, int64_t max_ctx, int64_t block_size) { + Sizes s; + if (entry_bytes <= 0) return s; + /* 16 MiB of staging a rank, as entries, between 64 and 4096 of them: the reasons are at the + * call in bringup. A copy out is four batches, and a restore is a whole chain, as long as the + * longest context the server takes. */ + s.max_batch = (int)std::min(4096, std::max(64, (16ll << 20) / entry_bytes)); + s.max_copy = 4ll * s.max_batch; + const int64_t bs = std::max(1, block_size); + s.max_chain = (std::max(1, max_ctx) + bs - 1) / bs + 1; + return s; +} + +/* What device_init() allocates, each allocation rounded to the pool granule the card hands VRAM + * out in. */ +int64_t TierExec::device_bytes(int64_t entry_bytes, int n_groups, const Sizes& s) { + if (entry_bytes <= 0 || n_groups <= 0 || s.max_batch <= 0) return 0; + const int64_t idx_n = (int64_t)n_groups * (s.max_copy + (int64_t)kRing * s.max_chain); + return align_up((int64_t)s.max_batch * entry_bytes, (int64_t)RAD_ALIGN_POOL) + + align_up(idx_n * (int64_t)sizeof(int32_t), (int64_t)RAD_ALIGN_POOL); +} + void TierExec::close() { /* Nothing may still be reading the buffers about to be freed. */ if (stream_) (void)rad_stream_sync(stream_); diff --git a/core/runtime/tierexec.h b/core/runtime/tierexec.h index 9c2ab4d6..4b5b4afd 100644 --- a/core/runtime/tierexec.h +++ b/core/runtime/tierexec.h @@ -76,6 +76,14 @@ public: bool enabled() const { return enabled_; } std::string report() const { return report_; } + /* THE SIZES A CONFIGURE IS GIVEN, from one entry's bytes on this rank, the longest context and + * the block size, and the VRAM device_init() then takes for them. The VRAM budget reserves + * device_bytes() before any of this exists and bringup configures with sizes(), so the two + * cannot drift apart. */ + struct Sizes { int max_batch = 0; int64_t max_copy = 0, max_chain = 0; }; + static Sizes sizes(int64_t entry_bytes, int64_t max_ctx, int64_t block_size); + static int64_t device_bytes(int64_t entry_bytes, int n_groups, const Sizes& s); + /* DECIDING AND DOING ARE SEPARATE, and under tensor parallelism that is the point. The policy * is one object describing CONVERSATIONS, which are not sharded; the transfer is per rank, * because each rank holds its own shard of every block. So the leader plans, every rank runs diff --git a/core/runtime/wtab.cpp b/core/runtime/wtab.cpp index c32974ae..bfbed040 100644 --- a/core/runtime/wtab.cpp +++ b/core/runtime/wtab.cpp @@ -2,12 +2,16 @@ #include "wtab.h" #include "device/device.h" +#include "rad_internal.h" namespace rad { int wtab_patch(const WtabPatch& p, RadStream s) { if (p.n == 0) return RAD_OK; + /* After the stream's queued work, for the reason step_advance gives: a host stream is a queue + * with a worker, and a write made ahead of it changes a table that work issued earlier reads. */ if (device_is_host()) { + RAD_TRY(rad_stream_sync(s)); for (uint32_t i = 0; i < p.n; ++i) *p.dst[i] = p.val[i]; return RAD_OK; } diff --git a/core/runtime/wtab.h b/core/runtime/wtab.h index 661b75a8..34dd9398 100644 --- a/core/runtime/wtab.h +++ b/core/runtime/wtab.h @@ -24,8 +24,8 @@ struct WtabPatch { void* val[kWtabPatch] = {}; }; -/* Enqueue `p` on `s`. Under the host backend, whose streams run their work as it is issued and - * whose device memory is host memory, the writes happen here. */ +/* Enqueue `p` on `s`. Under the host backend, whose device memory is host memory, the writes + * happen here once `s` has run everything issued before them. */ int wtab_patch(const WtabPatch& p, RadStream s); } /* namespace rad */ diff --git a/core/sched/advance.cpp b/core/sched/advance.cpp index 8605df2d..d4b5e8c3 100644 --- a/core/sched/advance.cpp +++ b/core/sched/advance.cpp @@ -7,9 +7,13 @@ namespace rad { int step_advance(const AdvanceArgs& a, RadStream s) { if (a.n_seq <= 0) return RAD_OK; - /* THE HOST BACKEND RUNS A STREAM'S WORK AS IT IS ISSUED, and its device memory is host memory, - * so the rows run here, now, in the order the stream would have run them. */ + /* THE HOST BACKEND'S STREAMS ARE QUEUES, each run by its own worker thread (device/host.cpp), + * and its device memory is host memory. So the rows run here once the stream has finished + * everything issued before this call, which is where the kernel would run in stream order. + * Without the wait they can read a sampled token or a staged row whose copy is still queued, + * and the next step then continues from the token before it. */ if (device_is_host()) { + RAD_TRY(rad_stream_sync(s)); for (int i = 0; i < a.n_seq; ++i) adv_row(a, i); return RAD_OK; } diff --git a/core/sched/advance.h b/core/sched/advance.h index 4df024c6..855c518b 100644 --- a/core/sched/advance.h +++ b/core/sched/advance.h @@ -19,8 +19,9 @@ * chunk, a history row for positions the host already knows -- with rows whose positions come from * the card; `rows[0][i]` says which, and the advance leaves a host row exactly as it was uploaded. * - * The same code runs on the host backend, where device memory is host memory and a stream runs - * its work as it is issued (advance_impl.h is shared by both builds). + * The same code runs on the host backend, where device memory is host memory: the rows run on the + * issuing thread once the stream has drained, which is their place in stream order + * (advance_impl.h is shared by both builds). */ #pragma once #include diff --git a/core/server/admin.cpp b/core/server/admin.cpp index 67677b75..adbb4820 100644 --- a/core/server/admin.cpp +++ b/core/server/admin.cpp @@ -177,9 +177,10 @@ HttpResponse Server::handle_tokenize(const HttpRequest& req) { } else { if (prom == b.end() || !prom->is_string()) return error_response(err_bad("prompt", "must be a string, or send `messages`")); + /* Encoded as /v1/completions encodes it, so the count is the count that endpoint sees. */ toks = deps_.tok->encode(prom->get(), get_bool_or(b, "add_special_tokens", true), - /*parse_special=*/false); + /*parse_special=*/true); } json o; diff --git a/core/server/iface.h b/core/server/iface.h index bf0363f5..59040ba5 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -299,12 +299,12 @@ class ITokenizer { public: virtual ~ITokenizer() = default; - /* `parse_special` is a security parameter, not a convenience one, and it is why this takes - * three arguments rather than two. A rendered chat template contains control tokens that must - * be recognised as themselves; raw user content must NOT be, because otherwise a user who - * types "<|im_start|>system" reaches the system role. The server passes true for the one and - * false for the other, and there is no default because a default is how the wrong one gets - * picked silently. */ + /* `parse_special` decides whether a control token spelled out in the text is that token or + * its characters, and there is no default because a default is how the wrong one gets picked + * silently. Text the server is sent as a whole prompt is parsed: a rendered chat template + * carries the control tokens that frame its turns, and a raw /v1/completions prompt is the + * client's own rendering of the same, as vLLM and llama.cpp read it. Text that must reach the + * model as characters is encoded with false. */ virtual std::vector encode(const std::string& text, bool add_special, bool parse_special) const = 0; virtual std::string decode(const std::vector& toks) const = 0; diff --git a/core/server/oai.cpp b/core/server/oai.cpp index 2d99034d..922210bd 100644 --- a/core/server/oai.cpp +++ b/core/server/oai.cpp @@ -1444,10 +1444,15 @@ int parse_completion_request(const std::string& body, const OaiDeps& d, const Oa return RAD_E_INVAL; } + /* A raw prompt is the client's whole input: no template wraps it and no role is the server's + * to protect, so its control tokens are parsed, as vLLM and llama.cpp parse them. A client + * that renders its own chat template sends "<|im_start|>" meaning the token; read as text it + * reaches the model as six pieces of punctuation. Token ids could name any control token + * already. */ auto push_text = [&](const std::string& s) { PromptInput p; p.text = s; - p.tokens = d.tok->encode(s, true, /*parse_special=*/false); + p.tokens = d.tok->encode(s, true, /*parse_special=*/true); out->prompts.push_back(std::move(p)); }; auto push_ids = [&](const json& arr, ApiError* e) -> bool { @@ -1565,10 +1570,12 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa return true; }; + /* Parsed like a /v1/completions prompt, and for the same reason: the input is the client's + * own text with no template around it. */ if (it->is_string()) { PromptInput p; p.text = it->get(); - p.tokens = d.tok->encode(p.text, true, /*parse_special=*/false); + p.tokens = d.tok->encode(p.text, true, /*parse_special=*/true); out->prompts.push_back(std::move(p)); } else if (it->is_array()) { if (it->empty()) { *err = err_bad("input", "must not be empty"); return RAD_E_INVAL; } @@ -1577,7 +1584,7 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa if (!s.is_string()) { *err = err_bad("input", "expected all strings"); return RAD_E_INVAL; } PromptInput p; p.text = s.get(); - p.tokens = d.tok->encode(p.text, true, /*parse_special=*/false); + p.tokens = d.tok->encode(p.text, true, /*parse_special=*/true); out->prompts.push_back(std::move(p)); } } else if (it->front().is_number_integer()) { diff --git a/core/text/tokenizer.cpp b/core/text/tokenizer.cpp index c6032adc..29b67ff8 100644 --- a/core/text/tokenizer.cpp +++ b/core/text/tokenizer.cpp @@ -1312,8 +1312,6 @@ int Tokenizer::encode(std::string_view text, std::vector& out, if (!v_ || !v_->ready()) return RAD_E_STATE; const TokEncoder& e = *v_->enc_; - if (add_special && v_->add_bos() && v_->bos() >= 0) out.push_back(v_->bos()); - /* Special-token partitioning. The text is cut into (raw, token, raw, token, ...) around any * declared special token that appears literally, before any other step touches it, because a * special token is not something the pre-tokeniser is allowed to split. @@ -1324,6 +1322,19 @@ int Tokenizer::encode(std::string_view text, std::vector& out, std::vector frags; e.specials.split(text, parse_special, frags); + /* A text that already opens with BOS gets no second one. A client that renders its own chat + * template writes the template's BOS into the prompt, and a doubled BOS is a sequence the + * model never saw in training. */ + if (add_special && v_->add_bos() && v_->bos() >= 0) { + int32_t first = -1; + for (const SpecialFrag& f : frags) { + if (f.id < 0 && f.len == 0) continue; + first = f.id; + break; + } + if (first != v_->bos()) out.push_back(v_->bos()); + } + EncodeScratch sc; WordCache words; for (const SpecialFrag& f : frags) { diff --git a/docs/GUIDE.md b/docs/GUIDE.md index ac343426..0f387632 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -513,6 +513,12 @@ quite keep its headroom is safe rather than fatal — but it is costing you the `--gpu-headroom-mib` past the number startup names, so the budget resolver sees it and the expert plane is sized against it instead of trimmed afterwards. +What the engine itself allocates after the card is read is charged before the split, so it never +comes out of the headroom: the step staging, the KV tiers' copy staging, and its hardware queues. +A queue costs more than its ring — the driver backs each one with VRAM of its own, 33 MiB on an +R9700 — so startup measures one and the receipt's `hardware queues` line shows how many a card +holds at that price. + ### 4.4 Long context ```sh @@ -958,6 +964,11 @@ Method spellings follow vLLM's, including the ones that look odd: `/tokenize` is input is a body, and `/ping` answers both GET and POST because different load balancers send different ones. +A text prompt to `/v1/completions`, `/v1/embeddings` or `/tokenize` reads the model's control +tokens as tokens, as vLLM and llama.cpp do: a client that renders its own chat template can send +`<|im_start|>user\n…` and the model sees the turn markers. The BOS the model declares is prepended +unless the prompt already opens with it. + ### 5.2 Chat ```sh diff --git a/docs/TOOLS.md b/docs/TOOLS.md index a0e446a5..a044c36b 100644 --- a/docs/TOOLS.md +++ b/docs/TOOLS.md @@ -452,7 +452,7 @@ rad-tokcheck [options] ... --hf-dir DIR compare against HuggingFace ids in DIR/.ids (little-endian int32, encode(text, add_special_tokens=False)) --no-ref skip the reference encoder, which is slow - --user encode with parse_special off, as the server does for user content + --user encode with parse_special off: a control token's spelling is text --turns N turns in the multi-turn measurement (default 40, 0 skips it) --repeat N timing repeats, best taken (default 3) --context N ids shown either side of a difference (default 6) diff --git a/tests/device_test.cpp b/tests/device_test.cpp index b625188b..74af61c7 100644 --- a/tests/device_test.cpp +++ b/tests/device_test.cpp @@ -12,6 +12,7 @@ #include "rad_internal.h" #include "device/device.h" #include "device/directio.h" +#include "sched/advance.h" #include #include @@ -471,6 +472,68 @@ TEST(waiting_on_an_unrecorded_event_is_a_no_op) { CHECK_OK(rad_stream_sync(st.s)); } +/* AN ADVANCE RUNS AT ITS PLACE IN STREAM ORDER. The sampled token it accepts is the last thing a + * step copies into place, and the advance is issued behind that copy without a host wait. The + * host backend's streams are queues with a worker thread each, so an advance run on the issuing + * thread without draining the stream read the token before the copy landed, and the next step + * continued from the previous token: CPU-only decode repeated words and differed at temperature + * 0. A long chain of copies goes ahead of the token's here, so an advance that jumps the queue + * reads the poison. */ +TEST(an_advance_reads_the_token_a_copy_issued_before_it_delivers) { + const int64_t big = 4 << 20; + const int chain = 16; + RadStream s = nullptr; + REQUIRE(rad_stream_create(&s, 0) >= 0); + auto* blob_src = (uint8_t*)rad_dev_alloc(big, RAD_MEM_HOST_PINNED); + auto* blob_dst = (uint8_t*)rad_dev_alloc(big, RAD_MEM_DEVICE); + auto* slab = (char*)rad_dev_alloc(4096, RAD_MEM_DEVICE); + auto* src = (int32_t*)rad_dev_alloc(64, RAD_MEM_DEVICE); + auto* st = (rad::StepSlot*)rad_dev_alloc((int64_t)sizeof(rad::StepSlot), RAD_MEM_DEVICE); + auto* stage = (int32_t*)rad_dev_alloc(4096, RAD_MEM_HOST_PINNED); + REQUIRE(blob_src && blob_dst && slab && src && st && stage); + std::memset(blob_src, 0x5A, (size_t)big); + + /* One device row that sampled row 0 with no drafts, at context 10, slot 0. */ + rad::AdvanceArgs a; + a.mode = rad::ADV_ACCEPT; + a.n_seq = 1; + a.slab = slab; + a.row_off = 0; a.row_pitch = 1; + a.tok_off = 16; a.pos_off = 24; a.ctx_off = 32; a.acc_off = 40; a.out_off = 48; + a.sid_off = 56; a.cu_off = 64; a.q_off = 72; a.grp_off = 80; + a.st = st; + a.src = src; + const int32_t layout[20] = { 1, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 }; + std::memcpy(stage, layout, sizeof(layout)); + for (int round = 0; round < 3; ++round) { + stage[64] = 7; /* the poison: what src holds before the copy */ + stage[65] = 4242 + round; /* the token the copy delivers */ + REQUIRE(rad_memcpy_async(slab, stage, sizeof(layout), s) >= 0); + REQUIRE(rad_memcpy_async(src, stage + 64, 4, s) >= 0); + REQUIRE(rad_memset_async(st, 0, (int64_t)sizeof(rad::StepSlot), s) >= 0); + REQUIRE(rad_stream_sync(s) >= 0); + + for (int i = 0; i < chain; ++i) REQUIRE(rad_memcpy_async(blob_dst, blob_src, big, s) >= 0); + REQUIRE(rad_memcpy_async(src, stage + 65, 4, s) >= 0); + CHECK_OK(rad::step_advance(a, s)); + rad::StepSlot got{}; + REQUIRE(rad_memcpy_async(stage + 128, st, (int64_t)sizeof(rad::StepSlot), s) >= 0); + REQUIRE(rad_stream_sync(s) >= 0); + std::memcpy(&got, stage + 128, sizeof(rad::StepSlot)); + CHECK_EQ(got.tok[0], 4242 + round); + CHECK_EQ(got.ctx, 11); + CHECK_EQ(got.n_acc, 1); + } + rad_dev_free(stage, RAD_MEM_HOST_PINNED); + rad_dev_free(st, RAD_MEM_DEVICE); + rad_dev_free(src, RAD_MEM_DEVICE); + rad_dev_free(slab, RAD_MEM_DEVICE); + rad_dev_free(blob_dst, RAD_MEM_DEVICE); + rad_dev_free(blob_src, RAD_MEM_HOST_PINNED); + rad_stream_destroy(s); +} + + TEST(the_null_stream_is_refused) { /* HIP's stream 0 serialises against every other blocking stream in the process, which is the * opposite of what a transfer is for here. Refusing it on both backends means a caller cannot diff --git a/tests/mem_test.cpp b/tests/mem_test.cpp index c5029b7b..32bd6ca4 100644 --- a/tests/mem_test.cpp +++ b/tests/mem_test.cpp @@ -307,6 +307,51 @@ TEST(a_dense_model_has_no_expert_share_to_lose) { CHECK(c.vram_weights_mib * MiB - f.statics < MiB); } +/* THE ENGINE'S HARDWARE QUEUES ARE A FIXED TERM. Each one costs the card VRAM the driver backs it + * with, and the streams are made after the card is read, so a split that left them out spent + * them out of the headroom: 67 MiB a card on a two-card Flash-Next server, leaving 9 MiB free + * under load against 96. The rank that needs most sets the term, as every fold here does. */ +TEST(the_engine_s_queues_come_off_the_card_before_the_split) { + Config c = small_config(); + c.vram_weights_mib = 0; + c.vram_kv_mib = 0; + c.gpu_headroom_mib = 96; + c.expert_cache_ratio = 0.75; + VramFacts f{}; + f.capacity = 32LL << 30; + f.free = f.capacity - (512LL << 20); + f.arena = 144LL << 20; + f.staging = 98LL << 20; + f.statics = 2LL << 30; + f.experts = 200LL << 30; + f.kv_ceiling = 100LL << 30; + VramBudget b0; + CHECK_OK(vram_budget_resolve(c, { f }, &b0)); + + /* A fresh config: the resolver writes its answer back into the one it is given. */ + Config c2 = small_config(); + c2.vram_weights_mib = 0; + c2.vram_kv_mib = 0; + c2.gpu_headroom_mib = 96; + c2.expert_cache_ratio = 0.75; + VramFacts g = f, h = f; + g.n_queues = 2; g.queue_bytes = 33LL << 20; + h.n_queues = 3; h.queue_bytes = 33LL << 20; /* a rank with a second compute lane */ + VramBudget b; + CHECK_OK(vram_budget_resolve(c2, { g, h }, &b)); + CHECK_EQ(b.queues, 99LL << 20); + CHECK_EQ(b.n_queues, 3); + CHECK_EQ(b.claimable, b0.claimable - (99LL << 20)); + CHECK(b.report.find("hardware queues") != std::string::npos); + + /* What is left after the pools is still the headroom, with the queues and the staging paid. */ + const int64_t MiB = 1024 * 1024; + const int64_t unclaimed = f.capacity - (512LL << 20) - f.arena - f.staging - b.queues + - c2.vram_weights_mib * MiB - c2.vram_kv_mib * MiB; + CHECK(unclaimed >= 96 * MiB); + CHECK(unclaimed < 98 * MiB); +} + TEST(a_stated_budget_still_wins_and_the_other_side_still_derives) { Config c = small_config(); c.vram_weights_mib = 20000; /* stated */ diff --git a/tests/runtime_test.cpp b/tests/runtime_test.cpp index 47dfd71e..dd206959 100644 --- a/tests/runtime_test.cpp +++ b/tests/runtime_test.cpp @@ -20,6 +20,7 @@ #include "runtime/ctx.h" #include "runtime/rank_barrier.h" #include "runtime/residency.h" +#include "runtime/wtab.h" #include #include @@ -1261,4 +1262,47 @@ TEST(arena_plan_bytes_returns_the_total_with_or_without_its_out_parameters) { CHECK_EQ(a, total); } +/* A WEIGHT-TABLE PATCH LANDS AT ITS PLACE IN STREAM ORDER: work issued before it reads the old + * entry, work issued after it the new one. On the host backend the patch is a host write, and + * made without draining the stream it reached the table before a queued reader issued ahead of + * it. A chain of copies holds that reader back long enough for a write that jumps the queue to + * show. */ +TEST(a_weight_table_patch_lands_in_stream_order) { + const int64_t big = 4 << 20; + const int chain = 16; + RadStream s = nullptr; + REQUIRE(rad_stream_create(&s, 0) >= 0); + auto* blob_src = (uint8_t*)rad_dev_alloc(big, RAD_MEM_HOST_PINNED); + auto* blob_dst = (uint8_t*)rad_dev_alloc(big, RAD_MEM_DEVICE); + auto* tab = (void**)rad_dev_alloc(64, RAD_MEM_DEVICE); + auto* stage = (void**)rad_dev_alloc(64, RAD_MEM_HOST_PINNED); + REQUIRE(blob_src && blob_dst && tab && stage); + std::memset(blob_src, 0x5A, (size_t)big); + for (int round = 0; round < 3; ++round) { + void* const before = (void*)(uintptr_t)(0x1000 + round); + void* const after = (void*)(uintptr_t)(0x2000 + round); + stage[0] = before; + stage[1] = stage[2] = nullptr; + REQUIRE(rad_memcpy_async(tab, stage, sizeof(void*), s) >= 0); + REQUIRE(rad_stream_sync(s) >= 0); + + for (int i = 0; i < chain; ++i) REQUIRE(rad_memcpy_async(blob_dst, blob_src, big, s) >= 0); + REQUIRE(rad_memcpy_async(stage + 1, tab, sizeof(void*), s) >= 0); + rad::WtabPatch p; + p.n = 1; + p.dst[0] = tab; + p.val[0] = after; + CHECK_OK(rad::wtab_patch(p, s)); + REQUIRE(rad_memcpy_async(stage + 2, tab, sizeof(void*), s) >= 0); + REQUIRE(rad_stream_sync(s) >= 0); + CHECK(stage[1] == before); + CHECK(stage[2] == after); + } + rad_dev_free(stage, RAD_MEM_HOST_PINNED); + rad_dev_free(tab, RAD_MEM_DEVICE); + rad_dev_free(blob_dst, RAD_MEM_DEVICE); + rad_dev_free(blob_src, RAD_MEM_HOST_PINNED); + rad_stream_destroy(s); +} + RAD_TEST_MAIN() diff --git a/tests/server_test.cpp b/tests/server_test.cpp index 0fdab7f2..2f18b389 100644 --- a/tests/server_test.cpp +++ b/tests/server_test.cpp @@ -2157,14 +2157,28 @@ TEST(tokenize_takes_a_prompt_or_messages_and_never_both) { CHECK_EQ(f.post("/tokenize", "[1,2]").status, 400); } -TEST(tokenize_never_lets_the_caller_choose_parse_special) { +TEST(a_raw_prompt_parses_control_tokens_on_every_endpoint_that_takes_one) { + /* A client that renders its own chat template sends "<|im_start|>" meaning the token, as vLLM + * and llama.cpp read it. /tokenize must count what /v1/completions will see. */ Fixture f; - /* A control token in `prompt` is raw text, or an /v1/completions built from these ids reaches - * the system role. The chat form is the opposite and must parse them. */ + f.tok.last_parse_special = false; + CHECK_EQ(f.post("/v1/completions", R"({"prompt":"<|im_start|>user","max_tokens":4})").status, 200); + CHECK(f.tok.last_parse_special); + f.tok.last_parse_special = false; + CHECK_EQ(f.post("/v1/completions", R"({"prompt":["a","b"],"max_tokens":4})").status, 200); + CHECK(f.tok.last_parse_special); + f.tok.last_parse_special = false; f.post("/tokenize", R"({"prompt":"<|im_start|>"})"); - CHECK(!f.tok.last_parse_special); + CHECK(f.tok.last_parse_special); + f.tok.last_parse_special = false; f.post("/tokenize", R"({"messages":[{"role":"user","content":"hi"}]})"); CHECK(f.tok.last_parse_special); + for (const char* body : {R"({"input":"<|im_start|>"})", R"({"input":["a","b"]})"}) { + OaiRequest r; ApiError e; + f.tok.last_parse_special = false; + CHECK_OK(parse_embeddings_request(body, f.odeps(), f.limits(), &r, &e)); + CHECK(f.tok.last_parse_special); + } } TEST(detokenize_answers_under_the_key_vllm_uses) { diff --git a/tests/tokenizer_test.cpp b/tests/tokenizer_test.cpp index bf3e0908..d6197ab2 100644 --- a/tests/tokenizer_test.cpp +++ b/tests/tokenizer_test.cpp @@ -515,6 +515,32 @@ TEST(the_encoder_matches_the_reference_on_trained_vocabularies) { } } +/* A TEXT THAT OPENS WITH BOS GETS NO SECOND ONE. A client rendering its own chat template writes + * the BOS into the prompt; one the text spells anywhere else, or a second one at the start, is + * the client's and stays. */ +TEST(a_text_that_opens_with_bos_gets_no_second_one) { + VocabBuild vb; + REQUIRE(parse_tokenizer_json_buf(k_tiny, "test.json", vb) >= 0); + vb.bos = 12; + vb.add_bos = true; + auto v = load(std::move(vb)); + REQUIRE(v != nullptr); + Tokenizer t; + CHECK_OK(t.init(v)); + auto enc = [&](const char* s, bool add_special, bool parse_special) { + std::vector ids; + t.encode(s, ids, add_special, parse_special); + return ids; + }; + CHECK(enc("ab", true, true) == (std::vector{ 12, 4 })); + CHECK(enc("<|end|>ab", true, true) == (std::vector{ 12, 4 })); + CHECK(enc("<|end|><|end|>ab", true, true) == (std::vector{ 12, 12, 4 })); + CHECK(enc("ab<|end|>", true, true) == (std::vector{ 12, 4, 12 })); + CHECK(enc("<|end|>ab", false, true) == (std::vector{ 12, 4 })); + /* Not parsed, the spelling is not the token, so the BOS is still owed. */ + CHECK(enc("<|end|>x", true, false) == (std::vector{ 12, 11 })); +} + /* SPECIAL TOKENS ARE CLAIMED LONGEST FIRST, not leftmost: "bcde" wins over "ab" in "abcde" even * though "ab" starts earlier, and "<|im_start|>" is never cut by its prefix "<|im". */ TEST(special_tokens_are_claimed_by_priority) { diff --git a/tools/rad_tokcheck.cpp b/tools/rad_tokcheck.cpp index 87cec4d2..eb3c7292 100644 --- a/tools/rad_tokcheck.cpp +++ b/tools/rad_tokcheck.cpp @@ -39,7 +39,7 @@ void usage() { " --hf-dir DIR compare against HuggingFace ids in DIR/.ids\n" " (little-endian int32, encode(text, add_special_tokens=False))\n" " --no-ref skip the reference encoder, which is slow\n" - " --user encode with parse_special off, as the server does for user content\n" + " --user encode with parse_special off: a control token's spelling is text\n" " --turns N turns in the multi-turn measurement (default 40, 0 skips it)\n" " --repeat N timing repeats, best taken (default 3)\n" " --context N ids shown either side of a difference (default 6)\n"