Archived
radiance 2.0.0
Radiance becomes a multi-model engine: one process serves several models behind one port, loads each when a request names it, parks it in host memory or restores it from its container, and shares the cards between them (docs/MULTIMODEL.md). The configuration is one YAML file; the command line flags are gone (`radiance --config FILE`, hot reload on SIGHUP). Formats. IQ8R (rotated int8) and IQR-V4 replace FP8 and MXFP4 as whole-model formats, with an int8 KV cache (`kv-cache-dtype: i8`) in place of the fp8 one. Containers whose weights are block FP8, MXFP4, M2XFP4, NVFP4 or ParoQuant are refused at startup by the name of the first such weight. Not served until they have int8 containers: GLM-5.3-Flash, Ornith-1.5, Sage-A1.5, Nemotron-3.5-Bolt-74B, Ling-3.0-flash, drama-3 and Anima's FP8 container; Nemotron-3.5-Bolt-E4B, the Gemma 4 31B DFlash containers and MiniCPM5-2B bf16 serve without their drafter. 1.17.0 serves all of them. Speed. Chained launches for Qwen3.8-27B, Gemma 4, Gemma 3 and the small bf16 models, a new Qwen3.8-Flash-Next container (IQR-V4 experts, int8 trunk) with its decode step and prefill reworked, and a reworked adaptive draft window. Deployment. deploy/compose has two fleet files, tp1.yaml and tp2.yaml, each with its configuration beside it, in place of the per-model files. `host-pool-mib` is a model's host pool in all, split among its ranks. The dashboard is rebuilt: an hour of history kept by the server, each accelerator's memory by model, model states over time. Merged since 1.17.0: Nemotron-3.5-Bolt-74B-A9B by keptn42 (#339); GLM-5.3-Flash on four cards by AnimusNull (#397); chained launches for Flash-Next's decode step (#396) and preempted requests keeping their prefix and place (#405) by mici81; --prefill-interleave auto by Code000 (#410); eight more libr3d kernels and the w4a4 reference by RikshaDriver (#403, #407, #408); libr3d large-BAR and E4M3 decode fixes by neuromanMD (#438, #439); int4/int5 decode tiles by Kezi (#426); attention for Nanbeige 4.3 33B by everplays (#417); expert_stats_report.py by baKon (#431). Fixed: #398, #402, #419, #437 (dschmitz's patch); added the metrics of #392, and multi-model serving as asked for in #367 and #109. Plugin ABI 39: out-of-tree plugins need to be rebuilt. Thanks to @keptn42, @AnimusNull, @mici81, @Code000, @RikshaDriver, @neuromanMD, @Kezi, @everplays, @baKon and @dschmitz.
This commit is contained in:
1 parent
b4c04b6042
commit
ddcb9c69bb
696 files changed
+120770
-56596
No files matched your search
@@ -0,0 +1,566 @@
|
||||
/* util/json.cpp -- rad::Json's text half: yyjson reads, this walks and writes.
|
||||
*
|
||||
* Parse converts yyjson's tree value for value (see util/json.h for the model being kept).
|
||||
* The walk is iterative -- a pre-order collect, then a bottom-up build -- so a deeply nested
|
||||
* document fails its checks instead of the stack. The bottom-up order doubles as the
|
||||
* counting order parse_bounded promises: scalars as they come, a container after its
|
||||
* children, matching the event order the predecessor's callback parser counted in.
|
||||
*
|
||||
* dump() writes the predecessor's bytes with one known exception: floats are shortest-round-trip
|
||||
* spellings (std::to_chars), where the predecessor's grisu2 occasionally prints one digit more for
|
||||
* the same bits. Same value on every re-read, sometimes a shorter spelling. Everything else
|
||||
* matches: compact separators, the same escapes, ".0" kept on integral floats, non-finite
|
||||
* floats as null, and invalid UTF-8 refused (or replaced, one U+FFFD per ill-formed maximal
|
||||
* subpart, as the predecessor's DFA places them). Error TEXTS are not the predecessor's; nothing may
|
||||
* parse them.
|
||||
*/
|
||||
#include "util/json.h"
|
||||
|
||||
#include "util/simd.h"
|
||||
|
||||
#include <yyjson/yyjson.h>
|
||||
|
||||
#include <charconv>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <istream>
|
||||
#include <ostream>
|
||||
#include <streambuf>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace rad {
|
||||
namespace {
|
||||
|
||||
/* ------------------------------------------------------------------ allocation budget
|
||||
* As in core/server's bounded read before it moved here: yyjson allocates an input copy
|
||||
* plus one value buffer grown by halves, and the cap covers both at their worst for any
|
||||
* body the value budget accepts. Refusing past the cap reads as a parse failure. */
|
||||
struct YyBudget {
|
||||
size_t live = 0;
|
||||
size_t cap = 0;
|
||||
};
|
||||
|
||||
void* yy_malloc(void* ctx, size_t size) {
|
||||
YyBudget* b = static_cast<YyBudget*>(ctx);
|
||||
if (size > b->cap - b->live || size > SIZE_MAX - 16) return nullptr;
|
||||
void* raw = std::malloc(size + 16);
|
||||
if (!raw) return nullptr;
|
||||
*static_cast<size_t*>(raw) = size;
|
||||
b->live += size;
|
||||
return static_cast<char*>(raw) + 16;
|
||||
}
|
||||
|
||||
void* yy_realloc(void* ctx, void* ptr, size_t /*old_size*/, size_t size) {
|
||||
if (!ptr) return yy_malloc(ctx, size);
|
||||
YyBudget* b = static_cast<YyBudget*>(ctx);
|
||||
char* raw = static_cast<char*>(ptr) - 16;
|
||||
const size_t old = *reinterpret_cast<size_t*>(raw);
|
||||
if (size > old && size - old > b->cap - b->live) return nullptr;
|
||||
if (size > SIZE_MAX - 16) return nullptr;
|
||||
void* grown = std::realloc(raw, size + 16);
|
||||
if (!grown) return nullptr;
|
||||
*static_cast<size_t*>(grown) = size;
|
||||
b->live = b->live - old + size;
|
||||
return static_cast<char*>(grown) + 16;
|
||||
}
|
||||
|
||||
void yy_free(void* ctx, void* ptr) {
|
||||
if (!ptr) return;
|
||||
YyBudget* b = static_cast<YyBudget*>(ctx);
|
||||
char* raw = static_cast<char*>(ptr) - 16;
|
||||
b->live -= *reinterpret_cast<size_t*>(raw);
|
||||
std::free(raw);
|
||||
}
|
||||
|
||||
size_t yy_cap(size_t body, int64_t budget) {
|
||||
__int128 cap = (__int128)body * 4 + (__int128)budget * 48 + (1 << 20);
|
||||
return cap > (__int128)SIZE_MAX ? SIZE_MAX : (size_t)cap;
|
||||
}
|
||||
|
||||
Json yy_scalar(yyjson_val* v) {
|
||||
switch (yyjson_get_type(v)) {
|
||||
case YYJSON_TYPE_NULL: return nullptr;
|
||||
case YYJSON_TYPE_BOOL: return yyjson_get_bool(v);
|
||||
case YYJSON_TYPE_STR: return std::string(yyjson_get_str(v), yyjson_get_len(v));
|
||||
case YYJSON_TYPE_NUM:
|
||||
switch (yyjson_get_subtype(v)) {
|
||||
case YYJSON_SUBTYPE_UINT: return yyjson_get_uint(v);
|
||||
case YYJSON_SUBTYPE_SINT: return yyjson_get_sint(v);
|
||||
default: return yyjson_get_real(v);
|
||||
}
|
||||
default: return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
/* Convert, counting against budget (containers after their children) and depth. Returns
|
||||
* discarded when either bound trips after setting the matching flag. */
|
||||
Json yy_convert(yyjson_val* root, int64_t budget, int max_depth, bool* over, bool* deep) {
|
||||
*over = false;
|
||||
*deep = false;
|
||||
struct Frame {
|
||||
yyjson_val* v;
|
||||
int depth;
|
||||
};
|
||||
std::vector<Frame> order;
|
||||
std::vector<Frame> stack;
|
||||
stack.push_back({ root, 0 });
|
||||
while (!stack.empty()) {
|
||||
const Frame f = stack.back();
|
||||
stack.pop_back();
|
||||
if (f.depth > max_depth) *deep = true;
|
||||
order.push_back(f);
|
||||
const yyjson_type t = yyjson_get_type(f.v);
|
||||
if (t == YYJSON_TYPE_ARR) {
|
||||
size_t idx, max;
|
||||
yyjson_val* el;
|
||||
yyjson_arr_foreach(f.v, idx, max, el) stack.push_back({ el, f.depth + 1 });
|
||||
} else if (t == YYJSON_TYPE_OBJ) {
|
||||
size_t idx, max;
|
||||
yyjson_val *k, *val;
|
||||
yyjson_obj_foreach(f.v, idx, max, k, val) stack.push_back({ val, f.depth + 1 });
|
||||
}
|
||||
}
|
||||
if (*deep) return Json(Json::value_t::discarded);
|
||||
|
||||
int64_t n = 0;
|
||||
std::vector<Json> st;
|
||||
st.reserve(64);
|
||||
for (size_t i = order.size(); i-- > 0;) {
|
||||
yyjson_val* v = order[i].v;
|
||||
const yyjson_type t = yyjson_get_type(v);
|
||||
if (t != YYJSON_TYPE_ARR && t != YYJSON_TYPE_OBJ) {
|
||||
if (++n > budget) {
|
||||
*over = true;
|
||||
return Json(Json::value_t::discarded);
|
||||
}
|
||||
st.push_back(yy_scalar(v));
|
||||
continue;
|
||||
}
|
||||
const size_t k = t == YYJSON_TYPE_ARR ? yyjson_arr_size(v) : yyjson_obj_size(v);
|
||||
/* Children sit on the stack in reverse document order. */
|
||||
const size_t base = st.size() - k;
|
||||
Json d;
|
||||
if (t == YYJSON_TYPE_ARR) {
|
||||
Json::array_t a;
|
||||
a.reserve(k);
|
||||
for (size_t c = 0; c < k; ++c) a.push_back(std::move(st[base + c]));
|
||||
d = Json(std::move(a));
|
||||
} else {
|
||||
/* Append members, never find-then-insert per member: operator[] over the
|
||||
* ordered vector is a linear scan, which made a flat object quadratic to
|
||||
* parse (a 262k-member tokenizer vocab took 27 s). A duplicate key keeps
|
||||
* its first position and takes the last value, as operator[] would have
|
||||
* left it; small objects find duplicates by scanning what was appended,
|
||||
* large ones through a hash of key views (the yyjson document outlives
|
||||
* this walk). */
|
||||
Json::object_t o;
|
||||
o.reserve(k);
|
||||
size_t idx, max, c = 0;
|
||||
yyjson_val *key, *val;
|
||||
if (k <= 48) {
|
||||
yyjson_obj_foreach(v, idx, max, key, val) {
|
||||
Json child = std::move(st[base + c++]);
|
||||
const std::string_view kv(yyjson_get_str(key), yyjson_get_len(key));
|
||||
size_t at = o.size();
|
||||
for (size_t m = 0; m < o.size(); ++m)
|
||||
if (o[m].first == kv) { at = m; break; }
|
||||
if (at < o.size()) o[at].second = std::move(child);
|
||||
else o.emplace_back(std::string(kv), std::move(child));
|
||||
}
|
||||
} else {
|
||||
std::unordered_map<std::string_view, size_t> seen;
|
||||
seen.reserve(k * 2);
|
||||
yyjson_obj_foreach(v, idx, max, key, val) {
|
||||
Json child = std::move(st[base + c++]);
|
||||
const std::string_view kv(yyjson_get_str(key), yyjson_get_len(key));
|
||||
const auto [it, fresh] = seen.try_emplace(kv, o.size());
|
||||
if (fresh) o.emplace_back(std::string(kv), std::move(child));
|
||||
else o[it->second].second = std::move(child);
|
||||
}
|
||||
}
|
||||
d = Json(std::move(o));
|
||||
}
|
||||
st.resize(base);
|
||||
if (++n > budget) {
|
||||
*over = true;
|
||||
return Json(Json::value_t::discarded);
|
||||
}
|
||||
st.push_back(std::move(d));
|
||||
}
|
||||
return std::move(st.back());
|
||||
}
|
||||
|
||||
struct YyDoc {
|
||||
YyBudget b;
|
||||
yyjson_doc* doc = nullptr;
|
||||
yyjson_read_err err{};
|
||||
explicit YyDoc(std::string_view text, int64_t budget, bool comments) {
|
||||
b.cap = yy_cap(text.size(), budget);
|
||||
yyjson_alc alc{ yy_malloc, yy_realloc, yy_free, &b };
|
||||
yyjson_read_flag flg = YYJSON_READ_ALLOW_BOM;
|
||||
if (comments) flg |= YYJSON_READ_ALLOW_COMMENTS;
|
||||
doc = yyjson_read_opts(const_cast<char*>(text.data()), text.size(), flg, &alc, &err);
|
||||
}
|
||||
~YyDoc() {
|
||||
if (doc) yyjson_doc_free(doc);
|
||||
}
|
||||
YyDoc(const YyDoc&) = delete;
|
||||
YyDoc& operator=(const YyDoc&) = delete;
|
||||
};
|
||||
|
||||
} /* namespace */
|
||||
|
||||
Json Json::parse_bounded(std::string_view text, int64_t budget, int max_depth, bool* over,
|
||||
bool* deep) {
|
||||
YyDoc d(text, budget, false);
|
||||
*over = false;
|
||||
*deep = false;
|
||||
if (!d.doc) return Json(value_t::discarded);
|
||||
Json out = yy_convert(yyjson_doc_get_root(d.doc), budget, max_depth, over, deep);
|
||||
if (*over || *deep) return Json();
|
||||
return out;
|
||||
}
|
||||
|
||||
Json Json::parse(std::string_view text) { return parse(text, nullptr, true, false); }
|
||||
|
||||
Json Json::parse(std::istream& in) {
|
||||
const std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||
return parse(std::string_view(text));
|
||||
}
|
||||
|
||||
Json Json::parse(std::istream& in, std::nullptr_t cb, bool allow_exceptions,
|
||||
bool ignore_comments) {
|
||||
const std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||
return parse(std::string_view(text), cb, allow_exceptions, ignore_comments);
|
||||
}
|
||||
|
||||
std::istream& operator>>(std::istream& in, Json& j) {
|
||||
j = Json::parse(in);
|
||||
return in;
|
||||
}
|
||||
|
||||
std::ostream& operator<<(std::ostream& out, const Json& j) { return out << j.dump(); }
|
||||
|
||||
Json Json::parse(std::string_view text, std::nullptr_t, bool allow_exceptions,
|
||||
bool ignore_comments) {
|
||||
YyDoc d(text, INT64_MAX, ignore_comments);
|
||||
if (!d.doc) {
|
||||
if (!allow_exceptions) return Json(value_t::discarded);
|
||||
std::string msg = "json: parse error at byte ";
|
||||
msg += std::to_string((unsigned long long)d.err.pos);
|
||||
if (d.err.msg) {
|
||||
msg += ": ";
|
||||
msg += d.err.msg;
|
||||
}
|
||||
throw exception(msg);
|
||||
}
|
||||
bool over = false, deep = false;
|
||||
Json out = yy_convert(yyjson_doc_get_root(d.doc), INT64_MAX, INT32_MAX, &over, &deep);
|
||||
return out;
|
||||
}
|
||||
|
||||
bool Json::accept(std::string_view text, bool ignore_comments) {
|
||||
YyDoc d(text, INT64_MAX, ignore_comments);
|
||||
return d.doc != nullptr;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ dump */
|
||||
|
||||
namespace {
|
||||
|
||||
/* Well-formed UTF-8 per the Unicode table the predecessor's DFA encodes (restricted second byte
|
||||
* after E0/ED/F0/F4). utf8_expected gives a lead byte's sequence length, 0 when the byte
|
||||
* cannot lead; utf8_second_ok applies the restriction; utf8_next decodes one sequence.
|
||||
* On failure nothing is consumed by these helpers -- the caller decides how much of the
|
||||
* ill-formed maximal subpart to skip (lead plus structurally valid continuations), which
|
||||
* is where the predecessor places its single replacement character. */
|
||||
int utf8_expected(unsigned char c) {
|
||||
if (c >= 0xC2 && c <= 0xDF) return 2;
|
||||
if (c >= 0xE0 && c <= 0xEF) return 3;
|
||||
if (c >= 0xF0 && c <= 0xF4) return 4;
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool utf8_second_ok(unsigned char lead, unsigned char b) {
|
||||
if ((b & 0xC0) != 0x80) return false;
|
||||
switch (lead) {
|
||||
case 0xE0: return b >= 0xA0;
|
||||
case 0xED: return b <= 0x9F;
|
||||
case 0xF0: return b >= 0x90;
|
||||
case 0xF4: return b <= 0x8F;
|
||||
default: return true;
|
||||
}
|
||||
}
|
||||
|
||||
bool utf8_next(const unsigned char* s, size_t left, uint32_t* cp, size_t* len) {
|
||||
const int want = utf8_expected(s[0]);
|
||||
if (want == 0 || left < (size_t)want) return false;
|
||||
if (!utf8_second_ok(s[0], s[1])) return false;
|
||||
uint32_t v = s[0] & (want == 2 ? 0x1Fu : want == 3 ? 0x0Fu : 0x07u);
|
||||
for (int i = 1; i < want; ++i) {
|
||||
if ((s[i] & 0xC0) != 0x80) return false;
|
||||
v = (v << 6) | (s[i] & 0x3Fu);
|
||||
}
|
||||
*cp = v;
|
||||
*len = (size_t)want;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Bytes to skip past an ill-formed start: the lead and any continuations that belong to
|
||||
* its maximal subpart, so one replacement covers E2 82 (truncated) but ED (bad second
|
||||
* byte range) stops before A0, which stands on its own. */
|
||||
size_t utf8_skip_ill(const unsigned char* s, size_t left) {
|
||||
const int want = utf8_expected(s[0]);
|
||||
if (want == 0) return 1;
|
||||
size_t n = 1;
|
||||
if (n < left && utf8_second_ok(s[0], s[n])) {
|
||||
++n;
|
||||
while (n < left && n < (size_t)want && (s[n] & 0xC0) == 0x80) ++n;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
struct Dumper {
|
||||
std::string out;
|
||||
int indent; /* <0 compact */
|
||||
char indent_char;
|
||||
bool ensure_ascii;
|
||||
Json::error_handler_t eh;
|
||||
|
||||
void newline_indent(int level) {
|
||||
if (indent < 0) return;
|
||||
out += '\n';
|
||||
out.append((size_t)(indent * level), indent_char);
|
||||
}
|
||||
|
||||
void write_string(const std::string& s) {
|
||||
out += '"';
|
||||
const unsigned char* p = (const unsigned char*)s.data();
|
||||
const size_t n = s.size();
|
||||
size_t i = 0;
|
||||
while (i < n) {
|
||||
size_t stop = i + simd::first_json_special(s.data() + i, n - i);
|
||||
if (ensure_ascii) {
|
||||
/* DEL is escaped too there, as the predecessor escaped every code point from
|
||||
* 0x7f up; first_json_special passes it. */
|
||||
const void* del = std::memchr(s.data() + i, 0x7f, stop - i);
|
||||
if (del) stop = (size_t)((const char*)del - s.data());
|
||||
}
|
||||
out.append(s.data() + i, stop - i);
|
||||
i = stop;
|
||||
if (i >= n) break;
|
||||
const unsigned char c = p[i];
|
||||
if (c < 0x80) {
|
||||
switch (c) {
|
||||
case '"': out += "\\\""; break;
|
||||
case '\\': out += "\\\\"; break;
|
||||
case '\b': out += "\\b"; break;
|
||||
case '\f': out += "\\f"; break;
|
||||
case '\n': out += "\\n"; break;
|
||||
case '\r': out += "\\r"; break;
|
||||
case '\t': out += "\\t"; break;
|
||||
default: {
|
||||
char buf[8];
|
||||
snprintf(buf, sizeof buf, "\\u%04x", c);
|
||||
out += buf;
|
||||
break;
|
||||
}
|
||||
}
|
||||
++i;
|
||||
continue;
|
||||
}
|
||||
uint32_t cp = 0;
|
||||
size_t len = 0;
|
||||
if (!utf8_next(p + i, n - i, &cp, &len)) {
|
||||
if (eh == Json::error_handler_t::strict)
|
||||
throw Json::exception("json: dump() found invalid UTF-8");
|
||||
if (eh == Json::error_handler_t::replace)
|
||||
out += ensure_ascii ? "\\ufffd" : "\xef\xbf\xbd";
|
||||
i += utf8_skip_ill(p + i, n - i);
|
||||
continue;
|
||||
}
|
||||
if (ensure_ascii) {
|
||||
char buf[16];
|
||||
if (cp <= 0xFFFF) {
|
||||
snprintf(buf, sizeof buf, "\\u%04x", cp);
|
||||
out += buf;
|
||||
} else {
|
||||
const uint32_t v = cp - 0x10000;
|
||||
snprintf(buf, sizeof buf, "\\u%04x\\u%04x", 0xD800 + (v >> 10),
|
||||
0xDC00 + (v & 0x3FF));
|
||||
out += buf;
|
||||
}
|
||||
} else {
|
||||
out.append((const char*)p + i, len);
|
||||
}
|
||||
i += len;
|
||||
}
|
||||
out += '"';
|
||||
}
|
||||
|
||||
void write_double(double d) { json_append_double(out, d); }
|
||||
|
||||
void write(const Json& j, int level) {
|
||||
switch (j.type()) {
|
||||
case Json::value_t::null: out += "null"; return;
|
||||
case Json::value_t::boolean: out += j.get<bool>() ? "true" : "false"; return;
|
||||
case Json::value_t::number_integer: {
|
||||
char buf[24];
|
||||
const auto r = std::to_chars(buf, buf + sizeof buf, j.get<int64_t>());
|
||||
out.append(buf, r.ptr);
|
||||
return;
|
||||
}
|
||||
case Json::value_t::number_unsigned: {
|
||||
char buf[24];
|
||||
const auto r = std::to_chars(buf, buf + sizeof buf, j.get<uint64_t>());
|
||||
out.append(buf, r.ptr);
|
||||
return;
|
||||
}
|
||||
case Json::value_t::number_float: write_double(j.get<double>()); return;
|
||||
case Json::value_t::string: {
|
||||
write_string(j.get_ref<const std::string&>());
|
||||
return;
|
||||
}
|
||||
case Json::value_t::array: {
|
||||
if (j.empty()) {
|
||||
out += "[]";
|
||||
return;
|
||||
}
|
||||
out += '[';
|
||||
bool first = true;
|
||||
for (const Json& e : j) {
|
||||
if (!first) out += ',';
|
||||
first = false;
|
||||
newline_indent(level + 1);
|
||||
write(e, level + 1);
|
||||
}
|
||||
newline_indent(level);
|
||||
out += ']';
|
||||
return;
|
||||
}
|
||||
case Json::value_t::object: {
|
||||
if (j.empty()) {
|
||||
out += "{}";
|
||||
return;
|
||||
}
|
||||
out += '{';
|
||||
bool first = true;
|
||||
for (auto it = j.begin(); it != j.end(); ++it) {
|
||||
if (!first) out += ',';
|
||||
first = false;
|
||||
newline_indent(level + 1);
|
||||
write_string(it.key());
|
||||
out += indent < 0 ? ":" : ": ";
|
||||
write(*it, level + 1);
|
||||
}
|
||||
newline_indent(level);
|
||||
out += '}';
|
||||
return;
|
||||
}
|
||||
case Json::value_t::discarded:
|
||||
throw Json::exception("json: cannot dump a discarded value");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} /* namespace */
|
||||
|
||||
namespace {
|
||||
|
||||
/* The shortest digits that read back as d in its own type, laid out as nlohmann's dump laid
|
||||
* them out: fixed while the decimal point falls in (-4, 15] places from the first digit
|
||||
* (100000.0, 0.0001), else d.ddde+XX with at least two exponent digits (1e+16, 1.5e-05), and
|
||||
* ".0" on an integral fixed value. Schemas and tool arguments are dumped into grammars and
|
||||
* prompts, so the spelling of a number is part of what a model is given. */
|
||||
template <typename T>
|
||||
void append_shortest(std::string& out, T d) {
|
||||
if (!std::isfinite(d)) {
|
||||
out += "null";
|
||||
return;
|
||||
}
|
||||
if (d == 0) {
|
||||
out += std::signbit(d) ? "-0.0" : "0.0";
|
||||
return;
|
||||
}
|
||||
char buf[40];
|
||||
const auto r = std::to_chars(buf, buf + sizeof buf, d, std::chars_format::scientific);
|
||||
const char* p = buf;
|
||||
const char* end = r.ptr;
|
||||
/* The spelling is laid out in o and appended once: a value is a handful of bytes, and one
|
||||
* append a value is what an embeddings array of hundreds of thousands of them pays. */
|
||||
char o[48];
|
||||
int w = 0;
|
||||
if (*p == '-') {
|
||||
o[w++] = '-';
|
||||
++p;
|
||||
}
|
||||
char dig[24];
|
||||
int k = 0;
|
||||
for (; p < end && *p != 'e'; ++p)
|
||||
if (*p != '.') dig[k++] = *p;
|
||||
/* p at 'e' (to_chars' scientific form always has one), then a sign and the digits; the
|
||||
* buffer is not NUL-terminated, so the exponent is read up to end only. */
|
||||
const char* q = p + 1;
|
||||
const bool neg_e = q < end && *q == '-';
|
||||
if (q < end && (*q == '-' || *q == '+')) ++q;
|
||||
int e = 0;
|
||||
for (; q < end; ++q) e = e * 10 + (*q - '0');
|
||||
if (neg_e) e = -e;
|
||||
const int n = e + 1; /* the decimal point's place after the first digit */
|
||||
if (k <= n && n <= 15) {
|
||||
std::memcpy(o + w, dig, (size_t)k);
|
||||
w += k;
|
||||
std::memset(o + w, '0', (size_t)(n - k));
|
||||
w += n - k;
|
||||
o[w++] = '.';
|
||||
o[w++] = '0';
|
||||
} else if (0 < n && n <= 15) {
|
||||
std::memcpy(o + w, dig, (size_t)n);
|
||||
w += n;
|
||||
o[w++] = '.';
|
||||
std::memcpy(o + w, dig + n, (size_t)(k - n));
|
||||
w += k - n;
|
||||
} else if (-4 < n && n <= 0) {
|
||||
o[w++] = '0';
|
||||
o[w++] = '.';
|
||||
std::memset(o + w, '0', (size_t)-n);
|
||||
w += -n;
|
||||
std::memcpy(o + w, dig, (size_t)k);
|
||||
w += k;
|
||||
} else {
|
||||
o[w++] = dig[0];
|
||||
if (k > 1) {
|
||||
o[w++] = '.';
|
||||
std::memcpy(o + w, dig + 1, (size_t)(k - 1));
|
||||
w += k - 1;
|
||||
}
|
||||
o[w++] = 'e';
|
||||
o[w++] = e < 0 ? '-' : '+';
|
||||
const int a = e < 0 ? -e : e;
|
||||
if (a >= 100) o[w++] = (char)('0' + a / 100);
|
||||
o[w++] = (char)('0' + a / 10 % 10);
|
||||
o[w++] = (char)('0' + a % 10);
|
||||
}
|
||||
out.append(o, (size_t)w);
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
void json_append_double(std::string& out, double d) { append_shortest(out, d); }
|
||||
|
||||
void json_append_float(std::string& out, float f) { append_shortest(out, f); }
|
||||
|
||||
std::string Json::dump(int indent, char indent_char, bool ensure_ascii,
|
||||
error_handler_t eh) const {
|
||||
Dumper d;
|
||||
d.out.reserve(256);
|
||||
d.indent = indent;
|
||||
d.indent_char = indent_char;
|
||||
d.ensure_ascii = ensure_ascii;
|
||||
d.eh = eh;
|
||||
d.write(*this, 0);
|
||||
return std::move(d.out);
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,947 @@
|
||||
/* util/json.h -- the ordered JSON DOM the server, chat templates and config files share.
|
||||
*
|
||||
* It exists because the reader matters: request bodies are parsed with yyjson
|
||||
* (vendor/yyjson) at several GB/s, where the DOM library this replaced read them at
|
||||
* ~340 MB/s, and a DOM vendored around another library's parser would still have owed that
|
||||
* parser its value model. The model kept is that predecessor's, where the tree's code can
|
||||
* observe it -- insertion-ordered objects, non-negative integers read as unsigned, an
|
||||
* integer past uint64 read as a double, duplicate keys keeping the first position with the
|
||||
* last value, dump() bytes for a parsed value -- and the type is otherwise the smallest
|
||||
* value type that carries the API the tree uses. tests/json_test.cpp pins the model on the
|
||||
* corpora that distinguish readers; json.cpp says where behaviour still differs from the
|
||||
* predecessor's (error texts, and a float's digits where the predecessor's were not the
|
||||
* shortest that read back).
|
||||
*
|
||||
* Numbers are int64, uint64 or double, never coerced at rest. get<T>() converts between
|
||||
* number kinds and throws Json::exception across kind boundaries (a string is not a
|
||||
* number). Iteration over an object yields its values in key order with it.key() naming
|
||||
* each; iteration over a scalar yields the scalar itself.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <deque>
|
||||
#include <initializer_list>
|
||||
#include <iosfwd>
|
||||
#include <iterator>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
namespace json_detail {
|
||||
/* The container types the implicit conversion operator may produce. Deliberately a closed
|
||||
* list: a structural "has value_type" test also claims std::optional and
|
||||
* std::initializer_list<char>, whose conversions then tie with ordinary assignments. */
|
||||
template <class T>
|
||||
struct is_gettable_container : std::false_type {};
|
||||
template <class U, class A>
|
||||
struct is_gettable_container<std::vector<U, A>> : std::true_type {};
|
||||
template <class U, class A>
|
||||
struct is_gettable_container<std::deque<U, A>> : std::true_type {};
|
||||
template <class U, class C, class A>
|
||||
struct is_gettable_container<std::set<U, C, A>> : std::true_type {};
|
||||
template <class U, class H, class E, class A>
|
||||
struct is_gettable_container<std::unordered_set<U, H, E, A>> : std::true_type {};
|
||||
template <class U, class C, class A>
|
||||
struct is_gettable_container<std::map<std::string, U, C, A>> : std::true_type {};
|
||||
template <class U, class H, class E, class A>
|
||||
struct is_gettable_container<std::unordered_map<std::string, U, H, E, A>> : std::true_type {};
|
||||
} /* namespace json_detail */
|
||||
|
||||
class Json {
|
||||
public:
|
||||
enum class value_t {
|
||||
null,
|
||||
boolean,
|
||||
number_integer,
|
||||
number_unsigned,
|
||||
number_float,
|
||||
object,
|
||||
array,
|
||||
string,
|
||||
discarded,
|
||||
};
|
||||
|
||||
/* One exception type, thrown for the type errors, missing keys and parse failures
|
||||
* the predecessor reported with its own hierarchy. Callers caught std::exception or
|
||||
* json::exception; both still work. The texts are this library's own. */
|
||||
struct exception : std::runtime_error {
|
||||
using std::runtime_error::runtime_error;
|
||||
};
|
||||
|
||||
enum class error_handler_t { strict, replace, ignore };
|
||||
|
||||
using array_t = std::vector<Json>;
|
||||
using object_t = std::vector<std::pair<std::string, Json>>;
|
||||
using string_t = std::string;
|
||||
|
||||
private:
|
||||
struct discarded_t {};
|
||||
|
||||
using storage_t = std::variant<std::monostate /* null */, bool, int64_t, uint64_t, double,
|
||||
string_t, array_t, object_t, discarded_t>;
|
||||
storage_t v_;
|
||||
|
||||
[[noreturn]] static void fail(const char* what) { throw exception(what); }
|
||||
[[noreturn]] void fail_type(const char* want) const;
|
||||
|
||||
bool is_number_kind() const {
|
||||
return std::holds_alternative<int64_t>(v_) || std::holds_alternative<uint64_t>(v_) ||
|
||||
std::holds_alternative<double>(v_);
|
||||
}
|
||||
long double as_long_double() const {
|
||||
if (const auto* p = std::get_if<int64_t>(&v_)) return (long double)*p;
|
||||
if (const auto* p = std::get_if<uint64_t>(&v_)) return (long double)*p;
|
||||
return (long double)std::get<double>(v_);
|
||||
}
|
||||
|
||||
public:
|
||||
Json() = default;
|
||||
/* Assignment copies (or moves) the source out before the old value dies: the source is
|
||||
* routinely a child of the target (`n = n["$defs"]`), which the variant's own assignment
|
||||
* would read after destroying. the predecessor's assignment was safe the same way. */
|
||||
Json(const Json&) = default;
|
||||
Json(Json&&) = default;
|
||||
Json& operator=(const Json& o) {
|
||||
if (this != &o) {
|
||||
storage_t tmp = o.v_;
|
||||
v_ = std::move(tmp);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
Json& operator=(Json&& o) {
|
||||
if (this != &o) {
|
||||
storage_t tmp = std::move(o.v_);
|
||||
v_ = std::move(tmp);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
Json(std::nullptr_t) {}
|
||||
Json(value_t t) {
|
||||
switch (t) {
|
||||
case value_t::boolean: v_ = false; break;
|
||||
case value_t::number_integer: v_ = int64_t(0); break;
|
||||
case value_t::number_unsigned: v_ = uint64_t(0); break;
|
||||
case value_t::number_float: v_ = 0.0; break;
|
||||
case value_t::string: v_ = string_t(); break;
|
||||
case value_t::array: v_ = array_t(); break;
|
||||
case value_t::object: v_ = object_t(); break;
|
||||
case value_t::discarded: v_ = discarded_t(); break;
|
||||
case value_t::null: break;
|
||||
}
|
||||
}
|
||||
Json(bool b) : v_(b) {}
|
||||
Json(int i) : v_((int64_t)i) {}
|
||||
Json(int64_t i) : v_(i) {}
|
||||
Json(long long i) : v_((int64_t)i) {}
|
||||
Json(unsigned u) : v_((uint64_t)u) {}
|
||||
Json(uint64_t u) : v_(u) {}
|
||||
Json(unsigned long long u) : v_((uint64_t)u) {}
|
||||
Json(double d) : v_(d) {}
|
||||
Json(float f) : v_((double)f) {}
|
||||
Json(const char* s) : v_(string_t(s)) {}
|
||||
Json(string_t s) : v_(std::move(s)) {}
|
||||
Json(std::string_view s) : v_(string_t(s)) {}
|
||||
Json(array_t a) : v_(std::move(a)) {}
|
||||
Json(object_t o) : v_(std::move(o)) {}
|
||||
|
||||
/* Container construction mirrors to_json on the obvious containers: a vector becomes an
|
||||
* array of converted elements, a string-keyed map an object. */
|
||||
template <class T, std::enable_if_t<!std::is_same_v<std::decay_t<T>, Json> &&
|
||||
!std::is_same_v<std::decay_t<T>, array_t> &&
|
||||
!std::is_same_v<std::decay_t<T>, std::vector<uint8_t>>, int> = 0>
|
||||
Json(const std::vector<T>& a) {
|
||||
array_t out;
|
||||
out.reserve(a.size());
|
||||
for (const T& e : a) out.emplace_back(e);
|
||||
v_ = std::move(out);
|
||||
}
|
||||
template <class M, std::enable_if_t<requires { typename M::mapped_type; } &&
|
||||
std::is_same_v<typename M::key_type, std::string>, int> = 0>
|
||||
Json(const M& m) {
|
||||
object_t out;
|
||||
out.reserve(m.size());
|
||||
for (const auto& kv : m) out.emplace_back(kv.first, Json(kv.second));
|
||||
v_ = std::move(out);
|
||||
}
|
||||
|
||||
/* the predecessor's rule: a list whose every element is a two-element array with a string first
|
||||
* is an object; anything else is an array. An empty list is an array. */
|
||||
Json(std::initializer_list<Json> init) {
|
||||
bool obj = init.size() > 0;
|
||||
for (const Json& e : init) {
|
||||
const auto* a = std::get_if<array_t>(&e.v_);
|
||||
if (!a || a->size() != 2 || !std::holds_alternative<string_t>((*a)[0].v_)) {
|
||||
obj = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (obj) {
|
||||
object_t out;
|
||||
out.reserve(init.size());
|
||||
for (const Json& e : init) {
|
||||
const array_t& a = std::get<array_t>(e.v_);
|
||||
out.emplace_back(std::get<string_t>(a[0].v_), a[1]);
|
||||
}
|
||||
v_ = std::move(out);
|
||||
} else {
|
||||
v_ = array_t(init.begin(), init.end());
|
||||
}
|
||||
}
|
||||
|
||||
static Json array(std::initializer_list<Json> init = {}) {
|
||||
Json j;
|
||||
j.v_ = array_t(init.begin(), init.end());
|
||||
return j;
|
||||
}
|
||||
static Json object(std::initializer_list<Json> init = {}) {
|
||||
Json j;
|
||||
j.v_ = object_t();
|
||||
for (const Json& e : init) {
|
||||
const auto* a = std::get_if<array_t>(&e.v_);
|
||||
if (!a || a->size() != 2 || !std::holds_alternative<string_t>((*a)[0].v_))
|
||||
fail("json::object() needs two-element {key, value} entries");
|
||||
std::get<object_t>(j.v_).emplace_back(std::get<string_t>((*a)[0].v_), (*a)[1]);
|
||||
}
|
||||
return j;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ kinds */
|
||||
value_t type() const {
|
||||
switch (v_.index()) {
|
||||
case 0: return value_t::null;
|
||||
case 1: return value_t::boolean;
|
||||
case 2: return value_t::number_integer;
|
||||
case 3: return value_t::number_unsigned;
|
||||
case 4: return value_t::number_float;
|
||||
case 5: return value_t::string;
|
||||
case 6: return value_t::array;
|
||||
case 7: return value_t::object;
|
||||
default: return value_t::discarded;
|
||||
}
|
||||
}
|
||||
const char* type_name() const {
|
||||
switch (type()) {
|
||||
case value_t::null: return "null";
|
||||
case value_t::boolean: return "boolean";
|
||||
case value_t::string: return "string";
|
||||
case value_t::array: return "array";
|
||||
case value_t::object: return "object";
|
||||
case value_t::discarded: return "discarded";
|
||||
default: return "number";
|
||||
}
|
||||
}
|
||||
bool is_null() const { return std::holds_alternative<std::monostate>(v_); }
|
||||
bool is_boolean() const { return std::holds_alternative<bool>(v_); }
|
||||
bool is_number() const { return is_number_kind(); }
|
||||
bool is_number_integer() const {
|
||||
return std::holds_alternative<int64_t>(v_) || std::holds_alternative<uint64_t>(v_);
|
||||
}
|
||||
bool is_number_unsigned() const { return std::holds_alternative<uint64_t>(v_); }
|
||||
bool is_number_float() const { return std::holds_alternative<double>(v_); }
|
||||
bool is_string() const { return std::holds_alternative<string_t>(v_); }
|
||||
bool is_array() const { return std::holds_alternative<array_t>(v_); }
|
||||
bool is_object() const { return std::holds_alternative<object_t>(v_); }
|
||||
bool is_discarded() const { return std::holds_alternative<discarded_t>(v_); }
|
||||
bool is_primitive() const { return is_null() || is_boolean() || is_number() || is_string(); }
|
||||
bool is_structured() const { return is_array() || is_object(); }
|
||||
|
||||
size_t size() const {
|
||||
if (const auto* a = std::get_if<array_t>(&v_)) return a->size();
|
||||
if (const auto* o = std::get_if<object_t>(&v_)) return o->size();
|
||||
return is_null() ? 0 : 1;
|
||||
}
|
||||
bool empty() const { return size() == 0; }
|
||||
void clear() {
|
||||
if (auto* a = std::get_if<array_t>(&v_)) a->clear();
|
||||
else if (auto* o = std::get_if<object_t>(&v_)) o->clear();
|
||||
else if (auto* s = std::get_if<string_t>(&v_)) s->clear();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ iterators
|
||||
* One iterator shape over arrays, objects and (as the predecessor's did) a lone scalar. key()
|
||||
* names the member for objects and the index as a string for arrays, as the predecessor's did. */
|
||||
template <bool Const>
|
||||
class iter_impl {
|
||||
friend class Json;
|
||||
template <bool B>
|
||||
friend class iter_impl;
|
||||
using J = std::conditional_t<Const, const Json, Json>;
|
||||
using arr_it = std::conditional_t<Const, array_t::const_iterator, array_t::iterator>;
|
||||
using obj_it = std::conditional_t<Const, object_t::const_iterator, object_t::iterator>;
|
||||
|
||||
J* owner_ = nullptr;
|
||||
arr_it a_{};
|
||||
obj_it o_{};
|
||||
size_t scalar_ = 0; /* 0: at the scalar itself, 1: past it */
|
||||
|
||||
static iter_impl for_array(J* owner, arr_it it) {
|
||||
iter_impl r;
|
||||
r.owner_ = owner;
|
||||
r.a_ = it;
|
||||
return r;
|
||||
}
|
||||
static iter_impl for_object(J* owner, obj_it it) {
|
||||
iter_impl r;
|
||||
r.owner_ = owner;
|
||||
r.o_ = it;
|
||||
return r;
|
||||
}
|
||||
static iter_impl for_scalar(J* owner, size_t at) {
|
||||
iter_impl r;
|
||||
r.owner_ = owner;
|
||||
r.scalar_ = at;
|
||||
return r;
|
||||
}
|
||||
|
||||
public:
|
||||
using iterator_category = std::bidirectional_iterator_tag;
|
||||
using value_type = Json;
|
||||
using difference_type = std::ptrdiff_t;
|
||||
using pointer = J*;
|
||||
using reference = J&;
|
||||
|
||||
iter_impl() = default;
|
||||
/* iterator converts to const_iterator */
|
||||
template <bool C2, std::enable_if_t<Const && !C2, int> = 0>
|
||||
iter_impl(const iter_impl<C2>& o) : owner_(o.owner_), a_(o.a_), o_(o.o_), scalar_(o.scalar_) {}
|
||||
|
||||
reference operator*() const {
|
||||
if (owner_->is_array()) return *a_;
|
||||
if (owner_->is_object()) return o_->second;
|
||||
return *owner_;
|
||||
}
|
||||
pointer operator->() const { return &operator*(); }
|
||||
|
||||
std::string key() const {
|
||||
if (owner_->is_object()) return o_->first;
|
||||
if (owner_->is_array())
|
||||
return std::to_string((size_t)(a_ - const_cast<J*>(owner_)->arr().begin()));
|
||||
return std::string();
|
||||
}
|
||||
reference value() const { return operator*(); }
|
||||
|
||||
iter_impl& operator++() {
|
||||
if (owner_->is_array()) ++a_;
|
||||
else if (owner_->is_object()) ++o_;
|
||||
else ++scalar_;
|
||||
return *this;
|
||||
}
|
||||
iter_impl operator++(int) {
|
||||
iter_impl t = *this;
|
||||
++*this;
|
||||
return t;
|
||||
}
|
||||
iter_impl& operator--() {
|
||||
if (owner_->is_array()) --a_;
|
||||
else if (owner_->is_object()) --o_;
|
||||
else --scalar_;
|
||||
return *this;
|
||||
}
|
||||
iter_impl operator--(int) {
|
||||
iter_impl t = *this;
|
||||
--*this;
|
||||
return t;
|
||||
}
|
||||
iter_impl& operator+=(difference_type n) {
|
||||
if (owner_->is_array()) a_ += n;
|
||||
else if (owner_->is_object()) o_ += n;
|
||||
else scalar_ = (size_t)((difference_type)scalar_ + n);
|
||||
return *this;
|
||||
}
|
||||
iter_impl& operator-=(difference_type n) { return *this += -n; }
|
||||
iter_impl operator+(difference_type n) const {
|
||||
iter_impl t = *this;
|
||||
return t += n;
|
||||
}
|
||||
iter_impl operator-(difference_type n) const {
|
||||
iter_impl t = *this;
|
||||
return t -= n;
|
||||
}
|
||||
difference_type operator-(const iter_impl& o) const {
|
||||
if (owner_->is_array()) return a_ - o.a_;
|
||||
if (owner_->is_object()) return o_ - o.o_;
|
||||
return (difference_type)scalar_ - (difference_type)o.scalar_;
|
||||
}
|
||||
bool operator==(const iter_impl& o) const {
|
||||
if (owner_ != o.owner_) return false;
|
||||
if (!owner_) return true;
|
||||
if (owner_->is_array()) return a_ == o.a_;
|
||||
if (owner_->is_object()) return o_ == o.o_;
|
||||
return scalar_ == o.scalar_;
|
||||
}
|
||||
bool operator!=(const iter_impl& o) const { return !(*this == o); }
|
||||
bool operator<(const iter_impl& o) const { return (*this - o) < 0; }
|
||||
};
|
||||
|
||||
using iterator = iter_impl<false>;
|
||||
using const_iterator = iter_impl<true>;
|
||||
using reverse_iterator = std::reverse_iterator<iterator>;
|
||||
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
|
||||
|
||||
private:
|
||||
array_t& arr() { return std::get<array_t>(v_); }
|
||||
const array_t& arr() const { return std::get<array_t>(v_); }
|
||||
object_t& obj() { return std::get<object_t>(v_); }
|
||||
const object_t& obj() const { return std::get<object_t>(v_); }
|
||||
|
||||
public:
|
||||
iterator begin() {
|
||||
if (is_array()) return iterator::for_array(this, arr().begin());
|
||||
if (is_object()) return iterator::for_object(this, obj().begin());
|
||||
return iterator::for_scalar(this, is_null() ? 1 : 0);
|
||||
}
|
||||
iterator end() {
|
||||
if (is_array()) return iterator::for_array(this, arr().end());
|
||||
if (is_object()) return iterator::for_object(this, obj().end());
|
||||
return iterator::for_scalar(this, 1);
|
||||
}
|
||||
const_iterator begin() const {
|
||||
if (is_array()) return const_iterator::for_array(this, arr().begin());
|
||||
if (is_object()) return const_iterator::for_object(this, obj().begin());
|
||||
return const_iterator::for_scalar(this, is_null() ? 1 : 0);
|
||||
}
|
||||
const_iterator end() const {
|
||||
if (is_array()) return const_iterator::for_array(this, arr().end());
|
||||
if (is_object()) return const_iterator::for_object(this, obj().end());
|
||||
return const_iterator::for_scalar(this, 1);
|
||||
}
|
||||
const_iterator cbegin() const { return begin(); }
|
||||
const_iterator cend() const { return end(); }
|
||||
reverse_iterator rbegin() { return reverse_iterator(end()); }
|
||||
reverse_iterator rend() { return reverse_iterator(begin()); }
|
||||
const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); }
|
||||
const_reverse_iterator rend() const { return const_reverse_iterator(begin()); }
|
||||
const_reverse_iterator crbegin() const { return rbegin(); }
|
||||
const_reverse_iterator crend() const { return rend(); }
|
||||
|
||||
/* items(): object members as key/value proxies, array elements under index keys, as
|
||||
* the predecessor's iteration proxy presented them. */
|
||||
template <bool Const>
|
||||
struct items_proxy {
|
||||
using base_it = iter_impl<Const>;
|
||||
struct proxy {
|
||||
base_it it;
|
||||
std::string key() const { return it.key(); }
|
||||
typename base_it::reference value() const { return it.value(); }
|
||||
/* Structured bindings: for (auto& [k, v] : obj.items()). */
|
||||
template <size_t I>
|
||||
decltype(auto) get() const {
|
||||
if constexpr (I == 0) return key();
|
||||
else return value();
|
||||
}
|
||||
};
|
||||
struct iterator {
|
||||
base_it it;
|
||||
proxy operator*() const { return proxy{ it }; }
|
||||
iterator& operator++() {
|
||||
++it;
|
||||
return *this;
|
||||
}
|
||||
iterator operator++(int) {
|
||||
iterator t = *this;
|
||||
++it;
|
||||
return t;
|
||||
}
|
||||
bool operator==(const iterator& o) const { return it == o.it; }
|
||||
bool operator!=(const iterator& o) const { return it != o.it; }
|
||||
};
|
||||
base_it b, e;
|
||||
iterator begin() const { return iterator{ b }; }
|
||||
iterator end() const { return iterator{ e }; }
|
||||
};
|
||||
items_proxy<false> items() { return { begin(), end() }; }
|
||||
items_proxy<true> items() const { return { begin(), end() }; }
|
||||
|
||||
/* ------------------------------------------------------------------ access */
|
||||
iterator find(const std::string& key) {
|
||||
if (!is_object()) return end();
|
||||
auto& o = obj();
|
||||
for (auto it = o.begin(); it != o.end(); ++it)
|
||||
if (it->first == key) return iterator::for_object(this, it);
|
||||
return end();
|
||||
}
|
||||
const_iterator find(const std::string& key) const {
|
||||
if (!is_object()) return end();
|
||||
const auto& o = obj();
|
||||
for (auto it = o.begin(); it != o.end(); ++it)
|
||||
if (it->first == key) return const_iterator::for_object(this, it);
|
||||
return end();
|
||||
}
|
||||
iterator find(const char* key) { return find(std::string(key)); }
|
||||
const_iterator find(const char* key) const { return find(std::string(key)); }
|
||||
|
||||
bool contains(const std::string& key) const { return find(key) != end(); }
|
||||
bool contains(const char* key) const { return find(key) != end(); }
|
||||
size_t count(const std::string& key) const { return contains(key) ? 1 : 0; }
|
||||
size_t count(const char* key) const { return contains(key) ? 1 : 0; }
|
||||
|
||||
Json& at(const std::string& key) {
|
||||
auto it = find(key);
|
||||
if (it == end()) fail("json: key not found");
|
||||
return *it;
|
||||
}
|
||||
const Json& at(const std::string& key) const {
|
||||
auto it = find(key);
|
||||
if (it == end()) fail("json: key not found");
|
||||
return *it;
|
||||
}
|
||||
Json& at(const char* key) { return at(std::string(key)); }
|
||||
const Json& at(const char* key) const { return at(std::string(key)); }
|
||||
Json& at(size_t idx) {
|
||||
if (!is_array()) fail_type("array");
|
||||
if (idx >= arr().size()) fail("json: array index out of range");
|
||||
return arr()[idx];
|
||||
}
|
||||
const Json& at(size_t idx) const {
|
||||
if (!is_array()) fail_type("array");
|
||||
if (idx >= arr().size()) fail("json: array index out of range");
|
||||
return arr()[idx];
|
||||
}
|
||||
Json& at(int idx) { return at((size_t)idx); }
|
||||
const Json& at(int idx) const { return at((size_t)idx); }
|
||||
|
||||
Json& operator[](const std::string& key) {
|
||||
if (is_null()) v_ = object_t();
|
||||
if (!is_object()) fail_type("object");
|
||||
auto it = find(key);
|
||||
if (it != end()) return *it;
|
||||
obj().emplace_back(key, Json());
|
||||
return obj().back().second;
|
||||
}
|
||||
Json& operator[](const char* key) { return operator[](std::string(key)); }
|
||||
Json& operator[](std::string_view key) { return operator[](std::string(key)); }
|
||||
const Json& operator[](const std::string& key) const { return at(key); }
|
||||
const Json& operator[](const char* key) const { return at(key); }
|
||||
const Json& operator[](std::string_view key) const { return at(std::string(key)); }
|
||||
|
||||
Json& operator[](size_t idx) {
|
||||
if (is_null()) v_ = array_t();
|
||||
if (!is_array()) fail_type("array");
|
||||
if (idx >= arr().size()) arr().resize(idx + 1);
|
||||
return arr()[idx];
|
||||
}
|
||||
Json& operator[](int idx) { return operator[]((size_t)idx); }
|
||||
Json& operator[](int64_t idx) { return operator[]((size_t)idx); }
|
||||
const Json& operator[](size_t idx) const { return at(idx); }
|
||||
const Json& operator[](int idx) const { return at((size_t)idx); }
|
||||
const Json& operator[](int64_t idx) const { return at((size_t)idx); }
|
||||
|
||||
Json& front() {
|
||||
if (is_array() || is_object()) {
|
||||
if (empty()) fail("json: front() on empty container");
|
||||
return *begin();
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
const Json& front() const {
|
||||
if (is_array() || is_object()) {
|
||||
if (empty()) fail("json: front() on empty container");
|
||||
return *begin();
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
Json& back() {
|
||||
if (is_array()) {
|
||||
if (arr().empty()) fail("json: back() on empty array");
|
||||
return arr().back();
|
||||
}
|
||||
if (is_object()) {
|
||||
if (obj().empty()) fail("json: back() on empty object");
|
||||
return obj().back().second;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
const Json& back() const {
|
||||
if (is_array()) {
|
||||
if (arr().empty()) fail("json: back() on empty array");
|
||||
return arr().back();
|
||||
}
|
||||
if (is_object()) {
|
||||
if (obj().empty()) fail("json: back() on empty object");
|
||||
return obj().back().second;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ conversion
|
||||
* the predecessor's rules: numbers convert between number kinds; nothing converts across the
|
||||
* string/bool/number/container boundaries without throwing. */
|
||||
template <class T>
|
||||
T get() const {
|
||||
if constexpr (std::is_same_v<T, Json>) {
|
||||
return *this;
|
||||
} else if constexpr (std::is_same_v<T, bool>) {
|
||||
if (!is_boolean()) fail_type("boolean");
|
||||
return std::get<bool>(v_);
|
||||
} else if constexpr (std::is_same_v<T, std::string>) {
|
||||
if (!is_string()) fail_type("string");
|
||||
return std::get<string_t>(v_);
|
||||
} else if constexpr (std::is_same_v<T, std::string_view>) {
|
||||
if (!is_string()) fail_type("string");
|
||||
return std::string_view(std::get<string_t>(v_));
|
||||
} else if constexpr (std::is_arithmetic_v<T>) {
|
||||
/* the predecessor's arithmetic read also accepts a boolean, as 0/1. */
|
||||
if (const auto* p = std::get_if<bool>(&v_)) return (T)(*p ? 1 : 0);
|
||||
if (!is_number()) fail_type("number");
|
||||
if (const auto* p = std::get_if<int64_t>(&v_)) return (T)*p;
|
||||
if (const auto* p = std::get_if<uint64_t>(&v_)) return (T)*p;
|
||||
return (T)std::get<double>(v_);
|
||||
} else {
|
||||
return get_container<T>();
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
template <class T>
|
||||
T get_container() const {
|
||||
/* vector<U>: element-wise. map<string,U>: member-wise. Everything else fails like
|
||||
* the predecessor's default serializer would. */
|
||||
if constexpr (requires { typename T::key_type; typename T::mapped_type; }) {
|
||||
if (!is_object()) fail_type("object");
|
||||
T out;
|
||||
for (const auto& kv : obj()) out.emplace(kv.first, kv.second.get<typename T::mapped_type>());
|
||||
return out;
|
||||
} else if constexpr (requires { typename T::value_type; }) {
|
||||
if (!is_array()) fail_type("array");
|
||||
T out;
|
||||
for (const Json& e : arr()) {
|
||||
if constexpr (requires(T& c, typename T::value_type v) { c.push_back(v); })
|
||||
out.push_back(e.get<typename T::value_type>());
|
||||
else
|
||||
out.insert(e.get<typename T::value_type>());
|
||||
}
|
||||
return out;
|
||||
} else {
|
||||
fail("json: unsupported get<T>() target");
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
/* A JSON Pointer (RFC 6901), for the value()/at() lookups spelled through one. */
|
||||
class json_pointer {
|
||||
std::string p_;
|
||||
|
||||
public:
|
||||
json_pointer() = default;
|
||||
explicit json_pointer(std::string p) : p_(std::move(p)) {}
|
||||
json_pointer(const char* p) : p_(p) {}
|
||||
const std::string& to_string() const { return p_; }
|
||||
json_pointer operator/(const std::string& seg) const {
|
||||
std::string e;
|
||||
for (char c : seg) {
|
||||
if (c == '~') e += "~0";
|
||||
else if (c == '/') e += "~1";
|
||||
else e += c;
|
||||
}
|
||||
return json_pointer(p_ + "/" + e);
|
||||
}
|
||||
json_pointer operator/(size_t idx) const { return json_pointer(p_ + "/" + std::to_string(idx)); }
|
||||
};
|
||||
|
||||
private:
|
||||
/* Walk a pointer; returns nullptr when any hop misses (at() turns that into a throw). */
|
||||
const Json* ptr_at(const json_pointer& jp) const {
|
||||
const Json* cur = this;
|
||||
const std::string& p = jp.to_string();
|
||||
size_t i = 0;
|
||||
while (i < p.size()) {
|
||||
if (p[i] != '/') return nullptr;
|
||||
const size_t next = p.find('/', i + 1);
|
||||
std::string tok = p.substr(i + 1, next == std::string::npos ? next : next - i - 1);
|
||||
for (size_t k = 0; k < tok.size(); ++k) {
|
||||
if (tok[k] == '~' && k + 1 < tok.size()) {
|
||||
tok.replace(k, 2, tok[k + 1] == '0' ? "~" : tok[k + 1] == '1' ? "/" : "~");
|
||||
}
|
||||
}
|
||||
if (cur->is_object()) {
|
||||
auto it = cur->find(tok);
|
||||
if (it == cur->end()) return nullptr;
|
||||
cur = &*it;
|
||||
} else if (cur->is_array()) {
|
||||
char* endp = nullptr;
|
||||
const unsigned long long idx = std::strtoull(tok.c_str(), &endp, 10);
|
||||
if (!endp || *endp != '\0' || tok.empty() || idx >= cur->size()) return nullptr;
|
||||
cur = &cur->at((size_t)idx);
|
||||
} else {
|
||||
return nullptr;
|
||||
}
|
||||
i = next == std::string::npos ? p.size() : next;
|
||||
}
|
||||
return cur;
|
||||
}
|
||||
|
||||
public:
|
||||
const Json& at(const json_pointer& jp) const {
|
||||
const Json* r = ptr_at(jp);
|
||||
if (!r) fail("json: json_pointer does not resolve");
|
||||
return *r;
|
||||
}
|
||||
bool contains(const json_pointer& jp) const { return ptr_at(jp) != nullptr; }
|
||||
template <class T>
|
||||
T value(const json_pointer& jp, const T& def) const {
|
||||
const Json* r = ptr_at(jp);
|
||||
return r ? r->get<T>() : def;
|
||||
}
|
||||
|
||||
/* the predecessor's get_to: assign the converted value into an existing object. */
|
||||
template <class T>
|
||||
void get_to(T& out) const {
|
||||
out = get<T>();
|
||||
}
|
||||
|
||||
template <class T>
|
||||
const std::string& get_ref() const {
|
||||
static_assert(std::is_same_v<std::decay_t<T>, std::string>,
|
||||
"get_ref is only defined for strings");
|
||||
if (!is_string()) fail_type("string");
|
||||
return std::get<string_t>(v_);
|
||||
}
|
||||
template <class T>
|
||||
std::string& get_ref() {
|
||||
static_assert(std::is_same_v<std::decay_t<T>, std::string>,
|
||||
"get_ref is only defined for strings");
|
||||
if (!is_string()) fail_type("string");
|
||||
return std::get<string_t>(v_);
|
||||
}
|
||||
|
||||
template <class T>
|
||||
T value(const std::string& key, const T& def) const {
|
||||
auto it = find(key);
|
||||
return it == end() ? def : it->get<T>();
|
||||
}
|
||||
template <class T>
|
||||
T value(const char* key, const T& def) const {
|
||||
return value(std::string(key), def);
|
||||
}
|
||||
/* the predecessor's value() with a const char* default yields a string. */
|
||||
std::string value(const std::string& key, const char* def) const {
|
||||
return value<std::string>(key, std::string(def));
|
||||
}
|
||||
std::string value(const char* key, const char* def) const {
|
||||
return value(std::string(key), def);
|
||||
}
|
||||
|
||||
/* The implicit conversions the predecessor allowed (assignment from Json to string/numeric/bool
|
||||
* targets is all over the chat lift). Constrained to those kinds so overloads do not go
|
||||
* ambiguous anywhere a Json merely sits in a boolean or numeric context by accident.
|
||||
* The string conversion is a plain overload so it wins over the arithmetic template
|
||||
* (std::string's assignment from char would otherwise tie with it). Character types are
|
||||
* excluded from the arithmetic route for the same reason. */
|
||||
operator std::string() const { return get<std::string>(); }
|
||||
template <class T,
|
||||
std::enable_if_t<std::is_arithmetic_v<T> && !std::is_same_v<T, char> &&
|
||||
!std::is_same_v<T, signed char> &&
|
||||
!std::is_same_v<T, unsigned char> && !std::is_same_v<T, wchar_t>,
|
||||
int> = 0>
|
||||
operator T() const {
|
||||
return get<T>();
|
||||
}
|
||||
/* Containers convert too (the predecessor's value semantics: vector<float> from an array).
|
||||
* Restricted to the sequence/associative containers get<>() supports -- an unconstrained
|
||||
* value_type match would also claim optional<T> and shadow its converting constructor. */
|
||||
template <class T, std::enable_if_t<json_detail::is_gettable_container<T>::value, int> = 0>
|
||||
operator T() const {
|
||||
return get<T>();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ mutation */
|
||||
void push_back(const Json& v) {
|
||||
if (is_null()) v_ = array_t();
|
||||
if (!is_array()) fail_type("array");
|
||||
arr().push_back(v);
|
||||
}
|
||||
void push_back(Json&& v) {
|
||||
if (is_null()) v_ = array_t();
|
||||
if (!is_array()) fail_type("array");
|
||||
arr().push_back(std::move(v));
|
||||
}
|
||||
template <class... Args>
|
||||
Json& emplace_back(Args&&... args) {
|
||||
if (is_null()) v_ = array_t();
|
||||
if (!is_array()) fail_type("array");
|
||||
return arr().emplace_back(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
size_t erase(const std::string& key) {
|
||||
if (!is_object()) return 0;
|
||||
auto& o = obj();
|
||||
for (auto it = o.begin(); it != o.end(); ++it)
|
||||
if (it->first == key) {
|
||||
o.erase(it);
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
size_t erase(const char* key) { return erase(std::string(key)); }
|
||||
iterator erase(iterator pos) {
|
||||
if (is_array()) return iterator::for_array(this, arr().erase(pos.a_));
|
||||
if (is_object()) return iterator::for_object(this, obj().erase(pos.o_));
|
||||
fail("json: erase() on a scalar");
|
||||
}
|
||||
iterator erase(size_t idx) {
|
||||
if (!is_array()) fail_type("array");
|
||||
if (idx >= arr().size()) fail("json: array index out of range");
|
||||
return iterator::for_array(this, arr().erase(arr().begin() + (difference_type)idx));
|
||||
}
|
||||
iterator insert(iterator pos, const Json& v) {
|
||||
if (!is_array()) fail_type("array");
|
||||
return iterator::for_array(this, arr().insert(pos.a_, v));
|
||||
}
|
||||
template <class It>
|
||||
iterator insert(iterator pos, It first, It last) {
|
||||
if (!is_array()) fail_type("array");
|
||||
return iterator::for_array(this, arr().insert(pos.a_, first, last));
|
||||
}
|
||||
|
||||
/* the predecessor's update: copy other's members over this object's, one level deep; with the
|
||||
* merge flag, nested objects merge instead of replacing. */
|
||||
void update(const Json& other, bool merge_objects = false) {
|
||||
if (!other.is_object()) fail_type("object");
|
||||
if (is_null()) v_ = object_t();
|
||||
if (!is_object()) fail_type("object");
|
||||
for (const auto& kv : other.obj()) {
|
||||
if (merge_objects) {
|
||||
auto it = find(kv.first);
|
||||
if (it != end() && it->is_object() && kv.second.is_object()) {
|
||||
it->update(kv.second, true);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
operator[](kv.first) = kv.second;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ comparison */
|
||||
bool operator==(const Json& o) const {
|
||||
if (is_number_kind() && o.is_number_kind()) {
|
||||
/* Exact cross-kind numeric equality: integers compare exactly; a float compares
|
||||
* equal only to integers it represents exactly (long double carries both). */
|
||||
return as_long_double() == o.as_long_double();
|
||||
}
|
||||
if (type() != o.type()) return false;
|
||||
switch (type()) {
|
||||
case value_t::null: return true;
|
||||
case value_t::boolean: return std::get<bool>(v_) == std::get<bool>(o.v_);
|
||||
case value_t::string: return std::get<string_t>(v_) == std::get<string_t>(o.v_);
|
||||
case value_t::array: return arr() == o.arr();
|
||||
/* Members in order, as ordered_json compared them: key order is part of what the
|
||||
* server writes and a template renders, so two objects that differ in it differ. */
|
||||
case value_t::object: return obj() == o.obj();
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
bool operator!=(const Json& o) const { return !(*this == o); }
|
||||
bool operator==(std::nullptr_t) const { return is_null(); }
|
||||
bool operator!=(std::nullptr_t) const { return !is_null(); }
|
||||
bool operator==(const char* s) const { return is_string() && std::get<string_t>(v_) == s; }
|
||||
bool operator!=(const char* s) const { return !(*this == s); }
|
||||
bool operator==(const std::string& s) const {
|
||||
return is_string() && std::get<string_t>(v_) == s;
|
||||
}
|
||||
bool operator!=(const std::string& s) const { return !(*this == s); }
|
||||
bool operator==(bool b) const { return is_boolean() && std::get<bool>(v_) == b; }
|
||||
bool operator!=(bool b) const { return !(*this == b); }
|
||||
template <class T,
|
||||
std::enable_if_t<std::is_arithmetic_v<T> && !std::is_same_v<T, bool>, int> = 0>
|
||||
bool operator==(T v) const {
|
||||
return is_number_kind() && as_long_double() == (long double)v;
|
||||
}
|
||||
template <class T,
|
||||
std::enable_if_t<std::is_arithmetic_v<T> && !std::is_same_v<T, bool>, int> = 0>
|
||||
bool operator!=(T v) const {
|
||||
return !(*this == v);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ text (json.cpp) */
|
||||
std::string dump(int indent = -1, char indent_char = ' ', bool ensure_ascii = false,
|
||||
error_handler_t eh = error_handler_t::strict) const;
|
||||
|
||||
static Json parse(std::string_view text);
|
||||
static Json parse(std::istream& in);
|
||||
static Json parse(std::istream& in, std::nullptr_t, bool allow_exceptions,
|
||||
bool ignore_comments = false);
|
||||
static Json parse(const char* text) { return parse(std::string_view(text)); }
|
||||
static Json parse(const std::string& text) { return parse(std::string_view(text)); }
|
||||
static Json parse(std::string_view text, std::nullptr_t, bool allow_exceptions,
|
||||
bool ignore_comments = false);
|
||||
static Json parse(const std::string& text, std::nullptr_t cb, bool allow_exceptions,
|
||||
bool ignore_comments = false) {
|
||||
return parse(std::string_view(text), cb, allow_exceptions, ignore_comments);
|
||||
}
|
||||
static Json parse(const char* text, std::nullptr_t cb, bool allow_exceptions,
|
||||
bool ignore_comments = false) {
|
||||
return parse(std::string_view(text), cb, allow_exceptions, ignore_comments);
|
||||
}
|
||||
static bool accept(std::string_view text, bool ignore_comments = false);
|
||||
|
||||
/* The bounded read core/server's parse_json_bounded is built on: at most `budget`
|
||||
* values (containers count once, keys not at all), nothing nested deeper than
|
||||
* max_depth below the root (root depth 0). Sets *over/*deep and returns null instead
|
||||
* of a tree when a bound trips; returns discarded on a syntax error. */
|
||||
static Json parse_bounded(std::string_view text, int64_t budget, int max_depth, bool* over,
|
||||
bool* deep);
|
||||
|
||||
private:
|
||||
using difference_type = std::ptrdiff_t;
|
||||
};
|
||||
|
||||
inline void Json::fail_type(const char* want) const {
|
||||
std::string msg = "json: value is ";
|
||||
msg += type_name();
|
||||
msg += ", not ";
|
||||
msg += want;
|
||||
throw exception(msg);
|
||||
}
|
||||
|
||||
/* d appended as Json::dump writes a float: the shortest digits that read back as d, fixed
|
||||
* notation while the decimal point is within (-4, 15] places of the first digit (with ".0" on
|
||||
* an integral value), else d.ddde+XX; a non-finite d as null. For writers that emit JSON
|
||||
* numbers without building a tree. */
|
||||
void json_append_double(std::string& out, double d);
|
||||
|
||||
/* f appended in the same layout with the shortest digits that read back as f as a float: what a
|
||||
* float32 holds, without the digits widening it to a double would add (0.1f is 0.1, not
|
||||
* 0.10000000149011612). */
|
||||
void json_append_float(std::string& out, float f);
|
||||
|
||||
std::istream& operator>>(std::istream& in, Json& j);
|
||||
std::ostream& operator<<(std::ostream& out, const Json& j);
|
||||
|
||||
} /* namespace rad */
|
||||
|
||||
template <>
|
||||
struct std::tuple_size<rad::Json::items_proxy<false>::proxy>
|
||||
: std::integral_constant<size_t, 2> {};
|
||||
template <>
|
||||
struct std::tuple_size<rad::Json::items_proxy<true>::proxy>
|
||||
: std::integral_constant<size_t, 2> {};
|
||||
template <>
|
||||
struct std::tuple_element<0, rad::Json::items_proxy<false>::proxy> {
|
||||
using type = std::string;
|
||||
};
|
||||
template <>
|
||||
struct std::tuple_element<0, rad::Json::items_proxy<true>::proxy> {
|
||||
using type = std::string;
|
||||
};
|
||||
template <>
|
||||
struct std::tuple_element<1, rad::Json::items_proxy<false>::proxy> {
|
||||
using type = rad::Json&;
|
||||
};
|
||||
template <>
|
||||
struct std::tuple_element<1, rad::Json::items_proxy<true>::proxy> {
|
||||
using type = const rad::Json&;
|
||||
};
|
||||
+23
-2
@@ -65,6 +65,21 @@ void log_rank_tags(bool on) { g_rank_tags = on; }
|
||||
LogRank::LogRank(int rank) : prev_(g_log_rank) { g_log_rank = rank; }
|
||||
LogRank::~LogRank() { g_log_rank = prev_; }
|
||||
|
||||
static thread_local int g_owner = 0;
|
||||
static thread_local const char* g_model = nullptr;
|
||||
static bool g_model_tags = false;
|
||||
|
||||
void log_model_tags(bool on) { g_model_tags = on; }
|
||||
int engine_owner() { return g_owner; }
|
||||
EngineScope::EngineScope(int owner, const char* model) : prev_owner_(g_owner), prev_model_(g_model) {
|
||||
g_owner = owner;
|
||||
g_model = model;
|
||||
}
|
||||
EngineScope::~EngineScope() {
|
||||
g_owner = prev_owner_;
|
||||
g_model = prev_model_;
|
||||
}
|
||||
|
||||
static std::atomic<uint64_t> g_last_line_ns{0};
|
||||
uint64_t log_last_line_ns() { return g_last_line_ns.load(std::memory_order_relaxed); }
|
||||
|
||||
@@ -101,8 +116,14 @@ void log_emit(Log l, const char* file, int line, const char* fmt, ...) {
|
||||
const char* col = level_colour(l);
|
||||
const char* rst = col[0] ? "\033[0m" : "";
|
||||
|
||||
char rank[16] = "";
|
||||
if (g_rank_tags && g_log_rank >= 0) snprintf(rank, sizeof rank, "[%d]", g_log_rank);
|
||||
char rank[80] = "";
|
||||
const bool tag_rank = g_rank_tags && g_log_rank >= 0;
|
||||
if (g_model_tags && g_model) {
|
||||
if (tag_rank) snprintf(rank, sizeof rank, "[%.60s/r%d]", g_model, g_log_rank);
|
||||
else snprintf(rank, sizeof rank, "[%.60s]", g_model);
|
||||
} else if (tag_rank) {
|
||||
snprintf(rank, sizeof rank, "[%d]", g_log_rank);
|
||||
}
|
||||
|
||||
/* Debug and Trace carry the source site; Info and above do not. */
|
||||
if ((int)l >= (int)Log::Debug)
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
/* rowpool.cpp -- see rowpool.h. */
|
||||
#include "util/rowpool.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <deque>
|
||||
#include <mutex>
|
||||
#include <pthread.h>
|
||||
#include <system_error>
|
||||
#include <thread>
|
||||
|
||||
namespace rad {
|
||||
|
||||
namespace {
|
||||
|
||||
struct Loop {
|
||||
const std::function<void(int64_t)>* row = nullptr;
|
||||
int64_t rows = 0;
|
||||
std::atomic<int64_t> next{0};
|
||||
int max_help = 0;
|
||||
int help = 0; /* workers inside the loop; under Pool::mu */
|
||||
};
|
||||
|
||||
class Pool {
|
||||
public:
|
||||
Pool() {
|
||||
const unsigned hw = std::thread::hardware_concurrency();
|
||||
cap_.store((int)std::min(15u, hw > 1 ? hw - 1 : 0u), std::memory_order_relaxed);
|
||||
}
|
||||
int cap() const { return cap_.load(std::memory_order_relaxed); }
|
||||
|
||||
void run(int64_t rows, int width, const std::function<void(int64_t)>& row) {
|
||||
Loop L;
|
||||
L.row = &row;
|
||||
L.rows = rows;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
start(std::min(width - 1, cap()));
|
||||
L.max_help = std::min(width - 1, started_);
|
||||
if (L.max_help > 0) q_.push_back(&L);
|
||||
}
|
||||
for (int k = 0; k < L.max_help; ++k) work_cv_.notify_one();
|
||||
for (int64_t i; (i = L.next.fetch_add(1, std::memory_order_relaxed)) < rows;) row(i);
|
||||
if (L.max_help == 0) return;
|
||||
/* Every row is taken. Once the loop is off the queue no worker can join it, and each that
|
||||
* did leaves after finishing the rows it took. */
|
||||
std::unique_lock<std::mutex> lk(mu_);
|
||||
q_.erase(std::find(q_.begin(), q_.end(), &L));
|
||||
done_cv_.wait(lk, [&] { return L.help == 0; });
|
||||
}
|
||||
|
||||
private:
|
||||
/* Starts workers until `want` run, under mu_. A thread that cannot be started leaves the pool
|
||||
* smaller; the caller's own rows still cover the loop. */
|
||||
void start(int want) {
|
||||
while (started_ < want) {
|
||||
try {
|
||||
std::thread([this] { work(); }).detach();
|
||||
} catch (const std::system_error&) {
|
||||
cap_.store(started_, std::memory_order_relaxed);
|
||||
return;
|
||||
}
|
||||
++started_;
|
||||
}
|
||||
}
|
||||
|
||||
Loop* pick() {
|
||||
for (Loop* L : q_)
|
||||
if (L->help < L->max_help && L->next.load(std::memory_order_relaxed) < L->rows) return L;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void work() {
|
||||
pthread_setname_np(pthread_self(), "rad-rows");
|
||||
std::unique_lock<std::mutex> lk(mu_);
|
||||
for (;;) {
|
||||
Loop* L = nullptr;
|
||||
work_cv_.wait(lk, [&] { return (L = pick()) != nullptr; });
|
||||
++L->help;
|
||||
lk.unlock();
|
||||
for (int64_t i; (i = L->next.fetch_add(1, std::memory_order_relaxed)) < L->rows;)
|
||||
(*L->row)(i);
|
||||
lk.lock();
|
||||
if (--L->help == 0) done_cv_.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
std::mutex mu_;
|
||||
std::condition_variable work_cv_, done_cv_;
|
||||
std::deque<Loop*> q_;
|
||||
std::atomic<int> cap_{0};
|
||||
int started_ = 0; /* under mu_ */
|
||||
};
|
||||
|
||||
/* Never destroyed: workers wait on it until the process ends, and a static destructor would free
|
||||
* the mutex under them. */
|
||||
Pool& pool() {
|
||||
static Pool* p = new Pool;
|
||||
return *p;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void row_pool_run(int64_t rows, int width, const std::function<void(int64_t)>& row,
|
||||
int64_t min_rows) {
|
||||
if (rows <= 0) return;
|
||||
if (width <= 1 || rows < std::max<int64_t>(min_rows, 2) || pool().cap() == 0) {
|
||||
for (int64_t i = 0; i < rows; ++i) row(i);
|
||||
return;
|
||||
}
|
||||
pool().run(rows, (int)std::min<int64_t>(width, rows), row);
|
||||
}
|
||||
|
||||
int row_pool_workers() { return pool().cap(); }
|
||||
|
||||
} // namespace rad
|
||||
@@ -0,0 +1,31 @@
|
||||
/* rowpool.h -- independent rows of a host loop spread over a pool of threads kept for the
|
||||
* process.
|
||||
*
|
||||
* A request's host work (a picture resampled, cut into patches) is a loop of rows that each write
|
||||
* only their own output. Starting threads for each such loop cost more than the rows: a resample
|
||||
* of a document page started eight threads per pass, about 32 a request, and their creation and
|
||||
* exit (stacks mapped, faulted and freed, per-thread library state set up) took twice the CPU of
|
||||
* the pixels. The pool's workers start once, on first use, and wait for loops.
|
||||
*
|
||||
* The calling thread takes rows too, so a loop never waits for a worker to wake, and concurrent
|
||||
* callers each get help: a worker serves the oldest loop that still has rows and fewer helpers than
|
||||
* it asked for. Rows are handed out one at a time from a shared counter, so which thread computes
|
||||
* a row varies; a loop whose rows are independent gives the same result however they fall.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* Runs row(i) for every i in [0, rows), on the calling thread and at most `width - 1` pool workers,
|
||||
* and returns when all rows are done. `width` <= 1, or a loop of fewer than `min_rows` rows, runs
|
||||
* inline. row must not throw. */
|
||||
void row_pool_run(int64_t rows, int width, const std::function<void(int64_t)>& row,
|
||||
int64_t min_rows = 2);
|
||||
|
||||
/* Workers the pool may start: one fewer than the host's hardware threads, at most 15. */
|
||||
int row_pool_workers();
|
||||
|
||||
} // namespace rad
|
||||
@@ -0,0 +1,184 @@
|
||||
/* simd.cpp -- CPU detection and dispatch for util/simd.h.
|
||||
*
|
||||
* Baseline-compiled (no -m flags): it decides which levels may run, so it must not itself
|
||||
* contain an instruction above the baseline. The tables come from the per-level objects of
|
||||
* simd_kernels.cpp; levels this build does not have (a non-x86 build has only the scalar one)
|
||||
* point at the scalar table. Detection mirrors libavx's avx_dispatch.cpp: __builtin_cpu_supports
|
||||
* rather than raw CPUID, because it also checks XGETBV -- a CPU may enumerate AVX-512 while the
|
||||
* OS has not enabled ZMM state, and executing it then faults.
|
||||
*/
|
||||
#include "util/simd.h"
|
||||
|
||||
#include <atomic>
|
||||
|
||||
extern "C" {
|
||||
#define RAD_SIMD_DECLS(sfx) \
|
||||
int32_t rad_simd_max_i32##sfx(const int32_t*, size_t); \
|
||||
size_t rad_simd_count_eq_i32##sfx(const int32_t*, size_t, int32_t); \
|
||||
int64_t rad_simd_find_eq_i64##sfx(const int64_t*, size_t, int64_t); \
|
||||
size_t rad_simd_first_non_ascii##sfx(const char*, size_t); \
|
||||
size_t rad_simd_first_json_special##sfx(const char*, size_t); \
|
||||
void rad_simd_bitstream_shr##sfx(uint32_t*, const uint32_t*, size_t, unsigned); \
|
||||
void rad_simd_bitmap_marks##sfx(uint8_t*, const int32_t*, size_t, const uint32_t*, size_t); \
|
||||
void rad_simd_or3_u8##sfx(uint8_t*, const uint8_t*, const uint8_t*, const uint8_t*, size_t); \
|
||||
void rad_simd_or_adjacent_u8##sfx(uint8_t*, const uint8_t*, size_t); \
|
||||
void rad_simd_madd_i32_i64##sfx(int64_t*, const int32_t*, int32_t, size_t); \
|
||||
size_t rad_simd_b64_encode_run##sfx(const uint8_t*, size_t, char*); \
|
||||
size_t rad_simd_b64_decode_run##sfx(const uint8_t*, size_t, uint8_t*); \
|
||||
void rad_simd_stripe_acc_u64x8##sfx(uint64_t*, const uint8_t*, size_t); \
|
||||
void rad_simd_level_bits_f32##sfx(const float*, size_t, float, float, uint64_t*, uint64_t*, \
|
||||
uint64_t*, uint64_t*)
|
||||
RAD_SIMD_DECLS(_sc);
|
||||
#ifdef RAD_SIMD_HAVE_X86_LEVELS
|
||||
RAD_SIMD_DECLS(_s4);
|
||||
RAD_SIMD_DECLS(_v1);
|
||||
RAD_SIMD_DECLS(_v2);
|
||||
RAD_SIMD_DECLS(_v3);
|
||||
#endif
|
||||
#undef RAD_SIMD_DECLS
|
||||
}
|
||||
|
||||
namespace rad {
|
||||
namespace simd {
|
||||
namespace {
|
||||
|
||||
struct Table {
|
||||
int32_t (*max_i32)(const int32_t*, size_t);
|
||||
size_t (*count_eq_i32)(const int32_t*, size_t, int32_t);
|
||||
int64_t (*find_eq_i64)(const int64_t*, size_t, int64_t);
|
||||
size_t (*first_non_ascii)(const char*, size_t);
|
||||
size_t (*first_json_special)(const char*, size_t);
|
||||
void (*bitstream_shr)(uint32_t*, const uint32_t*, size_t, unsigned);
|
||||
void (*bitmap_marks)(uint8_t*, const int32_t*, size_t, const uint32_t*, size_t);
|
||||
void (*or3_u8)(uint8_t*, const uint8_t*, const uint8_t*, const uint8_t*, size_t);
|
||||
void (*or_adjacent_u8)(uint8_t*, const uint8_t*, size_t);
|
||||
void (*madd_i32_i64)(int64_t*, const int32_t*, int32_t, size_t);
|
||||
size_t (*b64_encode_run)(const uint8_t*, size_t, char*);
|
||||
size_t (*b64_decode_run)(const uint8_t*, size_t, uint8_t*);
|
||||
void (*stripe_acc_u64x8)(uint64_t*, const uint8_t*, size_t);
|
||||
void (*level_bits_f32)(const float*, size_t, float, float, uint64_t*, uint64_t*, uint64_t*,
|
||||
uint64_t*);
|
||||
};
|
||||
|
||||
#define RAD_SIMD_TABLE(sfx) \
|
||||
{ rad_simd_max_i32##sfx, rad_simd_count_eq_i32##sfx, rad_simd_find_eq_i64##sfx, \
|
||||
rad_simd_first_non_ascii##sfx, rad_simd_first_json_special##sfx, \
|
||||
rad_simd_bitstream_shr##sfx, rad_simd_bitmap_marks##sfx, rad_simd_or3_u8##sfx, \
|
||||
rad_simd_or_adjacent_u8##sfx, rad_simd_madd_i32_i64##sfx, rad_simd_b64_encode_run##sfx, \
|
||||
rad_simd_b64_decode_run##sfx, rad_simd_stripe_acc_u64x8##sfx, rad_simd_level_bits_f32##sfx }
|
||||
|
||||
const Table kTables[kLevels] = {
|
||||
RAD_SIMD_TABLE(_sc),
|
||||
#ifdef RAD_SIMD_HAVE_X86_LEVELS
|
||||
RAD_SIMD_TABLE(_s4), RAD_SIMD_TABLE(_v1), RAD_SIMD_TABLE(_v2), RAD_SIMD_TABLE(_v3),
|
||||
#else
|
||||
RAD_SIMD_TABLE(_sc), RAD_SIMD_TABLE(_sc), RAD_SIMD_TABLE(_sc), RAD_SIMD_TABLE(_sc),
|
||||
#endif
|
||||
};
|
||||
#undef RAD_SIMD_TABLE
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int detect_level() {
|
||||
static const int lvl = [] {
|
||||
#if defined(__x86_64__) && defined(RAD_SIMD_HAVE_X86_LEVELS)
|
||||
__builtin_cpu_init();
|
||||
/* popcnt rides along from the sse4 level up (count_eq_i32 uses it); it has its own
|
||||
* CPUID bit, paired with SSE4.2 on every shipping part but checked rather than assumed. */
|
||||
if (!__builtin_cpu_supports("popcnt")) return (int)kScalar;
|
||||
/* AVX-512 as the conjunction F && BW && DQ && VL, as in libavx: Knights Landing has F
|
||||
* without the others. */
|
||||
if (__builtin_cpu_supports("avx512f") && __builtin_cpu_supports("avx512bw") &&
|
||||
__builtin_cpu_supports("avx512dq") && __builtin_cpu_supports("avx512vl") &&
|
||||
__builtin_cpu_supports("avx2"))
|
||||
return (int)kAvx512;
|
||||
if (__builtin_cpu_supports("avx2") && __builtin_cpu_supports("fma") &&
|
||||
__builtin_cpu_supports("f16c"))
|
||||
return (int)kAvx2;
|
||||
if (__builtin_cpu_supports("avx")) return (int)kAvx;
|
||||
if (__builtin_cpu_supports("sse4.2") && __builtin_cpu_supports("sse4.1"))
|
||||
return (int)kSse4;
|
||||
#endif
|
||||
return (int)kScalar;
|
||||
}();
|
||||
return lvl;
|
||||
}
|
||||
|
||||
namespace {
|
||||
/* The live level. Read on every call (one relaxed atomic load) so force_level takes effect for
|
||||
* the test that flips it between calls; production never writes it after static init. */
|
||||
std::atomic<int> g_level{ -1 };
|
||||
|
||||
const Table& live() {
|
||||
int l = g_level.load(std::memory_order_relaxed);
|
||||
if (l < 0) {
|
||||
l = detect_level();
|
||||
g_level.store(l, std::memory_order_relaxed);
|
||||
}
|
||||
return kTables[l];
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
int level() {
|
||||
const int l = g_level.load(std::memory_order_relaxed);
|
||||
return l < 0 ? detect_level() : l;
|
||||
}
|
||||
|
||||
const char* level_name(int lvl) {
|
||||
switch (lvl) {
|
||||
case kScalar: return "scalar";
|
||||
case kSse4: return "sse4";
|
||||
case kAvx: return "avx";
|
||||
case kAvx2: return "avx2";
|
||||
case kAvx512: return "avx512";
|
||||
default: return "?";
|
||||
}
|
||||
}
|
||||
|
||||
int force_level(int lvl) {
|
||||
const int top = detect_level();
|
||||
if (lvl > top) lvl = top;
|
||||
if (lvl < 0) lvl = 0;
|
||||
g_level.store(lvl, std::memory_order_relaxed);
|
||||
return lvl;
|
||||
}
|
||||
|
||||
int32_t max_i32(const int32_t* v, size_t n) { return live().max_i32(v, n); }
|
||||
size_t count_eq_i32(const int32_t* v, size_t n, int32_t x) {
|
||||
return live().count_eq_i32(v, n, x);
|
||||
}
|
||||
int64_t find_eq_i64(const int64_t* v, size_t n, int64_t x) {
|
||||
return live().find_eq_i64(v, n, x);
|
||||
}
|
||||
size_t first_non_ascii_large(const char* p, size_t n) { return live().first_non_ascii(p, n); }
|
||||
size_t first_json_special_large(const char* p, size_t n) { return live().first_json_special(p, n); }
|
||||
void bitstream_shr(uint32_t* dst, const uint32_t* src, size_t n_words, unsigned sh) {
|
||||
live().bitstream_shr(dst, src, n_words, sh);
|
||||
}
|
||||
void bitmap_marks(uint8_t* dst, const int32_t* ids, size_t n, const uint32_t* bits,
|
||||
size_t n_words) {
|
||||
live().bitmap_marks(dst, ids, n, bits, n_words);
|
||||
}
|
||||
|
||||
void or3_u8_impl(uint8_t* dst, const uint8_t* a, const uint8_t* b, const uint8_t* c, size_t n) {
|
||||
live().or3_u8(dst, a, b, c, n);
|
||||
}
|
||||
void or_adjacent_u8(uint8_t* dst, const uint8_t* s, size_t n) { live().or_adjacent_u8(dst, s, n); }
|
||||
void madd_i32_i64(int64_t* acc, const int32_t* h, int32_t c, size_t n) {
|
||||
live().madd_i32_i64(acc, h, c, n);
|
||||
}
|
||||
size_t b64_encode_run(const uint8_t* in, size_t n, char* out) { return live().b64_encode_run(in, n, out); }
|
||||
size_t b64_decode_run(const uint8_t* in, size_t n, uint8_t* out) {
|
||||
return live().b64_decode_run(in, n, out);
|
||||
}
|
||||
void stripe_acc_u64x8(uint64_t acc[8], const uint8_t* p, size_t stripes) {
|
||||
live().stripe_acc_u64x8(acc, p, stripes);
|
||||
}
|
||||
|
||||
void level_bits_f32(const float* v, size_t n, float lv, float band, uint64_t* gt, uint64_t* lt,
|
||||
uint64_t* nan, uint64_t* near) {
|
||||
live().level_bits_f32(v, n, lv, band, gt, lt, nan, near);
|
||||
}
|
||||
|
||||
} /* namespace simd */
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,145 @@
|
||||
/* simd.h -- small exact integer/bit primitives for the core's host hot paths, dispatched by CPU
|
||||
* feature like libavx (libavx/avx_isa.h): the shipped binary is built once and runs on machines
|
||||
* it was not built on, so no -march=native. simd_kernels.cpp is compiled once per level into
|
||||
* separate objects with their own -m flags; simd.cpp (baseline, no -m flags) picks a table once
|
||||
* at first use via __builtin_cpu_supports, which also checks the OS has enabled the register
|
||||
* state (XGETBV), so a level the CPU enumerates but the OS has not enabled is never selected.
|
||||
*
|
||||
* Every function here is integer or bit arithmetic, or float comparison, with a single exact
|
||||
* result: all levels must agree bit for bit on every input, which simd_test cases in tests/hostbench_test.cpp check by
|
||||
* forcing each level in turn (simd_force_level) against a scalar reference written in the test.
|
||||
* Nothing with floating-point reduction order belongs here.
|
||||
*
|
||||
* Levels:
|
||||
* 0 scalar x86-64 baseline (SSE2 exists but nothing is hand-vectorised)
|
||||
* 1 sse4 SSE4.1 + SSE4.2 (pmaxsd, pmovzx, pcmpeqq)
|
||||
* 2 avx AVX (256-bit float only; integer helpers split into 128-bit halves)
|
||||
* 3 avx2 AVX2 + FMA + F16C (256-bit integer)
|
||||
* 4 avx512 AVX-512 F/BW/DQ/VL (the conjunction libavx checks)
|
||||
*
|
||||
* On a non-x86 build only the scalar level exists and the dispatcher selects it.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
namespace simd {
|
||||
|
||||
enum Level {
|
||||
kScalar = 0,
|
||||
kSse4 = 1,
|
||||
kAvx = 2,
|
||||
kAvx2 = 3,
|
||||
kAvx512 = 4,
|
||||
kLevels = 5
|
||||
};
|
||||
|
||||
/* The highest level this CPU+OS can execute. Computed once. */
|
||||
int detect_level();
|
||||
/* The level in use (detect_level() unless forced). */
|
||||
int level();
|
||||
const char* level_name(int lvl);
|
||||
/* Force a level, clamped to detect_level(); for tests only, like avx_isa_force. Returns the
|
||||
* level now in use. */
|
||||
int force_level(int lvl);
|
||||
|
||||
/* Largest of v[0..n). n == 0 returns INT32_MIN (callers size-check; the value is the identity
|
||||
* for max, so folding it into a running maximum is harmless). */
|
||||
int32_t max_i32(const int32_t* v, size_t n);
|
||||
|
||||
/* How many of v[0..n) equal x. */
|
||||
size_t count_eq_i32(const int32_t* v, size_t n, int32_t x);
|
||||
|
||||
/* First index i with v[i] == x, or -1. */
|
||||
int64_t find_eq_i64(const int64_t* v, size_t n, int64_t x);
|
||||
|
||||
size_t first_non_ascii_large(const char* p, size_t n);
|
||||
size_t first_json_special_large(const char* p, size_t n);
|
||||
|
||||
/* First index i with (unsigned char)p[i] >= 0x80, or n when the whole range is ASCII.
|
||||
* Short ranges -- a tokenizer piece, a token of streamed text -- are scanned inline: the
|
||||
* dispatched kernels pay an atomic load and an indirect call to look at a handful of bytes,
|
||||
* which at a call per piece cost more than the scan. The word-at-a-time check is portable
|
||||
* scalar code, exact at every level like the kernels behind it. */
|
||||
inline size_t first_non_ascii(const char* p, size_t n) {
|
||||
if (n >= 32) return first_non_ascii_large(p, n);
|
||||
size_t i = 0;
|
||||
for (; i + 8 <= n; i += 8) {
|
||||
uint64_t w;
|
||||
std::memcpy(&w, p + i, 8);
|
||||
if (w & 0x8080808080808080ull) break;
|
||||
}
|
||||
for (; i < n; ++i)
|
||||
if ((unsigned char)p[i] >= 0x80) return i;
|
||||
return n;
|
||||
}
|
||||
|
||||
/* First index i whose byte cannot go into a JSON string as it stands -- below 0x20, '"' or
|
||||
* '\\' (an escape), or >= 0x80 (UTF-8 to validate) -- or n. The streaming escaper's run scan
|
||||
* (server/json_partial.cpp), with the same short-range inline path as first_non_ascii. */
|
||||
inline size_t first_json_special(const char* p, size_t n) {
|
||||
if (n >= 32) return first_json_special_large(p, n);
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
const unsigned char c = (unsigned char)p[i];
|
||||
if (c < 0x20 || c >= 0x80 || c == '"' || c == '\\') return i;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/* dst[i] = (src[i] >> sh) | (src[i+1] << (32 - sh)) for i in [0, n_words), reading src[n_words]
|
||||
* as 0. sh must be in [1, 31]. dst and src must not overlap. This is the bit-window realignment
|
||||
* a sharded vocabulary mask needs (sampler shard_mask). */
|
||||
void bitstream_shr(uint32_t* dst, const uint32_t* src, size_t n_words, unsigned sh);
|
||||
|
||||
/* dst[i] = bit ids[i] of the bitmap `bits` (id < n_words*32), 1 or 0; an id outside
|
||||
* [0, n_words*32) reads as 0. The DRY breaker-mark loop. */
|
||||
void bitmap_marks(uint8_t* dst, const int32_t* ids, size_t n, const uint32_t* bits,
|
||||
size_t n_words);
|
||||
|
||||
/* dst[i] = a[i] | b[i] | c[i] over n bytes; b or c null stands for no term. dst may be a, b or c
|
||||
* (each byte is read before it is written). A voxel grid's dilation along one axis (the shape
|
||||
* generator's octree refinement). */
|
||||
void or3_u8_impl(uint8_t* dst, const uint8_t* a, const uint8_t* b, const uint8_t* c, size_t n);
|
||||
inline void or3_u8(uint8_t* dst, const uint8_t* a, const uint8_t* b, const uint8_t* c, size_t n) {
|
||||
or3_u8_impl(dst, a, b ? b : a, c ? c : a, n);
|
||||
}
|
||||
|
||||
/* dst[i] = s[i - 1] | s[i] | s[i + 1] for i in [0, n), a neighbour past either end standing for
|
||||
* no term. dst and s must not overlap. The same dilation along a contiguous line. */
|
||||
void or_adjacent_u8(uint8_t* dst, const uint8_t* s, size_t n);
|
||||
|
||||
/* acc[i] += (int64_t)h[i] * c for i in [0, n), c within int32. Exact (no product or sum rounds;
|
||||
* the caller keeps the sums within int64). A fixed-point separable filter's vertical taps. */
|
||||
void madd_i32_i64(int64_t* acc, const int32_t* h, int32_t c, size_t n);
|
||||
|
||||
/* Base64 (RFC 4648 standard alphabet) over the input's leading whole blocks of the vector width:
|
||||
* encodes the leading bytes of in[0..n) to out, returning the bytes consumed (a multiple of 3;
|
||||
* out holds 4/3 as many digits). Reads stay inside in[0..n). Level 0 consumes nothing: the
|
||||
* caller's scalar loop does the rest, so every level gives the caller's exact output. */
|
||||
size_t b64_encode_run(const uint8_t* in, size_t n, char* out);
|
||||
/* Decodes leading digits of in[0..n) while every one of a vector block is a digit (no padding,
|
||||
* whitespace or other byte), returning the digits consumed (a multiple of 4; out holds 3/4 as
|
||||
* many bytes). Stops at the first block holding anything else, for the caller's scalar loop. */
|
||||
size_t b64_decode_run(const uint8_t* in, size_t n, uint8_t* out);
|
||||
|
||||
/* Accumulates `stripes` 64-byte stripes of p into eight 64-bit lanes, as XXH3 does: lane j of
|
||||
* stripe s takes d = the stripe's j-th word, k = d ^ key[s % 16 + j], adds lo32(k) * hi32(k) to
|
||||
* itself and d to lane j ^ 1; after every 16 stripes each lane is scrambled (xorshift 47, a key
|
||||
* word, times 0x9E3779B1). The keys slide a word a stripe so reordered stripes accumulate
|
||||
* differently. Integer arithmetic only, the same at every level. The bulk of a content hash;
|
||||
* the caller seeds the lanes and folds them. */
|
||||
void stripe_acc_u64x8(uint64_t acc[8], const uint8_t* p, size_t stripes);
|
||||
|
||||
/* Bitmaps of v[0..n) against a level, bit i of word i / 64 for element i, bits past n zero
|
||||
* ((n + 63) / 64 words each): gt v[i] > lv, lt v[i] < lv, nan v[i] is a NaN, near
|
||||
* |v[i] - lv| < band (the difference rounded to float first). A NaN sets only its nan bit. A
|
||||
* float comparison has one answer, so the levels agree bit for bit. One row of a scalar field
|
||||
* classified at a time (the shape generator's marching cubes and octree refinement). */
|
||||
void level_bits_f32(const float* v, size_t n, float lv, float band, uint64_t* gt, uint64_t* lt,
|
||||
uint64_t* nan, uint64_t* near);
|
||||
|
||||
} /* namespace simd */
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,820 @@
|
||||
/* simd_kernels.cpp -- the per-level bodies behind simd.h. Compiled once per level with
|
||||
* RAD_SIMD_LEVEL=0..4 and matching -m flags (core/CMakeLists.txt); the globbed copy built
|
||||
* without the definition is empty. Names carry the level suffix; simd.cpp holds the table.
|
||||
*
|
||||
* Correctness rule for every body: the result is exact integer arithmetic, identical at every
|
||||
* level. Where a vector trick would change a corner (signed compare of bit patterns, a masked
|
||||
* tail reading past the end), the scalar tail below is the level-0 code repeated, so the test
|
||||
* that forces each level compares like with like.
|
||||
*/
|
||||
#ifdef RAD_SIMD_LEVEL
|
||||
|
||||
#include "util/simd.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
|
||||
#if RAD_SIMD_LEVEL >= 1
|
||||
#include <immintrin.h>
|
||||
#endif
|
||||
|
||||
#if RAD_SIMD_LEVEL == 0
|
||||
#define RAD_SIMD_SUFFIX _sc
|
||||
#elif RAD_SIMD_LEVEL == 1
|
||||
#define RAD_SIMD_SUFFIX _s4
|
||||
#elif RAD_SIMD_LEVEL == 2
|
||||
#define RAD_SIMD_SUFFIX _v1
|
||||
#elif RAD_SIMD_LEVEL == 3
|
||||
#define RAD_SIMD_SUFFIX _v2
|
||||
#elif RAD_SIMD_LEVEL == 4
|
||||
#define RAD_SIMD_SUFFIX _v3
|
||||
#else
|
||||
#error "RAD_SIMD_LEVEL out of range"
|
||||
#endif
|
||||
|
||||
#define RAD_SIMD_CAT2(a, b) a##b
|
||||
#define RAD_SIMD_CAT(a, b) RAD_SIMD_CAT2(a, b)
|
||||
#define RAD_SIMD_FN(name) RAD_SIMD_CAT(rad_simd_##name, RAD_SIMD_SUFFIX)
|
||||
|
||||
extern "C" {
|
||||
|
||||
/* ---------------------------------------------------------------- max_i32 */
|
||||
int32_t RAD_SIMD_FN(max_i32)(const int32_t* v, size_t n) {
|
||||
int32_t m = INT32_MIN;
|
||||
size_t i = 0;
|
||||
#if RAD_SIMD_LEVEL == 4
|
||||
__m512i a = _mm512_set1_epi32(INT32_MIN);
|
||||
for (; i + 16 <= n; i += 16) a = _mm512_max_epi32(a, _mm512_loadu_si512(v + i));
|
||||
m = _mm512_reduce_max_epi32(a);
|
||||
#elif RAD_SIMD_LEVEL == 3
|
||||
__m256i a = _mm256_set1_epi32(INT32_MIN);
|
||||
for (; i + 8 <= n; i += 8) a = _mm256_max_epi32(a, _mm256_loadu_si256((const __m256i*)(v + i)));
|
||||
__m128i x = _mm_max_epi32(_mm256_castsi256_si128(a), _mm256_extracti128_si256(a, 1));
|
||||
x = _mm_max_epi32(x, _mm_shuffle_epi32(x, 0x4e));
|
||||
x = _mm_max_epi32(x, _mm_shuffle_epi32(x, 0xb1));
|
||||
m = _mm_cvtsi128_si32(x);
|
||||
#elif RAD_SIMD_LEVEL == 2
|
||||
/* AVX without AVX2 has no 256-bit integer max: two 128-bit halves (pmaxsd is SSE4.1, part of
|
||||
* every AVX part's SSE set, and this object is compiled -mavx only, so the 128-bit integer
|
||||
* instructions it uses are the SSE2..SSE4.1 ones __builtin_cpu_supports("avx") implies:
|
||||
* AVX requires SSE4.2 in every shipping part, and the compiler is told only -mavx, which
|
||||
* enables up to SSE4.2). */
|
||||
__m128i a = _mm_set1_epi32(INT32_MIN), b = _mm_set1_epi32(INT32_MIN);
|
||||
for (; i + 8 <= n; i += 8) {
|
||||
a = _mm_max_epi32(a, _mm_loadu_si128((const __m128i*)(v + i)));
|
||||
b = _mm_max_epi32(b, _mm_loadu_si128((const __m128i*)(v + i + 4)));
|
||||
}
|
||||
__m128i x = _mm_max_epi32(a, b);
|
||||
x = _mm_max_epi32(x, _mm_shuffle_epi32(x, 0x4e));
|
||||
x = _mm_max_epi32(x, _mm_shuffle_epi32(x, 0xb1));
|
||||
m = _mm_cvtsi128_si32(x);
|
||||
#elif RAD_SIMD_LEVEL == 1
|
||||
__m128i a = _mm_set1_epi32(INT32_MIN);
|
||||
for (; i + 4 <= n; i += 4) a = _mm_max_epi32(a, _mm_loadu_si128((const __m128i*)(v + i)));
|
||||
a = _mm_max_epi32(a, _mm_shuffle_epi32(a, 0x4e));
|
||||
a = _mm_max_epi32(a, _mm_shuffle_epi32(a, 0xb1));
|
||||
m = _mm_cvtsi128_si32(a);
|
||||
#endif
|
||||
for (; i < n; ++i) m = v[i] > m ? v[i] : m;
|
||||
return m;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- count_eq_i32 */
|
||||
size_t RAD_SIMD_FN(count_eq_i32)(const int32_t* v, size_t n, int32_t x) {
|
||||
size_t c = 0, i = 0;
|
||||
#if RAD_SIMD_LEVEL == 4
|
||||
const __m512i xv = _mm512_set1_epi32(x);
|
||||
for (; i + 16 <= n; i += 16)
|
||||
c += (size_t)__builtin_popcount(
|
||||
(unsigned)_mm512_cmpeq_epi32_mask(_mm512_loadu_si512(v + i), xv));
|
||||
#elif RAD_SIMD_LEVEL == 3
|
||||
const __m256i xv = _mm256_set1_epi32(x);
|
||||
for (; i + 8 <= n; i += 8)
|
||||
c += (size_t)__builtin_popcount((unsigned)_mm256_movemask_ps(_mm256_castsi256_ps(
|
||||
_mm256_cmpeq_epi32(_mm256_loadu_si256((const __m256i*)(v + i)), xv))));
|
||||
#elif RAD_SIMD_LEVEL == 2
|
||||
const __m128i xv = _mm_set1_epi32(x);
|
||||
for (; i + 8 <= n; i += 8) {
|
||||
c += (size_t)__builtin_popcount((unsigned)_mm_movemask_ps(_mm_castsi128_ps(
|
||||
_mm_cmpeq_epi32(_mm_loadu_si128((const __m128i*)(v + i)), xv))));
|
||||
c += (size_t)__builtin_popcount((unsigned)_mm_movemask_ps(_mm_castsi128_ps(
|
||||
_mm_cmpeq_epi32(_mm_loadu_si128((const __m128i*)(v + i + 4)), xv))));
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL == 1
|
||||
const __m128i xv = _mm_set1_epi32(x);
|
||||
for (; i + 4 <= n; i += 4)
|
||||
c += (size_t)__builtin_popcount((unsigned)_mm_movemask_ps(_mm_castsi128_ps(
|
||||
_mm_cmpeq_epi32(_mm_loadu_si128((const __m128i*)(v + i)), xv))));
|
||||
#endif
|
||||
for (; i < n; ++i) c += v[i] == x;
|
||||
return c;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- find_eq_i64 */
|
||||
int64_t RAD_SIMD_FN(find_eq_i64)(const int64_t* v, size_t n, int64_t x) {
|
||||
size_t i = 0;
|
||||
#if RAD_SIMD_LEVEL == 4
|
||||
const __m512i xv = _mm512_set1_epi64(x);
|
||||
for (; i + 8 <= n; i += 8) {
|
||||
const unsigned mk = (unsigned)_mm512_cmpeq_epi64_mask(_mm512_loadu_si512(v + i), xv);
|
||||
if (mk) return (int64_t)(i + (size_t)__builtin_ctz(mk));
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL == 3
|
||||
const __m256i xv = _mm256_set1_epi64x(x);
|
||||
for (; i + 4 <= n; i += 4) {
|
||||
const unsigned mk = (unsigned)_mm256_movemask_pd(_mm256_castsi256_pd(
|
||||
_mm256_cmpeq_epi64(_mm256_loadu_si256((const __m256i*)(v + i)), xv)));
|
||||
if (mk) return (int64_t)(i + (size_t)__builtin_ctz(mk));
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL == 2
|
||||
const __m128i xv = _mm_set1_epi64x(x);
|
||||
for (; i + 4 <= n; i += 4) {
|
||||
unsigned mk = (unsigned)_mm_movemask_pd(_mm_castsi128_pd(
|
||||
_mm_cmpeq_epi64(_mm_loadu_si128((const __m128i*)(v + i)), xv)));
|
||||
if (mk) return (int64_t)(i + (size_t)__builtin_ctz(mk));
|
||||
mk = (unsigned)_mm_movemask_pd(_mm_castsi128_pd(
|
||||
_mm_cmpeq_epi64(_mm_loadu_si128((const __m128i*)(v + i + 2)), xv)));
|
||||
if (mk) return (int64_t)(i + 2 + (size_t)__builtin_ctz(mk));
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL == 1
|
||||
const __m128i xv = _mm_set1_epi64x(x);
|
||||
for (; i + 2 <= n; i += 2) {
|
||||
const unsigned mk = (unsigned)_mm_movemask_pd(_mm_castsi128_pd(
|
||||
_mm_cmpeq_epi64(_mm_loadu_si128((const __m128i*)(v + i)), xv)));
|
||||
if (mk) return (int64_t)(i + (size_t)__builtin_ctz(mk));
|
||||
}
|
||||
#endif
|
||||
for (; i < n; ++i)
|
||||
if (v[i] == x) return (int64_t)i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- first_non_ascii */
|
||||
size_t RAD_SIMD_FN(first_non_ascii)(const char* p, size_t n) {
|
||||
size_t i = 0;
|
||||
#if RAD_SIMD_LEVEL == 4
|
||||
for (; i + 64 <= n; i += 64) {
|
||||
const __m512i v = _mm512_loadu_si512(p + i);
|
||||
/* Bytes >= 0x80 are negative as epi8 lanes: test against zero with the signed compare. */
|
||||
const uint64_t mk = (uint64_t)_mm512_cmplt_epi8_mask(v, _mm512_setzero_si512());
|
||||
if (mk) return i + (size_t)__builtin_ctzll(mk);
|
||||
}
|
||||
if (i < n) {
|
||||
const __mmask64 tail = (__mmask64)((1ull << (n - i)) - 1ull);
|
||||
const __m512i v = _mm512_maskz_loadu_epi8(tail, p + i);
|
||||
const uint64_t mk = (uint64_t)_mm512_mask_cmplt_epi8_mask(tail, v, _mm512_setzero_si512());
|
||||
if (mk) return i + (size_t)__builtin_ctzll(mk);
|
||||
return n;
|
||||
}
|
||||
return n;
|
||||
#elif RAD_SIMD_LEVEL == 3
|
||||
const __m256i hi = _mm256_set1_epi8((char)0x80);
|
||||
for (; i + 32 <= n; i += 32) {
|
||||
const __m256i v = _mm256_loadu_si256((const __m256i*)(p + i));
|
||||
const unsigned mk = (unsigned)_mm256_movemask_epi8(_mm256_and_si256(v, hi));
|
||||
if (mk) return i + (size_t)__builtin_ctz(mk);
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL == 2
|
||||
/* No 256-bit integer ops at this level: 128-bit halves, as in libavx. */
|
||||
const __m128i hi = _mm_set1_epi8((char)0x80);
|
||||
for (; i + 16 <= n; i += 16) {
|
||||
const unsigned mk = (unsigned)_mm_movemask_epi8(
|
||||
_mm_and_si128(_mm_loadu_si128((const __m128i*)(p + i)), hi));
|
||||
if (mk) return i + (size_t)__builtin_ctz(mk);
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL == 1
|
||||
const __m128i hi = _mm_set1_epi8((char)0x80);
|
||||
for (; i + 16 <= n; i += 16) {
|
||||
const unsigned mk = (unsigned)_mm_movemask_epi8(
|
||||
_mm_and_si128(_mm_loadu_si128((const __m128i*)(p + i)), hi));
|
||||
if (mk) return i + (size_t)__builtin_ctz(mk);
|
||||
}
|
||||
#endif
|
||||
for (; i < n; ++i)
|
||||
if ((unsigned char)p[i] >= 0x80) return i;
|
||||
return n;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- first_json_special */
|
||||
size_t RAD_SIMD_FN(first_json_special)(const char* p, size_t n) {
|
||||
size_t i = 0;
|
||||
/* Signed byte compare against 0x20 catches the controls and, being signed, every byte
|
||||
* >= 0x80 in the same mask; '"' and '\\' are equality compares OR'ed in. */
|
||||
#if RAD_SIMD_LEVEL == 4
|
||||
const __m512i sp = _mm512_set1_epi8(0x20), qu = _mm512_set1_epi8('"'),
|
||||
bs = _mm512_set1_epi8('\\');
|
||||
for (; i + 64 <= n; i += 64) {
|
||||
const __m512i v = _mm512_loadu_si512(p + i);
|
||||
const uint64_t mk = (uint64_t)(_mm512_cmplt_epi8_mask(v, sp) |
|
||||
_mm512_cmpeq_epi8_mask(v, qu) |
|
||||
_mm512_cmpeq_epi8_mask(v, bs));
|
||||
if (mk) return i + (size_t)__builtin_ctzll(mk);
|
||||
}
|
||||
if (i < n) {
|
||||
const __mmask64 tail = (__mmask64)((1ull << (n - i)) - 1ull);
|
||||
const __m512i v = _mm512_maskz_loadu_epi8(tail, p + i);
|
||||
const uint64_t mk = (uint64_t)(_mm512_mask_cmplt_epi8_mask(tail, v, sp) |
|
||||
_mm512_mask_cmpeq_epi8_mask(tail, v, qu) |
|
||||
_mm512_mask_cmpeq_epi8_mask(tail, v, bs));
|
||||
if (mk) return i + (size_t)__builtin_ctzll(mk);
|
||||
return n;
|
||||
}
|
||||
return n;
|
||||
#elif RAD_SIMD_LEVEL == 3
|
||||
const __m256i sp = _mm256_set1_epi8(0x20), qu = _mm256_set1_epi8('"'),
|
||||
bs = _mm256_set1_epi8('\\');
|
||||
for (; i + 32 <= n; i += 32) {
|
||||
const __m256i v = _mm256_loadu_si256((const __m256i*)(p + i));
|
||||
const __m256i m = _mm256_or_si256(_mm256_cmpgt_epi8(sp, v),
|
||||
_mm256_or_si256(_mm256_cmpeq_epi8(v, qu),
|
||||
_mm256_cmpeq_epi8(v, bs)));
|
||||
const unsigned mk = (unsigned)_mm256_movemask_epi8(m);
|
||||
if (mk) return i + (size_t)__builtin_ctz(mk);
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL == 2 || RAD_SIMD_LEVEL == 1
|
||||
const __m128i sp = _mm_set1_epi8(0x20), qu = _mm_set1_epi8('"'), bs = _mm_set1_epi8('\\');
|
||||
for (; i + 16 <= n; i += 16) {
|
||||
const __m128i v = _mm_loadu_si128((const __m128i*)(p + i));
|
||||
const __m128i m = _mm_or_si128(_mm_cmplt_epi8(v, sp),
|
||||
_mm_or_si128(_mm_cmpeq_epi8(v, qu), _mm_cmpeq_epi8(v, bs)));
|
||||
const unsigned mk = (unsigned)_mm_movemask_epi8(m);
|
||||
if (mk) return i + (size_t)__builtin_ctz(mk);
|
||||
}
|
||||
#endif
|
||||
for (; i < n; ++i) {
|
||||
const unsigned char c = (unsigned char)p[i];
|
||||
if (c < 0x20 || c == '"' || c == '\\' || c >= 0x80) return i;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- bitstream_shr */
|
||||
void RAD_SIMD_FN(bitstream_shr)(uint32_t* dst, const uint32_t* src, size_t n_words, unsigned sh) {
|
||||
if (n_words == 0) return;
|
||||
size_t i = 0;
|
||||
const unsigned lsh = 32 - sh;
|
||||
#if RAD_SIMD_LEVEL == 4
|
||||
/* Variable per-lane shift with a broadcast count; the (i+1) load goes one word past, which
|
||||
* the masked final store below keeps inside the caller's buffer: the main loop stops with
|
||||
* at least 16 words left, so src[i+16] is in bounds whenever it loads. */
|
||||
const __m512i cs = _mm512_set1_epi32((int)sh), cl = _mm512_set1_epi32((int)lsh);
|
||||
for (; i + 17 <= n_words; i += 16) {
|
||||
const __m512i a = _mm512_srlv_epi32(_mm512_loadu_si512(src + i), cs);
|
||||
const __m512i b = _mm512_sllv_epi32(_mm512_loadu_si512(src + i + 1), cl);
|
||||
_mm512_storeu_si512(dst + i, _mm512_or_si512(a, b));
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL == 3
|
||||
const __m256i cs = _mm256_set1_epi32((int)sh), cl = _mm256_set1_epi32((int)lsh);
|
||||
for (; i + 9 <= n_words; i += 8) {
|
||||
const __m256i a = _mm256_srlv_epi32(_mm256_loadu_si256((const __m256i*)(src + i)), cs);
|
||||
const __m256i b = _mm256_sllv_epi32(_mm256_loadu_si256((const __m256i*)(src + i + 1)), cl);
|
||||
_mm256_storeu_si256((__m256i*)(dst + i), _mm256_or_si256(a, b));
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL == 2 || RAD_SIMD_LEVEL == 1
|
||||
/* Shifts by a runtime count use the xmm count form; four words a step. The loop stops with
|
||||
* at least four words left, so src[i+4] is in bounds. */
|
||||
const __m128i cs = _mm_set_epi64x(0, (int64_t)sh), cl = _mm_set_epi64x(0, (int64_t)lsh);
|
||||
for (; i + 5 <= n_words; i += 4) {
|
||||
const __m128i a = _mm_srl_epi32(_mm_loadu_si128((const __m128i*)(src + i)), cs);
|
||||
const __m128i b = _mm_sll_epi32(_mm_loadu_si128((const __m128i*)(src + i + 1)), cl);
|
||||
_mm_storeu_si128((__m128i*)(dst + i), _mm_or_si128(a, b));
|
||||
}
|
||||
#endif
|
||||
for (; i < n_words; ++i) {
|
||||
const uint32_t hi = i + 1 < n_words ? src[i + 1] : 0u;
|
||||
dst[i] = (src[i] >> sh) | (hi << lsh);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- bitmap_marks */
|
||||
void RAD_SIMD_FN(bitmap_marks)(uint8_t* dst, const int32_t* ids, size_t n, const uint32_t* bits,
|
||||
size_t n_words) {
|
||||
/* A gather of the containing word, a variable shift and a mask: exact, with out-of-range ids
|
||||
* clamped to a zero word by index arithmetic rather than a branch per element. The clamp is
|
||||
* done in the scalar tail's arithmetic and, on the vector levels, by giving the gather a
|
||||
* zeroed guard word past the bitmap: indices land at n_words (the caller guarantees bits has
|
||||
* one readable word there? No -- it does not, so the vector levels clamp the index into
|
||||
* [0, n_words) and clear the result where the id was out of range). */
|
||||
if (n_words == 0) {
|
||||
for (size_t i = 0; i < n; ++i) dst[i] = 0;
|
||||
return;
|
||||
}
|
||||
size_t i = 0;
|
||||
/* A bitmap wider than int32 ids can name: the vector levels' range arithmetic is in int32,
|
||||
* so take the scalar loop (a >256 MiB bitmap; never a vocabulary mask). */
|
||||
[[maybe_unused]] const bool huge = (uint64_t)n_words * 32u > (uint64_t)INT32_MAX;
|
||||
[[maybe_unused]] const int32_t lim = huge ? 0 : (int32_t)n_words;
|
||||
#if RAD_SIMD_LEVEL == 4
|
||||
const __m512i top = _mm512_set1_epi32(lim - 1);
|
||||
for (; !huge && i + 16 <= n; i += 16) {
|
||||
const __m512i id = _mm512_loadu_si512(ids + i);
|
||||
const __m512i w = _mm512_min_epi32(_mm512_max_epi32(_mm512_srai_epi32(id, 5),
|
||||
_mm512_setzero_si512()), top);
|
||||
const __m512i g = _mm512_i32gather_epi32(w, bits, 4);
|
||||
const __m512i s = _mm512_and_si512(_mm512_srlv_epi32(g, _mm512_and_si512(id, _mm512_set1_epi32(31))), _mm512_set1_epi32(1));
|
||||
const __mmask16 in = _kand_mask16(_mm512_cmpge_epi32_mask(id, _mm512_setzero_si512()),
|
||||
_mm512_cmplt_epi32_mask(id, _mm512_set1_epi32(lim * 32)));
|
||||
_mm_storeu_si128((__m128i*)(dst + i),
|
||||
_mm512_cvtepi32_epi8(_mm512_maskz_mov_epi32(in, s)));
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL == 3
|
||||
const __m256i top = _mm256_set1_epi32(lim - 1);
|
||||
const __m256i nbits = _mm256_set1_epi32(lim * 32);
|
||||
for (; !huge && i + 8 <= n; i += 8) {
|
||||
const __m256i id = _mm256_loadu_si256((const __m256i*)(ids + i));
|
||||
const __m256i w = _mm256_min_epi32(_mm256_max_epi32(_mm256_srai_epi32(id, 5),
|
||||
_mm256_setzero_si256()), top);
|
||||
const __m256i g = _mm256_i32gather_epi32((const int*)bits, w, 4);
|
||||
__m256i s = _mm256_and_si256(_mm256_srlv_epi32(g, _mm256_and_si256(id, _mm256_set1_epi32(31))), _mm256_set1_epi32(1));
|
||||
const __m256i in = _mm256_and_si256(
|
||||
_mm256_cmpgt_epi32(id, _mm256_set1_epi32(-1)),
|
||||
_mm256_cmpgt_epi32(nbits, id));
|
||||
s = _mm256_and_si256(s, in);
|
||||
__m128i pk = _mm_packus_epi32(_mm256_castsi256_si128(s), _mm256_extracti128_si256(s, 1));
|
||||
pk = _mm_packus_epi16(pk, pk);
|
||||
_mm_storel_epi64((__m128i*)(dst + i), pk);
|
||||
}
|
||||
#endif
|
||||
for (; i < n; ++i) {
|
||||
const int32_t id = ids[i];
|
||||
dst[i] = id >= 0 && (size_t)(id >> 5) < n_words
|
||||
? (uint8_t)((bits[(size_t)(id >> 5)] >> (uint32_t)(id & 31)) & 1u)
|
||||
: (uint8_t)0;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- or3_u8 */
|
||||
void RAD_SIMD_FN(or3_u8)(uint8_t* dst, const uint8_t* a, const uint8_t* b, const uint8_t* c,
|
||||
size_t n) {
|
||||
size_t i = 0;
|
||||
#if RAD_SIMD_LEVEL == 4
|
||||
for (; i + 64 <= n; i += 64) {
|
||||
const __m512i v = _mm512_or_si512(_mm512_or_si512(_mm512_loadu_si512(a + i),
|
||||
_mm512_loadu_si512(b + i)),
|
||||
_mm512_loadu_si512(c + i));
|
||||
_mm512_storeu_si512(dst + i, v);
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL == 3
|
||||
for (; i + 32 <= n; i += 32) {
|
||||
const __m256i v = _mm256_or_si256(
|
||||
_mm256_or_si256(_mm256_loadu_si256((const __m256i*)(a + i)),
|
||||
_mm256_loadu_si256((const __m256i*)(b + i))),
|
||||
_mm256_loadu_si256((const __m256i*)(c + i)));
|
||||
_mm256_storeu_si256((__m256i*)(dst + i), v);
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL == 2
|
||||
/* AVX has 256-bit bitwise ops only on the float types; an OR of their bits is exact. */
|
||||
for (; i + 32 <= n; i += 32) {
|
||||
const __m256 v = _mm256_or_ps(_mm256_or_ps(_mm256_loadu_ps((const float*)(a + i)),
|
||||
_mm256_loadu_ps((const float*)(b + i))),
|
||||
_mm256_loadu_ps((const float*)(c + i)));
|
||||
_mm256_storeu_ps((float*)(dst + i), v);
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL == 1
|
||||
for (; i + 16 <= n; i += 16) {
|
||||
const __m128i v = _mm_or_si128(_mm_or_si128(_mm_loadu_si128((const __m128i*)(a + i)),
|
||||
_mm_loadu_si128((const __m128i*)(b + i))),
|
||||
_mm_loadu_si128((const __m128i*)(c + i)));
|
||||
_mm_storeu_si128((__m128i*)(dst + i), v);
|
||||
}
|
||||
#endif
|
||||
for (; i < n; ++i) dst[i] = (uint8_t)(a[i] | b[i] | c[i]);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- or_adjacent_u8 */
|
||||
void RAD_SIMD_FN(or_adjacent_u8)(uint8_t* dst, const uint8_t* s, size_t n) {
|
||||
if (n == 0) return;
|
||||
if (n == 1) { dst[0] = s[0]; return; }
|
||||
dst[0] = (uint8_t)(s[0] | s[1]);
|
||||
/* The interior: three overlapping unaligned loads a vector, at i - 1, i and i + 1. */
|
||||
size_t i = 1;
|
||||
const size_t end = n - 1;
|
||||
#if RAD_SIMD_LEVEL == 4
|
||||
for (; i + 64 <= end; i += 64) {
|
||||
const __m512i v = _mm512_or_si512(_mm512_or_si512(_mm512_loadu_si512(s + i - 1),
|
||||
_mm512_loadu_si512(s + i)),
|
||||
_mm512_loadu_si512(s + i + 1));
|
||||
_mm512_storeu_si512(dst + i, v);
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL == 3
|
||||
for (; i + 32 <= end; i += 32) {
|
||||
const __m256i v = _mm256_or_si256(
|
||||
_mm256_or_si256(_mm256_loadu_si256((const __m256i*)(s + i - 1)),
|
||||
_mm256_loadu_si256((const __m256i*)(s + i))),
|
||||
_mm256_loadu_si256((const __m256i*)(s + i + 1)));
|
||||
_mm256_storeu_si256((__m256i*)(dst + i), v);
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL == 2
|
||||
for (; i + 32 <= end; i += 32) {
|
||||
const __m256 v = _mm256_or_ps(_mm256_or_ps(_mm256_loadu_ps((const float*)(s + i - 1)),
|
||||
_mm256_loadu_ps((const float*)(s + i))),
|
||||
_mm256_loadu_ps((const float*)(s + i + 1)));
|
||||
_mm256_storeu_ps((float*)(dst + i), v);
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL == 1
|
||||
for (; i + 16 <= end; i += 16) {
|
||||
const __m128i v = _mm_or_si128(_mm_or_si128(_mm_loadu_si128((const __m128i*)(s + i - 1)),
|
||||
_mm_loadu_si128((const __m128i*)(s + i))),
|
||||
_mm_loadu_si128((const __m128i*)(s + i + 1)));
|
||||
_mm_storeu_si128((__m128i*)(dst + i), v);
|
||||
}
|
||||
#endif
|
||||
for (; i < end; ++i) dst[i] = (uint8_t)(s[i - 1] | s[i] | s[i + 1]);
|
||||
dst[n - 1] = (uint8_t)(s[n - 2] | s[n - 1]);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- madd_i32_i64 */
|
||||
void RAD_SIMD_FN(madd_i32_i64)(int64_t* acc, const int32_t* h, int32_t c, size_t n) {
|
||||
size_t i = 0;
|
||||
/* Each int32 widened to a 64-bit lane, then pmuldq: the signed product of the lanes' low
|
||||
* halves, exact in 64 bits. */
|
||||
#if RAD_SIMD_LEVEL == 4
|
||||
const __m512i k = _mm512_set1_epi64(c);
|
||||
for (; i + 8 <= n; i += 8) {
|
||||
const __m512i x = _mm512_cvtepi32_epi64(_mm256_loadu_si256((const __m256i*)(h + i)));
|
||||
_mm512_storeu_si512(acc + i, _mm512_add_epi64(_mm512_loadu_si512(acc + i),
|
||||
_mm512_mul_epi32(x, k)));
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL == 3
|
||||
const __m256i k = _mm256_set1_epi64x(c);
|
||||
for (; i + 4 <= n; i += 4) {
|
||||
const __m256i x = _mm256_cvtepi32_epi64(_mm_loadu_si128((const __m128i*)(h + i)));
|
||||
_mm256_storeu_si256((__m256i*)(acc + i),
|
||||
_mm256_add_epi64(_mm256_loadu_si256((const __m256i*)(acc + i)),
|
||||
_mm256_mul_epi32(x, k)));
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL == 2 || RAD_SIMD_LEVEL == 1
|
||||
/* No 256-bit integer below AVX2: SSE4.1's pmovsxdq and pmuldq, two lanes a step. */
|
||||
const __m128i k = _mm_set1_epi64x(c);
|
||||
for (; i + 4 <= n; i += 4) {
|
||||
const __m128i x = _mm_loadu_si128((const __m128i*)(h + i));
|
||||
const __m128i lo = _mm_cvtepi32_epi64(x), hi = _mm_cvtepi32_epi64(_mm_srli_si128(x, 8));
|
||||
_mm_storeu_si128((__m128i*)(acc + i),
|
||||
_mm_add_epi64(_mm_loadu_si128((const __m128i*)(acc + i)), _mm_mul_epi32(lo, k)));
|
||||
_mm_storeu_si128((__m128i*)(acc + i + 2),
|
||||
_mm_add_epi64(_mm_loadu_si128((const __m128i*)(acc + i + 2)), _mm_mul_epi32(hi, k)));
|
||||
}
|
||||
#endif
|
||||
for (; i < n; ++i) acc[i] += (int64_t)h[i] * c;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- base64
|
||||
*
|
||||
* Encode: each 3-byte group spread over one 32-bit lane as [b1 b0 b2 b1] (pshufb), its four
|
||||
* 6-bit fields moved to the low bits of four bytes with a 16-bit multiply-high and multiply-low,
|
||||
* then each field's digit as field + offset, the offset from four compares: +65 (A-Z), +6 more
|
||||
* past 25 (a-z), -75 past 51 (0-9), -15 past 61 ('+'), +3 past 62 ('/').
|
||||
*
|
||||
* Decode: a block is taken only if every byte is in A-Z, a-z, 0-9, '+' or '/', checked with
|
||||
* signed range compares (a byte >= 0x80 is negative and in no range); each digit's value is the
|
||||
* byte plus its range's offset; pmaddubsw and pmaddwd fold four 6-bit values into 24 bits a
|
||||
* lane, and pshufb packs the lanes' three bytes. */
|
||||
#if RAD_SIMD_LEVEL >= 1
|
||||
namespace {
|
||||
|
||||
inline __m128i b64_fields_128(__m128i in) {
|
||||
const __m128i spread = _mm_shuffle_epi8(in, _mm_setr_epi8(1, 0, 2, 1, 4, 3, 5, 4, 7, 6, 8, 7,
|
||||
10, 9, 11, 10));
|
||||
const __m128i t0 = _mm_and_si128(spread, _mm_set1_epi32(0x0fc0fc00));
|
||||
const __m128i t1 = _mm_mulhi_epu16(t0, _mm_set1_epi32(0x04000040));
|
||||
const __m128i t2 = _mm_and_si128(spread, _mm_set1_epi32(0x003f03f0));
|
||||
const __m128i t3 = _mm_mullo_epi16(t2, _mm_set1_epi32(0x01000010));
|
||||
return _mm_or_si128(t1, t3);
|
||||
}
|
||||
inline __m128i b64_digits_128(__m128i f) {
|
||||
__m128i off = _mm_set1_epi8(65);
|
||||
off = _mm_add_epi8(off, _mm_and_si128(_mm_cmpgt_epi8(f, _mm_set1_epi8(25)), _mm_set1_epi8(6)));
|
||||
off = _mm_add_epi8(off, _mm_and_si128(_mm_cmpgt_epi8(f, _mm_set1_epi8(51)), _mm_set1_epi8(-75)));
|
||||
off = _mm_add_epi8(off, _mm_and_si128(_mm_cmpgt_epi8(f, _mm_set1_epi8(61)), _mm_set1_epi8(-15)));
|
||||
off = _mm_add_epi8(off, _mm_and_si128(_mm_cmpgt_epi8(f, _mm_set1_epi8(62)), _mm_set1_epi8(3)));
|
||||
return _mm_add_epi8(f, off);
|
||||
}
|
||||
/* c in [lo, hi] as a signed byte compare; lo >= 1, so a byte >= 0x80 is never in it. */
|
||||
inline __m128i in_range_128(__m128i c, char lo, char hi) {
|
||||
return _mm_and_si128(_mm_cmpgt_epi8(c, _mm_set1_epi8((char)(lo - 1))),
|
||||
_mm_cmpgt_epi8(_mm_set1_epi8((char)(hi + 1)), c));
|
||||
}
|
||||
/* The block's 6-bit values, or false when any byte is not a digit. */
|
||||
inline bool b64_values_128(__m128i c, __m128i* v) {
|
||||
const __m128i up = in_range_128(c, 'A', 'Z'), lo = in_range_128(c, 'a', 'z'),
|
||||
dg = in_range_128(c, '0', '9'), pl = _mm_cmpeq_epi8(c, _mm_set1_epi8('+')),
|
||||
sl = _mm_cmpeq_epi8(c, _mm_set1_epi8('/'));
|
||||
const __m128i ok = _mm_or_si128(_mm_or_si128(_mm_or_si128(up, lo), _mm_or_si128(dg, pl)), sl);
|
||||
if (_mm_movemask_epi8(ok) != 0xffff) return false;
|
||||
__m128i off = _mm_and_si128(up, _mm_set1_epi8(-65));
|
||||
off = _mm_or_si128(off, _mm_and_si128(lo, _mm_set1_epi8(-71)));
|
||||
off = _mm_or_si128(off, _mm_and_si128(dg, _mm_set1_epi8(4)));
|
||||
off = _mm_or_si128(off, _mm_and_si128(pl, _mm_set1_epi8(19)));
|
||||
off = _mm_or_si128(off, _mm_and_si128(sl, _mm_set1_epi8(16)));
|
||||
*v = _mm_add_epi8(c, off);
|
||||
return true;
|
||||
}
|
||||
/* Sixteen 6-bit values to twelve bytes in the lane's first twelve. */
|
||||
inline __m128i b64_pack_128(__m128i v) {
|
||||
const __m128i ab = _mm_maddubs_epi16(v, _mm_set1_epi32(0x01400140));
|
||||
const __m128i abc = _mm_madd_epi16(ab, _mm_set1_epi32(0x00011000));
|
||||
return _mm_shuffle_epi8(abc, _mm_setr_epi8(2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, -1, -1, -1, -1));
|
||||
}
|
||||
|
||||
#if RAD_SIMD_LEVEL >= 3
|
||||
inline __m256i in_range_256(__m256i c, char lo, char hi) {
|
||||
return _mm256_and_si256(_mm256_cmpgt_epi8(c, _mm256_set1_epi8((char)(lo - 1))),
|
||||
_mm256_cmpgt_epi8(_mm256_set1_epi8((char)(hi + 1)), c));
|
||||
}
|
||||
#endif
|
||||
|
||||
} /* namespace */
|
||||
#endif
|
||||
|
||||
size_t RAD_SIMD_FN(b64_encode_run)(const uint8_t* in, size_t n, char* out) {
|
||||
size_t i = 0, o = 0;
|
||||
#if RAD_SIMD_LEVEL == 4
|
||||
/* Four 12-byte groups a register, one a 128-bit lane; the last lane loads 16 bytes from 36. */
|
||||
for (; i + 52 <= n; i += 48, o += 64) {
|
||||
__m512i x = _mm512_castsi128_si512(_mm_loadu_si128((const __m128i*)(in + i)));
|
||||
x = _mm512_inserti32x4(x, _mm_loadu_si128((const __m128i*)(in + i + 12)), 1);
|
||||
x = _mm512_inserti32x4(x, _mm_loadu_si128((const __m128i*)(in + i + 24)), 2);
|
||||
x = _mm512_inserti32x4(x, _mm_loadu_si128((const __m128i*)(in + i + 36)), 3);
|
||||
const __m512i sp = _mm512_shuffle_epi8(x, _mm512_broadcast_i32x4(_mm_setr_epi8(
|
||||
1, 0, 2, 1, 4, 3, 5, 4, 7, 6, 8, 7, 10, 9, 11, 10)));
|
||||
const __m512i t1 = _mm512_mulhi_epu16(_mm512_and_si512(sp, _mm512_set1_epi32(0x0fc0fc00)),
|
||||
_mm512_set1_epi32(0x04000040));
|
||||
const __m512i t3 = _mm512_mullo_epi16(_mm512_and_si512(sp, _mm512_set1_epi32(0x003f03f0)),
|
||||
_mm512_set1_epi32(0x01000010));
|
||||
const __m512i f = _mm512_or_si512(t1, t3);
|
||||
__m512i off = _mm512_set1_epi8(65);
|
||||
off = _mm512_mask_add_epi8(off, _mm512_cmpgt_epi8_mask(f, _mm512_set1_epi8(25)), off, _mm512_set1_epi8(6));
|
||||
off = _mm512_mask_add_epi8(off, _mm512_cmpgt_epi8_mask(f, _mm512_set1_epi8(51)), off, _mm512_set1_epi8(-75));
|
||||
off = _mm512_mask_add_epi8(off, _mm512_cmpgt_epi8_mask(f, _mm512_set1_epi8(61)), off, _mm512_set1_epi8(-15));
|
||||
off = _mm512_mask_add_epi8(off, _mm512_cmpgt_epi8_mask(f, _mm512_set1_epi8(62)), off, _mm512_set1_epi8(3));
|
||||
_mm512_storeu_si512(out + o, _mm512_add_epi8(f, off));
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL == 3
|
||||
/* Two 12-byte groups a register, one a lane; the high lane loads 16 bytes from 12. */
|
||||
for (; i + 28 <= n; i += 24, o += 32) {
|
||||
__m256i x = _mm256_castsi128_si256(_mm_loadu_si128((const __m128i*)(in + i)));
|
||||
x = _mm256_inserti128_si256(x, _mm_loadu_si128((const __m128i*)(in + i + 12)), 1);
|
||||
const __m256i sp = _mm256_shuffle_epi8(x, _mm256_setr_epi8(
|
||||
1, 0, 2, 1, 4, 3, 5, 4, 7, 6, 8, 7, 10, 9, 11, 10,
|
||||
1, 0, 2, 1, 4, 3, 5, 4, 7, 6, 8, 7, 10, 9, 11, 10));
|
||||
const __m256i t1 = _mm256_mulhi_epu16(_mm256_and_si256(sp, _mm256_set1_epi32(0x0fc0fc00)),
|
||||
_mm256_set1_epi32(0x04000040));
|
||||
const __m256i t3 = _mm256_mullo_epi16(_mm256_and_si256(sp, _mm256_set1_epi32(0x003f03f0)),
|
||||
_mm256_set1_epi32(0x01000010));
|
||||
const __m256i f = _mm256_or_si256(t1, t3);
|
||||
__m256i off = _mm256_set1_epi8(65);
|
||||
off = _mm256_add_epi8(off, _mm256_and_si256(_mm256_cmpgt_epi8(f, _mm256_set1_epi8(25)), _mm256_set1_epi8(6)));
|
||||
off = _mm256_add_epi8(off, _mm256_and_si256(_mm256_cmpgt_epi8(f, _mm256_set1_epi8(51)), _mm256_set1_epi8(-75)));
|
||||
off = _mm256_add_epi8(off, _mm256_and_si256(_mm256_cmpgt_epi8(f, _mm256_set1_epi8(61)), _mm256_set1_epi8(-15)));
|
||||
off = _mm256_add_epi8(off, _mm256_and_si256(_mm256_cmpgt_epi8(f, _mm256_set1_epi8(62)), _mm256_set1_epi8(3)));
|
||||
_mm256_storeu_si256((__m256i*)(out + o), _mm256_add_epi8(f, off));
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL >= 1
|
||||
for (; i + 16 <= n; i += 12, o += 16)
|
||||
_mm_storeu_si128((__m128i*)(out + o),
|
||||
b64_digits_128(b64_fields_128(_mm_loadu_si128((const __m128i*)(in + i)))));
|
||||
#endif
|
||||
(void)in; (void)n; (void)out; (void)o;
|
||||
return i;
|
||||
}
|
||||
|
||||
size_t RAD_SIMD_FN(b64_decode_run)(const uint8_t* in, size_t n, uint8_t* out) {
|
||||
size_t i = 0;
|
||||
#if RAD_SIMD_LEVEL >= 1
|
||||
size_t o = 0;
|
||||
alignas(64) uint8_t tmp[64];
|
||||
#if RAD_SIMD_LEVEL == 4
|
||||
for (; i + 64 <= n; i += 64, o += 48) {
|
||||
const __m512i c = _mm512_loadu_si512(in + i);
|
||||
auto rng = [&](char lo, char hi) {
|
||||
return _kand_mask64(_mm512_cmpgt_epi8_mask(c, _mm512_set1_epi8((char)(lo - 1))),
|
||||
_mm512_cmpgt_epi8_mask(_mm512_set1_epi8((char)(hi + 1)), c));
|
||||
};
|
||||
const __mmask64 up = rng('A', 'Z'), lo = rng('a', 'z'), dg = rng('0', '9'),
|
||||
pl = _mm512_cmpeq_epi8_mask(c, _mm512_set1_epi8('+')),
|
||||
sl = _mm512_cmpeq_epi8_mask(c, _mm512_set1_epi8('/'));
|
||||
if ((up | lo | dg | pl | sl) != ~(__mmask64)0) break;
|
||||
__m512i off = _mm512_maskz_mov_epi8(up, _mm512_set1_epi8(-65));
|
||||
off = _mm512_mask_mov_epi8(off, lo, _mm512_set1_epi8(-71));
|
||||
off = _mm512_mask_mov_epi8(off, dg, _mm512_set1_epi8(4));
|
||||
off = _mm512_mask_mov_epi8(off, pl, _mm512_set1_epi8(19));
|
||||
off = _mm512_mask_mov_epi8(off, sl, _mm512_set1_epi8(16));
|
||||
const __m512i v = _mm512_add_epi8(c, off);
|
||||
const __m512i ab = _mm512_maddubs_epi16(v, _mm512_set1_epi32(0x01400140));
|
||||
const __m512i abc = _mm512_madd_epi16(ab, _mm512_set1_epi32(0x00011000));
|
||||
const __m512i pk = _mm512_shuffle_epi8(abc, _mm512_broadcast_i32x4(_mm_setr_epi8(
|
||||
2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, -1, -1, -1, -1)));
|
||||
_mm512_store_si512(tmp, pk);
|
||||
for (int l = 0; l < 4; ++l) std::memcpy(out + o + 12 * l, tmp + 16 * l, 12);
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL == 3
|
||||
for (; i + 32 <= n; i += 32, o += 24) {
|
||||
const __m256i c = _mm256_loadu_si256((const __m256i*)(in + i));
|
||||
const __m256i up = in_range_256(c, 'A', 'Z'), lo = in_range_256(c, 'a', 'z'),
|
||||
dg = in_range_256(c, '0', '9'),
|
||||
pl = _mm256_cmpeq_epi8(c, _mm256_set1_epi8('+')),
|
||||
sl = _mm256_cmpeq_epi8(c, _mm256_set1_epi8('/'));
|
||||
const __m256i ok = _mm256_or_si256(_mm256_or_si256(_mm256_or_si256(up, lo),
|
||||
_mm256_or_si256(dg, pl)), sl);
|
||||
if ((uint32_t)_mm256_movemask_epi8(ok) != 0xffffffffu) break;
|
||||
__m256i off = _mm256_and_si256(up, _mm256_set1_epi8(-65));
|
||||
off = _mm256_or_si256(off, _mm256_and_si256(lo, _mm256_set1_epi8(-71)));
|
||||
off = _mm256_or_si256(off, _mm256_and_si256(dg, _mm256_set1_epi8(4)));
|
||||
off = _mm256_or_si256(off, _mm256_and_si256(pl, _mm256_set1_epi8(19)));
|
||||
off = _mm256_or_si256(off, _mm256_and_si256(sl, _mm256_set1_epi8(16)));
|
||||
const __m256i v = _mm256_add_epi8(c, off);
|
||||
const __m256i ab = _mm256_maddubs_epi16(v, _mm256_set1_epi32(0x01400140));
|
||||
const __m256i abc = _mm256_madd_epi16(ab, _mm256_set1_epi32(0x00011000));
|
||||
const __m256i pk = _mm256_shuffle_epi8(abc, _mm256_setr_epi8(
|
||||
2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, -1, -1, -1, -1,
|
||||
2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, -1, -1, -1, -1));
|
||||
_mm256_store_si256((__m256i*)tmp, pk);
|
||||
std::memcpy(out + o, tmp, 12);
|
||||
std::memcpy(out + o + 12, tmp + 16, 12);
|
||||
}
|
||||
#else
|
||||
for (; i + 16 <= n; i += 16, o += 12) {
|
||||
__m128i v;
|
||||
if (!b64_values_128(_mm_loadu_si128((const __m128i*)(in + i)), &v)) break;
|
||||
_mm_store_si128((__m128i*)tmp, b64_pack_128(v));
|
||||
std::memcpy(out + o, tmp, 12);
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
(void)in; (void)n; (void)out;
|
||||
return i;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- stripe_acc_u64x8 */
|
||||
namespace {
|
||||
/* 24 key words from splitmix64 over a fixed seed: words 0..22 are the stripes' sliding keys (16
|
||||
* stripes, eight lanes), 16..23 the scramble's. */
|
||||
constexpr uint64_t stripe_key_word(int i) {
|
||||
uint64_t z = 0x5241444943414e45ull + 0x9e3779b97f4a7c15ull * (uint64_t)(i + 1);
|
||||
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull;
|
||||
z = (z ^ (z >> 27)) * 0x94d049bb133111ebull;
|
||||
return z ^ (z >> 31);
|
||||
}
|
||||
struct StripeKeys {
|
||||
uint64_t w[24];
|
||||
constexpr StripeKeys() : w() { for (int i = 0; i < 24; ++i) w[i] = stripe_key_word(i); }
|
||||
};
|
||||
constexpr StripeKeys kStripeKeys{};
|
||||
constexpr uint64_t kStripePrime = 0x9E3779B1ull;
|
||||
constexpr size_t kStripesBlock = 16;
|
||||
} /* namespace */
|
||||
|
||||
void RAD_SIMD_FN(stripe_acc_u64x8)(uint64_t acc[8], const uint8_t* p, size_t stripes) {
|
||||
const uint64_t* K = kStripeKeys.w;
|
||||
#if RAD_SIMD_LEVEL == 4
|
||||
__m512i a = _mm512_loadu_si512(acc);
|
||||
const __m512i prime = _mm512_set1_epi64((long long)kStripePrime);
|
||||
for (size_t s = 0; s < stripes; ++s) {
|
||||
const size_t r = s % kStripesBlock;
|
||||
const __m512i d = _mm512_loadu_si512(p + 64 * s);
|
||||
const __m512i k = _mm512_xor_si512(d, _mm512_loadu_si512(K + r));
|
||||
a = _mm512_add_epi64(a, _mm512_mul_epu32(k, _mm512_srli_epi64(k, 32)));
|
||||
a = _mm512_add_epi64(a, _mm512_shuffle_epi32(d, (_MM_PERM_ENUM)0x4E));
|
||||
if (r == kStripesBlock - 1) {
|
||||
a = _mm512_xor_si512(_mm512_xor_si512(a, _mm512_srli_epi64(a, 47)), _mm512_loadu_si512(K + 16));
|
||||
a = _mm512_add_epi64(_mm512_mul_epu32(a, prime),
|
||||
_mm512_slli_epi64(_mm512_mul_epu32(_mm512_srli_epi64(a, 32), prime), 32));
|
||||
}
|
||||
}
|
||||
_mm512_storeu_si512(acc, a);
|
||||
#elif RAD_SIMD_LEVEL == 3
|
||||
__m256i a0 = _mm256_loadu_si256((const __m256i*)acc), a1 = _mm256_loadu_si256((const __m256i*)(acc + 4));
|
||||
const __m256i prime = _mm256_set1_epi64x((long long)kStripePrime);
|
||||
auto step = [](__m256i a, __m256i d, __m256i key) {
|
||||
const __m256i k = _mm256_xor_si256(d, key);
|
||||
a = _mm256_add_epi64(a, _mm256_mul_epu32(k, _mm256_srli_epi64(k, 32)));
|
||||
return _mm256_add_epi64(a, _mm256_shuffle_epi32(d, 0x4E));
|
||||
};
|
||||
auto scramble = [&](__m256i a, __m256i key) {
|
||||
a = _mm256_xor_si256(_mm256_xor_si256(a, _mm256_srli_epi64(a, 47)), key);
|
||||
return _mm256_add_epi64(_mm256_mul_epu32(a, prime),
|
||||
_mm256_slli_epi64(_mm256_mul_epu32(_mm256_srli_epi64(a, 32), prime), 32));
|
||||
};
|
||||
for (size_t s = 0; s < stripes; ++s) {
|
||||
const size_t r = s % kStripesBlock;
|
||||
a0 = step(a0, _mm256_loadu_si256((const __m256i*)(p + 64 * s)), _mm256_loadu_si256((const __m256i*)(K + r)));
|
||||
a1 = step(a1, _mm256_loadu_si256((const __m256i*)(p + 64 * s + 32)), _mm256_loadu_si256((const __m256i*)(K + r + 4)));
|
||||
if (r == kStripesBlock - 1) {
|
||||
a0 = scramble(a0, _mm256_loadu_si256((const __m256i*)(K + 16)));
|
||||
a1 = scramble(a1, _mm256_loadu_si256((const __m256i*)(K + 20)));
|
||||
}
|
||||
}
|
||||
_mm256_storeu_si256((__m256i*)acc, a0);
|
||||
_mm256_storeu_si256((__m256i*)(acc + 4), a1);
|
||||
#elif RAD_SIMD_LEVEL >= 1
|
||||
/* Two lanes a register (no 256-bit integer below AVX2); pmuludq is SSE2. */
|
||||
__m128i a[4];
|
||||
for (int q = 0; q < 4; ++q) a[q] = _mm_loadu_si128((const __m128i*)(acc + 2 * q));
|
||||
const __m128i prime = _mm_set1_epi64x((long long)kStripePrime);
|
||||
for (size_t s = 0; s < stripes; ++s) {
|
||||
const size_t r = s % kStripesBlock;
|
||||
for (int q = 0; q < 4; ++q) {
|
||||
const __m128i d = _mm_loadu_si128((const __m128i*)(p + 64 * s + 16 * q));
|
||||
const __m128i k = _mm_xor_si128(d, _mm_loadu_si128((const __m128i*)(K + r + 2 * q)));
|
||||
a[q] = _mm_add_epi64(a[q], _mm_mul_epu32(k, _mm_srli_epi64(k, 32)));
|
||||
a[q] = _mm_add_epi64(a[q], _mm_shuffle_epi32(d, 0x4E));
|
||||
}
|
||||
if (r == kStripesBlock - 1)
|
||||
for (int q = 0; q < 4; ++q) {
|
||||
__m128i x = _mm_xor_si128(_mm_xor_si128(a[q], _mm_srli_epi64(a[q], 47)),
|
||||
_mm_loadu_si128((const __m128i*)(K + 16 + 2 * q)));
|
||||
a[q] = _mm_add_epi64(_mm_mul_epu32(x, prime),
|
||||
_mm_slli_epi64(_mm_mul_epu32(_mm_srli_epi64(x, 32), prime), 32));
|
||||
}
|
||||
}
|
||||
for (int q = 0; q < 4; ++q) _mm_storeu_si128((__m128i*)(acc + 2 * q), a[q]);
|
||||
#else
|
||||
for (size_t s = 0; s < stripes; ++s) {
|
||||
const size_t r = s % kStripesBlock;
|
||||
uint64_t d[8];
|
||||
std::memcpy(d, p + 64 * s, 64);
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
const uint64_t k = d[j] ^ K[r + (size_t)j];
|
||||
acc[j] += (k & 0xffffffffull) * (k >> 32);
|
||||
acc[j ^ 1] += d[j];
|
||||
}
|
||||
if (r == kStripesBlock - 1)
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
const uint64_t x = acc[j] ^ (acc[j] >> 47) ^ K[16 + j];
|
||||
acc[j] = (x & 0xffffffffull) * kStripePrime + (((x >> 32) * kStripePrime) << 32);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- level_bits_f32 */
|
||||
void RAD_SIMD_FN(level_bits_f32)(const float* v, size_t n, float lv, float band, uint64_t* gt,
|
||||
uint64_t* lt, uint64_t* nan, uint64_t* near) {
|
||||
size_t w = 0;
|
||||
/* Whole words: 64 elements, a lane group's comparison masks placed side by side. The
|
||||
* difference is a float subtraction, as the scalar tail's. */
|
||||
#if RAD_SIMD_LEVEL == 4
|
||||
const __m512 L = _mm512_set1_ps(lv), B = _mm512_set1_ps(band);
|
||||
for (; (w + 1) * 64 <= n; ++w) {
|
||||
uint64_t g = 0, l = 0, q = 0, r = 0;
|
||||
for (int h = 0; h < 4; ++h) {
|
||||
const __m512 x = _mm512_loadu_ps(v + w * 64 + h * 16);
|
||||
const __m512 d = _mm512_abs_ps(_mm512_sub_ps(x, L));
|
||||
g |= (uint64_t)_mm512_cmp_ps_mask(x, L, _CMP_GT_OQ) << (16 * h);
|
||||
l |= (uint64_t)_mm512_cmp_ps_mask(x, L, _CMP_LT_OQ) << (16 * h);
|
||||
q |= (uint64_t)_mm512_cmp_ps_mask(x, x, _CMP_UNORD_Q) << (16 * h);
|
||||
r |= (uint64_t)_mm512_cmp_ps_mask(d, B, _CMP_LT_OQ) << (16 * h);
|
||||
}
|
||||
gt[w] = g; lt[w] = l; nan[w] = q; near[w] = r;
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL == 2 || RAD_SIMD_LEVEL == 3
|
||||
const __m256 L = _mm256_set1_ps(lv), B = _mm256_set1_ps(band);
|
||||
const __m256 abs = _mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff));
|
||||
for (; (w + 1) * 64 <= n; ++w) {
|
||||
uint64_t g = 0, l = 0, q = 0, r = 0;
|
||||
for (int h = 0; h < 8; ++h) {
|
||||
const __m256 x = _mm256_loadu_ps(v + w * 64 + h * 8);
|
||||
const __m256 d = _mm256_and_ps(_mm256_sub_ps(x, L), abs);
|
||||
g |= (uint64_t)(unsigned)_mm256_movemask_ps(_mm256_cmp_ps(x, L, _CMP_GT_OQ)) << (8 * h);
|
||||
l |= (uint64_t)(unsigned)_mm256_movemask_ps(_mm256_cmp_ps(x, L, _CMP_LT_OQ)) << (8 * h);
|
||||
q |= (uint64_t)(unsigned)_mm256_movemask_ps(_mm256_cmp_ps(x, x, _CMP_UNORD_Q)) << (8 * h);
|
||||
r |= (uint64_t)(unsigned)_mm256_movemask_ps(_mm256_cmp_ps(d, B, _CMP_LT_OQ)) << (8 * h);
|
||||
}
|
||||
gt[w] = g; lt[w] = l; nan[w] = q; near[w] = r;
|
||||
}
|
||||
#elif RAD_SIMD_LEVEL == 1
|
||||
const __m128 L = _mm_set1_ps(lv), B = _mm_set1_ps(band);
|
||||
const __m128 abs = _mm_castsi128_ps(_mm_set1_epi32(0x7fffffff));
|
||||
for (; (w + 1) * 64 <= n; ++w) {
|
||||
uint64_t g = 0, l = 0, q = 0, r = 0;
|
||||
for (int h = 0; h < 16; ++h) {
|
||||
const __m128 x = _mm_loadu_ps(v + w * 64 + h * 4);
|
||||
const __m128 d = _mm_and_ps(_mm_sub_ps(x, L), abs);
|
||||
g |= (uint64_t)(unsigned)_mm_movemask_ps(_mm_cmpgt_ps(x, L)) << (4 * h);
|
||||
l |= (uint64_t)(unsigned)_mm_movemask_ps(_mm_cmplt_ps(x, L)) << (4 * h);
|
||||
q |= (uint64_t)(unsigned)_mm_movemask_ps(_mm_cmpunord_ps(x, x)) << (4 * h);
|
||||
r |= (uint64_t)(unsigned)_mm_movemask_ps(_mm_cmplt_ps(d, B)) << (4 * h);
|
||||
}
|
||||
gt[w] = g; lt[w] = l; nan[w] = q; near[w] = r;
|
||||
}
|
||||
#endif
|
||||
for (; w * 64 < n; ++w) {
|
||||
uint64_t g = 0, l = 0, q = 0, r = 0;
|
||||
const size_t end = std::min(n, (w + 1) * 64);
|
||||
for (size_t i = w * 64; i < end; ++i) {
|
||||
const float x = v[i];
|
||||
const uint64_t b = 1ull << (i - w * 64);
|
||||
if (x > lv) g |= b;
|
||||
if (x < lv) l |= b;
|
||||
if (x != x) q |= b;
|
||||
float d = x - lv;
|
||||
d = d < 0.0f ? -d : d;
|
||||
if (d < band) r |= b;
|
||||
}
|
||||
gt[w] = g; lt[w] = l; nan[w] = q; near[w] = r;
|
||||
}
|
||||
}
|
||||
|
||||
} /* extern "C" */
|
||||
|
||||
#endif /* RAD_SIMD_LEVEL */
|
||||
Reference in new issue
Block a user