diff --git a/CMakeLists.txt b/CMakeLists.txt index 121c5f07..41a39124 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.8 LANGUAGES C CXX) +project(radiance VERSION 1.0.9 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/NOTICE b/NOTICE index 0b37443e..f9c8a359 100644 --- a/NOTICE +++ b/NOTICE @@ -2,8 +2,8 @@ radiance Copyright 2026 Deadcode and the radiance contributors Written by Deadcode, with contributions from tcclaviger (the N-rank all-reduce kernels), ggz14 -(the MXFP4 GEMM and the GDN kernels' overflow guards) and goodman-b (four-rank tensor parallelism -for Qwen3.8-Flash-Next). +(the MXFP4 GEMM and the GDN kernels' overflow guards), goodman-b (four-rank tensor parallelism +for Qwen3.8-Flash-Next) and keptn42 (the four-rank all-reduce served in place). This product includes software from the following projects, each under the MIT License. The license text is in the file named beside each. diff --git a/README.md b/README.md index eb744d60..0e3048ef 100644 --- a/README.md +++ b/README.md @@ -94,9 +94,13 @@ sequence holds its own recurrent state and 32 of them leave the attention cache keeps the 200K request and costs single-stream decode about 15%) and the 27B in bf16. See [`docs/GUIDE.md`](docs/GUIDE.md) §4.4. -`--tp 4` runs the unfused all-reduce chain, because the fused forms are two-rank, and it takes no -`--tp-wire`: `wht6` is a two-rank wire and four ranks run the exact one. It is a capacity -configuration; its per-step rate against `--tp 2` on the same cards has not been measured. The +`--tp 4` runs the unfused all-reduce chain, because the fused forms are two-rank. Its exact +all-reduce is one-shot up to 1 MiB a message, which covers decode, and two-shot above that, which +sends half the bytes on a prefill chunk; both produce the same bits. The row above runs exact. +`--tp-wire wht6` at four ranks selects a different lossy wire, tiered int8 over the two-shot, +above `--tp-wire-min-kb`. Eight ranks have no lossy wire, so `--tp 8 --tp-wire wht6` stops at +startup naming the all-reduce. Four ranks is a capacity configuration; its per-step rate against +`--tp 2` on the same cards has not been measured. The tiering flags are the tp2 recipe carried over. Above two ranks each rank still owns a **slice of every expert's width** — each parity's 128-column blocks are cut contiguously over the ranks and the odd block alternates with the parity, so every rank's share is whole blocks and every block has diff --git a/arch/common/rad_block_attn_gated.h b/arch/common/rad_block_attn_gated.h index 7a488cda..dd3ad321 100644 --- a/arch/common/rad_block_attn_gated.h +++ b/arch/common/rad_block_attn_gated.h @@ -298,7 +298,7 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in * here because the plugin put it here, and --debug-graph shows it exactly here (spec §9). * `exact` is stated rather than defaulted -- a caller that does not say it will accept a * quantised wire gets the exact kernel or no kernel. `hops` is not stated: one-shot against - * two-shot is the kernel's business. */ + * two-shot is the kernel library's choice, by message size. */ if (g.world > 1) op_ar = rw(b, RAD_OP(b, "all_reduce", RAD_PARAMS(RAD_INT("world_size", g.world), diff --git a/core/config.cpp b/core/config.cpp index 5df6fc66..ed8b5a25 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -35,8 +35,10 @@ static const Flag g_flags[] = { { "--kernels", "LIST", "kernel plugin hierarchy, comma-separated, first wins" }, { "--tp", "N", "tensor-parallel ranks" }, - { "--tp-wire", "MODE", "cross-rank all-reduce payload: exact (default) or wht6" }, - { "--tp-wire-min-kb", "N", "smallest all-reduce, in KiB, the wht6 wire is used for" }, + { "--tp-wire", "MODE", "cross-rank all-reduce payload: exact (default) or wht6, a\n" + "lossy wire: rotated 6-bit at 2 ranks, tiered int8 at 4,\n" + "none at 8" }, + { "--tp-wire-min-kb", "N", "smallest all-reduce, in KiB, the lossy wire is used for" }, { "--max-num-batched-tokens", "N", "the largest token count one step may carry" }, { "--max-num-seqs", "N", "the largest number of sequences one step may carry" }, { "--max-model-len", "N", "context bound; 0 takes the model's training context" }, diff --git a/core/device/aql.cpp b/core/device/aql.cpp index b5d5a5c3..507e59db 100644 --- a/core/device/aql.cpp +++ b/core/device/aql.cpp @@ -35,15 +35,20 @@ /* The standard headers first: HIP's defines __noinline__, which (reached through * ) uses as an attribute name. */ +#include #include #include #include #include +#include +#include #include #include +#include #include #include +#include #include #include #include @@ -52,6 +57,7 @@ #include #include #include +#include #include #include #include @@ -207,6 +213,7 @@ struct Dev { std::vector isas; /* the targets it accepts, preferred first; see agent_isas */ hsa_amd_memory_pool_t vram{}; bool has_vram = false; + uint32_t kfd_id = 0; /* the driver's gpu_id: its sysfs and ioctls name it so */ }; struct Global { @@ -349,6 +356,8 @@ bool init_devices() { g.dev[(size_t)i].agent = a; g.dev[(size_t)i].isa = agent_isa(a); g.dev[(size_t)i].isas = agent_isas(a); + hsa_agent_get_info(a, (hsa_agent_info_t)HSA_AMD_AGENT_INFO_DRIVER_UID, + &g.dev[(size_t)i].kfd_id); hsa_amd_agent_iterate_memory_pools(a, find_vram, &g.dev[(size_t)i]); found = true; break; @@ -1014,6 +1023,23 @@ void loc_keep(const void* host_base, size_t bytes, intptr_t shift, uint64_t owne h.gen = gen; } +/* The host ranges this backend pinned itself (see "pinned host memory, in pieces"): base -> + * length, ordered so an inner address finds its range. */ +std::mutex g_pinned_mu; +std::map g_pinned; + +bool pinned_range(const void* p, uintptr_t* lo, int64_t* len) { + const uintptr_t a = (uintptr_t)p; + std::lock_guard lk(g_pinned_mu); + auto it = g_pinned.upper_bound(a); + if (it == g_pinned.begin()) return false; + --it; + if (a - it->first >= (uintptr_t)it->second) return false; + if (lo) *lo = it->first; + if (len) *len = it->second; + return true; +} + Loc locate(const void* p, const Stream* s, const void** gpu) { *gpu = p; const uintptr_t a = (uintptr_t)p; @@ -1024,6 +1050,15 @@ Loc locate(const void* p, const Stream* s, const void** gpu) { if (!h.owner) return kHost; return h.owner == s->agent.handle ? kDevLocal : kDevPeer; } + /* PINNED HERE, ANSWERED HERE. hsa_amd_pointer_info reports memory locked with + * hsa_amd_memory_lock_to_pool as UNKNOWN on this runtime -- indistinguishable from pageable -- + * although the lock mapped it on every card at its own address. */ + uintptr_t plo = 0; + int64_t plen = 0; + if (pinned_range(p, &plo, &plen)) { + loc_keep((const void*)plo, (size_t)plen, 0, 0, gen); + return kHost; + } hsa_amd_pointer_info_t info{}; info.size = sizeof info; if (hsa_amd_pointer_info(const_cast(p), &info, nullptr, nullptr, nullptr) != @@ -1774,6 +1809,87 @@ int a_memset_async(void* dst, int value, int64_t bytes, RadStream rs) { return rc < 0 ? RAD_E_DEVICE : RAD_OK; } +/* ---- VRAM: the room check. + * + * A VRAM ALLOCATION THE DRIVER REFUSES KILLS THE PROCESS IN THIS RUNTIME once a queue has been + * destroyed. On a refusal ROCr releases its caches and asks again (GpuAgent::Trim), and the release + * walks every queue the process created on the card. ROCm 7.2's runtime adds a queue to that list + * (GpuAgent::aql_queues_, amd_gpu_agent.cpp) and never takes a destroyed one off it, so the walk + * calls into freed memory and the process dies of SIGSEGV inside libhsa-runtime64.so instead of + * being told no. Startup destroys queues before it allocates anything large -- the two it makes to + * measure what a queue costs, and the loader's when a load ends -- so every refused device + * allocation took that path: a card another process had taken memory from crashed startup in + * hipMalloc rather than refusing its arena. ROCr's develop branch takes the queue off the list on + * destroy; until a release carries that, every device allocation here is held to what the driver + * will still give on the card and refused by this layer, naming what the card has and which + * processes hold it, before the runtime is asked. + * + * The figure is the driver's own (AMDKFD_IOC_AVAILABLE_MEMORY), the one its allocation check + * compares against, and the request is rounded up to 2 MiB so one the driver rounds up is not + * passed by a hair. It is a check, not a reservation: memory another process takes between it and + * the allocation still reaches the runtime. */ + +/* What the driver will still allocate on card `ord`, -1 when it will not say. */ +int64_t card_available(int ord) { + if (ord < 0 || ord >= (int)G().dev.size() || G().kfd < 0) return -1; + kfd_ioctl_get_available_memory_args a{}; + a.gpu_id = G().dev[(size_t)ord].kfd_id; + if (!a.gpu_id || ioctl(G().kfd, AMDKFD_IOC_AVAILABLE_MEMORY, &a) < 0) return -1; + return (int64_t)a.available; +} + +/* The processes holding VRAM on card `ord`, largest first, as the driver lists them: host process + * ids, which inside a container are not this process's own numbering, so this process is named + * only where the ids agree. */ +std::string card_holders(int ord) { + const uint32_t id = G().dev[(size_t)ord].kfd_id; + std::vector> held; + if (DIR* d = opendir("/sys/class/kfd/kfd/proc")) { + while (dirent* e = readdir(d)) { + char* end = nullptr; + const long pid = std::strtol(e->d_name, &end, 10); + if (end == e->d_name || *end) continue; + char path[128]; + std::snprintf(path, sizeof path, "/sys/class/kfd/kfd/proc/%ld/vram_%u", pid, id); + FILE* f = std::fopen(path, "r"); + if (!f) continue; + long long v = 0; + if (std::fscanf(f, "%lld", &v) == 1 && v > 0) held.push_back({ (int64_t)v, pid }); + std::fclose(f); + } + closedir(d); + } + if (held.empty()) return std::string(); + std::sort(held.begin(), held.end(), [](const auto& x, const auto& y) { return x.first > y.first; }); + std::string s = fmt(" %zu process(es) hold memory on it, by host process id:", held.size()); + bool self = false; + for (size_t i = 0; i < held.size() && i < 8; ++i) { + const bool me = held[i].second == (long)getpid(); + self = self || me; + s += fmt("%s %ld %s%s", i ? "," : "", held[i].second, humanb(held[i].first).c_str(), + me ? " (this process)" : ""); + } + if (held.size() > 8) s += fmt(", and %zu more", held.size() - 8); + if (!self) s += "; this process is one of them under the host's numbering"; + return s + "."; +} + +/* True when card `ord` can take `bytes` more; otherwise false with the refusal set, `what` naming + * the call. A card whose figure the driver will not give is let through, as before this check. */ +bool card_has_room(int ord, int64_t bytes, const char* what) { + const int64_t avail = card_available(ord); + if (avail < 0) return true; + constexpr int64_t kUnit = (int64_t)2 << 20; + const int64_t need = (bytes + kUnit - 1) / kUnit * kUnit; + if (need <= avail) return true; + device_set_error("%s(%s) on card %d: the driver has %s left to give on it.%s Memory another " + "process took after the VRAM budget was measured is the usual cause: stop " + "that process, or start this one again once it has gone", + what, humanb(bytes).c_str(), ord, humanb(avail).c_str(), + card_holders(ord).c_str()); + return false; +} + /* ---- elastic memory, through HSA. * * HIP's virtual-memory calls build HIP's own default-stream queue on the card the first time a @@ -1857,6 +1973,7 @@ int a_vmem_commit(void* addr, int64_t bytes) { if (dev < 0 && hipGetDevice(&dev) != hipSuccess) return RAD_E_DEVICE; if (dev < 0 || dev >= (int)G().dev.size()) return RAD_E_DEVICE; const Dev& d = G().dev[(size_t)dev]; + if (!card_has_room(dev, bytes, "vmem commit")) return RAD_E_NOMEM; hsa_amd_vmem_alloc_handle_t h{}; if (hsa_amd_vmem_handle_create(d.vram, (size_t)bytes, MEMORY_TYPE_NONE, 0, &h) != HSA_STATUS_SUCCESS) { @@ -1903,13 +2020,191 @@ int a_vmem_decommit(void* addr, int64_t bytes) { return RAD_OK; } -/* HIP's own free, behind the forgetting every free needs (locate's cache). */ +/* ------------------------------------------------------------------ pinned host memory, in pieces + * + * EVERY PINNED OR MAPPED HOST ALLOCATION IS ONE ADDRESS RANGE LOCKED AS PIECES OF AT MOST + * kPinPiece, BECAUSE OF THE IOMMU. Host memory a card reaches is a userptr buffer object, which the + * kernel DMA-maps for each card as one scatterlist. On an Intel VT-d host in scalable mode (Linux + * 7.0, two R9700) that mapping fails for any single buffer larger than about 2.5 GiB while smaller + * ones succeed every time, so a 12 GiB host pool allocated whole was refused at startup far below + * the driver's pinned-memory cap. Passthrough (iommu=pt) lets the large pin through but takes peer + * access away, which every multi-rank kernel requires, so the configuration has to work with + * translation on. A range locked in pieces never asks the IOMMU for more than one piece at a time. + * + * The lock is ROCr's, hsa_amd_memory_lock_to_pool: the same userptr pin hipHostMalloc makes, one + * buffer object per call. hsa_amd_pointer_info does not report what it locked, so locate() answers + * from this backend's own record of the ranges (g_pinned) and HIP is never asked about them. + * hipHostRegister would be HIP's record instead, and HIP's record is not what the copies read. + * + * The cards still see one range: a locked piece is mapped at its own host address, so the pieces + * of one reservation are consecutive on the card too. Each piece is checked rather than assumed, + * because the pools, the mover and the activation arena all hand a kernel base + offset. + * + * What hipHostMalloc does besides the pin is kept, so the pages are the same pages: shared + * anonymous memory, huge pages advised from 2 MiB up, a preferred NUMA node that is the one + * nearest the current card (ROCr allocates from that node's pool), fine-grained coherence (the + * pool locked to), and access from every card. + * + * kPinPiece is a power of two well under the failing size. The cost is one buffer object per piece + * per card: a few dozen for the largest pools. */ +constexpr int64_t kPinPiece = (int64_t)1 << 30; + +/* The NUMA node sysfs reports for the current card, -1 when it reports none. */ +int current_card_numa_node() { + int dev = 0; + char bus[64] = {0}; + if (hipGetDevice(&dev) != hipSuccess || + hipDeviceGetPCIBusId(bus, (int)sizeof bus, dev) != hipSuccess || !bus[0]) + return -1; + for (char* c = bus; *c; ++c) *c = (char)std::tolower((unsigned char)*c); + char path[160]; + std::snprintf(path, sizeof path, "/sys/bus/pci/devices/%s/numa_node", bus); + FILE* f = std::fopen(path, "r"); + if (!f) return -1; + int node = -1; + if (std::fscanf(f, "%d", &node) != 1) node = -1; + std::fclose(f); + return node; +} + +/* MPOL_PREFERRED | MPOL_F_STATIC_NODES, the policy ROCr's own host allocations take. A refusal (a + * seccomp profile that blocks mbind, a node with no memory) leaves the pages on whichever node + * first touches them, which is a placement cost and not a correctness one: said once, then the + * lock goes ahead. */ +void prefer_numa_node(void* p, int64_t len, int node) { + constexpr int kMaxNodes = 1024; + constexpr int kBits = 8 * (int)sizeof(unsigned long); + if (node < 0 || node >= kMaxNodes) return; + unsigned long mask[kMaxNodes / kBits] = {}; + mask[node / kBits] |= 1ul << (node % kBits); + constexpr int kMpolPreferred = 1, kMpolStaticNodes = 1 << 15; + if (::syscall(SYS_mbind, p, (unsigned long)len, kMpolPreferred | kMpolStaticNodes, mask, + (unsigned long)kMaxNodes + 1, 0u) == 0) + return; + static std::atomic said{false}; + if (!said.exchange(true)) + RAD_WARN("device: pinned host memory could not prefer NUMA node %d, the one nearest the " + "card (mbind: %s); its pages land on whichever node touches them first", node, + std::strerror(errno)); +} + +const char* hsa_why(hsa_status_t st) { + const char* m = nullptr; + return hsa_status_string(st, &m) == HSA_STATUS_SUCCESS && m ? m : "unknown HSA status"; +} + +void* pin_pieces(int64_t bytes) { + const int64_t align = RAD_ALIGN_POOL; + const int64_t len = align_up(bytes, 4096); + /* One alignment over, trimmed at both ends, so the range starts on a 2 MiB boundary: a pool's + * fixed-stride slots inherit its base alignment, and a huge page needs it. */ + void* m = ::mmap(nullptr, (size_t)(len + align), PROT_READ | PROT_WRITE, + MAP_SHARED | MAP_ANONYMOUS, -1, 0); + if (m == MAP_FAILED) { + device_set_error("rad_dev_alloc(%s): mmap: %s", humanb(bytes).c_str(), std::strerror(errno)); + return nullptr; + } + const uintptr_t lo = (uintptr_t)m; + const uintptr_t at = (lo + (uintptr_t)align - 1) & ~((uintptr_t)align - 1); + if (at > lo) ::munmap(m, at - lo); + if (lo + (uintptr_t)align > at) ::munmap((void*)(at + (uintptr_t)len), lo + (uintptr_t)align - at); + char* const p = (char*)at; + + prefer_numa_node(p, len, current_card_numa_node()); + if (len >= ((int64_t)2 << 20)) ::madvise(p, (size_t)len, MADV_HUGEPAGE); + + std::vector cards; + for (const Dev& d : G().dev) cards.push_back(d.agent); + const int pieces = (int)((len + kPinPiece - 1) / kPinPiece); + int done = 0; + for (; done < pieces; ++done) { + const int64_t off = (int64_t)done * kPinPiece; + const int64_t n = std::min(kPinPiece, len - off); + void* on_card = nullptr; + const hsa_status_t st = hsa_amd_memory_lock_to_pool(p + off, (size_t)n, cards.data(), + (int)cards.size(), G().host_fine, 0, + &on_card); + if (st != HSA_STATUS_SUCCESS) { + device_set_error("rad_dev_alloc(%s): locking piece %d of %d (%s at +%s): %s", + humanb(bytes).c_str(), done + 1, pieces, humanb(n).c_str(), + humanb(off).c_str(), hsa_why(st)); + break; + } + if (on_card != p + off) { + ++done; + device_set_error("rad_dev_alloc(%s): piece %d of %d is mapped on the cards at %p, not " + "at its host address %p, so the pieces are not one range there", + humanb(bytes).c_str(), done, pieces, on_card, (void*)(p + off)); + break; + } + } + if (done < pieces) { + for (int i = 0; i < done; ++i) (void)hsa_amd_memory_unlock(p + (int64_t)i * kPinPiece); + ::munmap(p, (size_t)len); + return nullptr; + } + std::lock_guard lk(g_pinned_mu); + g_pinned.emplace((uintptr_t)p, len); + return p; +} + +void unpin_pieces(void* p) { + int64_t len = 0; + { + std::lock_guard lk(g_pinned_mu); + auto it = g_pinned.find((uintptr_t)p); + if (it == g_pinned.end()) { + RAD_WARN("rad_dev_free(%p): not the base of a pinned range this backend handed out; " + "leaked rather than unpinned", p); + return; + } + len = it->second; + g_pinned.erase(it); + } + for (int64_t off = 0; off < len; off += kPinPiece) { + const hsa_status_t st = hsa_amd_memory_unlock((char*)p + off); + if (st != HSA_STATUS_SUCCESS) + RAD_WARN("device: unlocking pinned piece %p: %s", (void*)((char*)p + off), hsa_why(st)); + } + ::munmap(p, (size_t)len); +} + +bool pinned_kind(int kind) { return kind == RAD_MEM_HOST_PINNED || kind == RAD_MEM_HOST_MAPPED; } + +/* HIP's own allocation calls for device and pageable memory; the pinned kinds are the pieces. The + * two pinned kinds are one thing here: RAD_MEM_HOST_PINNED (the mover's staging and the O_DIRECT + * landing zone, spec §5.4) and RAD_MEM_HOST_MAPPED (the zero-copy execution site, row three of + * spec §5.1's table) are both a locked range every card addresses at its host address. */ +void* (*g_hip_alloc)(int64_t, int) = nullptr; +void* a_alloc(int64_t bytes, int kind) { + if (kind == RAD_MEM_DEVICE && bytes > 0) { + int dev = -1; + if (hipGetDevice(&dev) == hipSuccess && !card_has_room(dev, bytes, "rad_dev_alloc")) + return nullptr; + } + if (!pinned_kind(kind)) return g_hip_alloc(bytes, kind); + if (bytes <= 0) { + device_set_error("rad_dev_alloc(%lld): size must be positive", (long long)bytes); + return nullptr; + } + return pin_pieces(bytes); +} + +/* Behind the forgetting every free needs (locate's cache). */ void (*g_hip_free)(void*, int) = nullptr; void a_free(void* p, int kind) { loc_forget(); - if (g_hip_free) g_hip_free(p, kind); + if (!p) return; + if (pinned_kind(kind)) unpin_pieces(p); + else if (g_hip_free) g_hip_free(p, kind); } +/* A pinned range is the same address on both sides, inner addresses included. */ +void* (*g_hip_host_ptr)(void*) = nullptr; +void* (*g_hip_device_ptr)(void*) = nullptr; +void* a_host_ptr(void* p) { return pinned_range(p, nullptr, nullptr) ? p : g_hip_host_ptr(p); } +void* a_device_ptr(void* p) { return pinned_range(p, nullptr, nullptr) ? p : g_hip_device_ptr(p); } + /* ------------------------------------------------------------------ plugin device code */ size_t a_code_mark(void) { @@ -1969,8 +2264,14 @@ const DeviceBackend* aql_backend_if_present(void) { G().ok = true; g_aql = *hip; g_aql.name = "aql"; + g_hip_alloc = hip->alloc; g_hip_free = hip->free; + g_hip_host_ptr = hip->host_ptr; + g_hip_device_ptr = hip->device_ptr; + g_aql.alloc = a_alloc; g_aql.free = a_free; + g_aql.host_ptr = a_host_ptr; + g_aql.device_ptr = a_device_ptr; g_aql.stream_create = a_stream_create; g_aql.stream_destroy = a_stream_destroy; g_aql.stream_sync = a_stream_sync; diff --git a/core/device/hip.cpp b/core/device/hip.cpp index 623d78ce..0ba4d4e6 100644 --- a/core/device/hip.cpp +++ b/core/device/hip.cpp @@ -1,7 +1,8 @@ /* hip.cpp -- the HIP half of the device backend: devices, memory and elastic memory. * * Streams, events, copies and fills are not here. They are AQL packets the engine writes into - * queues it owns (aql.cpp), which starts from this table and fills in the rest. + * queues it owns (aql.cpp), which starts from this table and fills in the rest -- pinned host + * memory included, because the copies have to recognise it. * * Thin by design. Every entry point is one hip* call plus an error capture, because anything * cleverer than that is a place where the host backend and this one can disagree, and the host @@ -293,18 +294,11 @@ void* d_alloc(int64_t bytes, int kind) { e = hipMalloc(&p, (size_t)bytes); break; case RAD_MEM_HOST_PINNED: - /* The mover's staging pool and the O_DIRECT landing zone. Pinned so a transfer is a - * DMA the driver does not have to stage through its own bounce buffer (spec §5.4). */ - e = hipHostMalloc(&p, (size_t)bytes, hipHostMallocDefault); - break; case RAD_MEM_HOST_MAPPED: - /* The zero-copy execution site: tier host, site device, no slab slot -- row three of - * spec §5.1's table. hipHostMallocMapped is what makes the allocation addressable from - * a kernel over the link, which is the whole mechanism. The cost is that every read is - * a link read, so this is for read-once weights and the planner decides which - * (spec §19.3). */ - e = hipHostMalloc(&p, (size_t)bytes, hipHostMallocMapped); - break; + /* The AQL backend's, which pins host memory through ROCr in pieces the IOMMU can map + * (aql.cpp, "pinned host memory, in pieces"). */ + device_set_error("rad_dev_alloc: pinned host memory is the AQL backend's"); + return nullptr; case RAD_MEM_HOST: /* Pageable. Aligned to a page anyway so the same buffer can be an O_DIRECT target. */ if (posix_memalign(&p, 4096, (size_t)((bytes + 4095) / 4096 * 4096)) != 0) p = nullptr; @@ -325,9 +319,11 @@ void d_free(void* p, int kind) { if (!p) return; switch (kind) { case RAD_MEM_DEVICE: HIP_NOTE(hipFree(p)); break; - case RAD_MEM_HOST_PINNED: - case RAD_MEM_HOST_MAPPED: HIP_NOTE(hipHostFree(p)); break; case RAD_MEM_HOST: std::free(p); break; + case RAD_MEM_HOST_PINNED: + case RAD_MEM_HOST_MAPPED: + RAD_WARN("rad_dev_free(%p): pinned host memory is the AQL backend's; leaked", p); + break; default: RAD_WARN("rad_dev_free(%p): unknown memory kind %d; leaked rather than freed with the " "wrong allocator", p, kind); diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 4c8f078c..6d131b94 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -506,9 +506,10 @@ int Engine::declare() { const int64_t row_bytes = meta_.n_embd > 0 ? meta_.n_embd * 2 : 1; const int64_t exact_rows = (cfg_.tp_wire_min_kb * 1024 + row_bytes - 1) / row_bytes - 1; RAD_WARN("tp wire: LOSSY (--tp-wire wht6) at %lld KiB a message and above. A cross-rank " - "all-reduce of that size carries a Walsh-Hadamard-rotated 6-bit payload instead " - "of bf16, so this process does not compute the same function the exact wire " - "does. Steps of at most %lld rows are exact: single-sequence decode, and a " + "all-reduce of that size carries a quantised payload instead of bf16 (libr4d's " + "is Walsh-Hadamard-rotated 6-bit at two ranks and tiered int8 at four), so this " + "process does not compute the same function the exact wire does. Steps of at " + "most %lld rows are exact: single-sequence decode, and a " "decode step until sequences x (1 + speculative depth) passes that; prefill and " "a busy decode step are lossy. --tp-wire-min-kb moves the floor.", (long long)cfg_.tp_wire_min_kb, (long long)exact_rows); diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index 08bcc526..081ff1f1 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -522,6 +522,26 @@ std::string scale_name(const std::string& codes) { return codes + "_scale_inv"; } /* namespace */ +std::string ckpt_tensor_of(const SrcTensor& t) { + const size_t br = t.name.size() && t.name.back() == ']' ? t.name.rfind('[') : std::string::npos; + return br == std::string::npos ? t.name : t.name.substr(0, br); +} + +bool ckpt_reads_any(const CkptWeight& w, const std::unordered_set& names, + std::unordered_set* hit) { + bool any = false; + for (const auto* list : { &w.pieces, &w.scales }) + for (const SrcTensor* t : *list) { + if (!t) continue; + const std::string n = ckpt_tensor_of(*t); + if (names.count(n)) { + any = true; + if (hit) hit->insert(n); + } + } + return any; +} + int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, bool optional, CkptWeight* out, std::string* why) { auto refuse = [&](int rc, std::string m) { diff --git a/core/format/checkpoint.h b/core/format/checkpoint.h index 29d2139f..a6d2e43a 100644 --- a/core/format/checkpoint.h +++ b/core/format/checkpoint.h @@ -24,6 +24,7 @@ #include #include #include +#include #include namespace rad { @@ -147,6 +148,15 @@ struct CkptWeight { int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, bool optional, CkptWeight* out, std::string* why); +/* The checkpoint tensor a piece or scale reads: its name without the "[index]" a slice of a + * stacked tensor carries, so an expert reads the stack it was cut from. */ +std::string ckpt_tensor_of(const SrcTensor& t); + +/* Whether `w` reads any tensor named in `names` (checkpoint names, as ckpt_tensor_of gives them), + * through a piece or a scale. Each name it reads is added to `hit` when that is given. */ +bool ckpt_reads_any(const CkptWeight& w, const std::unordered_set& names, + std::unordered_set* hit = nullptr); + /* Logical rows [r0, r0 + nr) of `w` as f32 [nr, cols], whatever the pieces are stored as: a * plain float widened, FP8 times its block scale, a GGUF block type dequantised. */ int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std::string* why); diff --git a/core/util/rad_util.cpp b/core/util/rad_util.cpp index 8496a1de..48ce2984 100644 --- a/core/util/rad_util.cpp +++ b/core/util/rad_util.cpp @@ -241,11 +241,10 @@ std::string Geometry::str() const { } /* ------------------------------------------------------------------ constraint matching */ -/* A constraint whose key the geometry does not carry does NOT hold. That is libr4d's rule and the - * reason its two-shot all-reduce rows have to precede the one-shot ones: a query that omits `hops` - * fails the row that needs it, so the more constrained row can never be reached unless it is - * asked for. Making the absence a failure is what makes "ask for hops=2 to be handed the two-shot" - * mean something. */ +/* A constraint whose key the geometry does not carry does NOT hold. That is libr4d's rule: a row + * that constrains an optional parameter serves only a caller that states it, so the more + * constrained of two rows is reached only when it is asked for, and a caller that leaves the + * parameter out is handed the row that does not need it. */ bool constraint_holds(const RadConstraint& c, const Geometry& g) { if (c.op == RAD_C_IN) { const char* v = g.get_s(c.key); diff --git a/docs/GUIDE.md b/docs/GUIDE.md index cacd3116..aa22933a 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -673,6 +673,13 @@ which is why it is a named flag and not a heuristic. `--tp-wire-min-kb` is the floor below which messages are still served exactly — 128 KiB leaves single-sequence decode exact and compresses prefill, which is where the win is. +At four ranks `wht6` selects a different lossy wire with the same floor: tiered int8 over a +two-shot all-reduce, both hops quantised. Eight ranks have no lossy wire, and `--tp 8 --tp-wire +wht6` stops at startup naming the all-reduce it found no kernel for. The exact wire at four and +eight ranks is one-shot up to 1 MiB a message and two-shot above it, which sends +2·(ranks−1)/ranks of the message per rank instead of (ranks−1) times it; the two produce the same +bits. + On a model with a gated residual (Qwen3.8-Flash-Next) the all-reduce rides inside the residual's write, with the MoE gather in front of it, on either wire: the rotated forms of `ar_hc_write` and `ar_gather_hc_write` produce the same bytes as the unfused chain on the same wire. There `wht6` is @@ -869,8 +876,8 @@ one line naming each one the command line moved. | flag | default | | |---|---|---| | `--tp N` | 1 | tensor-parallel ranks | -| `--tp-wire MODE` | exact | `exact` or `wht6` | -| `--tp-wire-min-kb N` | 128 | smallest all-reduce the `wht6` wire is used for | +| `--tp-wire MODE` | exact | `exact` or `wht6`, the lossy wire (§4.7) | +| `--tp-wire-min-kb N` | 128 | smallest all-reduce the lossy wire is used for | **Speculation** @@ -1431,6 +1438,7 @@ released until it does. | KV in VRAM stays high with one session and nothing moves | The idle tiers are **off** — they are sized, and with no size nothing is copied | Pass `--prefix-cache-host-mib N` | | `out of memory` / `the carve reserved N of address space and the card would not back it` | Something else is holding VRAM | Check with `rocm-smi`; stop the other process. The budget is stated before allocation, so the log says what it asked for | | `pool allocation refused` with `backing allocation of … refused` on the second card, after the first card's pools succeeded | The VRAM budget is measured before any rank allocates. A card that refuses its weights pool lost that memory to another process in between (the line below the refusal says how much is free now). A refused `host_pool` is pinned memory: **every rank pins its own `--host-pool-mib`**, so `--tp 2` pins it twice, and the amdgpu driver caps pinned memory system-wide at `ttm.pages_limit`, half of RAM by default | Stop the other process (`rocm-smi --showpids`). For the host pool, keep `--tp` × `--host-pool-mib` under the cap the refusal names, or raise it with the kernel parameter `ttm.pages_limit` | +| `host_pool: backing allocation of … refused: rad_dev_alloc(…): locking piece K of N`, and `failed to pin userptr` in `journalctl -k` | The IOMMU would not DMA-map one piece of the pinned host pool. Pinned host memory is locked in pieces of at most 1 GiB because an Intel VT-d host in scalable mode was seen to refuse any single pin above about 2.5 GiB; a piece failing means this machine refuses smaller pins still, or a total its IOMMU will not map | Keep IOMMU translation on: `iommu=pt` lets every pin through but on that host also removed peer access between the cards, and every multi-rank kernel requires it. Report the kernel version, the IOMMU mode and the refusal line | | `--draft-model is not implemented` | This engine loads its drafter from the container | `rad-convert --draft-model DIR` at conversion time | | `context_length_exceeded` on a request | The **prompt alone** does not fit the context. `max_tokens` is clamped rather than refused, so this fires only when there is no room left to generate at all | Shorten the prompt by the number of tokens the message names, or raise `--max-model-len` if the model allows it | | `unknown option '--foo'` and the engine exits | Deliberate. A typo in a budget flag is the difference between the plan you asked for and one the planner invented | Check `radiance --help` | diff --git a/docs/OPS.md b/docs/OPS.md index 650f2856..9f454d75 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -65,8 +65,8 @@ they are why `gdn_conv_prep` and `gdn_recurrent_update` carry the long operand l that lacks an operand cannot express the call at all, so the narrower reading always loses. An implementation ignores an optional operand it does not use; it cannot invent one it needs. 2. **Parameters are the UNION, and anything only one implementation needs is `optional`.** Same - argument. A constraint on an absent key simply does not hold, which is the correct answer and - is how `hops` works. + argument. A constraint on an absent key simply does not hold, which is the correct answer: a + row that needs a parameter the caller did not state is not a match. 3. **A float-valued parameter is `RAD_P_F64`.** `eps`, `scale`, `theta`, `softplus_thr`, `l2_eps`, `wadd`. A `"%.9g"` string round-trips an IEEE single exactly and is unreadable in a graph dump, which is the whole of the argument against spelling them as strings. **Constraints never match @@ -708,13 +708,17 @@ and the third is what needs the token stride carried separately. | op | params | operands | |---|---|---| -| `all_reduce` | `world_size` `numel` `dtype` `exact` `min_bytes`/opt `hops`/opt | `x`:inout, `y`:out? | +| `all_reduce` | `world_size` `numel`(range) `dtype` `exact` `min_bytes`/opt `hops`/opt | `x`:inout, `y`:out? | | `all_gather` | `world_size` `numel` `dtype` `row`/opt | `x` → `y` | `exact` separates the exact sum from the quantised wire, and a caller has to say which it wants: a request that does not declare it will accept a lossy wire gets no kernel rather than the quantised -one. `hops` separates one-shot from two-shot at a width that has both. Both are libr4d's rules and -they are right. +one. That is libr4d's rule and it is right. + +libr4d separates one-shot from two-shot, at a width that has both, by message size: its two-shot +rows start above 524288 elements, which makes that a band edge of the ranged `numel`, so a caller +states nothing for it. `hops` is a caller's request for one or the other (1 or 2); libref accepts +and ignores it, and no libr4d row reads it. Every all-reduce kernel serves `y` absent, in place. `min_bytes` is the byte floor under which a LOSSY row must serve the message exactly anyway, and it is a parameter rather than a constant in the library because it is a property of the link and not diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index 58856ec0..d9c9234a 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -431,9 +431,9 @@ static int nb_for(long words16, int max_nb) { } /* Shared front half of every all-reduce launch: find the instance, check the message against what - * init sized for, resolve the tuned point. Two-shot rows pass want_distinct because they gather into - * the output while the input is still being read for the scatter. */ -static int ar_setup(const RadArgs* a, ArCall* c, int want_distinct, int shard_nb) { + * init sized for, resolve the tuned point. Every kernel of the family runs in place (`y` absent or + * equal to `x`); each says why at its entry. */ +static int ar_setup(const RadArgs* a, ArCall* c, int shard_nb) { const ArInst* in = (const ArInst*)(a ? a->instance : nullptr); if (!in) return RAD_E_STATE; /* init did not run: a core sequencing bug */ const RadTensor* x = r4d_opt(a, AR_X); @@ -445,7 +445,6 @@ static int ar_setup(const RadArgs* a, ArCall* c, int want_distinct, int shard_nb if (!r4d_contig(y)) return RAD_E_STRIDE; if (r4d_numel(y) != r4d_numel(x)) return RAD_E_SHAPE; } - if (want_distinct && (!y || y->data == x->data)) return RAD_E_INVAL; const long n = (long)r4d_numel(x); if (n <= 0) return RAD_E_SHAPE; @@ -637,7 +636,7 @@ extern "C" int r4d_rad_ar_gather_8rank(const RadArgs* a, RadStream s) { extern "C" int r4d_rad_ar_oneshot_2rank_exact(const RadArgs* a, RadStream s) { ArCall c; - int rc = ar_setup(a, &c, 0, 0); + int rc = ar_setup(a, &c, 0); if (rc != RAD_OK) return rc; if (c.in->world != 2) return RAD_E_SHAPE; R4D_TRY("ar_oneshot_2rank_exact", @@ -669,7 +668,7 @@ enum { R4D_AR_WHT6_FUSED_THREADS = 512 }; extern "C" int r4d_rad_ar_oneshot_2rank_wht6(const RadArgs* a, RadStream s) { ArCall c; - int rc = ar_setup(a, &c, 0, 0); + int rc = ar_setup(a, &c, 0); if (rc != RAD_OK) return rc; if (c.in->world != 2) return RAD_E_SHAPE; if (c.in->dtype == 2) return RAD_E_DTYPE; /* the rotated wire is bf16/fp16 only */ @@ -718,34 +717,14 @@ extern "C" int r4d_rad_ar_oneshot_2rank_wht6(const RadArgs* a, RadStream s) { * The peer arguments are ascending global rank with the current rank removed, which is exactly * the order build() filled peer_scratch/peer_flags in. */ -/* Four-rank blocks issue every all_reduce in place and without `hops`, so the exact two-shot row - * (hops=2) is never selected. Above this floor the one-shot entry runs the two-shot kernel instead: - * 1.5N rather than 3N bytes a rank, same fp32 fold order, bit-identical. In place is safe for the - * reason given at the ti8 entry. Prefill +17% at 16k/64k on 4x R9700; decode stays one-shot. */ -enum { R4D_AR_EXACT_TWOSHOT_MIN_BYTES = 1024 * 1024 }; - +/* The one-shots run in place: the thread that stores word k of the output is the one that read + * word k of the input, for its push and again as its own term of the fold, and peers read only + * their own scratch (r4d_ar_oneshot_Nrank_exact.hip). */ extern "C" int r4d_rad_ar_oneshot_4rank_exact(const RadArgs* a, RadStream s) { ArCall c; - int rc = ar_setup(a, &c, 0, 0); + int rc = ar_setup(a, &c, 0); if (rc != RAD_OK) return rc; if (c.in->world != 4) return RAD_E_SHAPE; - const long long msg_b = (long long)c.numel * c.in->esize; - if (msg_b >= R4D_AR_EXACT_TWOSHOT_MIN_BYTES && c.numel <= R4D_AR_TWOSHOT_WIDE_MAX_ELEMS && - msg_b % 16 == 0 && (msg_b / 16) % c.in->world == 0 && - 2 * msg_b / c.in->world <= c.in->slot_bytes) { /* the two-shot's own preconditions */ - ArCall t; - if (ar_setup(a, &t, 0, 1) == RAD_OK) { /* shard-scaled block count */ - const ArInst* in = t.in; - R4D_TRY("ar_twoshot_4rank_exact", - r4d_ar_twoshot_4rank_exact(in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2], - in->peer_flags[0], in->peer_flags[1], in->peer_flags[2], - in->my_scratch, in->my_flags, in->my_seq, in->slot16, - t.inp, t.out, t.numel, in->dtype, in->rank, - (long)(uintptr_t)s, t.nblocks, t.nthreads, t.drain, t.acq, - t.pub)); - return RAD_OK; - } - } const ArInst* in = c.in; R4D_TRY("ar_oneshot_4rank_exact", r4d_ar_oneshot_4rank_exact(in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2], @@ -759,7 +738,7 @@ extern "C" int r4d_rad_ar_oneshot_4rank_exact(const RadArgs* a, RadStream s) { extern "C" int r4d_rad_ar_oneshot_8rank_exact(const RadArgs* a, RadStream s) { ArCall c; - int rc = ar_setup(a, &c, 0, 0); + int rc = ar_setup(a, &c, 0); if (rc != RAD_OK) return rc; if (c.in->world != 8) return RAD_E_SHAPE; const ArInst* in = c.in; @@ -778,11 +757,18 @@ extern "C" int r4d_rad_ar_oneshot_8rank_exact(const RadArgs* a, RadStream s) { } /* The two-shots shard the message, so their block count scales with the SHARD -- a full-message - * count over-launches the whole mid band. Both refuse an in-place call; the four-rank one-shot - * entry runs the exact one in place above R4D_AR_EXACT_TWOSHOT_MIN_BYTES. */ + * count over-launches the whole mid band. + * + * IN PLACE IS SAFE (r4d_ar_twoshot_Nrank_exact.hip). A thread takes one set of word offsets k + * within a shard and uses it in all three phases: the push reads word k of every peer's shard out + * of the input, the reduce reads word k of its own shard and stores the sum over it, and the + * assemble writes word k of every peer's shard. Each input word is therefore overwritten only by + * the thread that already read it, later in its own program order, and no peer reads this rank's + * input -- peers read their own scratch. The selector hands the two-shot the messages above the + * one-shot's size bound (r4d_rows.cpp, cArTsExact4). */ extern "C" int r4d_rad_ar_twoshot_4rank_exact(const RadArgs* a, RadStream s) { ArCall c; - int rc = ar_setup(a, &c, 1, 1); + int rc = ar_setup(a, &c, 1); if (rc != RAD_OK) return rc; if (c.in->world != 4) return RAD_E_SHAPE; if (c.numel > R4D_AR_TWOSHOT_WIDE_MAX_ELEMS) return RAD_E_SHAPE; @@ -804,7 +790,7 @@ extern "C" int r4d_rad_ar_twoshot_4rank_exact(const RadArgs* a, RadStream s) { extern "C" int r4d_rad_ar_twoshot_8rank_exact(const RadArgs* a, RadStream s) { ArCall c; - int rc = ar_setup(a, &c, 1, 1); + int rc = ar_setup(a, &c, 1); if (rc != RAD_OK) return rc; if (c.in->world != 8) return RAD_E_SHAPE; if (c.numel > R4D_AR_TWOSHOT_WIDE_MAX_ELEMS) return RAD_E_SHAPE; @@ -829,13 +815,16 @@ extern "C" int r4d_rad_ar_twoshot_8rank_exact(const RadArgs* a, RadStream s) { /* The tiered-int8 wire. Its slot stride is in BYTES, not 16-byte words: the wire is 38 bytes per * group of 32 and so is not 16-byte aligned at all. * - * Four-rank blocks issue every all_reduce in place and without `hops`, so a lossy wire lands here - * for every message. As in r4d_rad_ar_oneshot_2rank_wht6, a message under `min_bytes` (or one the - * groups do not tile) goes to the exact one-shot. In place is safe: each block reads its range of - * the input before it writes the same range of the output, and no peer reads this rank's input. */ + * It is the only lossy row at four ranks, so a lossy request resolves it at every message size. As + * in r4d_rad_ar_oneshot_2rank_wht6, a message under `min_bytes` (or one the groups do not tile) + * goes to the exact one-shot. The default floor is the two-rank wire's: every block declares + * `min_bytes` from --tp-wire-min-kb, so the default serves only a caller that leaves it out, and no + * four-rank crossover has been measured to set another. In place is safe for the exact two-shot's + * reason: a thread owns the same 8 elements of a shard in all three phases, reads them from the + * input before it writes them, and no peer reads this rank's input. */ extern "C" int r4d_rad_ar_twoshot_4rank_ti8(const RadArgs* a, RadStream s) { ArCall c; - int rc = ar_setup(a, &c, 0, 1); + int rc = ar_setup(a, &c, 1); if (rc != RAD_OK) return rc; if (c.in->world != 4) return RAD_E_SHAPE; if (c.in->dtype == 2) return RAD_E_DTYPE; diff --git a/libr4d/r4d_fuse.cpp b/libr4d/r4d_fuse.cpp index 52f22235..515fab19 100644 --- a/libr4d/r4d_fuse.cpp +++ b/libr4d/r4d_fuse.cpp @@ -657,10 +657,8 @@ extern "C" int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam* p, int n_p, u * 0." Leaving the key out would let a small message go out exact on one side of the * comparison and rotated on the other. * - * `hops` is deliberately NOT emitted. A query that omits it falls through to the one-shot rows, - * which is what this kernel is; naming it would be pinning a topology that does not exist at two - * ranks. `y` is RAD_FUSE_NONE: the fused kernel reduces in place into `x`, which is what the - * one-shot rows do and what the two-shot rows refuse by name. + * `hops` is not emitted: no libr4d row reads it, and two ranks have only the one-shot. `y` is + * RAD_FUSE_NONE: the fused kernel reduces in place into `x`, as every all-reduce row does. */ /* ========================================================================================== * attn_paged_gate_quant -- attn_paged, then gate_quant_fp8 over its output. diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 0dc49def..e58bac6b 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -25,9 +25,8 @@ enum { /* A two-shot row's constraints are a SUPERSET of the one-shot's at the same world_size, so a * two-shot that ranked below could never be reached: every query it serves the one-shot also - * matches. `hops` is ALSO a predicate, and both mechanisms are needed -- the predicate is what - * makes a query that omits `hops` fall through to the one-shot, and the priority is what makes - * hops=2 reachable at all. */ + * matches. Its lower bound on `numel` is what keeps a small message on the one-shot, and the + * priority is what hands a large one to the two-shot. */ R4D_PRIO_AR_TWOSHOT = 70, R4D_PRIO_AR_ONESHOT = 60, diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 2fda504a..918cb204 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -71,6 +71,18 @@ * r4d_ar_entry.hip static_asserts the two against each other. */ #define R4D_AR_TWOSHOT_WIDE_MAX_ELEMS 20971520 +/* The largest message, in elements, a 4- or 8-rank exact all-reduce keeps on the one-shot; above it + * the two-shot rows take it. 1 MiB of a 16-bit payload. The one-shot sends (ws-1)*N bytes a rank + * in one hop and the two-shot 2*(ws-1)/ws*N in two, so the one-shot wins while the second hop's + * latency outweighs the bytes it saves. The value is a separation, not a measured crossover: on + * Qwen3.8-Flash-Next (2560 wide, 5 KiB a row) the largest decode message is 640 KiB, at 32 + * sequences each verifying four tokens, and a 2048-token prefill chunk is 10 MiB, so any bound + * between the two sends decode one-shot and prefill two-shot. It is a multiple of 128 for the + * reason pAllReduce's `numel` gives. */ +#define R4D_AR_WIDE_ONESHOT_MAX_ELEMS 524288 +#define R4D_XSTR(v) R4D_STR(v) +#define R4D_STR(v) #v + /* ==================================================================================== schemas * * The first plugin in hierarchy order to declare an op fixes its schema (spec §2.3), and this @@ -617,11 +629,13 @@ static const RadOperandSpec oDflashSelect[] = { /* ------------------------------------------------------------------------------ collectives */ static const RadParamSpec pAllReduce[] = { { "world_size", RAD_P_INT, RAD_REQUIRED }, - /* THE LARGEST message this instance will ever carry, not the one a given step carries. init() - * sizes the peer scratch from it once and the launch reads the real count off the tensor. - * docs/OPS.md marks no parameter of `all_reduce` as ranged, and this is why that is right - * here even though the message size does vary per step: making `numel` a RANGE would put a - * RAD_C_DIV constraint on a ranged parameter, and a band is not divisible by anything. */ + /* The message, in elements. Every block declares it as a RANGE -- a step carries its row + * count times the width -- so the selector cuts it into bands at the bounds the rows below + * place on it and resolves each band at its upper bound: init() sizes the peer scratch for + * that bound once, and the launch reads the real count off the tensor. A row's RAD_C_DIV on + * `numel` is therefore checked at a band's upper bound, so every bound a row here places on + * it is a multiple of 128, the largest DIV among them; a bound that was not would leave a + * band no DIV row could serve. */ { "numel", RAD_P_INT, RAD_REQUIRED }, { "dtype", RAD_P_STR, RAD_REQUIRED }, { "exact", RAD_P_INT, RAD_REQUIRED }, @@ -631,12 +645,16 @@ static const RadParamSpec pAllReduce[] = { * stops costing more than the bytes it removes, and that is a bandwidth the deployment knows * and the library does not. An exact row ignores it -- there is nothing to fall back to. */ { "min_bytes", RAD_P_INT, RAD_OPTIONAL }, + /* A caller's request for a one-shot (1) or two-shot (2). docs/OPS.md's schema is the union of + * every plugin's parameters and libref accepts it, so it stays declared here; no row of this + * plugin reads it, because the message size picks the two-shot (the all-reduce constraints + * below). */ { "hops", RAD_P_INT, RAD_OPTIONAL }, }; -/* docs/OPS.md has `x` -> `x` (inout). The one-shot kernels reduce elementwise out[i] = in[i] + - * peer_staged[i] and are safe in place; the two-shots are not, because a rank gathers into the - * output while its own input is still being read for the scatter. So the output is an optional - * SECOND operand: absent means in place, and the two-shot shims refuse in place by name. */ +/* docs/OPS.md has `x` -> `x` (inout). Every kernel here is safe in place -- the thread that + * overwrites a word of the input is the one that read it (r4d_ar_entry.hip says so per kernel) -- + * and every block issues it that way. The output is an optional SECOND operand for a caller that + * wants the sum somewhere else: absent means in place. */ static const RadOperandSpec oAllReduce[] = { { "x", RAD_OPD_INOUT, 0 }, { "y", RAD_OPD_OUT, 1 }, @@ -1911,8 +1929,10 @@ static const RadOpSchema kSchemas[] = { "serial and the other K-1 rows of the score matrix are never read."), SCHEMA("all_reduce", pAllReduce, oAllReduce, "sum over the tensor-parallel group. `exact` separates the exact sum from the " - "quantised wire and a caller that does not declare it gets no kernel; `hops` separates " - "one-shot from two-shot at a width that has both."), + "quantised wire and a caller that does not declare it gets no kernel. At 4 and 8 ranks " + "the exact sum is one-shot up to " R4D_XSTR(R4D_AR_WIDE_ONESHOT_MAX_ELEMS) " elements and " + "two-shot above, chosen by the " + "message's band; `hops` is accepted and no row of this plugin reads it."), SCHEMA("all_gather", pAllGather, oAllGather, "y is [world_size * numel] with rank r's contribution at offset r * numel. The bytes are " "moved and never summed: the vocab-parallel sampler's payload is (u32 token id, f32 " @@ -2329,13 +2349,14 @@ static const RadConstraint cGdnGatedRmsNorm[] = { /* ---- all-reduce ------------------------------------------------------------------------------ * `exact` separates the two, and a caller has to say which it wants: a request that does not * declare it will accept a lossy wire format gets no kernel rather than the quantised one. - * `hops` separates the one-shot from the two-shot at a width that has both. It has to be a - * predicate and not just row order: a two-shot row's constraints are otherwise a superset of the - * one-shot's at the same world_size. Omitting `hops` still resolves to the one-shot, which is the - * latency-band default; ask for hops=2 to be handed the two-shot. On the kernel side that default - * falls out of row order; here it is R4D_PRIO_AR_TWOSHOT > R4D_PRIO_AR_ONESHOT, so the mechanism - * is written down rather than implied by position. The ti8 wire needs no such key -- exact=0 - * already separates it. */ + * MESSAGE SIZE separates the one-shot from the two-shot at a width that has both. The two-shot + * rows start above R4D_AR_WIDE_ONESHOT_MAX_ELEMS, which makes that bound a band edge of `numel`: + * the band at or under it resolves only the one-shot, and in the band above both rows match and + * R4D_PRIO_AR_TWOSHOT > R4D_PRIO_AR_ONESHOT hands it the two-shot. The GE is one past the bound so + * the band under it ends ON the bound, a multiple of every DIV here (see pAllReduce's `numel`). The + * choice is the selector's and so it is what the band report names; no entry point substitutes + * one kernel for another. The ti8 wire needs no such key -- exact=0 already separates it, and it + * serves its own small messages exactly. */ /* ---- all-gather ------------------------------------------------------------------------------- * The vocab-parallel sampler's candidate merge, and nothing else in the engine issues one. No * `exact` key: a gather MOVES its payload and cannot be lossy, so there is no second row for it @@ -2371,15 +2392,15 @@ static const RadConstraint cArExact8[] = { C_P2P, }; static const RadConstraint cArTsExact4[] = { - C_EQ("world_size", 4), C_EQ("exact", 1), C_EQ("hops", 2), - C_IN("dtype", "bf16 fp16 fp32"), - C_DIV("numel", 64), C_LE("numel", R4D_AR_TWOSHOT_WIDE_MAX_ELEMS), + C_EQ("world_size", 4), C_EQ("exact", 1), C_IN("dtype", "bf16 fp16 fp32"), + C_DIV("numel", 64), C_GE("numel", R4D_AR_WIDE_ONESHOT_MAX_ELEMS + 1), + C_LE("numel", R4D_AR_TWOSHOT_WIDE_MAX_ELEMS), C_P2P, }; static const RadConstraint cArTsExact8[] = { - C_EQ("world_size", 8), C_EQ("exact", 1), C_EQ("hops", 2), - C_IN("dtype", "bf16 fp16 fp32"), - C_DIV("numel", 64), C_LE("numel", R4D_AR_TWOSHOT_WIDE_MAX_ELEMS), + C_EQ("world_size", 8), C_EQ("exact", 1), C_IN("dtype", "bf16 fp16 fp32"), + C_DIV("numel", 64), C_GE("numel", R4D_AR_WIDE_ONESHOT_MAX_ELEMS + 1), + C_LE("numel", R4D_AR_TWOSHOT_WIDE_MAX_ELEMS), C_P2P, }; static const RadConstraint cArWht6[] = { @@ -3837,13 +3858,13 @@ static const RadKernelInfo kKernels[] = { r4d_shape_gdn_gated_rmsnorm }, /* ---------------------------------------------------------------------------- all-reduce ---- - * The two-shot rows come FIRST in libr4d and outrank here, for the reason the constraint block - * above states at length. */ + * The two-shot rows outrank the one-shots, for the reason the constraint block above states. */ { "ar_twoshot_4rank_exact", "all_reduce", "ar", "all-reduce (sum), reduce-scatter + all-gather over P2P IPC scratch, per-block pipelined " "handshake", - "exactly 4 ranks, all peer-accessible; two hops (select with hops=2); shares the wide family's " - "flag/seq/scratch set; message must shard evenly over the ranks; cudagraph-safe", + "exactly 4 ranks, all peer-accessible; messages above " + R4D_XSTR(R4D_AR_WIDE_ONESHOT_MAX_ELEMS) " elements, two hops; shares the wide family's " + "flag/seq/scratch set; message must shard evenly over the ranks; in place; cudagraph-safe", "bf16 / fp16 / fp32 payload, fp32 accumulate in ascending rank order, bit-identical across ranks", RAD_DOMAIN_DEVICE, R4D_PRIO_AR_TWOSHOT, ROW(cArTsExact4), ROW(tAr), nullptr, @@ -3853,8 +3874,9 @@ static const RadKernelInfo kKernels[] = { { "ar_twoshot_8rank_exact", "all_reduce", "ar", "all-reduce (sum), reduce-scatter + all-gather over P2P IPC scratch, per-block pipelined " "handshake", - "exactly 8 ranks, all peer-accessible; two hops (select with hops=2); shares the wide family's " - "flag/seq/scratch set; message must shard evenly over the ranks; cudagraph-safe", + "exactly 8 ranks, all peer-accessible; messages above " + R4D_XSTR(R4D_AR_WIDE_ONESHOT_MAX_ELEMS) " elements, two hops; shares the wide family's " + "flag/seq/scratch set; message must shard evenly over the ranks; in place; cudagraph-safe", "bf16 / fp16 / fp32 payload, fp32 accumulate in ascending rank order, bit-identical across ranks", RAD_DOMAIN_DEVICE, R4D_PRIO_AR_TWOSHOT, ROW(cArTsExact8), ROW(tAr), nullptr, @@ -3916,8 +3938,8 @@ static const RadKernelInfo kKernels[] = { { "ar_oneshot_4rank_exact", "all_reduce", "ar", "all-reduce (sum), one-shot push over P2P IPC scratch, per-block handshake", - "exactly 4 ranks, all peer-accessible; one scratch slot per (parity, source rank); " - "cudagraph-safe", + "exactly 4 ranks, all peer-accessible; one scratch slot per (parity, source rank); in " + "place; cudagraph-safe", "bf16 / fp16 / fp32 payload, fp32 accumulate in ascending rank order, bit-identical across ranks", RAD_DOMAIN_DEVICE, R4D_PRIO_AR_ONESHOT, ROW(cArExact4), ROW(tAr), nullptr, @@ -3926,8 +3948,8 @@ static const RadKernelInfo kKernels[] = { { "ar_oneshot_8rank_exact", "all_reduce", "ar", "all-reduce (sum), one-shot push over P2P IPC scratch, per-block handshake", - "exactly 8 ranks, all peer-accessible; one scratch slot per (parity, source rank); " - "cudagraph-safe", + "exactly 8 ranks, all peer-accessible; one scratch slot per (parity, source rank); in " + "place; cudagraph-safe", "bf16 / fp16 / fp32 payload, fp32 accumulate in ascending rank order, bit-identical across ranks", RAD_DOMAIN_DEVICE, R4D_PRIO_AR_ONESHOT, ROW(cArExact8), ROW(tAr), nullptr, diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index d1eb6c90..122b1515 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -1028,10 +1028,8 @@ extern "C" int r4d_shape_all_reduce(const RadParam* p, int n_p, int operand, const uint32_t D = dt_act(p, n_p, "dtype"); const RadOpdDesc l[] = { opd(D, numel), - /* The optional SECOND DESTINATION. Absent means in place, which is what the one-shot rows - * do; the two-shot rows are not safe in place -- a rank gathers into the output while its - * own input is still being read for the scatter -- and refuse a null by name. Passing it - * is the one description that serves every row of the op. */ + /* The optional SECOND DESTINATION. Absent means in place, which every row of the op + * serves; described so a caller that passes one is checked against the same extent. */ opd(D, numel), }; R4D_PICK(l); diff --git a/tests/checkpoint_test.cpp b/tests/checkpoint_test.cpp index b8f2d7eb..b61d59ef 100644 --- a/tests/checkpoint_test.cpp +++ b/tests/checkpoint_test.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include using namespace rad; @@ -262,6 +263,37 @@ TEST(an_expert_is_its_slice_of_a_stack) { remove_checkpoint(dir); } +/* A CHANGED TENSOR IS NAMED AS THE CHECKPOINT NAMES IT. An expert is a slice "exps[2]" of its + * stack, and it reads "exps"; a block-FP8 weight reads its scale plane as well as its codes, so a + * changed scale changes the weight. */ +TEST(a_weight_reads_the_checkpoint_tensors_its_pieces_and_scales_come_from) { + const std::string dir = write_checkpoint( + { bf16("exps", { 4, 2, 3 }, 0.0f), fp8("q.weight", { 2, 128, 128 }), + bf16("q.weight_scale_inv", { 2, 1, 1 }, 7.0f), bf16("a.weight", { 2, 3 }, 0.0f), + bf16("b.weight", { 2, 3 }, 0.0f) }, kConfig); + Checkpoint ck; + REQUIRE_EQ(ck.open(dir), RAD_OK); + Program prog; + prog.name_map.push_back(map("e2", RAD_MAP_COPY, { "exps" }, { 2 })); + prog.name_map.push_back(map("q1", RAD_MAP_COPY, { "q.weight" }, { 1 })); + prog.name_map.push_back(map("ab", RAD_MAP_CONCAT, { "a.weight", "b.weight" })); + CkptWeight e2, q1, ab; + std::string why; + REQUIRE_EQ(ckpt_resolve(ck, prog, "e2", false, &e2, &why), RAD_OK); + REQUIRE_EQ(ckpt_resolve(ck, prog, "q1", false, &q1, &why), RAD_OK); + REQUIRE_EQ(ckpt_resolve(ck, prog, "ab", false, &ab, &why), RAD_OK); + CHECK_EQ(ckpt_tensor_of(*e2.pieces[0]), std::string("exps")); + + std::unordered_set hit; + CHECK(ckpt_reads_any(e2, { "exps" }, &hit)); + CHECK(!ckpt_reads_any(e2, { "exps[2]" })); /* a slice is not a checkpoint name */ + CHECK(ckpt_reads_any(q1, { "q.weight_scale_inv" }, &hit)); + CHECK(ckpt_reads_any(ab, { "b.weight" }, &hit)); /* one changed piece of a join */ + CHECK(!ckpt_reads_any(ab, { "q.weight", "exps" })); + CHECK_EQ(hit.size(), (size_t)3); + remove_checkpoint(dir); +} + /* A COPY's sources are alternatives, first present wins: a tied head reads the embedding where * the checkpoint ships no head of its own. */ TEST(alternatives_take_the_first_tensor_present) { diff --git a/tests/device_test.cpp b/tests/device_test.cpp index 74af61c7..37d4ce3a 100644 --- a/tests/device_test.cpp +++ b/tests/device_test.cpp @@ -159,6 +159,81 @@ TEST(alloc_free_roundtrip) { CHECK(rad_dev_host_ptr(nullptr) == nullptr); } +/* A pinned range larger than one pin is locked in several (core/device/aql.cpp, pin_pieces), and + * nothing above the device layer may be able to tell: one base, every byte of it at the same + * address on the card, copies and fills that cross a piece boundary landing whole, and none of + * them taken for pageable memory -- a fill of pageable memory is refused, so the fill is the + * check. 2.5 GiB is the single-pin size an Intel VT-d host refused; the boundaries crossed are + * the whole GiBs. */ +TEST(a_pinned_range_larger_than_one_pin_is_one_range_on_the_card) { + const int64_t gib = (int64_t)1 << 30; + const int64_t n = 5 * (gib / 2) + 4096 + 17; + const int64_t w = 8 << 20; + Stream st; + auto* h = (uint8_t*)rad_dev_alloc(n, RAD_MEM_HOST_MAPPED); + auto* d = (uint8_t*)rad_dev_alloc(w, RAD_MEM_DEVICE); + CHECK(h != nullptr); + CHECK(d != nullptr); + if (!h || !d) { + rad_dev_free(h, RAD_MEM_HOST_MAPPED); + rad_dev_free(d, RAD_MEM_DEVICE); + return; + } + /* The host backend resolves only an allocation's base, so the interior addresses are a card's + * question. */ + CHECK_EQ(rad_dev_device_ptr(h), (void*)h); + if (!rad::device_is_host()) + for (int64_t off : { gib - 1, gib, 2 * gib - 4096, 2 * gib, n - 1 }) + CHECK_EQ(rad_dev_device_ptr(h + off), (void*)(h + off)); + + std::string expect((size_t)w, '\0'); + for (int64_t b : { gib, 2 * gib }) { + uint8_t* span = h + b - w / 2; + fill(span, w, (uint32_t)(b >> 20)); + std::memcpy(expect.data(), span, (size_t)w); + CHECK_OK(rad_memcpy_async(d, span, w, st.s)); + CHECK_OK(rad_stream_sync(st.s)); + std::memset(span, 0, (size_t)w); + CHECK_OK(rad_memcpy_async(span, d, w, st.s)); + CHECK_OK(rad_stream_sync(st.s)); + CHECK_EQ(std::memcmp(span, expect.data(), (size_t)w), 0); + CHECK_OK(rad_memset_async(span, 0xA5, w, st.s)); + CHECK_OK(rad_stream_sync(st.s)); + CHECK(span[0] == 0xA5 && span[w / 2 - 1] == 0xA5 && span[w / 2] == 0xA5 && span[w - 1] == 0xA5); + } + rad_dev_free(d, RAD_MEM_DEVICE); + rad_dev_free(h, RAD_MEM_HOST_MAPPED); +} + +/* A DEVICE ALLOCATION THE CARD CANNOT TAKE IS AN ERROR, AND STAYS ONE AFTER A QUEUE HAS BEEN + * DESTROYED. ROCm 7.2's runtime answers a VRAM allocation the driver refuses by walking every queue + * the process ever created, destroyed ones included, and dies of SIGSEGV there; the backend refuses + * such a request itself, before the runtime is asked (core/device/aql.cpp, "the room check"). A + * stream is made and destroyed first, so the walk would have a freed queue to touch, and then the + * whole card is asked for: more than the driver has left, since this process already holds some of + * it, and no more than one allocation may be, so without the check it reaches the driver. */ +TEST(an_allocation_the_card_cannot_take_is_refused_after_a_queue_was_destroyed) { + if (rad::device_is_host()) { + std::fprintf(stderr, " SKIP an_allocation_the_card_cannot_take_is_refused_after_a_queue_" + "was_destroyed: a card only\n"); + return; + } + { Stream st; CHECK(st.s != nullptr); } + RadDeviceProps p{}; + CHECK_OK(rad_dev_props(0, &p)); + void* d = rad_dev_alloc(p.vram_bytes, RAD_MEM_DEVICE); + CHECK(d == nullptr); + const char* why = rad_dev_last_error(); + CHECK(std::strstr(why, "on card 0: the driver has") != nullptr); + CHECK(std::strstr(why, "this process") != nullptr); + if (d) rad_dev_free(d, RAD_MEM_DEVICE); + + /* And the card still serves an allocation it can take. */ + void* ok = rad_dev_alloc(8 << 20, RAD_MEM_DEVICE); + CHECK(ok != nullptr); + rad_dev_free(ok, RAD_MEM_DEVICE); +} + TEST(device_allocation_moves_vram_free) { /* On a card, other processes move it too. */ if (!rad::device_is_host()) { diff --git a/tests/plugin_test.cpp b/tests/plugin_test.cpp index cf3b8b6e..19ac7f86 100644 --- a/tests/plugin_test.cpp +++ b/tests/plugin_test.cpp @@ -19,6 +19,7 @@ #include #include +#include #include #include @@ -488,8 +489,8 @@ TEST(every_constraint_operator_refuses_with_its_own_reason) { g = attn_geom(); g.set_s("kv_dtype", "f32"); CHECK(has(refusal(r, "t_attn", g), "kv_dtype in {bf16 fp8_e4m3}, have f32")); - /* A constraint whose key the geometry lacks does NOT hold -- libr4d's rule, and the reason its - * two-shot all-reduce rows can be reached at all. */ + /* A constraint whose key the geometry lacks does NOT hold -- libr4d's rule: a row that needs + * a parameter the caller did not state is not a match. */ Geometry partial; partial.set_i("q_len", 8); CHECK(has(refusal(r, "t_attn", partial), "did not name head_dim")); @@ -817,4 +818,67 @@ TEST(a_device_fact_constraint_is_matched_against_the_machine) { CHECK(has(why, "measured at launch")); } +/* THE SHIPPED libr4d PICKS THE ALL-REDUCE BY MESSAGE SIZE, and the selector is what says so. At 4 + * and 8 ranks the exact sum is a one-shot for a decode-sized message and a two-shot for a prefill + * chunk; the two-shot rows start one element above the one-shot bound, so that bound is a band + * edge of the blocks' ranged `numel`. The band at or under the edge has to stay resolvable for + * every row that places a DIV on `numel` -- the two-rank wht6 wire (64) and the four-rank ti8 wire + * (128) among them -- or a lossy two-rank serve would lose its decode band. Checked here against + * the real plugin, because nothing else can run a four- or eight-rank resolution on a two-card + * machine. Geometry is Qwen3.8-Flash-Next's: 2560 wide, a 2048-token chunk. */ +TEST(libr4d_resolves_the_all_reduce_by_message_size) { + const std::string so = home() + "/kernels/libr4d.so"; + if (access(so.c_str(), R_OK) != 0) { + fprintf(stderr, " SKIP %s: no %s (a build without HIP)\n", ::radtest::current(), + so.c_str()); + return; + } + Registry r; + CHECK(r.load_plugin(so, 0) >= 0); + r.set_device_fact(RAD_FACT_P2P, 1); + + const int64_t width = 2560, chunk = 2048; + auto bands = [&](int world, int exact, int64_t max_tok) { + Geometry g; + g.set_i("world_size", world); + g.set_s("dtype", "bf16"); + g.set_i("exact", exact); + g.set_i("min_bytes", 128 * 1024); + return r.build_bands("all_reduce", "numel", width, max_tok * width, g); + }; + auto names = [](const std::vector& b) { + std::string s; + for (const Band& x : b) + s += fmt("%lld:%s ", (long long)x.hi, picked(x.dom[RAD_DOMAIN_DEVICE].row).c_str()); + return s; + }; + + CHECK_EQ(names(bands(4, 1, chunk)), + "524288:ar_oneshot_4rank_exact 5242880:ar_twoshot_4rank_exact "); + CHECK_EQ(names(bands(8, 1, chunk)), + "524288:ar_oneshot_8rank_exact 5242880:ar_twoshot_8rank_exact "); + CHECK_EQ(names(bands(4, 0, chunk)), + "524288:ar_twoshot_4rank_ti8 5242880:ar_twoshot_4rank_ti8 "); + CHECK_EQ(names(bands(2, 0, chunk)), + "524288:ar_oneshot_2rank_wht6 5242880:ar_oneshot_2rank_wht6 "); + CHECK_EQ(names(bands(2, 1, chunk)), + "524288:ar_oneshot_2rank_exact 5242880:ar_oneshot_2rank_exact "); + + /* Above the two-shot's cap the one-shot takes the message back. */ + CHECK_EQ(names(bands(4, 1, 16384)), + "524288:ar_oneshot_4rank_exact 20971520:ar_twoshot_4rank_exact " + "41943040:ar_oneshot_4rank_exact "); + + /* A step that never exceeds the bound has one band, and it is the one-shot's. */ + CHECK_EQ(names(bands(4, 1, 128)), "327680:ar_oneshot_4rank_exact "); + + /* Eight ranks have no lossy wire: every band is a miss that names the request. */ + const std::vector none = bands(8, 0, chunk); + CHECK(!none.empty()); + for (const Band& b : none) { + CHECK(!b.dom[RAD_DOMAIN_DEVICE]); + CHECK(has(b.miss[RAD_DOMAIN_DEVICE], "exact")); + } +} + RAD_TEST_MAIN() diff --git a/tests/util_test.cpp b/tests/util_test.cpp index aa90f884..acabf1ef 100644 --- a/tests/util_test.cpp +++ b/tests/util_test.cpp @@ -343,8 +343,7 @@ TEST(a_zero_divisor_holds_for_nothing_rather_than_faulting) { } /* A CONSTRAINT WHOSE KEY THE GEOMETRY DOES NOT CARRY DOES NOT HOLD. The header names what this - * buys: libr4d's two-shot all-reduce rows are reachable only by a query that asks for `hops`, - * because a query that omits it fails the more constrained row. */ + * buys: a row that constrains an optional parameter serves only a caller that states it. */ TEST(an_absent_key_fails_every_constraint) { Geometry g; g.set_i("M", 64); diff --git a/tools/opshapes.h b/tools/opshapes.h index 351ec491..7bb39377 100644 --- a/tools/opshapes.h +++ b/tools/opshapes.h @@ -281,9 +281,8 @@ inline int rad_operand_shapes(const std::string& op, const Geometry& g, int n_op } else if (op == "all_reduce" || op == "all_gather") { /* Both take two operands. all_gather's second is [world_size * numel]; all_reduce's is the - * optional SECOND DESTINATION -- absent means in place, which is the form docs/OPS.md - * draws and the only one a one-shot kernel needs, but libr4d's two-shot rows are not safe - * in place and cannot be checked at all without it, so it is passed. */ + * optional SECOND DESTINATION -- absent means in place, the form docs/OPS.md draws and + * every block issues. It is passed so the out-of-place form is exercised too. */ const int64_t numel = gi("numel", n ? n : M); add(D, {numel}); add(D, {op == "all_gather" ? numel * gi("world_size", 1) : numel}); diff --git a/tools/rad_convert.cpp b/tools/rad_convert.cpp index c22d0411..e41752d8 100644 --- a/tools/rad_convert.cpp +++ b/tools/rad_convert.cpp @@ -43,6 +43,7 @@ #include #include #include +#include using namespace rad; @@ -233,6 +234,9 @@ void usage() { " --reuse FILE a container converted earlier from the SAME checkpoint. A weight\n" " it holds with the same encoding, quantiser, options and shape is\n" " copied from it instead of quantised again\n" + " --changed FILE with --reuse: checkpoint tensors (one name a line) that differ from\n" + " the checkpoint the --reuse container was converted from. Every\n" + " weight that reads one is converted; the rest are copied\n" " --in-place with --reuse: EXTEND that container instead of writing a new one.\n" " Its weights stay where they are; new ones are written past its\n" " end and the header last. Refused when a weight it holds would\n" @@ -257,7 +261,7 @@ int main(int argc, char** argv) { int max_spec = kMaxSpecDefault; int report_n = 20; bool verbose = false, plan_only = false, list_quant = false; - std::string reuse_path; + std::string reuse_path, changed_path; bool in_place = false; int kv_dtype = RAD_DT_INVALID; std::vector> set_kv; @@ -295,6 +299,7 @@ int main(int argc, char** argv) { else if (a == "--plan-only") plan_only = true; else if (a == "--report") report_n = std::atoi(next("--report")); else if (a == "--reuse") reuse_path = next("--reuse"); + else if (a == "--changed") changed_path = next("--changed"); else if (a == "--in-place") in_place = true; else if (a == "--kv-cache-dtype") { const std::string v = next("--kv-cache-dtype"); @@ -338,6 +343,12 @@ int main(int argc, char** argv) { return 0; } + if (!changed_path.empty() && (reuse_path.empty() || in_place)) { + std::fprintf(stderr, "rad-convert: --changed says which weights not to copy from the " + "container --reuse names, and needs --reuse without --in-place (a " + "weight cannot be replaced in place)\n"); + return 2; + } if (in_place) { if (reuse_path.empty()) { std::fprintf(stderr, "rad-convert: --in-place extends the container --reuse names\n"); @@ -396,6 +407,26 @@ int main(int argc, char** argv) { /* THE CONTAINER --reuse NAMES, read with pread and never paged through its mapping. */ RadFile reuse; if (!reuse_path.empty() && reuse.open(reuse_path.c_str()) != RAD_OK) return 1; + /* THE TENSORS --changed NAMES: a checkpoint that differs from the --reuse container's own in + * these and nowhere else -- a weight edit, a fine-tune of some matrices. --reuse matches a + * weight on how it was converted and not on its source bytes, so without this list it would + * copy the old weight for every one of them. */ + std::unordered_set changed, changed_read; + if (!changed_path.empty()) { + std::ifstream cf(changed_path); + if (!cf) { RAD_ERR("--changed %s: cannot read it", changed_path.c_str()); return 1; } + std::string line; + while (std::getline(cf, line)) { + const size_t a = line.find_first_not_of(" \t\r"); + const size_t z = line.find_last_not_of(" \t\r"); + if (a == std::string::npos || line[a] == '#') continue; + changed.insert(line.substr(a, z - a + 1)); + } + if (changed.empty()) { + RAD_ERR("--changed %s names no tensor", changed_path.c_str()); + return 1; + } + } /* EXTENDED, NOT RE-DECIDED. The container's radiance.* keys are the convert-time choices its * weights were made under, and a run that keeps those weights declares under the same ones. * `radiance.encoder` is not a choice; this run derives it. */ @@ -738,7 +769,7 @@ int main(int argc, char** argv) { }; std::vector jobs; jobs.reserve(plan.size()); - int64_t reused_inplace = 0, n_inplace = 0; + int64_t reused_inplace = 0, n_inplace = 0, n_changed = 0; for (Logical* Lp : plan) { Logical& L = *Lp; @@ -760,6 +791,12 @@ int main(int argc, char** argv) { * are the same planes, given the same checkpoint -- which --reuse leaves to the operator, * since nothing in either container records a Hessian's contents. */ const RadFileEntry* re = reuse.is_open() ? reuse.find(ww.name) : nullptr; + const bool reads_changed = + !changed.empty() && ckpt_reads_any(L.src, changed, &changed_read); + if (re && reads_changed) { + re = nullptr; + ++n_changed; + } if (re) { bool same = rad_enc_equal(&reuse.encoding(*re), &ww.enc) && ww.quantizer == reuse.str(re->quantizer) && @@ -789,6 +826,22 @@ int main(int argc, char** argv) { if (idx < 0) { w.abort(); return 1; } jobs.push_back(Job{ Lp, idx, re, plane_total }); } + /* A NAME NO WEIGHT READS changes nothing, so it is a typo or a tensor this program does not + * convert -- and either way the operator believes a weight is being converted that is not. */ + if (!changed.empty()) { + std::vector unread; + for (const std::string& n : changed) + if (!changed_read.count(n)) unread.push_back(n); + if (!unread.empty()) { + std::sort(unread.begin(), unread.end()); + RAD_ERR("--changed names %zu tensor(s) no weight of this conversion reads, e.g. '%s'", + unread.size(), unread[0].c_str()); + w.abort(); + return 1; + } + RAD_INFO("--changed: %zu tensor(s) read by %lld weight(s), which are converted rather " + "than copied", changed.size(), (long long)n_changed); + } /* ---------------------------------------------------------------- vocab */ /* core/text interprets the declared chain and serialises it; the writer places it and owns the