Skip to content

armgit / laya

Public Imported from GitHub
0

Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.

feat(cpp): decode, collate, infer::Session seam and the agent core

Adeshina Lasisi18e592ed2198
diff --git a/.github/workflows/cpp.yml b/.github/workflows/cpp.yml
index b23b7eb7..4036563d 100644
--- a/.github/workflows/cpp.yml
+++ b/.github/workflows/cpp.yml
@@ -42,7 +42,7 @@ concurrency:
env:
# The test floor: the number of ctest tests laya-cpp registers (the GoogleTest cases plus
# compile_flags). Raise it with every test added.
- MIN_TESTS: "365"
+ MIN_TESTS: "409"
GOLDENS: ${{ github.workspace }}/.cpp-goldens
LAYA_GOLDENS: ${{ github.workspace }}/.cpp-goldens
LAYA_CHECKPOINTS: ${{ github.workspace }}/laya-java/.work/checkpoints # the tokenizer tests need both shipped checkpoints
@@ -93,7 +93,7 @@ jobs:
LAYA_FIXTURE_CHECKPOINTS: ${{ github.workspace }}/laya-java/.work/checkpoints
PYTHONPATH: ${{ github.workspace }}
run: |
- python laya-java/scripts/gen_fixtures.py --strict --out "$GOLDENS" --only lang_tables.json --only lang_detect.json --only python_json.json --only tokenizer_ids.json --only decode_text.json --only sequences.json --only window_plan.json
+ python laya-java/scripts/gen_fixtures.py --strict --out "$GOLDENS" --only lang_tables.json --only lang_detect.json --only python_json.json --only tokenizer_ids.json --only decode_text.json --only sequences.json --only window_plan.json --only decode.json
python laya-go/scripts/gen_go_fixtures.py --out "$GOLDENS"
- name: Compiled C++ tables match CPython
env:
diff --git a/laya-cpp/CMakeLists.txt b/laya-cpp/CMakeLists.txt
index f76be6e7..ff41f10f 100644
--- a/laya-cpp/CMakeLists.txt
+++ b/laya-cpp/CMakeLists.txt
@@ -26,7 +26,7 @@ function(laya_target_flags target)
endfunction()
add_library(laya src/version.cpp src/sha256.cpp src/unicodedata.cpp src/pyjson.cpp src/pyvalue.cpp src/lang.cpp
- src/tokenizer.cpp src/schema.cpp src/sequence.cpp)
+ src/tokenizer.cpp src/schema.cpp src/sequence.cpp src/decode.cpp src/infer.cpp src/collate.cpp src/agent.cpp)
target_include_directories(laya PUBLIC include)
laya_target_flags(laya)
@@ -46,7 +46,7 @@ if(LAYA_BUILD_TESTS)
enable_testing()
add_executable(laya_tests tests/version_test.cpp tests/foundation_test.cpp tests/lang_test.cpp tests/hardening_test.cpp
- tests/tokenizer_test.cpp tests/schema_test.cpp tests/sequence_test.cpp)
+ tests/tokenizer_test.cpp tests/schema_test.cpp tests/sequence_test.cpp tests/decode_test.cpp tests/agent_test.cpp)
target_link_libraries(laya_tests PRIVATE laya GTest::gtest_main)
laya_target_flags(laya_tests)
diff --git a/laya-cpp/include/laya/agent.hpp b/laya-cpp/include/laya/agent.hpp
new file mode 100644
index 00000000..ac30a4fe
--- /dev/null
+++ b/laya-cpp/include/laya/agent.hpp
@@ -0,0 +1,109 @@
+#pragma once
+// The agent core (laya-go/agent): Open a checkpoint directory over a model Session, then Predict or
+// PredictBatch states against a question set. Hooks, the confidence gate, predict_long, calibration
+// and digests are later changes.
+//
+// Errors are returned as Result<T>; no exception crosses this API. An Agent is safe for concurrent
+// use: any number of threads may call Predict while another calls Close, which waits for the calls
+// in flight and then closes the Session.
+#include <atomic>
+#include <condition_variable>
+#include <cstdint>
+#include <memory>
+#include <mutex>
+#include <string>
+#include <vector>
+
+#include "laya/cancel.hpp"
+#include "laya/decode.hpp"
+#include "laya/infer.hpp"
+#include "laya/pyvalue.hpp"
+#include "laya/result.hpp"
+#include "laya/schema.hpp"
+#include "laya/sequence.hpp"
+#include "laya/tokenizer.hpp"
+
+namespace laya {
+namespace agent {
+
+// The text of the errors a caller may want to tell apart; test with IsClosed and IsCancelled.
+extern const char* const kClosed;
+extern const char* const kCancelled;
+bool IsClosed(const std::string& error);
+bool IsCancelled(const std::string& error);
+
+// Bounds on what one call may be given.
+constexpr int64_t kMaxStates = int64_t(1) << 20;
+constexpr int64_t kMaxSequenceLength = int64_t(1) << 20; // max_len and head_max_len
+
+// rl_agent_config.json, as far as the agent reads it.
+struct Config {
+ int64_t max_len = 512;
+ int64_t head_max_len = 192;
+ std::string option_layout = "sequential";
+ std::vector<std::string> warnings; // e.g. temperatures clamped into range
+};
+
+// Per-call settings. Zero values mean the defaults.
+struct CallOptions {
+ std::string lang; // language tag selecting a temperature override
+ int64_t batch_size = 0; // states per session run; <= 0 runs all states at once
+ bool sort_by_length = false; // group similar lengths per run; results stay in input order
+ int64_t max_len = 0; // > 0 overrides the checkpoint's
+ int64_t head_max_len = 0; // > 0 overrides the checkpoint's
+ CancelToken cancel; // checked between states and runs, and passed to the Session
+};
+
+class Agent {
+ public:
+ // checkpoint_dir holds rl_agent_config.json and the tokenizer. Takes ownership of the session; on
+ // failure the session is closed and destroyed.
+ static Result<std::unique_ptr<Agent>> Open(const std::string& checkpoint_dir, std::unique_ptr<infer::Session> session);
+ // From files already read: the config text and a loaded tokenizer.
+ static Result<std::unique_ptr<Agent>> OpenParts(std::string_view config_json, tokenizer::Tokenizer tok,
+ std::unique_ptr<infer::Session> session);
+ Agent(const Agent&) = delete;
+ Agent& operator=(const Agent&) = delete;
+ ~Agent();
+
+ const Config& config() const { return cfg_; }
+
+ // A state is a string, a list or an object (what the Python agent accepts).
+ Result<schema::Prediction> Predict(const pyvalue::Value& state, const schema::Questions& qs,
+ const CallOptions& opts = {}) const;
+ // One prediction per state, in input order whatever the batching and sorting.
+ Result<std::vector<schema::Prediction>> PredictBatch(const std::vector<pyvalue::Value>& states,
+ const schema::Questions& qs,
+ const CallOptions& opts = {}) const;
+ // Waits for the calls in flight, then closes the session. Idempotent; later calls fail with kClosed.
+ // Returns the session's close error, "" on success.
+ std::string Close();
+
+ private:
+ Agent() = default;
+ using Encoded = std::vector<std::vector<sequence::Sequence>>; // [state][question]
+ Result<std::vector<schema::Prediction>> Chunks(const std::vector<pyvalue::Value>& states, const schema::Questions& qs,
+ const CallOptions& c) const;
+ Result<std::vector<sequence::Sequence>> Encode(const pyvalue::Value& state, const schema::Questions& qs, const CallOptions& c) const;
+ Result<std::vector<schema::Prediction>> Run(const schema::Questions& qs, const Encoded& encoded,
+ const std::vector<size_t>& idx, const CallOptions& c) const;
+ bool Enter() const;
+ void Leave() const;
+
+ tokenizer::Tokenizer tok_;
+ int32_t pad_id_ = 0;
+ Config cfg_;
+ decode::Temperatures temps_;
+ std::unique_ptr<infer::Session> sess_;
+
+ mutable std::mutex mu_;
+ mutable std::condition_variable cv_;
+ mutable int64_t inflight_ = 0;
+ bool shut_ = false;
+ bool close_done_ = false;
+ std::string close_err_;
+ std::atomic<bool> closed_{false};
+};
+
+} // namespace agent
+} // namespace laya
diff --git a/laya-cpp/include/laya/cancel.hpp b/laya-cpp/include/laya/cancel.hpp
new file mode 100644
index 00000000..18e06064
--- /dev/null
+++ b/laya-cpp/include/laya/cancel.hpp
@@ -0,0 +1,26 @@
+#pragma once
+// A cancellation token. Copies share one flag, so the caller keeps a copy and cancels it from any
+// thread while a call holds another. A default token can never be cancelled.
+#include <atomic>
+#include <memory>
+
+namespace laya {
+
+class CancelToken {
+ public:
+ CancelToken() = default;
+ static CancelToken Make() {
+ CancelToken t;
+ t.flag_ = std::make_shared<std::atomic<bool>>(false);
+ return t;
+ }
+ void Cancel() const {
+ if (flag_) flag_->store(true, std::memory_order_release);
+ }
+ bool cancelled() const { return flag_ && flag_->load(std::memory_order_acquire); }
+
+ private:
+ std::shared_ptr<std::atomic<bool>> flag_;
+};
+
+} // namespace laya
diff --git a/laya-cpp/include/laya/collate.hpp b/laya-cpp/include/laya/collate.hpp
new file mode 100644
index 00000000..f442cd83
--- /dev/null
+++ b/laya-cpp/include/laya/collate.hpp
@@ -0,0 +1,31 @@
+#pragma once
+// Pads built sequences into the rectangular tensors the graph takes (laya-go/internal/collate).
+// One row per question, not per state: four questions about one document are four rows that share
+// a state. Rows are padded to the longest sequence and markers to the most options.
+#include <cstdint>
+#include <vector>
+
+#include "laya/infer.hpp"
+#include "laya/result.hpp"
+#include "laya/schema.hpp"
+
+namespace laya {
+namespace collate {
+
+// The fewest option slots the graph accepts: one-option rows get a masked second slot that
+// decoding never reads.
+constexpr int64_t kMinMarkerSlots = 2;
+
+struct Row {
+ std::vector<int32_t> ids;
+ std::vector<int64_t> markers;
+ schema::Type type = schema::Type::Invalid;
+};
+
+// pad_id is fed to the encoder under a zero mask, so it must be a real vocabulary id. Refuses an
+// empty list, a row with no ids, a row with an invalid type, a marker outside its ids, a negative
+// id, and a batch that would exceed infer::kMaxTensorElements.
+Result<infer::Batch> Collate(const std::vector<Row>& rows, int32_t pad_id);
+
+} // namespace collate
+} // namespace laya
diff --git a/laya-cpp/include/laya/decode.hpp b/laya-cpp/include/laya/decode.hpp
new file mode 100644
index 00000000..d49a11bd
--- /dev/null
+++ b/laya-cpp/include/laya/decode.hpp
@@ -0,0 +1,81 @@
+#pragma once
+// Head logits to typed answers (laya-go/internal/decode, Agent._decode_answers): slice the row to
+// the question's option count, divide by the temperature its bucket names (in float32, as numpy
+// does), softmax with the maximum subtracted, undo the option order, derive the type's fields and
+// round every number to four decimals as Python's round(x, 4) does.
+//
+// Everything after the float32 quotient is double here; Python computes exp and the sum in float32.
+// The choice is the first maximum, so an exact tie falls to the lower index as numpy.argmax does.
+#include <array>
+#include <cstdint>
+#include <map>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <vector>
+
+#include "laya/pyvalue.hpp"
+#include "laya/result.hpp"
+#include "laya/schema.hpp"
+
+namespace laya {
+namespace decode {
+
+// A fitted temperature below 0.5 would sharpen a coin flip into a certainty, so values are clamped.
+constexpr double kTempMin = 0.5;
+constexpr double kTempMax = 5.0;
+
+double Round4(double v); // round(v, 4): half to even on the exact binary value
+// clamp_temperature: v confined to [kTempMin, kTempMax]; 1.0 for a bool, a non-number, NaN or infinity.
+double Clamp(const pyvalue::Value& v);
+// float(s) for a string: surrounding space, Unicode decimal digits, single underscores between digits.
+std::optional<double> PyFloat(std::string_view s);
+// temp_bucket: "<type>:2", ":3-5", ":6-10" or ":11+" by option count.
+std::string Bucket(schema::Type t, int64_t options);
+
+struct Bins {
+ std::vector<double> values; // a confidence c maps to values[min(n-1, max(0, int(c*n)))]
+};
+double ApplyBinning(double confidence, const std::string& bucket, const std::map<std::string, Bins>& m);
+
+struct LanguageTemperatures {
+ std::array<double, 3> by_type{1, 1, 1};
+ std::map<std::string, double> by_options;
+};
+
+// A checkpoint's temperature tables, every value already clamped. Immutable once built.
+class Temperatures {
+ public:
+ Temperatures() = default; // all 1.0
+ // The raw config values, each nullptr when the key is absent. by_type is null or a list of 3;
+ // by_options an object of bucket -> number; by_language an object of tag -> null or
+ // {"temperature": list of 3 or null, "temperature_by_options": object}. When two tags share a
+ // primary subtag the last one listed wins, as in Python (laya-go refuses it).
+ static Result<Temperatures> Of(const pyvalue::Value* by_type, const pyvalue::Value* by_options,
+ const pyvalue::Value* by_language = nullptr);
+ // The temperature for a question of type t with k options, and whether a language override chose it.
+ double For(schema::Type t, int64_t k, std::string_view lang, bool* override_used = nullptr) const;
+ const std::array<double, 3>& by_type() const { return by_type_; }
+ const std::map<std::string, double>& by_options() const { return by_options_; }
+ std::map<std::string, Bins> binning; // empty: no recalibration
+
+ private:
+ std::array<double, 3> by_type_{1, 1, 1};
+ std::map<std::string, double> by_options_;
+ std::map<std::string, LanguageTemperatures> by_language_;
+};
+
+// One question's slice of the graph's outputs.
+struct Row {
+ std::vector<float> logits; // at least k wide; columns past k are ignored
+ int64_t k = 0; // how many option markers the question's sequence kept
+ float act = 0; // the action probability
+};
+
+Result<schema::Answer> Decode(const schema::Question& q, const Row& row, std::string_view lang,
+ const Temperatures* t);
+// softmax of one row of act_logits; the decoder takes probabilities, never the raw logit.
+Result<std::vector<float>> ActionProbabilities(const std::vector<float>& act_logits);
+
+} // namespace decode
+} // namespace laya
diff --git a/laya-cpp/include/laya/infer.hpp b/laya-cpp/include/laya/infer.hpp
new file mode 100644
index 00000000..2e7eb42c
--- /dev/null
+++ b/laya-cpp/include/laya/infer.hpp
@@ -0,0 +1,64 @@
+#pragma once
+// The seam between the agent and a model runtime (laya-go/infer). A Session takes one collated
+// batch of the graph's five inputs and returns its two outputs; the ONNX backend (C5) implements it.
+#include <cstdint>
+#include <string>
+#include <vector>
+
+#include "laya/cancel.hpp"
+#include "laya/result.hpp"
+
+namespace laya {
+namespace infer {
+
+// The graph's tensor names, as an error names them and as a native session binds them.
+extern const char* const kInputIds;
+extern const char* const kAttentionMask;
+extern const char* const kMarkerPos;
+extern const char* const kMarkerMask;
+extern const char* const kQType;
+extern const char* const kLogits;
+extern const char* const kActLogits;
+
+// The most elements any one tensor of a batch may hold: a hostile row count or length is refused
+// before anything is allocated.
+constexpr int64_t kMaxTensorElements = int64_t(1) << 24;
+
+// Each input flattened row-major. A value type: copy or move it freely.
+struct Batch {
+ std::vector<int64_t> input_ids; // [rows*length]; padding is the pad id
+ std::vector<int64_t> attention_mask; // [rows*length]; 1 for real tokens
+ std::vector<int64_t> marker_pos; // [rows*markers]
+ std::vector<uint8_t> marker_mask; // [rows*markers]; 1 for real markers
+ std::vector<int64_t> qtype; // [rows]; 0, 1 or 2
+ int64_t rows = 0, length = 0, markers = 0;
+
+ // Empty when the batch is well formed, else the first problem: negative or oversize dimensions,
+ // fewer than 2 marker slots (the exported head takes topk(2)), a slice whose length does not match,
+ // a marker outside [0, length), a negative token id, a question type outside 0..2.
+ std::string Validate() const;
+};
+
+// Row-major: logits [rows*markers], act_logits [rows*2].
+struct Output {
+ std::vector<float> logits, act_logits;
+ std::string Check(const Batch& b) const; // empty when both hold the lengths b calls for
+};
+
+// Run may be called from several threads at once. Close is idempotent and never runs concurrently
+// with Run (the agent guarantees it). A Session is owned through std::unique_ptr, so it is moved,
+// never copied.
+class Session {
+ public:
+ Session() = default;
+ Session(const Session&) = delete;
+ Session& operator=(const Session&) = delete;
+ virtual ~Session() = default;
+ // Must not modify or retain b. Should return early with an error when cancel fires.
+ virtual Result<Output> Run(const Batch& b, const CancelToken& cancel) = 0;
+ // Releases the runtime; "" on success, else the error. Run after Close fails.
+ virtual std::string Close() = 0;
+};
+
+} // namespace infer
+} // namespace laya
diff --git a/laya-cpp/src/agent.cpp b/laya-cpp/src/agent.cpp
new file mode 100644
index 00000000..28f0c558
--- /dev/null
+++ b/laya-cpp/src/agent.cpp
@@ -0,0 +1,336 @@
+#include "laya/agent.hpp"
+
+#include <algorithm>
+#include <fstream>
+#include <sstream>
+
+#include "laya/collate.hpp"
+#include "laya/unicodedata.hpp"
+
+namespace laya {
+namespace agent {
+
+const char* const kClosed = "agent: agent is closed";
+const char* const kCancelled = "agent: call cancelled";
+
+bool IsClosed(const std::string& e) { return e == kClosed; }
+bool IsCancelled(const std::string& e) { return e == kCancelled; }
+
+namespace {
+
+using pyvalue::Value;
+using Kind = Value::Kind;
+constexpr int64_t kLookaheadBatches = 8;
+const char* const kConfigFile = "rl_agent_config.json";
+
+std::string Num(double d) {
+ std::string s = pyvalue::Repr(Value::Float(d));
+ if (s.size() > 2 && s.compare(s.size() - 2, 2, ".0") == 0) s.resize(s.size() - 2);
+ return s;
+}
+
+// Whether the raw value is exactly what clamp_temperature returned.
+bool SameNumber(const Value& raw, double applied) {
+ switch (raw.kind()) {
+ case Kind::String: {
+ auto f = decode::PyFloat(raw.as_string());
+ return f && *f == applied;
+ }
+ case Kind::Int: return double(raw.as_int()) == applied;
+ case Kind::Float: return raw.as_float() == applied;
+ default: return false; // a bool is no number to clamp_temperature
+ }
+}
+
+Result<int64_t> LengthField(const Value& obj, const char* key, int64_t dflt) {
+ using R = Result<int64_t>;
+ const Value* v = obj.Find(key);
+ if (v == nullptr) return R::Ok(dflt);
+ const std::string name = std::string("agent: ") + kConfigFile + ": " + key + ": ";
+ if (v->kind() == Kind::BigInt && v->big_int().rfind('-', 0) != 0) return R::Fail(name + "too large for an int");
+ if (v->kind() != Kind::Int || v->as_int() <= 0) return R::Fail(name + "want a positive integer, got " + pyvalue::Repr(*v));
+ if (v->as_int() > kMaxSequenceLength) return R::Fail(name + "too large (the limit is " + std::to_string(kMaxSequenceLength) + ")");
+ return R::Ok(v->as_int());
+}
+
+
+} // namespace
+
+Result<std::unique_ptr<Agent>> Agent::Open(const std::string& dir, std::unique_ptr<infer::Session> session) {
+ using R = Result<std::unique_ptr<Agent>>;
+ if (!session) return R::Fail("agent: Open needs a session");
+ std::ifstream in(dir + "/" + kConfigFile, std::ios::binary);
+ if (!in) return R::Fail(std::string("agent: ") + kConfigFile + ": cannot read " + dir + "/" + kConfigFile);
+ std::stringstream ss;
+ ss << in.rdbuf();
+ auto tok = tokenizer::Tokenizer::LoadDir(dir);
+ if (!tok.ok()) return R::Fail("agent: tokenizer: " + tok.error());
+ return OpenParts(ss.str(), std::move(tok).value(), std::move(session));
+}
+
+Result<std::unique_ptr<Agent>> Agent::OpenParts(std::string_view config_json, tokenizer::Tokenizer tok,
+ std::unique_ptr<infer::Session> session) {
+ using R = Result<std::unique_ptr<Agent>>;
+ if (!session) return R::Fail("agent: Open needs a session");
+ const std::string where = std::string("agent: ") + kConfigFile + ": ";
+ auto parsed = pyvalue::Parse(config_json);
+ if (!parsed.ok()) return R::Fail(where + parsed.error());
+ const Value& obj = parsed.value();
+ if (obj.kind() != Kind::Object) return R::Fail(where + "want a JSON object, got " + pyvalue::TypeName(obj));
+ std::unique_ptr<Agent> a(new Agent());
+ if (const Value* l = obj.Find("option_layout")) {
+ if (l->kind() != Kind::String || l->as_string() != "sequential") {
+ return R::Fail(where + "option_layout: option_layout is not supported by the ONNX runtime: " + pyvalue::Repr(*l));
+ }
+ }
+ auto max_len = LengthField(obj, "max_len", 512);
+ if (!max_len.ok()) return R::Fail(max_len.error());
+ auto head_max_len = LengthField(obj, "head_max_len", 192);
+ if (!head_max_len.ok()) return R::Fail(head_max_len.error());
+ a->cfg_.max_len = max_len.value();
+ a->cfg_.head_max_len = head_max_len.value();
+
+ const Value* by_type = obj.Find("temperature");
+ if (by_type != nullptr && by_type->kind() != Kind::Array) {
+ return R::Fail(where + "temperature: want a list of 3 numbers, got " + pyvalue::Repr(*by_type));
+ }
+ const Value* by_options = obj.Find("temperature_by_options");
+ if (by_options != nullptr && by_options->kind() != Kind::Object) {
+ return R::Fail(where + "temperature_by_options: want an object of bucket to number, got " + pyvalue::Repr(*by_options));
+ }
+ auto temps = decode::Temperatures::Of(by_type, by_options);
+ if (!temps.ok()) return R::Fail(where + "temperature: " + temps.error());
+ a->temps_ = std::move(temps).value();
+ std::vector<std::string> rejected;
+ if (by_options != nullptr) {
+ for (size_t i = 0; i < by_options->size(); i++) {
+ const double applied = a->temps_.by_options().at(by_options->key(i));
+ if (!SameNumber(by_options->value(i), applied)) {
+ rejected.push_back(by_options->key(i) + "=" + pyvalue::Repr(by_options->value(i)) + " -> " + Num(applied));
+ }
+ }
+ }
+ if (by_type != nullptr) {
+ for (size_t i = 0; i < by_type->size(); i++) {
+ if (!SameNumber(by_type->items()[i], a->temps_.by_type()[i])) {
+ rejected.push_back("temperature[" + std::to_string(i) + "]=" + pyvalue::Repr(by_type->items()[i]) + " -> " + Num(a->temps_.by_type()[i]));
+ }
+ }
+ }
+ if (!rejected.empty()) {
+ std::string joined;
+ for (size_t i = 0; i < rejected.size(); i++) joined += (i ? ", " : "") + rejected[i];
+ a->cfg_.warnings.push_back("this checkpoint ships temperatures outside [0.5, 5] which would distort confidence; clamping " +
+ joined + ". Treat confidence from the affected buckets as uncalibrated.");
+ }
+
+ const std::optional<int32_t> pad = tok.Pad(), cls = tok.Cls(), sep = tok.Sep(), mask = tok.Mask();
+ if (!pad) return R::Fail("agent: missing special token: no pad token");
+ if (!cls) return R::Fail("agent: missing special token: no CLS token");
+ if (!sep) return R::Fail("agent: missing special token: no SEP token");
+ if (!mask) return R::Fail("agent: missing special token: no mask token");
+ a->pad_id_ = *pad;
+ a->tok_ = std::move(tok);
+ a->sess_ = std::move(session);
+ return R::Ok(std::move(a));
+}
+
+Agent::~Agent() { Close(); }
+
+bool Agent::Enter() const {
+ std::lock_guard<std::mutex> lock(mu_);
+ if (shut_ || !sess_) return false;
+ inflight_++;
+ return true;
+}
+
+void Agent::Leave() const {
+ std::lock_guard<std::mutex> lock(mu_);
+ if (--inflight_ == 0) cv_.notify_all();
+}
+
+std::string Agent::Close() {
+ std::unique_lock<std::mutex> lock(mu_);
+ shut_ = true;
+ closed_.store(true);
+ cv_.wait(lock, [&] { return inflight_ == 0; });
+ if (!close_done_) {
+ close_done_ = true;
+ if (sess_) close_err_ = sess_->Close();
+ }
+ return close_err_;
+}
+
+Result<schema::Prediction> Agent::Predict(const Value& state, const schema::Questions& qs, const CallOptions& opts) const {
+ using R = Result<schema::Prediction>;
+ auto r = PredictBatch(std::vector<Value>{state}, qs, opts);
+ if (!r.ok()) {
+ // The top-level error only: drop the "agent: state 0: " prefix a one-state call has no use for.
+ std::string e = r.error();
+ const std::string prefix = "agent: state 0: ";
+ if (e.compare(0, prefix.size(), prefix) == 0) e = "agent: " + e.substr(prefix.size());
+ return R::Fail(e);
+ }
+ return R::Ok(std::move(r).value()[0]);
+}
+
+Result<std::vector<schema::Prediction>> Agent::PredictBatch(const std::vector<Value>& states, const schema::Questions& qs,
+ const CallOptions& opts) const {
+ using R = Result<std::vector<schema::Prediction>>;
+ if (opts.cancel.cancelled()) return R::Fail(kCancelled);
+ if (int64_t(states.size()) > kMaxStates) {
+ return R::Fail("agent: " + std::to_string(states.size()) + " states in one call, the limit is " + std::to_string(kMaxStates));
+ }
+ if (opts.max_len > kMaxSequenceLength || opts.head_max_len > kMaxSequenceLength) {
+ return R::Fail("agent: max_len and head_max_len are limited to " + std::to_string(kMaxSequenceLength));
+ }
+ if (!Enter()) return R::Fail(kClosed);
+ struct Leaver {
+ const Agent* a;
+ ~Leaver() { a->Leave(); }
+ } leaver{this};
+ for (size_t i = 0; i < states.size(); i++) {
+ if (states[i].is_null()) return R::Fail("agent: state " + std::to_string(i) + ": state is null; pass a string, an object or a list");
+ }
+ if (states.empty()) return R::Ok({});
+ if (qs.size() == 0) {
+ std::vector<schema::Prediction> preds(states.size());
+ return R::Ok(std::move(preds));
+ }
+ return Chunks(states, qs, opts);
+}
+
+Result<std::vector<sequence::Sequence>> Agent::Encode(const Value& state, const schema::Questions& qs, const CallOptions& c) const {
+ using R = Result<std::vector<sequence::Sequence>>;
+ auto st = sequence::EncodeState(tok_, state);
+ if (!st.ok()) return R::Fail(st.error());
+ sequence::Budget budget{cfg_.max_len, cfg_.head_max_len};
+ if (c.max_len > 0) budget.max_len = c.max_len;
+ if (c.head_max_len > 0) budget.head_max_len = c.head_max_len;
+ std::vector<sequence::Sequence> seqs;
+ seqs.reserve(qs.size());
+ for (size_t i = 0; i < qs.size(); i++) {
+ sequence::MarkersError me;
+ auto s = sequence::Build(tok_, qs.at(i).question, st.value(), budget, &me);
+ if (!s.ok()) return R::Fail(me.max_len != 0 ? me.Message(qs.at(i).id) : s.error());
+ seqs.push_back(std::move(s).value());
+ }
+ return R::Ok(std::move(seqs));
+}
+
+Result<std::vector<schema::Prediction>> Agent::Chunks(const std::vector<Value>& states, const schema::Questions& qs,
+ const CallOptions& c) const {
+ using R = Result<std::vector<schema::Prediction>>;
+ const size_t n = states.size();
+ size_t chunk = n;
+ if (c.batch_size > 0) chunk = std::min(size_t(c.batch_size), n);
+ const bool reorder = c.sort_by_length && 1 < chunk && chunk < n;
+ const size_t window = reorder ? chunk * size_t(kLookaheadBatches) : chunk;
+ std::vector<schema::Prediction> results(n);
+ for (size_t start = 0; start < n; start += window) {
+ const size_t len = std::min(window, n - start);
+ Encoded encoded(len);
+ for (size_t i = 0; i < len; i++) {
+ if (c.cancel.cancelled()) return R::Fail(kCancelled);
+ auto e = Encode(states[start + i], qs, c);
+ if (!e.ok()) return R::Fail("agent: state " + std::to_string(start + i) + ": " + e.error());
+ encoded[i] = std::move(e).value();
+ }
+ std::vector<size_t> order(len);
+ for (size_t i = 0; i < len; i++) order[i] = i;
+ if (reorder) {
+ std::vector<size_t> longest(len, 0);
+ for (size_t i = 0; i < len; i++) {
+ for (const auto& s : encoded[i]) longest[i] = std::max(longest[i], s.ids.size());
+ }
+ std::stable_sort(order.begin(), order.end(), [&](size_t x, size_t y) { return longest[x] < longest[y]; });
+ }
+ for (size_t off = 0; off < len; off += chunk) {
+ if (c.cancel.cancelled()) return R::Fail(kCancelled);
+ if (closed_.load()) return R::Fail(kClosed);
+ std::vector<size_t> idx(order.begin() + std::ptrdiff_t(off), order.begin() + std::ptrdiff_t(std::min(off + chunk, len)));
+ auto preds = Run(qs, encoded, idx, c);
+ if (!preds.ok()) return R::Fail(preds.error());
+ for (size_t j = 0; j < idx.size(); j++) results[start + idx[j]] = std::move(preds.value()[j]);
+ }
+ }
+ return R::Ok(std::move(results));
+}
+
+namespace {
+
+schema::Usage UsageOf(const schema::Questions& qs, const std::vector<sequence::Sequence>& seqs, int64_t input_tokens) {
+ schema::Usage u;
+ u.input_tokens = input_tokens;
+ u.state_tokens = seqs[0].truncation.state_tokens;
+ for (size_t i = 0; i < seqs.size(); i++) {
+ const std::string& id = qs.at(i).id;
+ const sequence::Sequence& s = seqs[i];
+ u.state_tokens_dropped = std::max(u.state_tokens_dropped, s.truncation.state_tokens_dropped);
+ if (s.truncation.truncated) u.truncated_questions.push_back(id);
+ if (s.stats.Collapsed()) {
+ schema::CollapsedQuestion c;
+ c.id = id;
+ c.options.total = s.stats.options;
+ c.options.distinct = s.stats.options_distinct;
+ c.options.tokens_per_option = s.stats.tokens_per_option;
+ u.collapsed_options.push_back(std::move(c));
+ }
+ }
+ u.truncated = u.state_tokens_dropped > 0;
+ return u;
+}
+
+} // namespace
+
+Result<std::vector<schema::Prediction>> Agent::Run(const schema::Questions& qs, const Encoded& encoded,
+ const std::vector<size_t>& idx, const CallOptions& c) const {
+ using R = Result<std::vector<schema::Prediction>>;
+ std::vector<collate::Row> rows;
+ rows.reserve(idx.size() * qs.size());
+ for (size_t i : idx) {
+ for (size_t r = 0; r < encoded[i].size(); r++) {
+ rows.push_back({encoded[i][r].ids, encoded[i][r].markers, qs.at(r).question.type()});
+ }
+ }
+ auto batch = collate::Collate(rows, pad_id_);
+ if (!batch.ok()) return R::Fail("agent: " + batch.error());
+ const infer::Batch& b = batch.value();
+ auto fail = [&](const std::string& why) {
+ return R::Fail("agent: running " + std::to_string(b.rows) + " rows of " + std::to_string(b.length) + " tokens with " +
+ std::to_string(b.markers) + " marker slots: " + why);
+ };
+ if (std::string bad = b.Validate(); !bad.empty()) return fail(bad);
+ auto out = sess_->Run(b, c.cancel);
+ if (!out.ok()) return c.cancel.cancelled() ? R::Fail(kCancelled) : fail(out.error());
+ if (std::string bad = out.value().Check(b); !bad.empty()) return fail(bad);
+ const infer::Output& o = out.value();
+
+ std::vector<schema::Prediction> preds(idx.size());
+ size_t row = 0;
+ for (size_t j = 0; j < idx.size(); j++) {
+ const auto& seqs = encoded[idx[j]];
+ int64_t input_tokens = 0;
+ for (size_t r = 0; r < seqs.size(); r++) {
+ const size_t at = row + r;
+ for (int64_t m = 0; m < b.length; m++) input_tokens += b.attention_mask[at * size_t(b.length) + size_t(m)];
+ const auto& e = qs.at(r);
+ auto act = decode::ActionProbabilities({o.act_logits[at * 2], o.act_logits[at * 2 + 1]});
+ if (!act.ok()) return fail("action logits of question " + e.id + ": " + act.error());
+ decode::Row dr;
+ dr.logits.assign(o.logits.begin() + std::ptrdiff_t(at * size_t(b.markers)),
+ o.logits.begin() + std::ptrdiff_t((at + 1) * size_t(b.markers)));
+ dr.k = int64_t(seqs[r].markers.size());
+ dr.act = act.value()[0];
+ auto ans = decode::Decode(e.question, dr, c.lang, &temps_);
+ if (!ans.ok()) return fail("question " + e.id + ": " + ans.error());
+ preds[j].answers.push_back({e.id, std::move(ans).value()});
+ }
+ preds[j].usage = UsageOf(qs, seqs, input_tokens);
+ row += seqs.size();
+ }
+ return R::Ok(std::move(preds));
+}
+
+} // namespace agent
+} // namespace laya
diff --git a/laya-cpp/src/collate.cpp b/laya-cpp/src/collate.cpp
new file mode 100644
index 00000000..82d3794c
--- /dev/null
+++ b/laya-cpp/src/collate.cpp
@@ -0,0 +1,60 @@
+#include "laya/collate.hpp"
+
+#include <algorithm>
+
+namespace laya {
+namespace collate {
+
+Result<infer::Batch> Collate(const std::vector<Row>& rows, int32_t pad_id) {
+ using R = Result<infer::Batch>;
+ if (rows.empty()) return R::Fail("collate: nothing to collate");
+ if (pad_id < 0) return R::Fail("collate: the pad id is negative");
+ int64_t length = 0, width = kMinMarkerSlots;
+ for (size_t i = 0; i < rows.size(); i++) {
+ const Row& r = rows[i];
+ const std::string at = "collate: row " + std::to_string(i);
+ if (r.ids.empty()) return R::Fail(at + " has no token ids");
+ if (schema::Code(r.type) < 0) return R::Fail(at + " has an invalid question type");
+ for (int32_t id : r.ids) {
+ if (id < 0) return R::Fail(at + " has a negative token id");
+ }
+ for (int64_t m : r.markers) {
+ if (m < 0 || m >= int64_t(r.ids.size())) {
+ return R::Fail(at + " has a marker at " + std::to_string(m) + " outside its " + std::to_string(r.ids.size()) + " ids");
+ }
+ }
+ length = std::max(length, int64_t(r.ids.size()));
+ width = std::max(width, int64_t(r.markers.size()));
+ }
+ const int64_t n = int64_t(rows.size());
+ if (length > infer::kMaxTensorElements / n || width > infer::kMaxTensorElements / n) {
+ return R::Fail("collate: " + std::to_string(n) + " rows of " + std::to_string(length) + " tokens and " +
+ std::to_string(width) + " markers are too large");
+ }
+ infer::Batch b;
+ b.rows = n;
+ b.length = length;
+ b.markers = width;
+ b.input_ids.assign(size_t(n * length), int64_t(pad_id));
+ b.attention_mask.assign(size_t(n * length), 0);
+ b.marker_pos.assign(size_t(n * width), 0);
+ b.marker_mask.assign(size_t(n * width), 0);
+ b.qtype.assign(size_t(n), 0);
+ for (size_t i = 0; i < rows.size(); i++) {
+ const Row& r = rows[i];
+ const size_t base = i * size_t(length);
+ for (size_t j = 0; j < r.ids.size(); j++) {
+ b.input_ids[base + j] = r.ids[j];
+ b.attention_mask[base + j] = 1;
+ }
+ for (size_t j = 0; j < r.markers.size(); j++) {
+ b.marker_pos[i * size_t(width) + j] = r.markers[j];
+ b.marker_mask[i * size_t(width) + j] = 1;
+ }
+ b.qtype[i] = schema::Code(r.type);
+ }
+ return R::Ok(std::move(b));
+}
+
+} // namespace collate
+} // namespace laya
diff --git a/laya-cpp/src/decode.cpp b/laya-cpp/src/decode.cpp
new file mode 100644
index 00000000..e931580d
--- /dev/null
+++ b/laya-cpp/src/decode.cpp
@@ -0,0 +1,312 @@
+#include "laya/decode.hpp"
+
+#include <algorithm>
+#include <cmath>
+#include <limits>
+
+#include "cnum.hpp"
+#include "laya/unicodedata.hpp"
+
+namespace laya {
+namespace decode {
+
+namespace {
+
+using pyvalue::Value;
+namespace ud = unicodedata;
+using Kind = Value::Kind;
+
+constexpr double kInf = std::numeric_limits<double>::infinity();
+
+bool Finite(double x) { return std::isfinite(x); }
+
+std::string Shape(const std::string& why) { return "decode: logits do not fit the question: " + why; }
+
+bool IsDigit(char c) { return c >= '0' && c <= '9'; }
+
+std::string PrimarySubtag(std::string_view lang) {
+ return ud::Lower(lang.substr(0, lang.find('-')));
+}
+
+// A list of exactly three clamped values, from a Value list.
+bool ThreeOf(const Value& list, std::array<double, 3>* out) {
+ if (list.kind() != Kind::Array || list.size() != 3) return false;
+ for (size_t i = 0; i < 3; i++) (*out)[i] = Clamp(list.items()[i]);
+ return true;
+}
+
+bool Truthy(const Value* v) {
+ if (v == nullptr) return false;
+ switch (v->kind()) {
+ case Kind::Null: return false;
+ case Kind::Bool: return v->as_bool();
+ case Kind::Int: return v->as_int() != 0;
+ case Kind::Float: return v->as_float() != 0;
+ case Kind::String: return !v->as_string().empty();
+ case Kind::Array: case Kind::Object: return v->size() != 0;
+ default: return true;
+ }
+}
+
+} // namespace
+
+double Round4(double v) {
+ if (!Finite(v)) return v;
+ return cnum::ToDouble(cnum::Fixed(v, 4));
+}
+
+std::optional<double> PyFloat(std::string_view in) {
+ std::string s = ud::DecimalASCII(ud::StripNumeric(std::string(in)));
+ if (s.find_first_of("xXpP") != std::string::npos) return std::nullopt;
+ if (s.find('_') != std::string::npos) {
+ std::string t;
+ for (size_t i = 0; i < s.size(); i++) {
+ if (s[i] == '_') {
+ if (i == 0 || i + 1 == s.size() || !IsDigit(s[i - 1]) || !IsDigit(s[i + 1])) return std::nullopt;
+ continue;
+ }
+ t.push_back(s[i]);
+ }
+ s = t;
+ }
+ size_t i = 0;
+ bool neg = false;
+ if (i < s.size() && (s[i] == '+' || s[i] == '-')) neg = s[i++] == '-';
+ std::string rest = s.substr(i), low;
+ for (char c : rest) low.push_back(c >= 'A' && c <= 'Z' ? char(c + 32) : c);
+ if (low == "nan") return std::numeric_limits<double>::quiet_NaN();
+ if (low == "inf" || low == "infinity") return neg ? -kInf : kInf;
+ // [digits][.digits][e[+-]digits] with at least one mantissa digit.
+ size_t j = 0, digits = 0;
+ while (j < rest.size() && IsDigit(rest[j])) j++, digits++;
+ if (j < rest.size() && rest[j] == '.') {
+ j++;
+ while (j < rest.size() && IsDigit(rest[j])) j++, digits++;
+ }
+ if (digits == 0) return std::nullopt;
+ if (j < rest.size() && (rest[j] == 'e' || rest[j] == 'E')) {
+ j++;
+ if (j < rest.size() && (rest[j] == '+' || rest[j] == '-')) j++;
+ size_t e = 0;
+ while (j < rest.size() && IsDigit(rest[j])) j++, e++;
+ if (e == 0) return std::nullopt;
+ }
+ if (j != rest.size()) return std::nullopt;
+ double v = cnum::ToDouble(rest); // out of range is infinite, as in Python
+ return neg ? -v : v;
+}
+
+double Clamp(const Value& v) {
+ double f = 0;
+ switch (v.kind()) {
+ case Kind::Int: f = double(v.as_int()); break;
+ case Kind::BigInt: f = cnum::ToDouble(v.big_int()); break;
+ case Kind::Float: f = v.as_float(); break;
+ case Kind::String: {
+ auto p = PyFloat(v.as_string());
+ if (!p) return 1;
+ f = *p;
+ break;
+ }
+ default: return 1;
+ }
+ if (!Finite(f)) return 1;
+ return std::min(kTempMax, std::max(kTempMin, f));
+}
+
+std::string Bucket(schema::Type t, int64_t k) {
+ std::string name(schema::Name(t));
+ if (k <= 2) return name + ":2";
+ if (k <= 5) return name + ":3-5";
+ if (k <= 10) return name + ":6-10";
+ return name + ":11+";
+}
+
+double ApplyBinning(double confidence, const std::string& bucket, const std::map<std::string, Bins>& m) {
+ auto it = m.find(bucket);
+ if (it == m.end() || it->second.values.empty()) return confidence;
+ const auto& v = it->second.values;
+ const int64_t n = int64_t(v.size());
+ int64_t idx = int64_t(confidence * double(n));
+ return v[size_t(std::min(n - 1, std::max<int64_t>(0, idx)))];
+}
+
+Result<Temperatures> Temperatures::Of(const Value* by_type, const Value* by_options, const Value* by_language) {
+ using R = Result<Temperatures>;
+ Temperatures t;
+ std::array<double, 3> base{1, 1, 1};
+ if (by_type != nullptr && !by_type->is_null()) {
+ if (!ThreeOf(*by_type, &base)) return R::Fail("decode: temperature must list 3 values, one per question type");
+ }
+ t.by_type_ = base;
+ if (by_options != nullptr && by_options->kind() == Kind::Object) {
+ for (size_t i = 0; i < by_options->size(); i++) t.by_options_[by_options->key(i)] = Clamp(by_options->value(i));
+ }
+ if (Truthy(by_language)) {
+ if (by_language->kind() != Kind::Object) return R::Fail("decode: lang_temperatures must be a mapping of tag -> overrides");
+ for (size_t i = 0; i < by_language->size(); i++) {
+ const std::string& lang = by_language->key(i);
+ const Value& raw = by_language->value(i);
+ if (!raw.is_null() && raw.kind() != Kind::Object) {
+ return R::Fail("decode: language override '" + lang + "' must be a mapping, got " + pyvalue::TypeName(raw));
+ }
+ LanguageTemperatures l;
+ l.by_type = base; // null inherits the checkpoint's own
+ if (raw.kind() == Kind::Object) {
+ if (const Value* tr = raw.Find("temperature"); tr != nullptr && !tr->is_null()) {
+ if (!ThreeOf(*tr, &l.by_type)) {
+ return R::Fail("decode: language override '" + lang + "' temperature must be a list of 3 floats");
+ }
+ }
+ if (const Value* bo = raw.Find("temperature_by_options"); Truthy(bo)) {
+ if (bo->kind() != Kind::Object) {
+ return R::Fail("decode: language override '" + lang + "' temperature_by_options must be a mapping of bucket -> float");
+ }
+ for (size_t j = 0; j < bo->size(); j++) l.by_options[bo->key(j)] = Clamp(bo->value(j));
+ }
+ }
+ t.by_language_[PrimarySubtag(lang)] = std::move(l); // the last tag with this subtag wins
+ }
+ }
+ return R::Ok(std::move(t));
+}
+
+double Temperatures::For(schema::Type typ, int64_t k, std::string_view lang, bool* override_used) const {
+ if (override_used) *override_used = false;
+ if (schema::Code(typ) < 0) return 1;
+ const std::string bucket = Bucket(typ, k);
+ auto it = by_options_.find(bucket);
+ double temperature = it != by_options_.end() ? it->second : by_type_[size_t(schema::Code(typ))];
+ if (!lang.empty()) {
+ auto l = by_language_.find(PrimarySubtag(lang));
+ if (l != by_language_.end()) {
+ auto lo = l->second.by_options.find(bucket);
+ if (override_used) *override_used = true;
+ return lo != l->second.by_options.end() ? lo->second : l->second.by_type[size_t(schema::Code(typ))];
+ }
+ }
+ return temperature;
+}
+
+namespace {
+
+std::vector<schema::Probability> Probabilities(const std::vector<schema::Label>& labels, const std::vector<double>& p) {
+ std::vector<schema::Probability> out;
+ out.reserve(p.size());
+ for (size_t i = 0; i < p.size(); i++) out.push_back({labels[i], Round4(p[i])});
+ return out;
+}
+
+double AnswerConfidence(const std::vector<double>& p) {
+ if (p.empty()) return 1;
+ double top = p[0];
+ for (size_t i = 1; i < p.size(); i++) top = std::max(top, p[i]);
+ return std::min(1.0, std::max(0.0, top));
+}
+
+// 1 - H(p)/log(k), clipped to [0, 1]; 1 for fewer than two options. Probabilities are clipped to
+// [1e-12, 1] inside the log only.
+double EntropyConfidence(const std::vector<double>& p) {
+ if (p.size() < 2) return 1;
+ double h = 0;
+ for (double v : p) h -= v * std::log(std::min(1.0, std::max(1e-12, v)));
+ return std::min(1.0, std::max(0.0, 1 - h / std::log(double(p.size()))));
+}
+
+} // namespace
+
+Result<schema::Answer> Decode(const schema::Question& q, const Row& row, std::string_view lang, const Temperatures* t) {
+ using R = Result<schema::Answer>;
+ const schema::Type typ = q.type();
+ if (typ == schema::Type::Invalid) return R::Fail(Shape("the zero Question has no answer"));
+ const int64_t k = row.k;
+ if (k != int64_t(q.NumOptions())) {
+ return R::Fail(Shape(std::to_string(k) + " option markers for a question of " + std::to_string(q.NumOptions()) + " options"));
+ }
+ if (int64_t(row.logits.size()) < k) {
+ return R::Fail(Shape(std::to_string(row.logits.size()) + " logits for " + std::to_string(k) + " options"));
+ }
+ for (int64_t i = 0; i < k; i++) {
+ if (!Finite(double(row.logits[size_t(i)]))) return R::Fail(Shape("non-finite logit"));
+ }
+ if (!Finite(double(row.act))) return R::Fail(Shape("non-finite action probability"));
+
+ bool override_used = false;
+ const double temperature = t ? t->For(typ, k, lang, &override_used) : 1.0;
+ // softmax(logits[:k] / temperature), the maximum subtracted so a large logit cannot overflow.
+ std::vector<float> z;
+ z.resize(size_t(k));
+ float peak = -std::numeric_limits<float>::infinity();
+ for (size_t i = 0; i < z.size(); i++) {
+ z[i] = row.logits[i] / float(temperature); // float32 division, as numpy does it
+ if (std::isinf(z[i])) return R::Fail(Shape("a logit over the temperature is not finite"));
+ peak = std::max(peak, z[i]);
+ }
+ std::vector<double> p;
+ p.resize(z.size());
+ double sum = 0;
+ for (size_t i = 0; i < z.size(); i++) {
+ p[i] = std::exp(double(z[i]) - double(peak));
+ sum += p[i];
+ }
+ for (double& v : p) v /= sum;
+ // The row is in slot order; everything below indexes by option.
+ const std::vector<int>& order = q.OptionOrder();
+ if (order.size() == p.size()) {
+ std::vector<double> canonical(p.size());
+ for (size_t slot = 0; slot < order.size(); slot++) canonical[size_t(order[slot])] = p[slot];
+ p = std::move(canonical);
+ }
+ schema::Answer a;
+ a.type = typ;
+ double conf = AnswerConfidence(p);
+ if (t != nullptr && !override_used) conf = ApplyBinning(conf, Bucket(typ, k), t->binning);
+ a.answer_confidence = Round4(conf);
+ a.act_probability = Round4(double(row.act));
+ if (typ == schema::Type::Noul) {
+ if (k < 2) return R::Fail(Shape("a noul question needs two options"));
+ const double yes = p[1];
+ a.confidence = Round4(std::max(yes, 1 - yes));
+ a.noul = Round4(yes);
+ return R::Ok(std::move(a));
+ }
+ a.confidence = Round4(EntropyConfidence(p));
+ const std::vector<schema::Label> labels = q.AnswerLabels();
+ if (labels.size() != p.size()) return R::Fail(Shape("label count differs from option count"));
+ a.probabilities = Probabilities(labels, p);
+ if (typ == schema::Type::Choice) {
+ size_t best = 0;
+ for (size_t i = 0; i < p.size(); i++) {
+ if (p[i] > p[best]) best = i; // strict: the first maximum wins, as numpy.argmax breaks a tie
+ }
+ a.choice = labels[best];
+ } else {
+ double expected = 0;
+ for (size_t i = 0; i < p.size(); i++) expected += double(i) * p[i];
+ a.score = Round4(expected);
+ a.legend = q.Legend();
+ }
+ return R::Ok(std::move(a));
+}
+
+Result<std::vector<float>> ActionProbabilities(const std::vector<float>& x) {
+ using R = Result<std::vector<float>>;
+ if (x.empty()) return R::Fail(Shape("an empty action row"));
+ double peak = -kInf;
+ for (float v : x) {
+ if (!Finite(double(v))) return R::Fail(Shape("non-finite action logit"));
+ peak = std::max(peak, double(v));
+ }
+ std::vector<double> e(x.size());
+ double sum = 0;
+ for (size_t i = 0; i < x.size(); i++) {
+ e[i] = std::exp(double(x[i]) - peak);
+ sum += e[i];
+ }
+ std::vector<float> out(x.size());
+ for (size_t i = 0; i < x.size(); i++) out[i] = float(e[i] / sum);
+ return R::Ok(std::move(out));
+}
+
+} // namespace decode
+} // namespace laya
diff --git a/laya-cpp/src/infer.cpp b/laya-cpp/src/infer.cpp
new file mode 100644
index 00000000..eeecacd6
--- /dev/null
+++ b/laya-cpp/src/infer.cpp
@@ -0,0 +1,66 @@
+#include "laya/infer.hpp"
+
+namespace laya {
+namespace infer {
+
+const char* const kInputIds = "input_ids";
+const char* const kAttentionMask = "attention_mask";
+const char* const kMarkerPos = "marker_pos";
+const char* const kMarkerMask = "marker_mask";
+const char* const kQType = "qtype";
+const char* const kLogits = "logits";
+const char* const kActLogits = "act_logits";
+
+namespace {
+std::string Shape(const char* name, size_t got, int64_t want) {
+ return std::string("infer: ") + name + " has " + std::to_string(got) + " values, want " + std::to_string(want);
+}
+} // namespace
+
+std::string Batch::Validate() const {
+ if (rows < 0 || length < 0 || markers < 0) return "infer: batch has negative dimensions";
+ if (rows > 0) {
+ if (length == 0) return "infer: batch has rows of 0 tokens";
+ if (markers < 2) return "infer: batch has " + std::to_string(markers) + " marker slots, the graph needs at least 2";
+ if (length > kMaxTensorElements / rows || markers > kMaxTensorElements / rows) {
+ return "infer: batch dimensions " + std::to_string(rows) + " x " + std::to_string(length) + " x " +
+ std::to_string(markers) + " are too large";
+ }
+ }
+ const int64_t rl = rows * length, rm = rows * markers;
+ struct Check {
+ const char* name;
+ size_t got;
+ int64_t want;
+ };
+ const Check checks[] = {{kInputIds, input_ids.size(), rl},
+ {kAttentionMask, attention_mask.size(), rl},
+ {kMarkerPos, marker_pos.size(), rm},
+ {kMarkerMask, marker_mask.size(), rm},
+ {kQType, qtype.size(), rows}};
+ for (const Check& c : checks) {
+ if (int64_t(c.got) != c.want) return Shape(c.name, c.got, c.want);
+ }
+ for (size_t i = 0; i < marker_pos.size(); i++) {
+ if (marker_pos[i] < 0 || marker_pos[i] >= length) {
+ return "infer: marker_pos[" + std::to_string(i) + "] is " + std::to_string(marker_pos[i]) + ", outside [0, " +
+ std::to_string(length) + ")";
+ }
+ }
+ for (size_t i = 0; i < input_ids.size(); i++) {
+ if (input_ids[i] < 0) return "infer: input_ids[" + std::to_string(i) + "] is negative, token ids must not be";
+ }
+ for (size_t i = 0; i < qtype.size(); i++) {
+ if (qtype[i] < 0 || qtype[i] > 2) return "infer: qtype row " + std::to_string(i) + " is not 0, 1 or 2";
+ }
+ return "";
+}
+
+std::string Output::Check(const Batch& b) const {
+ if (int64_t(logits.size()) != b.rows * b.markers) return Shape(kLogits, logits.size(), b.rows * b.markers);
+ if (int64_t(act_logits.size()) != b.rows * 2) return Shape(kActLogits, act_logits.size(), b.rows * 2);
+ return "";
+}
+
+} // namespace infer
+} // namespace laya
diff --git a/laya-cpp/tests/agent_test.cpp b/laya-cpp/tests/agent_test.cpp
new file mode 100644
index 00000000..67b43eed
--- /dev/null
+++ b/laya-cpp/tests/agent_test.cpp
@@ -0,0 +1,577 @@
+#include "laya/agent.hpp"
+
+#include <gtest/gtest.h>
+
+#include <algorithm>
+#include <cmath>
+#include <fstream>
+#include <sstream>
+#include <thread>
+
+#include "checkpoint.hpp"
+#include "golden.hpp"
+#include "laya/collate.hpp"
+#include "stub_session.hpp"
+
+namespace {
+
+using laya::pyvalue::Value;
+namespace ag = laya::agent;
+namespace sc = laya::schema;
+namespace in = laya::infer;
+using laya_test::RunRecord;
+using laya_test::StubSession;
+using Kind = Value::Kind;
+
+constexpr const char* kModels[] = {"english", "multilingual"};
+const char* const kConfig = R"({"max_len":512,"head_max_len":192,"option_layout":"sequential"})";
+
+std::string Root() {
+ const char* r = std::getenv("LAYA_CHECKPOINTS");
+ return r ? r : "";
+}
+
+std::string ReadFile(const std::string& path) {
+ std::ifstream in(path, std::ios::binary);
+ std::stringstream ss;
+ ss << in.rdbuf();
+ return ss.str();
+}
+
+// ---- collate and infer: no checkpoint needed ----
+
+laya::collate::Row Seq(std::vector<int32_t> ids, std::vector<int64_t> markers, sc::Type t = sc::Type::Choice) {
+ return {std::move(ids), std::move(markers), t};
+}
+
+TEST(Collate, PadsToTheLongestAndWidestAndMasks) {
+ auto b = laya::collate::Collate({Seq({5, 6, 7}, {0, 2, 1}), Seq({9}, {0}, sc::Type::Noul)}, 99);
+ ASSERT_TRUE(b.ok()) << b.error();
+ const in::Batch& x = b.value();
+ EXPECT_EQ(x.rows, 2);
+ EXPECT_EQ(x.length, 3);
+ EXPECT_EQ(x.markers, 3);
+ EXPECT_EQ(x.input_ids, (std::vector<int64_t>{5, 6, 7, 9, 99, 99}));
+ EXPECT_EQ(x.attention_mask, (std::vector<int64_t>{1, 1, 1, 1, 0, 0}));
+ EXPECT_EQ(x.marker_pos, (std::vector<int64_t>{0, 2, 1, 0, 0, 0}));
+ EXPECT_EQ(x.marker_mask, (std::vector<uint8_t>{1, 1, 1, 1, 0, 0}));
+ EXPECT_EQ(x.qtype, (std::vector<int64_t>{0, 2}));
+ EXPECT_EQ(x.Validate(), "");
+}
+
+TEST(Collate, OneOptionRowsGetAMaskedSecondSlot) {
+ auto b = laya::collate::Collate({Seq({1, 2}, {1})}, 0);
+ ASSERT_TRUE(b.ok());
+ EXPECT_EQ(b.value().markers, 2);
+ EXPECT_EQ(b.value().marker_mask, (std::vector<uint8_t>{1, 0}));
+}
+
+TEST(Collate, RefusesBadRows) {
+ using laya::collate::Collate;
+ EXPECT_FALSE(Collate({}, 0).ok());
+ EXPECT_FALSE(Collate({Seq({}, {})}, 0).ok());
+ EXPECT_FALSE(Collate({Seq({1}, {1})}, 0).ok()); // marker at the end
+ EXPECT_FALSE(Collate({Seq({1, 2}, {-1})}, 0).ok());
+ EXPECT_FALSE(Collate({Seq({1, -2}, {0})}, 0).ok());
+ EXPECT_FALSE(Collate({Seq({1}, {0}, sc::Type::Invalid)}, 0).ok());
+ EXPECT_FALSE(Collate({Seq({1}, {0})}, -1).ok());
+}
+
+TEST(Collate, RefusesAHostileSize) {
+ // 2 rows of 2^23+1 tokens hold more than kMaxTensorElements: refused before the tensors are allocated.
+ laya::collate::Row big = Seq(std::vector<int32_t>((size_t(1) << 23) + 1, 1), {0});
+ std::vector<laya::collate::Row> rows(2, big);
+ auto b = laya::collate::Collate(rows, 0);
+ EXPECT_FALSE(b.ok());
+}
+
+TEST(Infer, ValidateCatchesEachShape) {
+ in::Batch ok = laya::collate::Collate({Seq({1, 2}, {0, 1})}, 0).value();
+ EXPECT_EQ(ok.Validate(), "");
+ auto bad = [&](auto mutate) {
+ in::Batch b = ok;
+ mutate(b);
+ return b.Validate();
+ };
+ EXPECT_NE(bad([](in::Batch& b) { b.input_ids.pop_back(); }), "");
+ EXPECT_NE(bad([](in::Batch& b) { b.marker_mask.push_back(0); }), "");
+ EXPECT_NE(bad([](in::Batch& b) { b.marker_pos[0] = 2; }), "");
+ EXPECT_NE(bad([](in::Batch& b) { b.input_ids[0] = -1; }), "");
+ EXPECT_NE(bad([](in::Batch& b) { b.qtype[0] = 3; }), "");
+ EXPECT_NE(bad([](in::Batch& b) { b.rows = -1; }), "");
+ EXPECT_NE(bad([](in::Batch& b) { b.markers = 1; }), "");
+ EXPECT_NE(bad([](in::Batch& b) { b.rows = int64_t(1) << 62; }), "");
+}
+
+TEST(Infer, OutputCheck) {
+ in::Batch b = laya::collate::Collate({Seq({1, 2}, {0, 1})}, 0).value();
+ in::Output o;
+ o.logits = {0, 0};
+ o.act_logits = {0, 0};
+ EXPECT_EQ(o.Check(b), "");
+ o.logits.pop_back();
+ EXPECT_NE(o.Check(b), "");
+}
+
+TEST(CancelToken, CopiesShareAFlagAndADefaultNeverFires) {
+ laya::CancelToken none;
+ none.Cancel();
+ EXPECT_FALSE(none.cancelled());
+ laya::CancelToken a = laya::CancelToken::Make(), b = a;
+ EXPECT_FALSE(b.cancelled());
+ a.Cancel();
+ EXPECT_TRUE(b.cancelled());
+}
+
+// ---- the agent on the stub session, tokenizer-backed ----
+
+struct Rig {
+ std::unique_ptr<ag::Agent> agent;
+ std::shared_ptr<StubSession::State> st;
+};
+
+Rig OpenRig(const char* model, const char* config = kConfig) {
+ Rig r;
+ const laya::tokenizer::Tokenizer* tok = laya_test::LoadCheckpoint(model);
+ if (tok == nullptr) return r;
+ auto s = std::make_unique<StubSession>();
+ r.st = s->state();
+ auto a = ag::Agent::OpenParts(config, *tok, std::move(s));
+ EXPECT_TRUE(a.ok()) << (a.ok() ? "" : a.error());
+ if (a.ok()) r.agent = std::move(a).value();
+ return r;
+}
+
+#define LAYA_RIG_OPEN(var, open_expr) \
+ Rig var = open_expr; \
+ if (!var.agent) { \
+ if (laya_test::RequireGoldens()) ADD_FAILURE() << "no checkpoint"; \
+ else GTEST_SKIP() << "LAYA_CHECKPOINTS unset (local run)"; \
+ return; \
+ }
+#define LAYA_RIG(var, model) LAYA_RIG_OPEN(var, OpenRig(model))
+#define LAYA_RIG_CFG(var, model, cfg) LAYA_RIG_OPEN(var, OpenRig(model, cfg))
+
+sc::Questions Mix() {
+ return sc::Questions::Parse(R"({
+ "intent":{"type":"choice","instructions":"What does the customer want?","criteria":{"refund":"asks for money back","status":"asks where the order is","other":"anything else"}},
+ "urgency":{"type":"score","instructions":"How urgent is it?","criteria":["not at all","slightly","moderately","very","critical"]},
+ "angry":{"type":"noul","instructions":"Is the customer angry?"}})").value();
+}
+
+std::vector<Value> States(int n) {
+ std::vector<Value> out;
+ for (int i = 0; i < n; i++) {
+ std::string s = "state";
+ for (int j = 0; j < (i * 7) % 23; j++) s += " alpha bravo";
+ out.push_back(Value::String(s + " " + std::to_string(i)));
+ }
+ return out;
+}
+
+std::vector<std::string> Jsons(const std::vector<sc::Prediction>& p) {
+ std::vector<std::string> out;
+ for (const auto& x : p) out.push_back(x.ToJson().value());
+ return out;
+}
+
+// Which rows each run holds, compared with ONNXAgent._infer_batch on the same states; numbers within
+// the tolerance Python's float32 needs, the chosen label only when it was decisive.
+struct Tally {
+ int64_t numbers = 0, differing = 0, failures = 0, ties = 0, choices = 0;
+ std::string where;
+ void Fail(const std::string& m) {
+ if (failures++ < 10) ADD_FAILURE() << where << ": " << m;
+ }
+ void Compare(const std::string& path, const std::string& key, const Value& got, const Value& want) {
+ auto num = [](const Value& v) { return v.kind() == Kind::Int || v.kind() == Kind::Float; };
+ if (want.kind() == Kind::Object) {
+ bool same = got.kind() == Kind::Object && got.size() == want.size();
+ for (size_t i = 0; same && i < want.size(); i++) same = got.key(i) == want.key(i);
+ if (!same) return Fail(path + ": keys differ: " + laya::pyvalue::Repr(got) + " vs " + laya::pyvalue::Repr(want));
+ for (size_t i = 0; i < want.size(); i++) Compare(path + "." + want.key(i), want.key(i), got.value(i), want.value(i));
+ } else if (want.kind() == Kind::Array) {
+ if (got.kind() != Kind::Array || got.size() != want.size()) return Fail(path + ": array differs");
+ for (size_t i = 0; i < want.size(); i++) Compare(path + "[]", key, got.items()[i], want.items()[i]);
+ } else if (num(want)) {
+ if (!num(got)) return Fail(path + ": not a number");
+ const double tol = key == "score" ? 8e-4 : 2e-4, d = std::fabs(laya_test::Num(got) - laya_test::Num(want));
+ numbers++;
+ if (laya::pyvalue::Repr(got) != laya::pyvalue::Repr(want)) differing++;
+ if (d > tol) Fail(path + ": off by " + std::to_string(d));
+ } else if (laya::pyvalue::Repr(got) != laya::pyvalue::Repr(want)) {
+ Fail(path + ": " + laya::pyvalue::Repr(got) + " vs " + laya::pyvalue::Repr(want));
+ }
+ }
+ void Answer(const std::string& path, const Value& got, const Value& want) {
+ if (const Value* t = want.Find("type"); t != nullptr && t->as_string() == "choice") {
+ std::vector<double> ps;
+ const Value* probs = want.Find("probabilities");
+ for (size_t i = 0; i < probs->size(); i++) ps.push_back(laya_test::Num(probs->value(i)));
+ std::sort(ps.rbegin(), ps.rend());
+ if (ps.size() > 1 && ps[0] - ps[1] <= 1e-3) {
+ ties++;
+ auto trim = [](const Value& o) {
+ Value r = Value::Object();
+ for (size_t i = 0; i < o.size(); i++) {
+ if (o.key(i) != "choice") r.Set(o.key(i), o.value(i));
+ }
+ return r;
+ };
+ return Compare(path, "", trim(got), trim(want));
+ }
+ choices++;
+ }
+ Compare(path, "", got, want);
+ }
+};
+
+RunRecord RunFrom(const Value& v) {
+ auto ints = [&](const char* k) {
+ std::vector<int64_t> out;
+ for (const Value& x : v.Find(k)->items()) out.push_back(x.as_int());
+ return out;
+ };
+ RunRecord r;
+ r.rows = v.Find("rows")->as_int(), r.length = v.Find("length")->as_int(), r.markers = v.Find("markers")->as_int();
+ r.id_sums = ints("id_sums"), r.tokens = ints("tokens"), r.marker_sums = ints("marker_sums"), r.qtypes = ints("qtypes");
+ return r;
+}
+
+bool SameRun(const RunRecord& a, const RunRecord& b) {
+ return a.rows == b.rows && a.length == b.length && a.markers == b.markers && a.id_sums == b.id_sums &&
+ a.tokens == b.tokens && a.marker_sums == b.marker_sums && a.qtypes == b.qtypes;
+}
+
+TEST(AgentGolden, PredictPlan) {
+ for (const char* model : kModels) {
+ LAYA_GOLDEN_LIST(golden, "go_extra.json", "predict_plan");
+ const Value* cases = golden->Find(model)->Find("cases");
+ LAYA_EXPECT_ROWS(cases, 24);
+ const Value* defs = golden->Find("questions");
+ const std::string cfg = ReadFile(Root() + "/" + model + "/rl_agent_config.json");
+ LAYA_RIG_CFG(rig, model, cfg.c_str());
+ Tally t;
+ int64_t runs = 0;
+ for (const Value& rec : cases->items()) {
+ t.where = std::string(model) + "/" + rec.Find("name")->as_string();
+ auto qs = sc::Questions::Parse(laya::pyvalue::Dumps(*defs->Find(rec.Find("questions")->as_string())).value());
+ ASSERT_TRUE(qs.ok()) << qs.error();
+ ag::CallOptions o;
+ if (!rec.Find("batch_size")->is_null()) o.batch_size = rec.Find("batch_size")->as_int();
+ o.sort_by_length = rec.Find("sort")->as_bool();
+ if (!rec.Find("lang")->is_null()) o.lang = rec.Find("lang")->as_string();
+ rig.st->runs.clear();
+ auto preds = rig.agent->PredictBatch(rec.Find("states")->items(), qs.value(), o);
+ ASSERT_TRUE(preds.ok()) << t.where << ": " << preds.error();
+ const Value* want_runs = rec.Find("runs");
+ if (rig.st->runs.size() != want_runs->size()) {
+ t.Fail(std::to_string(rig.st->runs.size()) + " runs, want " + std::to_string(want_runs->size()));
+ continue;
+ }
+ runs += int64_t(rig.st->runs.size());
+ for (size_t i = 0; i < want_runs->size(); i++) {
+ if (!SameRun(rig.st->runs[i], RunFrom(want_runs->items()[i]))) t.Fail("run " + std::to_string(i) + " differs");
+ }
+ const Value* want = rec.Find("results");
+ ASSERT_EQ(preds.value().size(), want->size()) << t.where;
+ for (size_t i = 0; i < want->size(); i++) {
+ const Value got = laya::pyvalue::Parse(preds.value()[i].ToJson().value()).value();
+ const Value& w = want->items()[i];
+ const std::string path = t.where + "/state" + std::to_string(i);
+ t.Compare(path + ".model", "model", *got.Find("model"), *w.Find("model"));
+ if (laya::pyvalue::Dumps(*got.Find("usage")).value() != laya::pyvalue::Dumps(*w.Find("usage")).value()) {
+ t.Fail(path + " usage\n got " + laya::pyvalue::Dumps(*got.Find("usage")).value() + "\nwant " +
+ laya::pyvalue::Dumps(*w.Find("usage")).value());
+ }
+ const Value* ga = got.Find("answers");
+ const Value* wa = w.Find("answers");
+ std::vector<std::string> want_ids;
+ for (const Value& id : w.Find("answer_ids")->items()) want_ids.push_back(id.as_string());
+ std::vector<std::string> got_ids;
+ for (size_t k = 0; k < ga->size(); k++) got_ids.push_back(ga->key(k));
+ if (got_ids != want_ids) {
+ t.Fail(path + " answer ids differ");
+ continue;
+ }
+ for (size_t k = 0; k < wa->size(); k++) t.Answer(path + "." + wa->key(k), ga->value(k), wa->value(k));
+ }
+ }
+ std::printf("%s: %lld runs, %lld numbers, %lld differ at all, %lld choices checked, %lld near-ties skipped\n", model,
+ (long long)runs, (long long)t.numbers, (long long)t.differing, (long long)t.choices, (long long)t.ties);
+ EXPECT_EQ(t.failures, 0);
+ EXPECT_GE(t.numbers, 2000);
+ EXPECT_GE(runs, 80);
+ EXPECT_LE(double(t.differing), 0.05 * double(t.numbers));
+ }
+}
+
+// ---- behavior on the stub ----
+
+TEST(Agent, ResultsComeBackInInputOrderWhateverTheBatching) {
+ for (const char* model : kModels) {
+ LAYA_RIG(rig, model);
+ const auto qs = Mix();
+ const auto states = States(19);
+ auto whole = rig.agent->PredictBatch(states, qs);
+ ASSERT_TRUE(whole.ok()) << whole.error();
+ for (int64_t batch : {1, 2, 5, 19, 50}) {
+ for (bool sort : {false, true}) {
+ ag::CallOptions o;
+ o.batch_size = batch;
+ o.sort_by_length = sort;
+ auto p = rig.agent->PredictBatch(states, qs, o);
+ ASSERT_TRUE(p.ok()) << p.error();
+ EXPECT_EQ(Jsons(p.value()), Jsons(whole.value())) << model << " batch " << batch << " sort " << sort;
+ }
+ }
+ for (size_t i : {size_t(0), size_t(7), size_t(18)}) { // a single Predict agrees with its slot
+ auto one = rig.agent->Predict(states[i], qs);
+ ASSERT_TRUE(one.ok());
+ EXPECT_EQ(one.value().ToJson().value(), whole.value()[i].ToJson().value());
+ }
+ }
+}
+
+TEST(Agent, BatchSizeSetsTheNumberOfRunsAndSortGroupsByLength) {
+ LAYA_RIG(rig, "english");
+ const auto qs = Mix();
+ const auto states = States(10);
+ struct Case {
+ int64_t batch;
+ size_t runs;
+ };
+ for (Case c : {Case{0, 1}, Case{-3, 1}, Case{1, 10}, Case{3, 4}, Case{10, 1}, Case{99, 1}}) {
+ ag::CallOptions o;
+ o.batch_size = c.batch;
+ rig.st->runs.clear();
+ ASSERT_TRUE(rig.agent->PredictBatch(states, qs, o).ok());
+ EXPECT_EQ(rig.st->runs.size(), c.runs) << "batch " << c.batch;
+ for (const RunRecord& r : rig.st->runs) EXPECT_EQ(r.rows % 3, 0); // three questions per state
+ }
+ // Sorted, chunks hold neighbors in length: the longest row of each run never shrinks run to run.
+ ag::CallOptions o;
+ o.batch_size = 3;
+ o.sort_by_length = true;
+ rig.st->runs.clear();
+ ASSERT_TRUE(rig.agent->PredictBatch(states, qs, o).ok());
+ int64_t prev = 0;
+ for (const RunRecord& r : rig.st->runs) {
+ EXPECT_GE(r.length, prev);
+ prev = r.length;
+ }
+ EXPECT_GT(rig.st->runs.back().length, rig.st->runs.front().length);
+}
+
+TEST(Agent, UsageCountsTheMaskedTokens) {
+ LAYA_RIG(rig, "english");
+ const auto qs = Mix();
+ rig.st->runs.clear();
+ auto p = rig.agent->Predict(Value::String("alpha bravo charlie"), qs);
+ ASSERT_TRUE(p.ok());
+ int64_t tokens = 0;
+ for (int64_t t : rig.st->runs[0].tokens) tokens += t;
+ EXPECT_EQ(p.value().usage.input_tokens, tokens);
+ EXPECT_GT(tokens, 0);
+}
+
+TEST(Agent, EmptyInputs) {
+ LAYA_RIG(rig, "english");
+ auto none = rig.agent->PredictBatch({}, Mix());
+ ASSERT_TRUE(none.ok());
+ EXPECT_TRUE(none.value().empty());
+ auto noq = rig.agent->PredictBatch(States(2), sc::Questions());
+ ASSERT_TRUE(noq.ok());
+ EXPECT_EQ(noq.value().size(), 2u);
+ EXPECT_TRUE(noq.value()[0].answers.empty());
+ EXPECT_TRUE(rig.st->runs.empty());
+}
+
+TEST(Agent, RefusesANullStateAndNamesIt) {
+ LAYA_RIG(rig, "english");
+ auto states = States(3);
+ states[2] = Value::Null();
+ auto p = rig.agent->PredictBatch(states, Mix());
+ ASSERT_FALSE(p.ok());
+ EXPECT_NE(p.error().find("agent: state 2:"), std::string::npos) << p.error();
+ auto one = rig.agent->Predict(Value::Null(), Mix());
+ ASSERT_FALSE(one.ok());
+ EXPECT_EQ(one.error().find("state 0"), std::string::npos) << one.error();
+ EXPECT_TRUE(rig.st->runs.empty());
+}
+
+TEST(Agent, RefusesHostileCallSettings) {
+ LAYA_RIG(rig, "english");
+ ag::CallOptions o;
+ o.max_len = ag::kMaxSequenceLength + 1;
+ EXPECT_FALSE(rig.agent->Predict(Value::String("x"), Mix(), o).ok());
+ o = {};
+ o.head_max_len = int64_t(1) << 40;
+ EXPECT_FALSE(rig.agent->Predict(Value::String("x"), Mix(), o).ok());
+ EXPECT_TRUE(rig.st->runs.empty());
+}
+
+TEST(Agent, SessionFailuresNameTheRun) {
+ LAYA_RIG(rig, "english");
+ rig.st->fail = "boom";
+ auto p = rig.agent->Predict(Value::String("alpha"), Mix());
+ ASSERT_FALSE(p.ok());
+ EXPECT_NE(p.error().find("agent: running 3 rows of"), std::string::npos) << p.error();
+ EXPECT_NE(p.error().find("boom"), std::string::npos);
+ rig.st->fail.clear();
+ rig.st->tamper = [](in::Output* o) { o->logits.pop_back(); };
+ EXPECT_FALSE(rig.agent->Predict(Value::String("alpha"), Mix()).ok());
+ rig.st->tamper = [](in::Output* o) { o->logits[0] = NAN; };
+ EXPECT_FALSE(rig.agent->Predict(Value::String("alpha"), Mix()).ok());
+ rig.st->tamper = [](in::Output* o) { o->act_logits[1] = INFINITY; };
+ EXPECT_FALSE(rig.agent->Predict(Value::String("alpha"), Mix()).ok());
+}
+
+TEST(Agent, CancelBeforeTheCallRunsNothing) {
+ LAYA_RIG(rig, "english");
+ ag::CallOptions o;
+ o.cancel = laya::CancelToken::Make();
+ o.cancel.Cancel();
+ auto p = rig.agent->PredictBatch(States(4), Mix(), o);
+ ASSERT_FALSE(p.ok());
+ EXPECT_TRUE(ag::IsCancelled(p.error()));
+ EXPECT_TRUE(rig.st->runs.empty());
+}
+
+TEST(Agent, CancelBetweenRunsStopsTheNextOne) {
+ LAYA_RIG(rig, "english");
+ ag::CallOptions o;
+ o.batch_size = 1;
+ o.cancel = laya::CancelToken::Make();
+ rig.st->on_run = [c = o.cancel] { c.Cancel(); }; // the first run cancels the call
+ auto p = rig.agent->PredictBatch(States(5), Mix(), o);
+ ASSERT_FALSE(p.ok());
+ EXPECT_TRUE(ag::IsCancelled(p.error())) << p.error();
+ EXPECT_EQ(rig.st->runs.size(), 0u); // the stub sees the flag and fails that run
+}
+
+TEST(Agent, CloseIsIdempotentAndRefusesLaterCalls) {
+ LAYA_RIG(rig, "english");
+ EXPECT_EQ(rig.agent->Close(), "");
+ EXPECT_EQ(rig.agent->Close(), "");
+ EXPECT_EQ(rig.st->closes, 1);
+ auto p = rig.agent->Predict(Value::String("x"), Mix());
+ ASSERT_FALSE(p.ok());
+ EXPECT_TRUE(ag::IsClosed(p.error()));
+}
+
+TEST(Agent, DestroyingClosesTheSession) {
+ LAYA_RIG(rig, "english");
+ auto st = rig.st;
+ rig.agent.reset();
+ EXPECT_EQ(st->closes, 1);
+ EXPECT_TRUE(st->destroyed);
+}
+
+TEST(Agent, ConcurrentPredictsAgreeWithASerialOne) {
+ LAYA_RIG(rig, "multilingual");
+ const auto qs = Mix();
+ const auto states = States(12);
+ const auto want = Jsons(rig.agent->PredictBatch(states, qs).value());
+ std::atomic<int> bad{0};
+ std::vector<std::thread> threads;
+ for (int t = 0; t < 8; t++) {
+ threads.emplace_back([&, t] {
+ for (int i = 0; i < 10; i++) {
+ ag::CallOptions o;
+ o.batch_size = 1 + (t + i) % 5;
+ o.sort_by_length = (t + i) % 2 == 0;
+ auto p = rig.agent->PredictBatch(states, qs, o);
+ if (!p.ok() || Jsons(p.value()) != want) bad++;
+ }
+ });
+ }
+ for (auto& th : threads) th.join();
+ EXPECT_EQ(bad, 0);
+}
+
+TEST(Agent, CloseWaitsForCallsInFlightAndNoneStartsAfter) {
+ LAYA_RIG(rig, "english");
+ const auto qs = Mix();
+ const auto states = States(6);
+ std::atomic<int> ok{0}, closed{0}, other{0};
+ std::vector<std::thread> threads;
+ for (int t = 0; t < 6; t++) {
+ threads.emplace_back([&] {
+ for (int i = 0; i < 20; i++) {
+ ag::CallOptions o;
+ o.batch_size = 1;
+ auto p = rig.agent->PredictBatch(states, qs, o);
+ if (p.ok()) ok++;
+ else if (ag::IsClosed(p.error())) closed++;
+ else other++; // a Run must never meet a closed session
+ }
+ });
+ }
+ std::this_thread::sleep_for(std::chrono::milliseconds(2));
+ rig.agent->Close();
+ for (auto& th : threads) th.join();
+ EXPECT_EQ(other, 0);
+ EXPECT_EQ(rig.st->closes, 1);
+ EXPECT_GT(ok + closed, 0);
+}
+
+// ---- Open ----
+
+TEST(AgentOpen, ReadsTheCheckpointDirectory) {
+ for (const char* model : kModels) {
+ if (Root().empty()) {
+ if (laya_test::RequireGoldens()) ADD_FAILURE() << "LAYA_CHECKPOINTS unset";
+ GTEST_SKIP();
+ }
+ auto s = std::make_unique<StubSession>();
+ auto st = s->state();
+ auto a = ag::Agent::Open(Root() + "/" + model, std::move(s));
+ ASSERT_TRUE(a.ok()) << a.error();
+ EXPECT_EQ(a.value()->config().option_layout, "sequential");
+ EXPECT_GT(a.value()->config().max_len, a.value()->config().head_max_len);
+ EXPECT_TRUE(a.value()->Predict(Value::String("alpha bravo"), Mix()).ok());
+ }
+}
+
+TEST(AgentOpen, FailureDestroysTheSession) {
+ auto s = std::make_unique<StubSession>();
+ auto st = s->state();
+ auto a = ag::Agent::Open("/nonexistent/checkpoint", std::move(s));
+ EXPECT_FALSE(a.ok());
+ EXPECT_TRUE(st->destroyed);
+ EXPECT_FALSE(ag::Agent::Open("/x", nullptr).ok());
+}
+
+TEST(AgentOpen, RefusesABadConfig) {
+ for (const char* model : kModels) {
+ const laya::tokenizer::Tokenizer* tok = laya_test::LoadCheckpoint(model);
+ if (tok == nullptr) GTEST_SKIP() << "LAYA_CHECKPOINTS unset (local run)";
+ for (const char* cfg : {"[]", "{", R"({"option_layout":"parallel"})", R"({"option_layout":1})", R"({"max_len":0})",
+ R"({"max_len":-5})", R"({"max_len":true})", R"({"max_len":512.0})", R"({"max_len":"512"})",
+ R"({"head_max_len":99999999999999999999})", R"({"max_len":2000000})",
+ R"({"temperature":[1,2]})", R"({"temperature":"x"})", R"({"temperature_by_options":[1]})"}) {
+ auto a = ag::Agent::OpenParts(cfg, *tok, std::make_unique<StubSession>());
+ EXPECT_FALSE(a.ok()) << cfg;
+ }
+ auto ok = ag::Agent::OpenParts("{}", *tok, std::make_unique<StubSession>());
+ ASSERT_TRUE(ok.ok());
+ EXPECT_EQ(ok.value()->config().max_len, 512);
+ EXPECT_EQ(ok.value()->config().head_max_len, 192);
+ break;
+ }
+}
+
+TEST(AgentOpen, WarnsWhenTemperaturesAreClamped) {
+ LAYA_RIG_CFG(rig, "english", R"({"temperature":[0.1,"9",1.5],"temperature_by_options":{"choice:2":0.3,"noul:2":2}})");
+ ASSERT_EQ(rig.agent->config().warnings.size(), 1u);
+ const std::string& w = rig.agent->config().warnings[0];
+ EXPECT_NE(w.find("choice:2=0.3 -> 0.5"), std::string::npos) << w;
+ EXPECT_NE(w.find("temperature[0]=0.1 -> 0.5"), std::string::npos) << w;
+ EXPECT_NE(w.find("temperature[1]='9' -> 5"), std::string::npos) << w;
+ EXPECT_EQ(w.find("noul:2"), std::string::npos);
+ LAYA_RIG_CFG(fine, "english", R"({"temperature":[1,2,3]})");
+ EXPECT_TRUE(fine.agent->config().warnings.empty());
+}
+
+} // namespace
diff --git a/laya-cpp/tests/decode_test.cpp b/laya-cpp/tests/decode_test.cpp
new file mode 100644
index 00000000..2be11603
--- /dev/null
+++ b/laya-cpp/tests/decode_test.cpp
@@ -0,0 +1,417 @@
+#include "laya/decode.hpp"
+
+#include <gtest/gtest.h>
+
+#include <cmath>
+#include <cstring>
+
+#include "golden.hpp"
+#include "question_fixture.hpp"
+
+namespace {
+
+using laya::pyvalue::Value;
+namespace dc = laya::decode;
+namespace sc = laya::schema;
+using Kind = Value::Kind;
+using laya_test::GoldenQuestion;
+
+constexpr const char* kModels[] = {"english", "multilingual"};
+
+float F32(const Value& v) { return float(laya_test::Num(v)); }
+
+std::vector<float> Floats(const Value& list) {
+ std::vector<float> out;
+ for (const Value& v : list.items()) out.push_back(F32(v));
+ return out;
+}
+
+dc::Temperatures TempsOf(const Value& config) {
+ auto t = dc::Temperatures::Of(config.Find("temperature"), config.Find("temperature_by_options"),
+ config.Find("lang_temperatures_raw"));
+ EXPECT_TRUE(t.ok()) << (t.ok() ? "" : t.error());
+ if (!t.ok()) std::abort();
+ return std::move(t).value();
+}
+
+std::string Compact(const std::string& json) { // normalize through the parser: one spelling
+ auto v = laya::pyvalue::Parse(json);
+ return v.ok() ? laya::pyvalue::Dumps(v.value()).value() : "unparsable: " + json;
+}
+
+dc::Temperatures Uniform(double t) {
+ Value a = Value::Array({Value::Float(t), Value::Float(t), Value::Float(t)});
+ return dc::Temperatures::Of(&a, nullptr).value();
+}
+
+// decode.json: Agent._decode_answers on logit rows aimed at every bucket, a tie, a uniform row,
+// overflowing magnitudes, the option permutation and the language override. Exact, key order included.
+TEST(DecodeGolden, DecodeJson) {
+ for (const char* name : kModels) {
+ LAYA_GOLDEN_LIST(entry, "decode.json", name);
+ const Value* cases = entry->Find("cases");
+ LAYA_EXPECT_ROWS(cases, 20);
+ const dc::Temperatures temps = TempsOf(*entry->Find("config"));
+ for (size_t i = 0; i < cases->size(); i++) {
+ const Value& rec = cases->value(i);
+ const std::string where = std::string(name) + "/" + cases->key(i);
+ sc::Question q = GoldenQuestion(*rec.Find("question"), *rec.Find("option_order"));
+ dc::Row row;
+ row.logits = Floats(*rec.Find("logits"));
+ row.k = int64_t(row.logits.size());
+ for (int64_t w = int64_t(row.logits.size()); w < rec.Find("logits_block_width")->as_int(); w++) {
+ row.logits.push_back(99); // columns past k must not be read
+ }
+ row.act = Floats(*rec.Find("act"))[0];
+ const Value* lang = rec.Find("lang");
+ auto a = dc::Decode(q, row, lang->is_null() ? "" : lang->as_string(), &temps);
+ ASSERT_TRUE(a.ok()) << where << ": " << a.error();
+ EXPECT_EQ(Compact(a.value().ToJson().value()), laya::pyvalue::Dumps(*rec.Find("answer")).value()) << where;
+ }
+ }
+}
+
+// The checkpoints' own configs, clamped, must be the tables decode.json was recorded with.
+TEST(DecodeGolden, TemperaturesOfTheCheckpointConfigs) {
+ for (const char* name : kModels) {
+ LAYA_GOLDEN_LIST(seq, "sequences.json", name, "config");
+ LAYA_GOLDEN_LIST(rec, "decode.json", name, "config");
+ auto t = dc::Temperatures::Of(seq->Find("temperature"), seq->Find("temperature_by_options"));
+ ASSERT_TRUE(t.ok());
+ const Value* by_type = rec->Find("temperature");
+ for (size_t i = 0; i < 3; i++) EXPECT_EQ(t.value().by_type()[i], laya_test::Num(by_type->items()[i])) << name << i;
+ const Value* by_options = rec->Find("temperature_by_options");
+ EXPECT_EQ(t.value().by_options().size(), by_options->size()) << name;
+ for (size_t i = 0; i < by_options->size(); i++) {
+ EXPECT_EQ(t.value().by_options().at(by_options->key(i)), laya_test::Num(by_options->value(i))) << by_options->key(i);
+ }
+ }
+}
+
+TEST(DecodeGolden, Round4) {
+ LAYA_GOLDEN_LIST(g, "go_extra.json", "round4");
+ const Value* values = g->Find("values");
+ const Value* rounded = g->Find("rounded");
+ LAYA_EXPECT_ROWS(values, 5605);
+ ASSERT_EQ(rounded->size(), values->size());
+ int bad = 0;
+ for (size_t i = 0; i < values->size(); i++) {
+ const double got = dc::Round4(laya_test::Num(values->items()[i]));
+ const double want = laya_test::Num(rounded->items()[i]);
+ if (std::memcmp(&got, &want, sizeof got) != 0 && !(std::isnan(got) && std::isnan(want))) {
+ if (bad++ < 5) ADD_FAILURE() << "round4(" << laya_test::Num(values->items()[i]) << ") = " << got << ", Python " << want;
+ }
+ }
+ EXPECT_EQ(bad, 0);
+}
+
+// Round4 reads and writes through "%.4f"; a comma-decimal locale must not change it.
+TEST(Round4, IgnoresACommaDecimalLocale) {
+ laya_test::CommaLocale comma;
+ if (!comma.ok()) GTEST_SKIP() << "no comma-decimal locale installed";
+ EXPECT_EQ(dc::Round4(0.12345), 0.1235);
+ EXPECT_EQ(dc::Round4(0.00005), 0.0001);
+ EXPECT_EQ(dc::Round4(2.5), 2.5);
+ EXPECT_EQ(dc::PyFloat("1.5").value(), 1.5);
+}
+
+TEST(Round4, HalfEvenOnTheBinaryValue) {
+ EXPECT_EQ(dc::Round4(0.00005), 0.0001); // the double is a hair above the tie
+ EXPECT_EQ(dc::Round4(0.00015), 0.0001); // a hair below
+ EXPECT_EQ(dc::Round4(0.03125), 0.0312); // an exact tie: even
+ EXPECT_EQ(dc::Round4(0.09375), 0.0938);
+ EXPECT_TRUE(std::signbit(dc::Round4(-0.00001)));
+ EXPECT_TRUE(std::isnan(dc::Round4(NAN)));
+ EXPECT_TRUE(std::isinf(dc::Round4(INFINITY)));
+}
+
+// 5,000 random, tied and near-tied rows against Python's bytes. Python computes exp in float32,
+// whose last bits differ between CPUs; two kinds of difference are tolerated and counted: a number
+// one unit in the fourth decimal on a rounding boundary, and a choice between options whose
+// quotients are within kNearTieBand of the largest. Anything else fails.
+constexpr double kNearTieBand = 1e-6;
+
+struct Diff {
+ std::string path;
+ double delta = -1; // -1: not a number
+ std::string got, want;
+};
+
+void DiffJson(const std::string& path, const Value& got, const Value& want, std::vector<Diff>* out) {
+ auto num = [](const Value& v) { return v.kind() == Kind::Int || v.kind() == Kind::Float; };
+ if (want.kind() == Kind::Object) {
+ bool same = got.kind() == Kind::Object && got.size() == want.size();
+ for (size_t i = 0; same && i < want.size(); i++) same = got.key(i) == want.key(i);
+ if (!same) {
+ out->push_back({path, -1, laya::pyvalue::Repr(got), laya::pyvalue::Repr(want)});
+ return;
+ }
+ for (size_t i = 0; i < want.size(); i++) DiffJson(path + "/" + want.key(i), got.value(i), want.value(i), out);
+ } else if (num(want) && num(got)) {
+ if (laya::pyvalue::Repr(got) != laya::pyvalue::Repr(want)) {
+ out->push_back({path, std::fabs(laya_test::Num(got) - laya_test::Num(want)), laya::pyvalue::Repr(got), laya::pyvalue::Repr(want)});
+ }
+ } else if (laya::pyvalue::Repr(got) != laya::pyvalue::Repr(want)) {
+ out->push_back({path, -1, laya::pyvalue::Repr(got), laya::pyvalue::Repr(want)});
+ }
+}
+
+bool NearTied(const std::vector<float>& logits, const std::vector<int>& order, const dc::Temperatures& t, sc::Type kind,
+ int go_idx, int py_idx) {
+ const double temp = t.For(kind, int64_t(logits.size()), "");
+ std::vector<float> z(logits.size());
+ float top = -INFINITY;
+ for (size_t i = 0; i < z.size(); i++) top = std::max(top, z[i] = logits[i] / float(temp));
+ if (!order.empty()) {
+ std::vector<float> canonical(z.size());
+ for (size_t slot = 0; slot < order.size(); slot++) canonical[size_t(order[slot])] = z[slot];
+ z = canonical;
+ }
+ for (int i : {go_idx, py_idx}) {
+ if (i < 0 || size_t(i) >= z.size() || double(top) - double(z[size_t(i)]) > kNearTieBand) return false;
+ }
+ return true;
+}
+
+sc::Question FuzzQuestion(const std::string& kind, const Value& crit, const Value& order) {
+ Value g = Value::Object();
+ g.Set("t", Value::String(kind));
+ g.Set("ins", Value::String("i"));
+ Value labels = Value::Object();
+ if (kind == "choice") {
+ for (const Value& l : crit.items()) labels.Set(l.as_string(), Value::Null());
+ g.Set("crit", labels);
+ } else {
+ g.Set("crit", crit);
+ }
+ return GoldenQuestion(g, order);
+}
+
+TEST(DecodeGolden, AnswersFuzz) {
+ LAYA_GOLDEN_LIST(cases, "go_extra.json", "answers_fuzz", "cases");
+ LAYA_EXPECT_ROWS(cases, 5000);
+ int identical = 0, near_tie = 0, rounded = 0, bad = 0;
+ for (size_t i = 0; i < cases->size(); i++) {
+ const Value& rec = cases->items()[i];
+ const std::string kind = rec.Find("type")->as_string();
+ const Value& order_v = *rec.Find("option_order");
+ std::vector<int> order;
+ for (const Value& o : order_v.items()) order.push_back(int(o.as_int()));
+ sc::Question q = FuzzQuestion(kind, *rec.Find("criteria"), order_v);
+ std::vector<float> logits;
+ for (const Value& s : rec.Find("logits")->items()) logits.push_back(float(dc::PyFloat(s.as_string()).value()));
+ const Value* temp_v = rec.Find("temperature");
+ const dc::Temperatures temps = Uniform(laya_test::Num(*temp_v));
+ dc::Row row;
+ row.logits = logits;
+ row.k = int64_t(logits.size());
+ row.act = 0.25f;
+ auto a = dc::Decode(q, row, "", &temps);
+ ASSERT_TRUE(a.ok()) << i << ": " << a.error();
+ const std::string got = a.value().ToJson().value(), want = rec.Find("answer_text")->as_string();
+ if (got == want) {
+ identical++;
+ continue;
+ }
+ std::vector<Diff> diffs;
+ DiffJson("", laya::pyvalue::Parse(got).value(), laya::pyvalue::Parse(want).value(), &diffs);
+ bool ok = true, saw_choice = false, saw_round = false;
+ for (const Diff& d : diffs) {
+ if (d.path == "/choice" && kind == "choice") {
+ saw_choice = true;
+ ok = ok && NearTied(logits, order, temps, sc::Type::Choice, std::atoi(d.got.c_str() + 2), std::atoi(d.want.c_str() + 2));
+ } else if (d.delta > 0 && d.delta < 1.5e-4) {
+ saw_round = true;
+ } else {
+ ok = false;
+ }
+ }
+ if (!ok) {
+ if (bad++ < 5) ADD_FAILURE() << "case " << i << " (" << kind << ")\n go: " << got << "\n py: " << want;
+ } else if (saw_choice) {
+ near_tie++;
+ } else if (saw_round) {
+ rounded++;
+ }
+ }
+ std::printf("answers_fuzz: %d identical, %d near-tie choices, %d one-in-the-fourth-decimal, %d bad\n", identical, near_tie, rounded, bad);
+ EXPECT_EQ(bad, 0);
+ EXPECT_LE(rounded, 25) << "the tolerance is hiding more than float32 arithmetic";
+}
+
+
+sc::Question Pick(int n) {
+ std::vector<std::string> labels;
+ for (int i = 0; i < n; i++) labels.push_back("o" + std::to_string(i));
+ return sc::Question::ChoiceOf("pick", labels).value();
+}
+
+dc::Row RowOf(std::vector<float> logits) {
+ dc::Row r;
+ r.k = int64_t(logits.size());
+ r.logits = std::move(logits);
+ r.act = 0.5f;
+ return r;
+}
+
+TEST(Bucket, EdgesByOptionCount) {
+ const sc::Type c = sc::Type::Choice;
+ EXPECT_EQ(dc::Bucket(c, 1), "choice:2");
+ EXPECT_EQ(dc::Bucket(c, 2), "choice:2");
+ EXPECT_EQ(dc::Bucket(c, 3), "choice:3-5");
+ EXPECT_EQ(dc::Bucket(c, 5), "choice:3-5");
+ EXPECT_EQ(dc::Bucket(c, 6), "choice:6-10");
+ EXPECT_EQ(dc::Bucket(c, 10), "choice:6-10");
+ EXPECT_EQ(dc::Bucket(c, 11), "choice:11+");
+ EXPECT_EQ(dc::Bucket(sc::Type::Score, 4), "score:3-5");
+}
+
+// The bucket table beats the type table, and a language override beats both.
+TEST(Temperatures, BucketThenTypeThenLanguage) {
+ auto js = laya::pyvalue::Parse(R"({"t":[1.5,2,3],"o":{"choice:3-5":4},"l":{"zh-Hans":{"temperature":[2,2,2],"temperature_by_options":{"choice:2":2.5}},"yo":null}})").value();
+ auto t = dc::Temperatures::Of(js.Find("t"), js.Find("o"), js.Find("l")).value();
+ bool ov = true;
+ EXPECT_EQ(t.For(sc::Type::Choice, 4, "", &ov), 4.0);
+ EXPECT_FALSE(ov);
+ EXPECT_EQ(t.For(sc::Type::Choice, 7, ""), 1.5);
+ EXPECT_EQ(t.For(sc::Type::Score, 7, ""), 2.0);
+ EXPECT_EQ(t.For(sc::Type::Choice, 2, "ZH-Hant", &ov), 2.5);
+ EXPECT_TRUE(ov);
+ EXPECT_EQ(t.For(sc::Type::Choice, 4, "zh"), 2.0);
+ EXPECT_EQ(t.For(sc::Type::Choice, 4, "yo-NG"), 1.5); // null inherits the checkpoint's own
+ EXPECT_EQ(t.For(sc::Type::Choice, 4, "xx"), 4.0);
+}
+
+TEST(Temperatures, RefusesWhatPythonRefuses) {
+ auto of = [](const char* json) {
+ auto v = laya::pyvalue::Parse(json).value();
+ return dc::Temperatures::Of(&v, nullptr);
+ };
+ EXPECT_FALSE(of("[1,2]").ok());
+ EXPECT_FALSE(of("[1,2,3,4]").ok());
+ EXPECT_FALSE(of(R"("abc")").ok());
+ auto v = laya::pyvalue::Parse(R"({"zh":5})").value();
+ EXPECT_FALSE(dc::Temperatures::Of(nullptr, nullptr, &v).ok());
+}
+
+TEST(Clamp, BoundsAndNonNumbers) {
+ auto c = [](const char* j) { return dc::Clamp(laya::pyvalue::Parse(j).value()); };
+ EXPECT_EQ(c("0.1"), 0.5);
+ EXPECT_EQ(c("9"), 5.0);
+ EXPECT_EQ(c("2"), 2.0);
+ EXPECT_EQ(c("true"), 1.0);
+ EXPECT_EQ(c("null"), 1.0);
+ EXPECT_EQ(c("[2]"), 1.0);
+ EXPECT_EQ(c("NaN"), 1.0);
+ EXPECT_EQ(c("Infinity"), 1.0);
+ EXPECT_EQ(c(R"(" 1_0.5 ")"), 5.0);
+ EXPECT_EQ(c(R"("1__0")"), 1.0);
+ EXPECT_EQ(c(R"("0x10")"), 1.0);
+ EXPECT_EQ(c(R"("1e400")"), 1.0); // out of range is infinite
+ EXPECT_EQ(c("100000000000000000000000"), 5.0);
+}
+
+TEST(PyFloat, Spellings) {
+ EXPECT_EQ(dc::PyFloat("1.5").value(), 1.5);
+ EXPECT_EQ(dc::PyFloat(".5").value(), 0.5);
+ EXPECT_EQ(dc::PyFloat("5.").value(), 5.0);
+ EXPECT_EQ(dc::PyFloat("-1e2").value(), -100.0);
+ EXPECT_EQ(dc::PyFloat("\xD9\xA1.\xD9\xA5").value(), 1.5); // Arabic-Indic digits
+ EXPECT_TRUE(std::isinf(dc::PyFloat("-Infinity").value()));
+ EXPECT_TRUE(std::isnan(dc::PyFloat("nan").value()));
+ for (const char* bad : {"", ".", "e5", "1e", "1.5x", "_1", "1_", "1_.5", "0x1p3", "--1", "1 2"}) {
+ EXPECT_FALSE(dc::PyFloat(bad).has_value()) << bad;
+ }
+}
+
+// Python divides in float32, so two adjacent float32 logits can become one quotient: an exact tie
+// that numpy.argmax gives to the lower index. The first pair fails if the quotient is kept in
+// double; the second, whose temperature is not a float32, also fails if it is divided in double and rounded.
+TEST(Decode, QuotientTieFallsToTheFirst) {
+ struct Case {
+ double temperature;
+ uint32_t lower, upper;
+ };
+ for (const Case& c : {Case{3.0, 1069547521u, 1069547522u}, Case{1.3, 1072020843u, 1072020844u}}) {
+ float lo, hi;
+ std::memcpy(&lo, &c.lower, 4);
+ std::memcpy(&hi, &c.upper, 4);
+ ASSERT_TRUE(lo < hi && lo / float(c.temperature) == hi / float(c.temperature));
+ auto t = Uniform(c.temperature);
+ auto a = dc::Decode(Pick(2), RowOf({lo, hi}), "", &t);
+ ASSERT_TRUE(a.ok());
+ EXPECT_EQ(a.value().choice.Key(), "o0") << c.temperature;
+ }
+}
+
+TEST(Decode, FirstMaximumWinsAnExactTie) {
+ auto t = Uniform(1);
+ EXPECT_EQ(dc::Decode(Pick(3), RowOf({1, 1, 1}), "", &t).value().choice.Key(), "o0");
+ EXPECT_EQ(dc::Decode(Pick(3), RowOf({0, 2, 2}), "", &t).value().choice.Key(), "o1");
+}
+
+TEST(Decode, LargeLogitsDoNotOverflow) {
+ auto t = Uniform(1);
+ auto a = dc::Decode(Pick(2), RowOf({800, 0}), "", &t);
+ ASSERT_TRUE(a.ok());
+ EXPECT_EQ(a.value().probabilities[0].p, 1.0);
+ EXPECT_EQ(a.value().probabilities[1].p, 0.0);
+}
+
+TEST(Decode, RefusesWhatDoesNotFit) {
+ auto t = Uniform(1);
+ EXPECT_FALSE(dc::Decode(sc::Question(), RowOf({1, 2}), "", &t).ok());
+ EXPECT_FALSE(dc::Decode(Pick(3), RowOf({1, 2}), "", &t).ok()); // k differs from the options
+ dc::Row wide = RowOf({1, 2, 3});
+ wide.k = 2;
+ EXPECT_FALSE(dc::Decode(Pick(3), wide, "", &t).ok());
+ dc::Row narrow = RowOf({1, 2});
+ narrow.k = 3;
+ EXPECT_FALSE(dc::Decode(Pick(3), narrow, "", &t).ok()); // fewer logits than options
+ EXPECT_FALSE(dc::Decode(Pick(2), RowOf({1, NAN}), "", &t).ok());
+ EXPECT_FALSE(dc::Decode(Pick(2), RowOf({1, INFINITY}), "", &t).ok());
+ dc::Row bad_act = RowOf({1, 2});
+ bad_act.act = NAN;
+ EXPECT_FALSE(dc::Decode(Pick(2), bad_act, "", &t).ok());
+ auto small = Uniform(0.5);
+ EXPECT_FALSE(dc::Decode(Pick(2), RowOf({3e38f, 0}), "", &small).ok()); // overflows float32 once divided
+ EXPECT_FALSE(dc::Decode(sc::Question::Noul("n").value(), RowOf({1}), "", &t).ok());
+}
+
+TEST(Decode, PadColumnsAreNeverRead) {
+ auto t = Uniform(1);
+ dc::Row r = RowOf({1, 2});
+ r.logits.push_back(NAN); // past k
+ EXPECT_TRUE(dc::Decode(Pick(2), r, "", &t).ok());
+}
+
+TEST(Decode, OptionOrderIsUndone) {
+ auto t = Uniform(1);
+ sc::Question q = Pick(3).WithOptionOrder({2, 0, 1}).value(); // slot 0 holds option 2, ...
+ auto a = dc::Decode(q, RowOf({9, 0, 0}), "", &t);
+ ASSERT_TRUE(a.ok());
+ EXPECT_EQ(a.value().choice.Key(), "o2");
+}
+
+TEST(Decode, BinningReplacesTheConfidenceOnlyWithoutALanguageOverride) {
+ auto js = laya::pyvalue::Parse(R"({"l":{"zh":null}})").value();
+ auto t = dc::Temperatures::Of(nullptr, nullptr, js.Find("l")).value();
+ t.binning["choice:2"].values = {0.25, 0.75};
+ auto plain = dc::Decode(Pick(2), RowOf({4, 0}), "", &t).value();
+ EXPECT_EQ(plain.answer_confidence, 0.75); // 0.98 falls in the top of two bins
+ auto zh = dc::Decode(Pick(2), RowOf({4, 0}), "zh", &t).value();
+ EXPECT_NE(zh.answer_confidence, 0.75);
+ EXPECT_EQ(dc::ApplyBinning(1.0, "choice:2", t.binning), 0.75); // clamped into the last bin
+ EXPECT_EQ(dc::ApplyBinning(0.3, "absent", t.binning), 0.3);
+}
+
+TEST(ActionProbabilities, SoftmaxAndRefusals) {
+ auto p = dc::ActionProbabilities({0, 0});
+ ASSERT_TRUE(p.ok());
+ EXPECT_EQ(p.value()[0], 0.5f);
+ EXPECT_FALSE(dc::ActionProbabilities({}).ok());
+ EXPECT_FALSE(dc::ActionProbabilities({1, NAN}).ok());
+ EXPECT_TRUE(dc::ActionProbabilities({800, 0}).ok());
+}
+
+} // namespace
diff --git a/laya-cpp/tests/question_fixture.hpp b/laya-cpp/tests/question_fixture.hpp
new file mode 100644
index 00000000..488d7320
--- /dev/null
+++ b/laya-cpp/tests/question_fixture.hpp
@@ -0,0 +1,51 @@
+#pragma once
+// A schema::Question from the golden's internal form {"t", "ins", "crit", "labels"}, with an option order.
+#include <gtest/gtest.h>
+
+#include <cstdlib>
+#include <vector>
+
+#include "laya/schema.hpp"
+
+namespace laya_test {
+
+using laya::pyvalue::Value;
+namespace sc = laya::schema;
+using Kind = Value::Kind;
+
+inline sc::Question GoldenQuestion(const Value& g, const Value& order) {
+ const std::string kind = g.Find("t")->as_string();
+ const std::string ins = g.Find("ins")->as_string();
+ const Value* crit = g.Find("crit");
+ laya::Result<sc::Question> q = laya::Result<sc::Question>::Fail("unset");
+ if (kind == "choice") {
+ std::vector<sc::Option> opts;
+ for (size_t i = 0; i < crit->size(); i++) opts.push_back({sc::Label::Text(crit->key(i)), crit->value(i)});
+ q = sc::Question::Choice(ins, opts);
+ } else if (kind == "score") {
+ q = sc::Question::Score(ins, crit->items());
+ } else {
+ sc::NoulSpec spec;
+ if (crit != nullptr && crit->kind() == Kind::Object) {
+ if (const Value* t = crit->Find("true")) spec.true_text = *t;
+ if (const Value* f = crit->Find("false")) spec.false_text = *f;
+ }
+ if (const Value* l = g.Find("labels"); l != nullptr && !l->is_null()) {
+ spec.false_label = l->Find("false")->as_string();
+ spec.true_label = l->Find("true")->as_string();
+ }
+ q = sc::Question::Noul(ins, spec);
+ }
+ EXPECT_TRUE(q.ok()) << (q.ok() ? "" : q.error());
+ if (!q.ok()) std::abort();
+ if (!order.is_null()) {
+ std::vector<int> o;
+ for (const Value& v : order.items()) o.push_back(int(v.as_int()));
+ q = q.value().WithOptionOrder(o);
+ EXPECT_TRUE(q.ok());
+ if (!q.ok()) std::abort();
+ }
+ return q.value();
+}
+
+} // namespace laya_test
diff --git a/laya-cpp/tests/stub_session.hpp b/laya-cpp/tests/stub_session.hpp
new file mode 100644
index 00000000..15c0c9b2
--- /dev/null
+++ b/laya-cpp/tests/stub_session.hpp
@@ -0,0 +1,85 @@
+#pragma once
+// A stand-in for the model runtime: its outputs are a function of the integers it is fed (exact in
+// float32), as the Python generator's _plan_session. Records every run. Safe for concurrent Run.
+#include <atomic>
+#include <functional>
+#include <memory>
+#include <mutex>
+#include <vector>
+
+#include "laya/infer.hpp"
+
+namespace laya_test {
+
+struct RunRecord {
+ int64_t rows = 0, length = 0, markers = 0;
+ std::vector<int64_t> id_sums, tokens, marker_sums, qtypes;
+};
+
+class StubSession : public laya::infer::Session {
+ public:
+ // Shared with the test so counts survive the agent that owns the session.
+ struct State {
+ std::mutex mu;
+ std::vector<RunRecord> runs;
+ int closes = 0;
+ bool destroyed = false;
+ bool closed = false;
+ std::function<void()> on_run; // called at the start of every Run
+ std::function<void(laya::infer::Output*)> tamper; // may break the output
+ std::string fail; // non-empty: Run fails with this
+ };
+ explicit StubSession(std::shared_ptr<State> s = std::make_shared<State>()) : st_(std::move(s)) {}
+ ~StubSession() override {
+ std::lock_guard<std::mutex> l(st_->mu);
+ st_->destroyed = true;
+ }
+ std::shared_ptr<State> state() const { return st_; }
+
+ laya::Result<laya::infer::Output> Run(const laya::infer::Batch& b, const laya::CancelToken& cancel) override {
+ using R = laya::Result<laya::infer::Output>;
+ std::function<void()> hook;
+ {
+ std::lock_guard<std::mutex> l(st_->mu);
+ if (st_->closed) return R::Fail("infer: session is closed");
+ hook = st_->on_run;
+ }
+ if (hook) hook();
+ if (cancel.cancelled()) return R::Fail("cancelled");
+ RunRecord rec;
+ rec.rows = b.rows, rec.length = b.length, rec.markers = b.markers;
+ laya::infer::Output out;
+ for (int64_t r = 0; r < b.rows; r++) {
+ int64_t sum = 0, tokens = 0, msum = 0;
+ for (int64_t i = 0; i < b.length; i++) {
+ if (b.attention_mask[size_t(r * b.length + i)] == 1) {
+ sum += b.input_ids[size_t(r * b.length + i)];
+ tokens++;
+ }
+ }
+ for (int64_t j = 0; j < b.markers; j++) {
+ if (b.marker_mask[size_t(r * b.markers + j)]) msum += b.marker_pos[size_t(r * b.markers + j)];
+ out.logits.push_back(float(((sum + 31 * j) % 97 - 48) / 8.0));
+ }
+ for (int64_t c = 0; c < 2; c++) out.act_logits.push_back(float(((sum + 17 * c) % 97 - 48) / 8.0));
+ rec.id_sums.push_back(sum), rec.tokens.push_back(tokens), rec.marker_sums.push_back(msum);
+ rec.qtypes.push_back(b.qtype[size_t(r)]);
+ }
+ std::lock_guard<std::mutex> l(st_->mu);
+ st_->runs.push_back(std::move(rec));
+ if (!st_->fail.empty()) return R::Fail(st_->fail);
+ if (st_->tamper) st_->tamper(&out);
+ return R::Ok(std::move(out));
+ }
+ std::string Close() override {
+ std::lock_guard<std::mutex> l(st_->mu);
+ st_->closes++;
+ st_->closed = true;
+ return "";
+ }
+
+ private:
+ std::shared_ptr<State> st_;
+};
+
+} // namespace laya_test