Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

Merge branch 'f-139-prs' into f-139-rel

Niko12213ed9dafa1e8c
diff --cc setup.py
index 6a4c18d95,1b4650f15..05dda6aab
--- a/setup.py
+++ b/setup.py
@@@ -2612,27 -2479,37 +2612,53 @@@ def is_wsl() -> bool
return sys.platform.startswith("linux") and "microsoft" in platform.uname().release.lower()
+def rotational_disk(path) -> str | None:
+ """#605 (Linux): the disk's name when `path` is on a rotational disk (sysfs queue/rotational), else None."""
+ if WIN:
+ return None
+ try:
+ st = os.stat(path)
+ p = Path(f"/sys/dev/block/{os.major(st.st_dev)}:{os.minor(st.st_dev)}").resolve()
+ for q in (p, p.parent): # a partition has its disk's queue
+ f = q / "queue" / "rotational"
+ if f.exists():
+ return q.name if f.read_text().strip() == "1" else None
+ except (OSError, ValueError, AttributeError):
+ pass
+ return None
+
+
+ def hip_config_cards(sel) -> list[dict]:
+ """#566: the AMD cards a HIP config runs on - its "gpu" (one index or a list) in HIP's numbering, as amd_gpus
+ lists them; no "gpu": the supported card with the most VRAM, as setup picks it. Each card's name carries its
+ architecture (an RX 7900 XTX and an RX 7900 XT are both gfx1100; a card without a product name in sysfs is known
+ by its arch only). A card that is not found is {} (the key then says "?")."""
+ amd = amd_gpus()
+ if sel is None:
+ usable = [g for g in amd if amd_problem(g) is None]
+ sel = max(usable, key=lambda x: (round(x["vram_gb"]), -x["index"]))["index"] if usable else None
+ byid = {g["index"]: g for g in amd}
+ cards = []
+ for i in (sel if isinstance(sel, list) else [sel]):
+ g = byid.get(i)
+ if g is None:
+ cards.append({})
+ continue
+ arch = g.get("arch") or ""
+ name = g.get("name") or "?"
+ cards.append({**g, "name": name if not arch or arch in name else f"{name} ({arch})"})
+ return cards
+
+
def hardware_key(cfg: dict) -> str:
"""What a calibration is valid for: this GPU, CPU and RAM, and the model with its context and images setting
- (the context's KV cache and the image encoder take VRAM from the expert cache)."""
+ (the context's KV cache and the image encoder take VRAM from the expert cache). #566: a HIP config's cards are
+ AMD's (hip_config_cards) - nvidia-smi's list named them "?" (or another card with that number) before."""
sel = cfg.get("gpu")
- gl = [gpu_info(i) or {} for i in sel] if isinstance(sel, list) else [gpu_info(sel) or {}]
+ if cfg.get("backend") == "hip":
+ gl = hip_config_cards(sel)
+ else:
+ gl = [gpu_info(i) or {} for i in sel] if isinstance(sel, list) else [gpu_info(sel) or {}]
g = {"name": " + ".join(x.get("name", "?") for x in gl), "vram_gb": sum(x.get("vram_gb", 0) for x in gl)}
a = cfg.get("args", [])
ctx = a[a.index("--max-context") + 1] if "--max-context" in a else "?"
@@@ -2904,32 -2787,7 +2941,32 @@@ def saved_draft_vocab(cfg_path: Path) -
return v if v in DRAFT_VOCABS else None
+def vision_tokens(asked: int | None, vision: str, earlier: Path | None) -> int:
+ """#625: the most image tokens a picture becomes (the config's vision.max_tokens): --vision-tokens N, else what an
+ earlier config of this model chose for the same encoder device (a setup run again keeps it), else the device's
+ default (VISION). More is allowed with a note on the time it takes: setup recommends, it does not cap."""
+ default = VISION[vision]["max_tokens"]
+ if asked is None and earlier is not None:
+ try:
+ v = json.loads(earlier.read_text(encoding="utf-8-sig")).get("vision")
+ except (OSError, ValueError, AttributeError):
+ v = None
+ mt = v.get("max_tokens") if isinstance(v, dict) and bool(v.get("gpu")) == (vision == "gpu") else None
+ if isinstance(mt, int) and mt > 0 and mt != default:
+ asked = mt
+ if asked is None:
+ return default
+ note = ""
+ if vision == "cpu" and asked > default:
+ note = (" - on the CPU a picture takes longer to encode the more tokens it gets (several seconds more at "
+ "1,024 than at 300)")
+ elif asked > VISION["gpu"]["max_tokens"]:
+ note = " - more than the encoder's default needs more VRAM and context per picture"
+ ok(f"images: up to {asked} image tokens per picture (--vision-tokens; default {default}){note}")
+ return asked
+
+
- DRAFT_VOCAB_MIB = {"cjk": 348, "cyrillic": 193, "en": 133} # the draft head's VRAM per subset (IQ3_S: the largest)
+ DRAFT_VOCAB_MIB = {"cjk": 348, "cyrillic": 193, "fr": 151, "en": 133} # the draft head's VRAM per subset (IQ3_S: the largest)
SMALL_DRAFT_VRAM_GB = 14 # #474: below this the default subset's head can be what does not fit
@@@ -3865,19 -3691,13 +3904,19 @@@ def main() -> int
cfg["api_key"] = a.api_key
if draft_vocab:
cfg["draft_vocab"] = draft_vocab
+ if a.browser is not None: # #609: only when given (else an earlier choice is carried over)
+ cfg["open_browser"] = a.browser
if vision != "none":
+ old_cfg = ROOT / f"strata-{tag.lower()}.json"
+ vt = vision_tokens(a.vision_tokens, vision, old_cfg if old_cfg.is_file() else adopted)
cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), "model": str(shards[0]),
- "gpu": vision == "gpu", "max_tokens": VISION[vision]["max_tokens"]}
+ "gpu": vision == "gpu", "max_tokens": vt}
if vision == "cpu":
cfg["vision"]["threads"] = max(1, (os.cpu_count() or 8) // 2)
+ elif a.vision_tokens is not None:
+ warn("--vision-tokens: images are off for this model, so it is not used")
cfg_path = ROOT / f"strata-{tag.lower()}.json"
- cal = None if hip else saved_calibration(cfg) # tools/calibrate.py is NVIDIA-only for now
+ cal = setup_calibration(cfg, hip) # #566: Linux HIP too; the tuning is offered on NVIDIA only
if cal is not None:
sys.path.insert(0, str(ROOT / "tools"))
import calibrate as CAL
diff --cc src/core/expert_source.cpp
index 08edd46b9,83a061868..e2154941a
--- a/src/core/expert_source.cpp
+++ b/src/core/expert_source.cpp
@@@ -2681,37 -2581,44 +2681,76 @@@ bool ArenaExpertSource::open(const std:
}
}
+ // STRATA_ARENA_MMAP=1 (a small-RAM machine whose GPUs hold most experts): the arena is the pack's experts.bin
+ // mapped READ-ONLY - not locked, not pinned. The page cache keeps what the CPU pool and the prompt path
+ // actually read (the experts no VRAM cache holds) and gives back the rest under memory pressure; a page
+ // dropped is re-read from the file, so a result never depends on what is resident. The GPUs then get no
+ // mapped alias: run with --pcie-frac 0. The first start writes experts.bin (arena layout, padded by one blob
+ // so a whole-slot copy may start at any expert), later ones map it.
+ #if defined(_WIN32)
+ static const bool arena_mmap = false; // POSIX mmap/madvise: Linux only for now
+ #else
+ static const bool arena_mmap = [] { const char* v = std::getenv("STRATA_ARENA_MMAP"); return v && v[0] == '1'; }();
+ if (arena_mmap) {
+ const uint64_t file_bytes = want + (uint64_t) blob;
+ uint64_t have = 0;
+ {
+ std::ifstream f(path, std::ios::binary | std::ios::ate);
+ if (f) have = (uint64_t) f.tellg();
+ }
+ if (have == file_bytes) {
+ const int fd = ::open(path.c_str(), O_RDONLY);
+ void* v = fd >= 0 ? mmap(nullptr, (size_t) file_bytes, PROT_READ, MAP_SHARED, fd, 0) : MAP_FAILED;
+ if (fd >= 0) ::close(fd);
+ if (v == MAP_FAILED) { err = "ArenaExpertSource: mmap of " + path + " failed"; return false; }
+ map_ = v;
+ map_bytes_ = file_bytes;
+ base_ = (const uint8_t*) v;
+ pinned_bytes_ = 0;
+ dev_slice_.clear();
+ slice_bytes_ = 0;
+ blobs_ = n_layers * n_expert;
+ n_expert_ = n_expert;
+ reads_ = 0;
+ note_ = "mapped read-only from " + path + " (STRATA_ARENA_MMAP: not locked, not pinned)";
+ gib_per_s_ = 0.0;
+ load_seconds_ = load_read_s_ = load_copy_s_ = 0.0;
+ return true;
+ }
+ }
+ #endif
++
+ // #633: THE RAM BEFORE THE ALLOCATION. On Linux the arena is an anonymous mapping that succeeds whatever the host
+ // has; its pages are committed as the load writes them, so a container whose memory limit is below the arena was
+ // killed by the OOM killer part-way through the load, without a message. A hard cgroup limit below it is
+ // certain to end that way: refused, with the numbers. Less RAM available than the arena (another program, an
+ // engine still exiting) is only a warning - the OS may make room - per the recommend-not-force rule.
+ ram_warning_.clear();
+ // (a shared arena, --shared-expert-arena, may already be in RAM for another engine: not checked)
+ if (detail::HostMemory hm; shared_arena_file.empty() && detail::host_available_memory(hm)) {
+ const uint64_t need = want + (uint64_t) blob;
+ const double gib = 1073741824.0;
+ char buf[512];
+ if (hm.cgroup_limit < need) {
+ std::snprintf(buf, sizeof buf,
+ "ArenaExpertSource: the expert arena needs %.2f GiB of RAM but this process's memory limit "
+ "(cgroup memory.max / memory.limit_in_bytes) is %.2f GiB: it would be killed while loading. "
+ "Raise the container's limit, or run with less RAM: --mmap-experts with "
+ "--resident-budget-gib N keeps only the hottest experts in RAM",
+ (double) need / gib, (double) hm.cgroup_limit / gib);
+ err = buf;
+ return false;
+ }
+ if (hm.available < need) {
+ std::snprintf(buf, sizeof buf,
+ "the expert arena needs %.2f GiB of RAM but %.2f GiB is available (%.2f GiB short): the load "
+ "may swap or be stopped by the OS. Close other programs (or wait for an engine that is "
+ "still exiting), or run with less RAM: --mmap-experts with --resident-budget-gib N",
+ (double) need / gib, (double) hm.available / gib, (double) (need - hm.available) / gib);
+ ram_warning_ = buf;
+ }
+ }
+
uint64_t pack_hash = 0;
if (!shared_arena_file.empty() &&
!shared_arena_pack_hash(pack_dir, path, gguf_, lay, pack_hash, err)) return false;
diff --cc src/program/generate.cpp
index bb9037e8d,083f52165..1b6ed60e2
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@@ -115,21 -113,71 +115,85 @@@ bool under_wddm()
#endif
}
+// #620 #486: " (N MiB of M MiB VRAM free on this GPU)" for an allocation's failure message (clears the error first)
+std::string vram_free_note() {
+ (void) cudaGetLastError();
+ size_t free_b = 0, total_b = 0;
+ if (cudaMemGetInfo(&free_b, &total_b) != cudaSuccess) {
+ (void) cudaGetLastError();
+ return {};
+ }
+ char buf[96];
+ std::snprintf(buf, sizeof buf, " (%llu MiB of %llu MiB VRAM free on this GPU)", (unsigned long long) (free_b >> 20),
+ (unsigned long long) (total_b >> 20));
+ return buf;
+}
+
// perf-review D-4: the lent slots are refilled with queued copies and one wait; STRATA_REFILL_BLOCKING=1 waits on each
+ // A file-backed arena on AMD (STRATA_ARENA_MMAP; the engine raises ROCclr's pin-in-place threshold, see main): an
+ // adaptive swap copies one expert straight from the mapped file. Through ROCclr's staging that copy blocks the host
+ // (decode windows of 150+ ms); instead the batch's pages are locked here for the async copies and unlocked when they
+ // have landed (unpin_blobs), so the release that follows can hand them back. Neighbouring experts share a page and
+ // a copy from a range only PART of which is registered fails ("invalid argument"), so the page ranges are merged
+ // first and each merged span is registered once. A span that does not register is copied through the staging
+ // path. Portable: a layer split copies to either card.
+ // Whether pin_blobs locks anything (AMD on Linux with STRATA_ARENA_MMAP=1): the callers only gather the swaps' spans
+ // then - `blob()` is not free (it counts reads, and the file tier may assemble the blob), so the default runs skip it.
+ bool pin_blobs_on() {
+ #if (defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)) && !defined(_WIN32)
+ static const bool on = std::getenv("STRATA_ARENA_MMAP") && std::getenv("STRATA_ARENA_MMAP")[0] == '1';
+ return on;
+ #else
+ return false;
+ #endif
+ }
+ int pin_blobs(std::vector<std::pair<uintptr_t, uintptr_t>> r, std::vector<void*>& live) {
+ int failed = 0; // ranges left pageable (a copy from them still works, through the driver's staging)
+ #if (defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)) && !defined(_WIN32)
+ if (!pin_blobs_on() || r.empty()) return 0;
+ for (auto& [a, e] : r) { a &= ~(uintptr_t) 4095; e = (e + 4095) & ~(uintptr_t) 4095; }
+ std::sort(r.begin(), r.end());
+ size_t k = 0;
+ for (size_t i = 1; i < r.size(); ++i) {
+ if (r[i].first <= r[k].second) r[k].second = std::max(r[k].second, r[i].second);
+ else r[++k] = r[i];
+ }
+ r.resize(k + 1);
+ for (const auto& [a, e] : r) {
+ if (cudaHostRegister((void*) a, (size_t) (e - a), cudaHostRegisterReadOnly | cudaHostRegisterPortable) ==
+ cudaSuccess)
+ live.push_back((void*) a);
+ else {
+ (void) cudaGetLastError();
+ ++failed;
+ }
+ }
+ #else
+ (void) r; (void) live;
+ #endif
+ return failed;
+ }
+ void unpin_blobs(std::vector<void*>& v) {
+ for (void* p : v) (void) cudaHostUnregister(p);
+ (void) cudaGetLastError();
+ v.clear();
+ }
+
+ // STRATA_RSS_TRACE=1: the process's mapped file pages (the arena) at a startup step - who reads the arena back
+ void rss_probe(const char* where) {
+ static const bool on = std::getenv("STRATA_RSS_TRACE") != nullptr;
+ if (!on) return;
+ FILE* f = std::fopen("/proc/self/status", "r");
+ if (!f) return;
+ char line[256];
+ long long kb = -1;
+ while (std::fgets(line, sizeof line, f))
+ if (std::strncmp(line, "RssFile:", 8) == 0) { kb = std::atoll(line + 8); break; }
+ std::fclose(f);
+ std::fprintf(stderr, "strata rss: %s: RssFile %.2f GiB\n", where, (double) kb / (1024.0 * 1024.0));
+ std::fflush(stderr);
+ }
+
bool refill_blocking() {
static const bool v = std::getenv("STRATA_REFILL_BLOCKING") != nullptr;
return v;