Archived
laya: Laya decision models on /v1/systemone (arch/laya)
This commit is contained in:
1 parent
d24cf32a13
commit
9c605a103d
18 files changed
+2346
-175
No files matched your search
@@ -301,7 +301,7 @@ set(RAD_E2E_DEPS radiance rad-convert libref libquant qwen35_bf16 lfm2_bf16 gemm
|
||||
if(TARGET libavx)
|
||||
list(APPEND RAD_E2E_DEPS libavx)
|
||||
endif()
|
||||
foreach(t engine_e2e_test convert_test clef_decision_test)
|
||||
foreach(t engine_e2e_test convert_test clef_decision_test laya_decision_test)
|
||||
if(TARGET ${t})
|
||||
target_compile_definitions(${t} PRIVATE
|
||||
RAD_E2E_SERVER="$<TARGET_FILE:radiance>" RAD_E2E_CONVERT="$<TARGET_FILE:rad-convert>"
|
||||
@@ -311,6 +311,11 @@ foreach(t engine_e2e_test convert_test clef_decision_test)
|
||||
target_compile_definitions(${t} PRIVATE
|
||||
RAD_CLEF_GOLDEN="${CMAKE_CURRENT_SOURCE_DIR}/data/golden/clef_tiny.json")
|
||||
add_dependencies(${t} radiance rad-convert libref libquant clef_bf16)
|
||||
elseif(t STREQUAL "laya_decision_test")
|
||||
# The tiny Laya's golden (tests/mklayagolden.py) and the plugin a Laya container selects.
|
||||
target_compile_definitions(${t} PRIVATE
|
||||
RAD_LAYA_GOLDEN="${CMAKE_CURRENT_SOURCE_DIR}/data/golden/laya_tiny.json")
|
||||
add_dependencies(${t} radiance rad-convert libref libquant laya)
|
||||
else()
|
||||
add_dependencies(${t} ${RAD_E2E_DEPS})
|
||||
endif()
|
||||
@@ -324,6 +329,9 @@ endif()
|
||||
if(TARGET clef_decision_test)
|
||||
set_tests_properties(clef_decision_test PROPERTIES LABELS "e2e" TIMEOUT 300)
|
||||
endif()
|
||||
if(TARGET laya_decision_test)
|
||||
set_tests_properties(laya_decision_test PROPERTIES LABELS "e2e" TIMEOUT 300)
|
||||
endif()
|
||||
|
||||
# abi_layout_test compares the ABI's struct layouts with a C translation unit's: abi_c_test.c
|
||||
# includes every abi/ header as strict C11, so a header only C++ accepts fails the build.
|
||||
|
||||
@@ -14,186 +14,19 @@
|
||||
* the container header; then the same request again, a whole prefix hit, so the head reads every
|
||||
* row from the cache alone; and the bounds and the image refusal.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
#include "tiny_model.h"
|
||||
#include "decision_e2e.h"
|
||||
|
||||
#include "rad_clef.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <cerrno>
|
||||
#include <cmath>
|
||||
#include <condition_variable>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
|
||||
using json = nlohmann::json;
|
||||
using namespace decision_e2e;
|
||||
|
||||
namespace {
|
||||
|
||||
std::vector<std::string> engine_env() {
|
||||
return { "ROCR_VISIBLE_DEVICES=99", "RADIANCE_HOST_VRAM_MIB=1024", "OMP_WAIT_POLICY=passive",
|
||||
"OMP_NUM_THREADS=2", std::string("RADIANCE_HOME=") + RAD_E2E_HOME };
|
||||
}
|
||||
|
||||
std::vector<std::string> engine_argv(const std::string& model,
|
||||
const std::vector<std::string>& args) {
|
||||
std::vector<std::string> a = { RAD_E2E_SERVER, "--model", model, "--kernels", "libref",
|
||||
"--debug-accept-reference-kernels" };
|
||||
a.insert(a.end(), args.begin(), args.end());
|
||||
return a;
|
||||
}
|
||||
|
||||
std::string tail(const std::string& log, int n = 14) {
|
||||
size_t at = log.size();
|
||||
for (int i = 0; i <= n && at != std::string::npos && at > 0; ++i) at = log.rfind('\n', at - 1);
|
||||
return at == std::string::npos || at >= log.size() ? log : log.substr(at + 1);
|
||||
}
|
||||
|
||||
/* A server on a free loopback port (as engine_e2e_test.cpp runs one). */
|
||||
struct Server {
|
||||
tiny::Child child;
|
||||
std::thread drain;
|
||||
std::mutex mu;
|
||||
std::condition_variable cv;
|
||||
std::string log;
|
||||
bool eof = false;
|
||||
int port = 0;
|
||||
|
||||
bool start(const std::string& model, const std::vector<std::string>& args) {
|
||||
std::vector<std::string> a = { "--host", "127.0.0.1", "--port", "0" };
|
||||
a.insert(a.end(), args.begin(), args.end());
|
||||
if (!child.start(engine_argv(model, a), engine_env())) return false;
|
||||
drain = std::thread([this] {
|
||||
char buf[4096];
|
||||
for (;;) {
|
||||
const ssize_t n = ::read(child.fd, buf, sizeof buf);
|
||||
if (n < 0 && errno == EINTR) continue;
|
||||
std::lock_guard<std::mutex> lk(mu);
|
||||
if (n <= 0) { eof = true; cv.notify_all(); return; }
|
||||
log.append(buf, (size_t)n);
|
||||
cv.notify_all();
|
||||
}
|
||||
});
|
||||
static const std::string kTag = "listening on http://127.0.0.1:";
|
||||
std::unique_lock<std::mutex> lk(mu);
|
||||
cv.wait(lk, [&] { return eof || log.find(kTag) != std::string::npos; });
|
||||
const size_t at = log.find(kTag);
|
||||
if (at != std::string::npos) port = std::atoi(log.c_str() + at + kTag.size());
|
||||
if (port <= 0) fprintf(stderr, " the server did not start:\n%s\n", tail(log).c_str());
|
||||
return port > 0;
|
||||
}
|
||||
int stop() {
|
||||
if (child.pid <= 0) return -1;
|
||||
kill(child.pid, SIGTERM);
|
||||
if (drain.joinable()) drain.join();
|
||||
close(child.fd);
|
||||
child.fd = -1;
|
||||
std::string rest;
|
||||
return child.wait(&rest);
|
||||
}
|
||||
std::string output() {
|
||||
std::lock_guard<std::mutex> lk(mu);
|
||||
return log;
|
||||
}
|
||||
~Server() {
|
||||
if (child.pid > 0) kill(child.pid, SIGKILL);
|
||||
if (drain.joinable()) drain.join();
|
||||
}
|
||||
};
|
||||
|
||||
/* One request on its own loopback connection. */
|
||||
struct Call {
|
||||
int fd = -1;
|
||||
std::string why;
|
||||
bool fail(const char* what) {
|
||||
why = std::string(what) + ": " + std::strerror(errno);
|
||||
return false;
|
||||
}
|
||||
bool send(int port, const char* method, const std::string& path, const std::string& body) {
|
||||
fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
|
||||
if (fd < 0) return fail("socket");
|
||||
sockaddr_in a{};
|
||||
a.sin_family = AF_INET;
|
||||
a.sin_port = htons((uint16_t)port);
|
||||
a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
if (connect(fd, (sockaddr*)&a, sizeof a) != 0) return fail("connect");
|
||||
std::string req = std::string(method) + " " + path + " HTTP/1.1\r\nHost: 127.0.0.1\r\n" +
|
||||
"Connection: close\r\nContent-Type: application/json\r\n" +
|
||||
"Content-Length: " + std::to_string(body.size()) + "\r\n\r\n" + body;
|
||||
for (size_t off = 0; off < req.size();) {
|
||||
const ssize_t n = ::send(fd, req.data() + off, req.size() - off, MSG_NOSIGNAL);
|
||||
if (n <= 0) return fail("send");
|
||||
off += (size_t)n;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
int read(std::string* body) {
|
||||
std::string raw;
|
||||
char buf[16384];
|
||||
for (;;) {
|
||||
const ssize_t n = ::recv(fd, buf, sizeof buf, 0);
|
||||
if (n < 0 && errno == EINTR) continue;
|
||||
if (n <= 0) break;
|
||||
raw.append(buf, (size_t)n);
|
||||
}
|
||||
close(fd);
|
||||
fd = -1;
|
||||
const size_t h = raw.find("\r\n\r\n");
|
||||
if (raw.compare(0, 9, "HTTP/1.1 ") != 0 || h == std::string::npos) {
|
||||
why = "no response (" + std::to_string(raw.size()) + " bytes)";
|
||||
return -1;
|
||||
}
|
||||
std::string head = raw.substr(0, h), rest = raw.substr(h + 4);
|
||||
for (char& c : head) c = (char)std::tolower((unsigned char)c);
|
||||
if (head.find("transfer-encoding: chunked") != std::string::npos) {
|
||||
std::string out;
|
||||
for (size_t at = 0;;) {
|
||||
const size_t eol = rest.find("\r\n", at);
|
||||
if (eol == std::string::npos) break;
|
||||
const size_t n = std::strtoul(rest.c_str() + at, nullptr, 16);
|
||||
if (n == 0) break;
|
||||
out += rest.substr(eol + 2, n);
|
||||
at = eol + 2 + n + 2;
|
||||
}
|
||||
rest = out;
|
||||
}
|
||||
*body = rest;
|
||||
return std::atoi(raw.c_str() + 9);
|
||||
}
|
||||
~Call() { if (fd >= 0) close(fd); }
|
||||
};
|
||||
|
||||
json call(int port, const char* method, const std::string& path, const json& body, int* status) {
|
||||
Call c;
|
||||
std::string out;
|
||||
const int st = c.send(port, method, path, body.is_null() ? "" : body.dump()) ? c.read(&out) : -1;
|
||||
*status = st;
|
||||
if (st < 0) fprintf(stderr, " %s %s: %s\n", method, path.c_str(), c.why.c_str());
|
||||
return json::parse(out, nullptr, false);
|
||||
}
|
||||
|
||||
uint64_t fnv1a(const std::string& path) {
|
||||
std::ifstream f(path, std::ios::binary);
|
||||
std::string bytes((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
|
||||
uint64_t h = 0xcbf29ce484222325ull;
|
||||
for (unsigned char c : bytes) h = (h ^ c) * 0x100000001b3ull;
|
||||
return h;
|
||||
}
|
||||
|
||||
std::string hex16(uint64_t v) {
|
||||
char s[24];
|
||||
std::snprintf(s, sizeof s, "%016llx", (unsigned long long)v);
|
||||
return s;
|
||||
}
|
||||
|
||||
/* The tiny clef: tiny_model.h's qwen35 (hidden 64) and a head of width 64 with one head of 64
|
||||
* (libr4d's attention width, so the same declaration serves the card), feedforward 128, one
|
||||
* routing and one decoder layer; LayerNorm gains near one, every linear at unit gain, the three
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
{
|
||||
"weights_fnv": "230e9131e87efe05",
|
||||
"laya_commit": "fe9a6c3502",
|
||||
"requests": [
|
||||
{
|
||||
"state": "Charged twice for one order; refund one please.",
|
||||
"questions": {
|
||||
"refund": {
|
||||
"type": "noul",
|
||||
"instructions": "Does the customer ask for money back?"
|
||||
},
|
||||
"team": {
|
||||
"type": "choice",
|
||||
"instructions": "Which team should take this?",
|
||||
"criteria": {
|
||||
"billing": "Charges and refunds",
|
||||
"shipping": "Delivery",
|
||||
"product": ""
|
||||
}
|
||||
},
|
||||
"tone": {
|
||||
"type": "score",
|
||||
"instructions": "How upset is the customer?",
|
||||
"criteria": [
|
||||
"Calm",
|
||||
"Mildly annoyed",
|
||||
"Angry"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"state": {
|
||||
"message": "The parcel arrived two weeks late and the box was crushed, but the vase inside was intact. I would like a partial refund for the delay, and please tell the courier.",
|
||||
"channel": "email"
|
||||
},
|
||||
"questions": {
|
||||
"topic": {
|
||||
"type": "choice",
|
||||
"instructions": "Topic?",
|
||||
"criteria": [
|
||||
"a",
|
||||
"b",
|
||||
"c",
|
||||
"d",
|
||||
"e",
|
||||
"f",
|
||||
"g",
|
||||
"h",
|
||||
"i",
|
||||
"j",
|
||||
"k",
|
||||
"l"
|
||||
]
|
||||
},
|
||||
"spam": {
|
||||
"type": "noul",
|
||||
"instructions": {
|
||||
"ask": "Is this unsolicited?"
|
||||
},
|
||||
"criteria": {
|
||||
"true": "unsolicited bulk mail"
|
||||
}
|
||||
},
|
||||
"team": {
|
||||
"type": "choice",
|
||||
"instructions": "Route it.",
|
||||
"criteria": [
|
||||
"billing",
|
||||
"technical",
|
||||
"sales",
|
||||
"other"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"state": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "The parcel arrived two weeks late and the box was crushed, but the vase inside was intact. I would like a partial refund for the delay, and please tell the courier."
|
||||
},
|
||||
{
|
||||
"role": "agent",
|
||||
"content": "Sorry, checking."
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Any news on the refund?"
|
||||
}
|
||||
],
|
||||
"questions": {
|
||||
"waiting": {
|
||||
"type": "noul",
|
||||
"instructions": "Is the customer still waiting?"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"results": [
|
||||
{
|
||||
"answers": {
|
||||
"refund": {
|
||||
"type": "noul",
|
||||
"noul": 0.4816,
|
||||
"confidence": 0.5184,
|
||||
"answer_confidence": 0.5184,
|
||||
"action": {
|
||||
"act_probability": 0.3778
|
||||
}
|
||||
},
|
||||
"team": {
|
||||
"type": "choice",
|
||||
"choice": "product",
|
||||
"probabilities": {
|
||||
"billing": 0.2738,
|
||||
"shipping": 0.3475,
|
||||
"product": 0.3787
|
||||
},
|
||||
"confidence": 0.0081,
|
||||
"answer_confidence": 0.3787,
|
||||
"action": {
|
||||
"act_probability": 0.6045
|
||||
}
|
||||
},
|
||||
"tone": {
|
||||
"type": "score",
|
||||
"score": 1.3351,
|
||||
"legend": {
|
||||
"0": "Calm",
|
||||
"1": "Mildly annoyed",
|
||||
"2": "Angry"
|
||||
},
|
||||
"probabilities": {
|
||||
"0": 0.2201,
|
||||
"1": 0.2247,
|
||||
"2": 0.5552
|
||||
},
|
||||
"confidence": 0.094,
|
||||
"answer_confidence": 0.5552,
|
||||
"action": {
|
||||
"act_probability": 0.8258
|
||||
}
|
||||
}
|
||||
},
|
||||
"usage": {
|
||||
"input_tokens": 297,
|
||||
"output_tokens": 0,
|
||||
"state_tokens": 47,
|
||||
"state_tokens_dropped": 0,
|
||||
"truncated": false,
|
||||
"truncated_questions": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"answers": {
|
||||
"topic": {
|
||||
"type": "choice",
|
||||
"choice": "d",
|
||||
"probabilities": {
|
||||
"a": 0.0212,
|
||||
"b": 0.0235,
|
||||
"c": 0.0906,
|
||||
"d": 0.2956,
|
||||
"e": 0.1971,
|
||||
"f": 0.1235,
|
||||
"g": 0.0387,
|
||||
"h": 0.001,
|
||||
"i": 0.0043,
|
||||
"j": 0.0429,
|
||||
"k": 0.1461,
|
||||
"l": 0.0153
|
||||
},
|
||||
"confidence": 0.2101,
|
||||
"answer_confidence": 0.2956,
|
||||
"action": {
|
||||
"act_probability": 0.5545
|
||||
}
|
||||
},
|
||||
"spam": {
|
||||
"type": "noul",
|
||||
"noul": 0.4899,
|
||||
"confidence": 0.5101,
|
||||
"answer_confidence": 0.5101,
|
||||
"action": {
|
||||
"act_probability": 0.4172
|
||||
}
|
||||
},
|
||||
"team": {
|
||||
"type": "choice",
|
||||
"choice": "billing",
|
||||
"probabilities": {
|
||||
"billing": 0.3187,
|
||||
"technical": 0.2485,
|
||||
"sales": 0.2368,
|
||||
"other": 0.1961
|
||||
},
|
||||
"confidence": 0.0111,
|
||||
"answer_confidence": 0.3187,
|
||||
"action": {
|
||||
"act_probability": 0.4443
|
||||
}
|
||||
}
|
||||
},
|
||||
"usage": {
|
||||
"input_tokens": 384,
|
||||
"output_tokens": 0,
|
||||
"state_tokens": 199,
|
||||
"state_tokens_dropped": 123,
|
||||
"truncated": true,
|
||||
"truncated_questions": [
|
||||
"topic",
|
||||
"spam",
|
||||
"team"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"answers": {
|
||||
"waiting": {
|
||||
"type": "noul",
|
||||
"noul": 0.4588,
|
||||
"confidence": 0.5412,
|
||||
"answer_confidence": 0.5412,
|
||||
"action": {
|
||||
"act_probability": 0.6247
|
||||
}
|
||||
}
|
||||
},
|
||||
"usage": {
|
||||
"input_tokens": 128,
|
||||
"output_tokens": 0,
|
||||
"state_tokens": 303,
|
||||
"state_tokens_dropped": 227,
|
||||
"truncated": true,
|
||||
"truncated_questions": [
|
||||
"waiting"
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
/* decision_e2e.h -- the radiance binary on a free loopback port and plain HTTP calls to it, for
|
||||
* the decision models' end-to-end tests (clef_decision_test.cpp, laya_decision_test.cpp).
|
||||
*
|
||||
* The server runs on the host backend with the reference kernels, as engine_e2e_test.cpp runs one.
|
||||
* RAD_E2E_SERVER and RAD_E2E_HOME come from tests/CMakeLists.txt.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include "rad_test.h"
|
||||
#include "tiny_model.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/socket.h>
|
||||
|
||||
#include <cerrno>
|
||||
#include <condition_variable>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
|
||||
namespace decision_e2e {
|
||||
|
||||
using json = nlohmann::ordered_json; /* the request order, which Laya reads */
|
||||
|
||||
inline std::vector<std::string> engine_env() {
|
||||
return { "ROCR_VISIBLE_DEVICES=99", "RADIANCE_HOST_VRAM_MIB=1024", "OMP_WAIT_POLICY=passive",
|
||||
"OMP_NUM_THREADS=2", std::string("RADIANCE_HOME=") + RAD_E2E_HOME };
|
||||
}
|
||||
|
||||
inline std::vector<std::string> engine_argv(const std::string& model,
|
||||
const std::vector<std::string>& args) {
|
||||
std::vector<std::string> a = { RAD_E2E_SERVER, "--model", model, "--kernels", "libref",
|
||||
"--debug-accept-reference-kernels" };
|
||||
a.insert(a.end(), args.begin(), args.end());
|
||||
return a;
|
||||
}
|
||||
|
||||
inline std::string tail(const std::string& log, int n = 14) {
|
||||
size_t at = log.size();
|
||||
for (int i = 0; i <= n && at != std::string::npos && at > 0; ++i) at = log.rfind('\n', at - 1);
|
||||
return at == std::string::npos || at >= log.size() ? log : log.substr(at + 1);
|
||||
}
|
||||
|
||||
/* A server on a free loopback port (as engine_e2e_test.cpp runs one). */
|
||||
struct Server {
|
||||
tiny::Child child;
|
||||
std::thread drain;
|
||||
std::mutex mu;
|
||||
std::condition_variable cv;
|
||||
std::string log;
|
||||
bool eof = false;
|
||||
int port = 0;
|
||||
|
||||
bool start(const std::string& model, const std::vector<std::string>& args) {
|
||||
std::vector<std::string> a = { "--host", "127.0.0.1", "--port", "0" };
|
||||
a.insert(a.end(), args.begin(), args.end());
|
||||
if (!child.start(engine_argv(model, a), engine_env())) return false;
|
||||
drain = std::thread([this] {
|
||||
char buf[4096];
|
||||
for (;;) {
|
||||
const ssize_t n = ::read(child.fd, buf, sizeof buf);
|
||||
if (n < 0 && errno == EINTR) continue;
|
||||
std::lock_guard<std::mutex> lk(mu);
|
||||
if (n <= 0) { eof = true; cv.notify_all(); return; }
|
||||
log.append(buf, (size_t)n);
|
||||
cv.notify_all();
|
||||
}
|
||||
});
|
||||
static const std::string kTag = "listening on http://127.0.0.1:";
|
||||
std::unique_lock<std::mutex> lk(mu);
|
||||
cv.wait(lk, [&] { return eof || log.find(kTag) != std::string::npos; });
|
||||
const size_t at = log.find(kTag);
|
||||
if (at != std::string::npos) port = std::atoi(log.c_str() + at + kTag.size());
|
||||
if (port <= 0) fprintf(stderr, " the server did not start:\n%s\n", tail(log).c_str());
|
||||
return port > 0;
|
||||
}
|
||||
int stop() {
|
||||
if (child.pid <= 0) return -1;
|
||||
kill(child.pid, SIGTERM);
|
||||
if (drain.joinable()) drain.join();
|
||||
close(child.fd);
|
||||
child.fd = -1;
|
||||
std::string rest;
|
||||
return child.wait(&rest);
|
||||
}
|
||||
std::string output() {
|
||||
std::lock_guard<std::mutex> lk(mu);
|
||||
return log;
|
||||
}
|
||||
~Server() {
|
||||
if (child.pid > 0) kill(child.pid, SIGKILL);
|
||||
if (drain.joinable()) drain.join();
|
||||
}
|
||||
};
|
||||
|
||||
/* One request on its own loopback connection. */
|
||||
struct Call {
|
||||
int fd = -1;
|
||||
std::string why;
|
||||
bool fail(const char* what) {
|
||||
why = std::string(what) + ": " + std::strerror(errno);
|
||||
return false;
|
||||
}
|
||||
bool send(int port, const char* method, const std::string& path, const std::string& body) {
|
||||
fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
|
||||
if (fd < 0) return fail("socket");
|
||||
sockaddr_in a{};
|
||||
a.sin_family = AF_INET;
|
||||
a.sin_port = htons((uint16_t)port);
|
||||
a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
if (connect(fd, (sockaddr*)&a, sizeof a) != 0) return fail("connect");
|
||||
std::string req = std::string(method) + " " + path + " HTTP/1.1\r\nHost: 127.0.0.1\r\n" +
|
||||
"Connection: close\r\nContent-Type: application/json\r\n" +
|
||||
"Content-Length: " + std::to_string(body.size()) + "\r\n\r\n" + body;
|
||||
for (size_t off = 0; off < req.size();) {
|
||||
const ssize_t n = ::send(fd, req.data() + off, req.size() - off, MSG_NOSIGNAL);
|
||||
if (n <= 0) return fail("send");
|
||||
off += (size_t)n;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
int read(std::string* body) {
|
||||
std::string raw;
|
||||
char buf[16384];
|
||||
for (;;) {
|
||||
const ssize_t n = ::recv(fd, buf, sizeof buf, 0);
|
||||
if (n < 0 && errno == EINTR) continue;
|
||||
if (n <= 0) break;
|
||||
raw.append(buf, (size_t)n);
|
||||
}
|
||||
close(fd);
|
||||
fd = -1;
|
||||
const size_t h = raw.find("\r\n\r\n");
|
||||
if (raw.compare(0, 9, "HTTP/1.1 ") != 0 || h == std::string::npos) {
|
||||
why = "no response (" + std::to_string(raw.size()) + " bytes)";
|
||||
return -1;
|
||||
}
|
||||
std::string head = raw.substr(0, h), rest = raw.substr(h + 4);
|
||||
for (char& c : head) c = (char)std::tolower((unsigned char)c);
|
||||
if (head.find("transfer-encoding: chunked") != std::string::npos) {
|
||||
std::string out;
|
||||
for (size_t at = 0;;) {
|
||||
const size_t eol = rest.find("\r\n", at);
|
||||
if (eol == std::string::npos) break;
|
||||
const size_t n = std::strtoul(rest.c_str() + at, nullptr, 16);
|
||||
if (n == 0) break;
|
||||
out += rest.substr(eol + 2, n);
|
||||
at = eol + 2 + n + 2;
|
||||
}
|
||||
rest = out;
|
||||
}
|
||||
*body = rest;
|
||||
return std::atoi(raw.c_str() + 9);
|
||||
}
|
||||
~Call() { if (fd >= 0) close(fd); }
|
||||
};
|
||||
|
||||
inline json call(int port, const char* method, const std::string& path, const json& body, int* status) {
|
||||
Call c;
|
||||
std::string out;
|
||||
const int st = c.send(port, method, path, body.is_null() ? "" : body.dump()) ? c.read(&out) : -1;
|
||||
*status = st;
|
||||
if (st < 0) fprintf(stderr, " %s %s: %s\n", method, path.c_str(), c.why.c_str());
|
||||
return json::parse(out, nullptr, false);
|
||||
}
|
||||
|
||||
inline uint64_t fnv1a(const std::string& path) {
|
||||
std::ifstream f(path, std::ios::binary);
|
||||
std::string bytes((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
|
||||
uint64_t h = 0xcbf29ce484222325ull;
|
||||
for (unsigned char c : bytes) h = (h ^ c) * 0x100000001b3ull;
|
||||
return h;
|
||||
}
|
||||
|
||||
inline std::string hex16(uint64_t v) {
|
||||
char s[24];
|
||||
std::snprintf(s, sizeof s, "%016llx", (unsigned long long)v);
|
||||
return s;
|
||||
}
|
||||
|
||||
} /* namespace decision_e2e */
|
||||
@@ -0,0 +1,288 @@
|
||||
/* laya_decision_test.cpp -- /v1/systemone on a Laya container, end to end on the CPU.
|
||||
*
|
||||
* A tiny Laya in the release's own layout (config.json saying model_type laya, encoder/config.json
|
||||
* a three-layer ModernBERT with one sliding layer pair, rl_agent_config.json, tokenizer/, and
|
||||
* model.safetensors with the release's tensor names), converted with `--set decision.type=laya`
|
||||
* and served by the radiance binary on the host backend. The answers and usage are checked against
|
||||
* tests/data/golden/laya_tiny.json, laya's own Agent.predict on the same checkpoint in float32,
|
||||
* made by tests/mklayagolden.py from the directory this test writes (RAD_E2E_KEEP=1 keeps it). The
|
||||
* golden carries the weights' hash, so a golden for other weights is refused by name.
|
||||
*
|
||||
* What one run covers: rad-convert reading the release's folders; each question's sequence, the
|
||||
* state cut and its report; one engine request a question on the embedding path; the plugin's
|
||||
* encoder (full and sliding layers), head and scorer on libref; the option logits through the
|
||||
* pooled row; the fitted temperatures (one clamped) and the package's confidence; then the same
|
||||
* request again, the capability report, and the refusals.
|
||||
*/
|
||||
#include "decision_e2e.h"
|
||||
|
||||
#include "rad_laya.h"
|
||||
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <fstream>
|
||||
|
||||
using namespace decision_e2e;
|
||||
|
||||
namespace {
|
||||
|
||||
/* The tiny Laya: hidden 64 in one head of 64 (libr4d's attention width, so the same declaration
|
||||
* serves the card), feed-forward 96, three encoder layers (full, sliding, sliding over
|
||||
* local_attention 8), two head layers; LayerNorm gains near one, every linear at unit gain but the
|
||||
* scorer's last, which spreads the option logits. The byte tokenizer's specials after its own three
|
||||
* are [CLS] 259, [SEP] 260, [MASK] 261, [PAD] 262, [UNK] 263; the vocabulary pads to 320. */
|
||||
bool write_tiny_laya(const std::string& dir, uint64_t seed) {
|
||||
const int64_t E = 64, F = 96, L = 3, V = 320, HL = 2, A = 256;
|
||||
tiny::Rng r(seed);
|
||||
std::vector<tiny::Tensor> ts;
|
||||
auto gain = [&](const std::string& n, int64_t k) { ts.push_back(tiny::noise(n, { k }, r, 0.1f, 1.0f)); };
|
||||
auto bias = [&](const std::string& n, int64_t k) { ts.push_back(tiny::noise(n, { k }, r, 0.1f)); };
|
||||
auto lin = [&](const std::string& n, int64_t o, int64_t i, float g = 1.0f) {
|
||||
ts.push_back(tiny::linear(n, o, i, r, g));
|
||||
};
|
||||
ts.push_back(tiny::noise("encoder.embeddings.tok_embeddings.weight", { V, E }, r, 1.0f));
|
||||
gain("encoder.embeddings.norm.weight", E);
|
||||
for (int64_t l = 0; l < L; ++l) {
|
||||
const std::string p = "encoder.layers." + std::to_string(l) + ".";
|
||||
if (l > 0) gain(p + "attn_norm.weight", E);
|
||||
lin(p + "attn.Wqkv.weight", 3 * E, E);
|
||||
lin(p + "attn.Wo.weight", E, E);
|
||||
gain(p + "mlp_norm.weight", E);
|
||||
lin(p + "mlp.Wi.weight", 2 * F, E);
|
||||
lin(p + "mlp.Wo.weight", E, F);
|
||||
}
|
||||
gain("encoder.final_norm.weight", E);
|
||||
for (int64_t j = 0; j < HL; ++j) {
|
||||
const std::string p = "head.layers." + std::to_string(j) + ".";
|
||||
lin(p + "self_attn.in_proj_weight", 3 * E, E);
|
||||
bias(p + "self_attn.in_proj_bias", 3 * E);
|
||||
lin(p + "self_attn.out_proj.weight", E, E);
|
||||
bias(p + "self_attn.out_proj.bias", E);
|
||||
lin(p + "linear1.weight", 4 * E, E);
|
||||
bias(p + "linear1.bias", 4 * E);
|
||||
lin(p + "linear2.weight", E, 4 * E);
|
||||
bias(p + "linear2.bias", E);
|
||||
gain(p + "norm1.weight", E);
|
||||
bias(p + "norm1.bias", E);
|
||||
gain(p + "norm2.weight", E);
|
||||
bias(p + "norm2.bias", E);
|
||||
}
|
||||
ts.push_back(tiny::noise("type_emb.weight", { 3, E }, r, 0.5f));
|
||||
gain("scorer.0.weight", E);
|
||||
bias("scorer.0.bias", E);
|
||||
lin("scorer.1.weight", E, E);
|
||||
bias("scorer.1.bias", E);
|
||||
lin("scorer.3.weight", 1, E, 3.0f);
|
||||
bias("scorer.3.bias", 1);
|
||||
/* The escalation head and the stored temperatures: in the release's state dict (its loader
|
||||
* is strict), not declared by the plugin. */
|
||||
lin("act_head.0.weight", A, E + 4);
|
||||
bias("act_head.0.bias", A);
|
||||
lin("act_head.2.weight", 2, A);
|
||||
bias("act_head.2.bias", 2);
|
||||
ts.push_back(tiny::noise("temperature", { 3 }, r, 0.0f, 1.0f, "F32"));
|
||||
if (!tiny::write_safetensors(dir + "/model.safetensors", ts)) return false;
|
||||
|
||||
nlohmann::ordered_json root;
|
||||
root["model_type"] = "laya";
|
||||
root["architectures"] = { "LayaTypedDecisions" };
|
||||
nlohmann::ordered_json enc;
|
||||
enc["architectures"] = { "ModernBertForMaskedLM" };
|
||||
enc["model_type"] = "modernbert";
|
||||
enc["hidden_size"] = E;
|
||||
enc["intermediate_size"] = F;
|
||||
enc["num_hidden_layers"] = L;
|
||||
enc["num_attention_heads"] = 1;
|
||||
enc["layer_types"] = { "full_attention", "sliding_attention", "sliding_attention" };
|
||||
enc["global_attn_every_n_layers"] = 3;
|
||||
enc["local_attention"] = 8;
|
||||
enc["rope_parameters"] = { { "full_attention", { { "rope_theta", 160000.0 }, { "rope_type", "default" } } },
|
||||
{ "sliding_attention", { { "rope_theta", 10000.0 }, { "rope_type", "default" } } } };
|
||||
enc["max_position_embeddings"] = 8192;
|
||||
enc["vocab_size"] = V;
|
||||
enc["norm_eps"] = 1e-5;
|
||||
enc["norm_bias"] = false;
|
||||
enc["attention_bias"] = false;
|
||||
enc["mlp_bias"] = false;
|
||||
enc["hidden_activation"] = "gelu";
|
||||
enc["embedding_dropout"] = 0.0;
|
||||
enc["attention_dropout"] = 0.0;
|
||||
enc["mlp_dropout"] = 0.0;
|
||||
enc["pad_token_id"] = 262;
|
||||
enc["cls_token_id"] = 259;
|
||||
enc["sep_token_id"] = 260;
|
||||
enc["bos_token_id"] = 259;
|
||||
enc["eos_token_id"] = 260;
|
||||
enc["tie_word_embeddings"] = true;
|
||||
nlohmann::ordered_json rl;
|
||||
rl["encoder"] = "answerdotai/ModernBERT-large";
|
||||
rl["head_layers"] = HL;
|
||||
rl["max_len"] = 128;
|
||||
rl["head_max_len"] = 48;
|
||||
rl["max_prefixes"] = 6;
|
||||
rl["act_costs"] = { { "escalate", 0.5 } };
|
||||
rl["amp_dtype"] = "bf16";
|
||||
rl["model_name"] = "laya-tiny";
|
||||
rl["temperature"] = { 1.3, 0.9, 1.7 };
|
||||
rl["temperature_by_options"] = { { "choice:3-5", 1.6 }, { "noul:2", 2.2 }, { "choice:11+", 0.1 } };
|
||||
nlohmann::ordered_json tc;
|
||||
tc["cls_token"] = "[CLS]";
|
||||
tc["mask_token"] = "[MASK]";
|
||||
tc["pad_token"] = "[PAD]";
|
||||
tc["sep_token"] = "[SEP]";
|
||||
tc["unk_token"] = "[UNK]";
|
||||
tc["model_max_length"] = 8192;
|
||||
tc["tokenizer_class"] = "PreTrainedTokenizerFast";
|
||||
return mkdir((dir + "/encoder").c_str(), 0755) == 0 &&
|
||||
mkdir((dir + "/tokenizer").c_str(), 0755) == 0 &&
|
||||
tiny::write_text(dir + "/config.json", root.dump(2)) &&
|
||||
tiny::write_text(dir + "/encoder/config.json", enc.dump(2)) &&
|
||||
tiny::write_text(dir + "/rl_agent_config.json", rl.dump(2)) &&
|
||||
tiny::write_text(dir + "/tokenizer/tokenizer_config.json", tc.dump(2)) &&
|
||||
tiny::write_text(dir + "/tokenizer/tokenizer.json",
|
||||
tiny::tokenizer_json({ "[CLS]", "[SEP]", "[MASK]", "[PAD]", "[UNK]" }));
|
||||
}
|
||||
|
||||
/* The largest difference between radiance's answers and the package's: every probability, every
|
||||
* confidence, every noul and score; and whether each choice agrees where the package's top two are
|
||||
* apart. */
|
||||
double compare(const json& got, const json& want, bool* choices_agree) {
|
||||
double worst = 0.0;
|
||||
auto d = [&](const json& a, const json& b) {
|
||||
worst = std::max(worst, std::fabs(a.get<double>() - b.get<double>()));
|
||||
};
|
||||
for (const auto& kv : want.items()) {
|
||||
const json& w = kv.value();
|
||||
if (!got.contains(kv.key())) { *choices_agree = false; return 1.0; }
|
||||
const json& g = got[kv.key()];
|
||||
if (g["type"] != w["type"]) { *choices_agree = false; return 1.0; }
|
||||
if (w["type"] == "noul") { d(g["noul"], w["noul"]); continue; }
|
||||
d(g["confidence"], w["confidence"]);
|
||||
if (w["type"] == "score") d(g["score"], w["score"]);
|
||||
std::vector<double> top;
|
||||
for (const auto& p : w["probabilities"].items()) {
|
||||
if (!g["probabilities"].contains(p.key())) { *choices_agree = false; return 1.0; }
|
||||
d(g["probabilities"][p.key()], p.value());
|
||||
top.push_back(p.value().get<double>());
|
||||
}
|
||||
if (w["type"] == "choice") {
|
||||
std::sort(top.rbegin(), top.rend());
|
||||
if (top.size() < 2 || top[0] - top[1] > 0.02) *choices_agree = *choices_agree && g["choice"] == w["choice"];
|
||||
CHECK(!g.contains("legend"));
|
||||
} else {
|
||||
CHECK(g["legend"] == w["legend"]);
|
||||
}
|
||||
}
|
||||
return worst;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
TEST(a_laya_container_answers_every_question_and_matches_the_package) {
|
||||
const bool keep = std::getenv("RAD_E2E_KEEP") != nullptr;
|
||||
tiny::TempDir dir{ "laya", keep };
|
||||
REQUIRE(dir.ok());
|
||||
const std::string ck = dir / "laya-tiny";
|
||||
REQUIRE_EQ(mkdir(ck.c_str(), 0755), 0);
|
||||
REQUIRE(write_tiny_laya(ck, 11));
|
||||
if (keep) fprintf(stderr, " the tiny Laya is kept at %s (tests/mklayagolden.py)\n", ck.c_str());
|
||||
|
||||
const std::string rad = dir / "laya-tiny.rad";
|
||||
std::string log;
|
||||
const int st = tiny::run({ RAD_E2E_CONVERT, ck, "-o", rad, "--set", "decision.type=laya" },
|
||||
engine_env(), &log, 300);
|
||||
if (st != 0) fprintf(stderr, " rad-convert exited %d:\n%s\n", st, tail(log).c_str());
|
||||
REQUIRE_EQ(st, 0);
|
||||
CHECK(log.find("encoder 3 x 64, head 2 layers, max_len 128, head_max_len 48") != std::string::npos);
|
||||
|
||||
std::ifstream gf(RAD_LAYA_GOLDEN);
|
||||
if (!gf.is_open())
|
||||
fprintf(stderr, " no golden at %s: run this test with RAD_E2E_KEEP=1, then "
|
||||
"tests/mklayagolden.py on the kept directory\n", RAD_LAYA_GOLDEN);
|
||||
REQUIRE(gf.is_open());
|
||||
const json gold = json::parse(gf);
|
||||
const std::string wf = hex16(fnv1a(ck + "/model.safetensors"));
|
||||
if (gold["weights_fnv"] != wf)
|
||||
fprintf(stderr, " the golden was made from other weights (%s here): regenerate it with "
|
||||
"tests/mklayagolden.py\n", wf.c_str());
|
||||
REQUIRE(gold["weights_fnv"] == wf);
|
||||
|
||||
Server s;
|
||||
REQUIRE(s.start(rad, { "--max-num-seqs", "4", "--max-num-batched-tokens", "512" }));
|
||||
int status = 0;
|
||||
const json models = call(s.port, "GET", "/v1/models", json(), &status);
|
||||
CHECK_EQ(status, 200);
|
||||
CHECK(models["data"][0]["capabilities"]["decision"] == "laya");
|
||||
CHECK(models["data"][0]["capabilities"]["embedding"] == false);
|
||||
|
||||
double worst = 0.0;
|
||||
for (size_t i = 0; i < gold["requests"].size(); ++i) {
|
||||
const json& req = gold["requests"][i];
|
||||
const json& want = gold["results"][i];
|
||||
const json a = call(s.port, "POST", "/v1/systemone", req, &status);
|
||||
if (status != 200) fprintf(stderr, " %s\n%s\n", a.dump().c_str(), tail(s.output()).c_str());
|
||||
REQUIRE_EQ(status, 200);
|
||||
/* The sequences and the cut are the package's to the token. */
|
||||
for (const char* k : { "input_tokens", "output_tokens", "state_tokens", "state_tokens_dropped",
|
||||
"truncated", "truncated_questions" }) {
|
||||
if (a["usage"][k] != want["usage"][k])
|
||||
fprintf(stderr, " request %zu: usage.%s %s, the package's %s\n", i, k,
|
||||
a["usage"][k].dump().c_str(), want["usage"][k].dump().c_str());
|
||||
CHECK(a["usage"][k] == want["usage"][k]);
|
||||
}
|
||||
bool agree = true;
|
||||
const double w = compare(a["answers"], want["answers"], &agree);
|
||||
fprintf(stderr, " request %zu: largest difference from the package %.4f\n", i, w);
|
||||
CHECK(agree);
|
||||
worst = std::max(worst, w);
|
||||
/* The same request again: no cache, the same step, the same answer. */
|
||||
const json b = call(s.port, "POST", "/v1/decisions", req, &status);
|
||||
CHECK_EQ(status, 200);
|
||||
CHECK(b["answers"] == a["answers"]);
|
||||
}
|
||||
CHECK(worst < 0.03);
|
||||
|
||||
/* The refusals. */
|
||||
json base = gold["requests"][0];
|
||||
json many = base;
|
||||
many["questions"] = { { "q", { { "type", "choice" }, { "instructions", "x" }, { "criteria", json::array() } } } };
|
||||
for (int i = 0; i <= RAD_LAYA_MAX_OPTIONS; ++i) many["questions"]["q"]["criteria"].push_back("o" + std::to_string(i));
|
||||
call(s.port, "POST", "/v1/systemone", many, &status);
|
||||
CHECK_EQ(status, 400);
|
||||
json empty = base;
|
||||
empty["state"] = "";
|
||||
call(s.port, "POST", "/v1/systemone", empty, &status);
|
||||
CHECK_EQ(status, 400);
|
||||
json img = base;
|
||||
img["images"] = json::array({ "data:image/png;base64,AAAA" });
|
||||
call(s.port, "POST", "/v1/systemone", img, &status);
|
||||
CHECK_EQ(status, 501);
|
||||
call(s.port, "POST", "/v1/embeddings", json{ { "input", "hello" } }, &status);
|
||||
CHECK_EQ(status, 501);
|
||||
|
||||
CHECK_EQ(s.stop(), 0);
|
||||
}
|
||||
|
||||
/* The checkpoint names its own type, so --set is optional; a checkpoint that is not Laya's is
|
||||
* refused by name. */
|
||||
TEST(a_laya_checkpoint_converts_without_flags_and_another_is_refused) {
|
||||
tiny::TempDir dir{ "laya" };
|
||||
REQUIRE(dir.ok());
|
||||
const std::string ck = dir / "laya-tiny";
|
||||
REQUIRE_EQ(mkdir(ck.c_str(), 0755), 0);
|
||||
REQUIRE(write_tiny_laya(ck, 11));
|
||||
std::string log;
|
||||
CHECK_EQ(tiny::run({ RAD_E2E_CONVERT, ck, "-o", dir / "plain.rad" }, engine_env(), &log, 300), 0);
|
||||
CHECK(log.find("laya ") != std::string::npos);
|
||||
|
||||
const std::string other = dir / "qwen";
|
||||
REQUIRE_EQ(mkdir(other.c_str(), 0755), 0);
|
||||
REQUIRE(tiny::write_qwen35(other, tiny::Qwen35{}));
|
||||
log.clear();
|
||||
CHECK(tiny::run({ RAD_E2E_CONVERT, other, "-o", dir / "no.rad", "--set", "decision.type=laya" },
|
||||
engine_env(), &log, 300) != 0);
|
||||
CHECK(log.find("model_type laya") != std::string::npos);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -0,0 +1,237 @@
|
||||
/* laya_test.cpp -- Laya's sequences, words and answers (core/server/laya.h).
|
||||
*
|
||||
* A byte tokenizer makes every piece of a sequence decode back to its exact text, so the layout
|
||||
* build_head and build_sequence produce is checked as text: [CLS], "<type> question: ...", [SEP],
|
||||
* each option behind its [MASK], [SEP], the state, [SEP]. The state cut, the option budget, the
|
||||
* refusals and the answer arithmetic (temperature bucket and clamp, softmax, confidence) follow
|
||||
* laya's own common.py and agent.py; tests/laya_decision_test.cpp checks the whole path against
|
||||
* the package's Agent.predict.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
#include "server/laya.h"
|
||||
#include "text/tokenizer.h"
|
||||
|
||||
#include "rad_laya.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <cmath>
|
||||
|
||||
using namespace rad;
|
||||
using namespace rad::server;
|
||||
|
||||
namespace {
|
||||
|
||||
enum : int32_t { kCls = 1000, kSep = 1001, kMask = 1002 };
|
||||
|
||||
/* One id a byte; the specials above the bytes. */
|
||||
struct ByteTokenizer : ITokenizer {
|
||||
std::vector<int32_t> encode(const std::string& s, bool, bool) const override {
|
||||
std::vector<int32_t> v;
|
||||
for (unsigned char c : s) v.push_back(c);
|
||||
return v;
|
||||
}
|
||||
std::string token_bytes(int32_t id) const override { return std::string(1, (char)id); }
|
||||
std::string decode(const std::vector<int32_t>& t) const override {
|
||||
std::string s;
|
||||
for (int32_t x : t) s += x == kCls ? "<CLS>" : x == kSep ? "<SEP>" : x == kMask ? "<MASK>" : std::string(1, (char)x);
|
||||
return s;
|
||||
}
|
||||
int32_t eos() const override { return 0; }
|
||||
int32_t bos() const override { return -1; }
|
||||
std::unique_ptr<IDetokenizer> detokenizer(const std::vector<std::string>&,
|
||||
const std::vector<std::string>&) const override {
|
||||
return nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
LayaSettings settings(int64_t max_len = 512, int64_t head_max_len = 192) {
|
||||
LayaSettings s;
|
||||
s.max_len = max_len;
|
||||
s.head_max_len = head_max_len;
|
||||
s.cls = kCls;
|
||||
s.sep = kSep;
|
||||
s.mask = kMask;
|
||||
s.mask_token = "[MASK]";
|
||||
return s;
|
||||
}
|
||||
|
||||
int parse(const std::string& body, LayaRequest* r, ApiError* e, const LayaSettings& s = settings()) {
|
||||
static ByteTokenizer tok;
|
||||
OaiDeps d;
|
||||
d.tok = &tok;
|
||||
OaiLimits l;
|
||||
l.model_id = "laya";
|
||||
return parse_laya_request(body, d, l, "laya", s, r, e);
|
||||
}
|
||||
|
||||
std::string text(const LayaQuestion& q) { return ByteTokenizer().decode(q.tokens); }
|
||||
|
||||
} /* namespace */
|
||||
|
||||
TEST(laya_render_is_python_json_dumps_with_the_request_order_kept) {
|
||||
const json v = json::parse(R"({"b": [1, 2.5, "x", null], "a": {"é": true, "q": "say \"hi\"\n"}})");
|
||||
CHECK_EQ(laya_render(v), std::string(R"({"b": [1, 2.5, "x", null], "a": {"é": true, "q": "say \"hi\"\n"}})"));
|
||||
CHECK_EQ(laya_render(json::parse("[]")), std::string("[]"));
|
||||
CHECK_EQ(laya_render(json::parse("{}")), std::string("{}"));
|
||||
CHECK_EQ(laya_render(json::parse("1.0")), std::string("1.0"));
|
||||
}
|
||||
|
||||
TEST(each_question_is_its_own_sequence_with_the_state_after_its_options) {
|
||||
LayaRequest r;
|
||||
ApiError e;
|
||||
CHECK_EQ(parse(R"({"state": "Charged [MASK] twice.", "questions": {
|
||||
"team": {"type": "choice", "instructions": "Which team?",
|
||||
"criteria": {"billing": "Charges", "tech": "", "other": null}},
|
||||
"level": {"type": "score", "instructions": {"ask": "How urgent?"}, "criteria": ["Low", {"x": 1}]},
|
||||
"refund": {"type": "noul", "instructions": "Refund?", "criteria": {"True": "asks for money"}}}})",
|
||||
&r, &e), RAD_OK);
|
||||
CHECK_EQ(r.questions.size(), (size_t)3);
|
||||
CHECK_EQ(r.state_tokens, (int64_t)std::string("Charged twice.").size());
|
||||
const LayaQuestion& t = r.questions[0];
|
||||
CHECK_EQ(text(t), std::string("<CLS>choice question: Which team?<SEP><MASK> billing: Charges"
|
||||
"<MASK> tech<MASK> other<SEP>Charged twice.<SEP>"));
|
||||
CHECK_EQ(t.type_id, (int)RAD_LAYA_CHOICE);
|
||||
CHECK_EQ(t.markers.size(), (size_t)3);
|
||||
for (int32_t m : t.markers) CHECK_EQ(t.tokens[(size_t)m], (int32_t)kMask);
|
||||
CHECK(t.keys == std::vector<std::string>({ "billing", "tech", "other" }));
|
||||
const LayaQuestion& l = r.questions[1];
|
||||
CHECK_EQ(text(l), std::string("<CLS>score question: {\"ask\": \"How urgent?\"}<SEP><MASK> level 0: Low"
|
||||
"<MASK> level 1: {\"x\": 1}<SEP>Charged twice.<SEP>"));
|
||||
CHECK(l.legend == std::vector<std::string>({ "Low", "{\"x\": 1}" }));
|
||||
const LayaQuestion& n = r.questions[2];
|
||||
CHECK_EQ(text(n), std::string("<CLS>noul question: Refund?<SEP><MASK> false: no, the statement does "
|
||||
"not hold<MASK> true: asks for money<SEP>Charged twice.<SEP>"));
|
||||
CHECK(n.keys == std::vector<std::string>({ "false", "true" }));
|
||||
|
||||
const std::vector<int32_t> w = laya_words(t);
|
||||
CHECK_EQ(w.size(), (size_t)RAD_LAYA_W_MARKERS + 3);
|
||||
CHECK_EQ(w[RAD_LAYA_W_N], (int32_t)t.tokens.size());
|
||||
CHECK_EQ(w[RAD_LAYA_W_TYPE], (int32_t)RAD_LAYA_CHOICE);
|
||||
CHECK_EQ(w[RAD_LAYA_W_K], 3);
|
||||
CHECK_EQ(w[RAD_LAYA_W_MARKERS + 2], t.markers[2]);
|
||||
|
||||
const json u = laya_usage(r);
|
||||
CHECK_EQ(u["input_tokens"].get<int64_t>(),
|
||||
(int64_t)(t.tokens.size() + l.tokens.size() + n.tokens.size()));
|
||||
CHECK(u["truncated"] == false);
|
||||
CHECK_EQ(u["state_tokens_dropped"].get<int64_t>(), (int64_t)0);
|
||||
CHECK(u["truncated_questions"].empty());
|
||||
}
|
||||
|
||||
TEST(a_long_state_is_cut_to_the_room_its_question_leaves_and_usage_says_so) {
|
||||
LayaRequest r;
|
||||
ApiError e;
|
||||
std::string state(200, 'a');
|
||||
state += "END";
|
||||
const std::string q = R"(, "questions": {"q": {"type": "noul", "instructions": "Ok?"}}})";
|
||||
CHECK_EQ(parse("{\"state\": \"" + state + "\"" + q, &r, &e, settings(128, 64)), RAD_OK);
|
||||
const LayaQuestion& a = r.questions[0];
|
||||
CHECK_EQ(a.tokens.size(), (size_t)128);
|
||||
CHECK_EQ(a.tokens.back(), (int32_t)kSep);
|
||||
CHECK_EQ(a.tokens[a.tokens.size() - 2], (int32_t)'a'); /* the start is kept */
|
||||
const json u = laya_usage(r);
|
||||
CHECK(u["truncated"] == true);
|
||||
CHECK_EQ(u["state_tokens"].get<int64_t>(), (int64_t)state.size());
|
||||
CHECK_EQ(u["state_tokens_dropped"].get<int64_t>(), (int64_t)state.size() - a.state_used);
|
||||
CHECK(u["truncated_questions"] == json::array({ "q" }));
|
||||
|
||||
/* A list of turns keeps its end. */
|
||||
CHECK_EQ(parse("{\"state\": [\"" + state + "\"]" + q, &r, &e, settings(128, 64)), RAD_OK);
|
||||
const std::string s = text(r.questions[0]);
|
||||
CHECK(s.size() > 11 && s.substr(s.size() - 11) == "aEND\"]<SEP>");
|
||||
}
|
||||
|
||||
TEST(many_options_share_the_head_budget_and_too_many_are_refused) {
|
||||
LayaRequest r;
|
||||
ApiError e;
|
||||
/* Fifteen options of ~44 bytes leave fewer than 16 of 64: each is cut to
|
||||
* max(4, (64 - 16) / 15) = 4, and the instruction keeps max(8, 64 - 60) = 8 tokens. */
|
||||
json c = json::object();
|
||||
for (int i = 0; i < 15; ++i) c["option number " + std::to_string(i)] = "a fairly long description";
|
||||
json body = { { "state", "s" }, { "questions", { { "q", { { "type", "choice" }, { "instructions", "Which?" },
|
||||
{ "criteria", c } } } } } };
|
||||
CHECK_EQ(parse(body.dump(), &r, &e, settings(512, 64)), RAD_OK);
|
||||
const LayaQuestion& q = r.questions[0];
|
||||
for (size_t i = 0; i + 1 < q.markers.size(); ++i) CHECK_EQ(q.markers[i + 1] - q.markers[i], 4);
|
||||
CHECK_EQ(text(q).substr(0, 18), std::string("<CLS>choice q<SEP>"));
|
||||
/* Options past the sequence are refused, not answered with fewer options. */
|
||||
CHECK(parse(body.dump(), &r, &e, settings(24, 64)) < 0);
|
||||
CHECK_EQ(e.status, 400);
|
||||
}
|
||||
|
||||
TEST(what_the_package_refuses_is_a_400_and_images_are_a_501) {
|
||||
LayaRequest r;
|
||||
ApiError e;
|
||||
const char* bad[] = {
|
||||
R"({"questions": {"q": {"type": "noul", "instructions": "x"}}})",
|
||||
R"({"state": "", "questions": {"q": {"type": "noul", "instructions": "x"}}})",
|
||||
R"({"state": "s", "questions": {}})",
|
||||
R"({"state": "s", "questions": {"q": {"type": "rank", "instructions": "x"}}})",
|
||||
R"({"state": "s", "questions": {"q": {"type": "noul", "instructions": " "}}})",
|
||||
R"({"state": "s", "questions": {"q": {"type": "choice", "instructions": "x", "criteria": []}}})",
|
||||
R"({"state": "s", "questions": {"q": {"type": "choice", "instructions": "x", "criteria": [1, 1.0]}}})",
|
||||
R"({"state": "s", "questions": {"q": {"type": "choice", "instructions": "x", "criteria": ["a", null]}}})",
|
||||
R"({"state": "s", "questions": {"q": {"type": "score", "instructions": "x", "criteria": ["a", null]}}})",
|
||||
R"({"state": "s", "questions": {"q": {"type": "noul", "instructions": "x", "criteria": {"maybe": "?"}}}})",
|
||||
R"({"state": "s", "questions": {"q": {"type": "noul", "instructions": "x", "labels": {}}}})",
|
||||
R"({"state": "s", "questions": {" ": {"type": "noul", "instructions": "x"}}})",
|
||||
};
|
||||
for (const char* b : bad) {
|
||||
e = ApiError{};
|
||||
CHECK(parse(b, &r, &e) < 0);
|
||||
CHECK_EQ(e.status, 400);
|
||||
}
|
||||
CHECK(parse(R"({"state": "s", "images": ["data:image/png;base64,AA"], "questions": {"q": {"type": "noul", "instructions": "x"}}})",
|
||||
&r, &e) < 0);
|
||||
CHECK_EQ(e.status, 501);
|
||||
}
|
||||
|
||||
TEST(the_answer_is_the_packages_softmax_rounding_and_confidence) {
|
||||
LayaRequest r;
|
||||
ApiError e;
|
||||
CHECK_EQ(parse(R"({"state": "s", "questions": {
|
||||
"c": {"type": "choice", "instructions": "x", "criteria": [1, 2.5, false]},
|
||||
"s": {"type": "score", "instructions": "x", "criteria": ["lo", "mid", "hi"]},
|
||||
"n": {"type": "noul", "instructions": "x"}}})", &r, &e), RAD_OK);
|
||||
LayaSettings s = settings();
|
||||
s.temperature[RAD_LAYA_CHOICE] = 9.0; /* clamped to 5 */
|
||||
s.temperature_by_options["score:3-5"] = 0.1; /* clamped to 0.5 */
|
||||
s.temperature[RAD_LAYA_NOUL] = 2.0;
|
||||
auto softmax = [](std::vector<double> z) {
|
||||
double m = *std::max_element(z.begin(), z.end()), t = 0;
|
||||
for (double& v : z) t += (v = std::exp(v - m));
|
||||
for (double& v : z) v /= t;
|
||||
return z;
|
||||
};
|
||||
auto conf = [](const std::vector<double>& p) {
|
||||
double h = 0;
|
||||
for (double v : p) h -= v * std::log(v);
|
||||
return 1.0 - h / std::log((double)p.size());
|
||||
};
|
||||
auto near = [](double a, double b) { return std::fabs(a - b) < 1.5e-4; };
|
||||
|
||||
json a;
|
||||
CHECK_EQ(laya_answer(r.questions[0], { 3.0f, 1.0f, 0.0f, -1e4f }, s, &a, &e), RAD_OK);
|
||||
const std::vector<double> pc = softmax({ 3.0 / 5, 1.0 / 5, 0.0 });
|
||||
CHECK(a["choice"] == 1);
|
||||
CHECK(near(a["probabilities"]["1"].get<double>(), pc[0]));
|
||||
CHECK(near(a["probabilities"]["2.5"].get<double>(), pc[1]));
|
||||
CHECK(near(a["probabilities"]["false"].get<double>(), pc[2]));
|
||||
CHECK(near(a["confidence"].get<double>(), conf(pc)));
|
||||
CHECK(text(r.questions[0]).find("<MASK> 2.5<MASK> False<SEP>") != std::string::npos);
|
||||
|
||||
CHECK_EQ(laya_answer(r.questions[1], { 0.0f, 0.5f, 0.25f }, s, &a, &e), RAD_OK);
|
||||
const std::vector<double> ps = softmax({ 0.0, 1.0, 0.5 });
|
||||
CHECK(near(a["score"].get<double>(), ps[1] + 2 * ps[2]));
|
||||
CHECK(near(a["confidence"].get<double>(), conf(ps)));
|
||||
CHECK(a["legend"] == json::parse(R"({"0": "lo", "1": "mid", "2": "hi"})"));
|
||||
|
||||
CHECK_EQ(laya_answer(r.questions[2], { -1.0f, 1.0f }, s, &a, &e), RAD_OK);
|
||||
CHECK(near(a["noul"].get<double>(), softmax({ -0.5, 0.5 })[1]));
|
||||
CHECK(!a.contains("confidence"));
|
||||
|
||||
CHECK(laya_answer(r.questions[2], { NAN, 1.0f }, s, &a, &e) < 0);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -0,0 +1,66 @@
|
||||
"""mklayagolden.py CKPTDIR OUT.json -- the golden for tests/laya_decision_test.cpp: laya's own
|
||||
Agent.predict (the package in LAYA_SRC, a checkout of github.com/NandhaKishorM/laya) on the tiny
|
||||
Laya the test writes, on the CPU in float32, for the requests below.
|
||||
|
||||
CKPTDIR is the tiny Laya's directory as the test keeps it: run `RAD_E2E_KEEP=1
|
||||
build/tests/laya_decision_test` and pass the directory it prints. The golden records the FNV-1a hash
|
||||
of model.safetensors (the test refuses a golden made from other weights), the package's commit
|
||||
(LAYA_COMMIT), each request, and the package's answers and usage for it.
|
||||
|
||||
The three requests: one whose state fits every question's sequence; one whose JSON-object state
|
||||
is cut to the room each question leaves, with a 12-option choice (the 11+ temperature bucket,
|
||||
whose fitted 0.1 the package clamps to 0.5); one whose state is a list of turns, which keeps its
|
||||
end."""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
ckpt_dir, out = sys.argv[1], sys.argv[2]
|
||||
sys.path.insert(0, os.environ["LAYA_SRC"])
|
||||
from laya.agent import Agent # noqa: E402
|
||||
|
||||
LONG = ("The parcel arrived two weeks late and the box was crushed, but the vase inside was "
|
||||
"intact. I would like a partial refund for the delay, and please tell the courier.")
|
||||
REQUESTS = [
|
||||
{"state": "Charged twice for one order; refund one please.",
|
||||
"questions": {
|
||||
"refund": {"type": "noul", "instructions": "Does the customer ask for money back?"},
|
||||
"team": {"type": "choice", "instructions": "Which team should take this?",
|
||||
"criteria": {"billing": "Charges and refunds", "shipping": "Delivery",
|
||||
"product": ""}},
|
||||
"tone": {"type": "score", "instructions": "How upset is the customer?",
|
||||
"criteria": ["Calm", "Mildly annoyed", "Angry"]}}},
|
||||
{"state": {"message": LONG, "channel": "email"},
|
||||
"questions": {
|
||||
"topic": {"type": "choice", "instructions": "Topic?",
|
||||
"criteria": ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"]},
|
||||
"spam": {"type": "noul", "instructions": {"ask": "Is this unsolicited?"},
|
||||
"criteria": {"true": "unsolicited bulk mail"}},
|
||||
"team": {"type": "choice", "instructions": "Route it.",
|
||||
"criteria": ["billing", "technical", "sales", "other"]}}},
|
||||
{"state": [{"role": "user", "content": LONG}, {"role": "agent", "content": "Sorry, checking."},
|
||||
{"role": "user", "content": "Any news on the refund?"}],
|
||||
"questions": {
|
||||
"waiting": {"type": "noul", "instructions": "Is the customer still waiting?"}}},
|
||||
]
|
||||
|
||||
|
||||
def fnv(path):
|
||||
h = 0xcbf29ce484222325
|
||||
for b in open(path, "rb").read():
|
||||
h = ((h ^ b) * 0x100000001b3) & (2**64 - 1)
|
||||
return h
|
||||
|
||||
|
||||
agent = Agent(ckpt_dir, device="cpu")
|
||||
results = [agent.predict(r["state"], r["questions"]) for r in REQUESTS]
|
||||
golden = {
|
||||
"weights_fnv": "%016x" % fnv(os.path.join(ckpt_dir, "model.safetensors")),
|
||||
"laya_commit": os.environ.get("LAYA_COMMIT", ""),
|
||||
"requests": REQUESTS,
|
||||
"results": [{"answers": r["answers"], "usage": r["usage"]} for r in results],
|
||||
}
|
||||
with open(out, "w") as f:
|
||||
json.dump(golden, f, indent=1, ensure_ascii=False)
|
||||
f.write("\n")
|
||||
print(json.dumps([r["usage"] for r in results]))
|
||||
@@ -96,7 +96,7 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) {
|
||||
{ "gemma3", "" }, { "gemma4", "" },
|
||||
{ "gemma4", "compressed-tensors" }, { "glm5next", "" },
|
||||
{ "hyv3", "" }, { "hyv3", "fp8" }, { "hyv3", "gguf_ftype_15" },
|
||||
{ "lfm2", "" }, { "llama", "" },
|
||||
{ "laya", "" }, { "lfm2", "" }, { "llama", "" },
|
||||
{ "llama", "fp8_e4m3" }, { "nomicbert", "" }, { "qwen35", "" },
|
||||
{ "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" },
|
||||
{ "qwen3asr", "" }, { "krea2", "" }, { "ltx2", "" }, { "minimaxh3", "" },
|
||||
|
||||
Reference in new issue
Block a user