test: verify DSpark device KV rollback

This commit is contained in:
Constantin committed 2026-11-03 13:56:46 -05:00
1 parent e14463b8eb
commit c96cfc9e7b
8 files changed
+418 -11

No files matched your search

+1
View File
@@ -20,6 +20,7 @@ set(RAD_WITH_FFMPEG "AUTO" CACHE STRING
"ON | OFF | AUTO -- decode image, video and audio parts with libavformat/libavcodec/libswscale/libswresample")
set_property(CACHE RAD_WITH_FFMPEG PROPERTY STRINGS ON OFF AUTO)
option(RAD_BUILD_TESTS "Build the test suite" ON)
option(RAD_ENABLE_KV_ROLLBACK_TEST_HOOK "Compile the test-only device KV rollback observer" OFF)
option(RAD_ASAN "Build host code with AddressSanitizer and UBSan" OFF)
option(RAD_TSAN "Build host code with ThreadSanitizer" OFF)
# LLVM 24's VOPD pairing is not repeatable unless patched (docker/llvm-vopd-pairing.patch); when
+5
View File
@@ -23,6 +23,11 @@ list(APPEND RAD_CORE_SRC ${_top})
add_library(rad_core STATIC ${RAD_CORE_SRC})
target_link_libraries(rad_core PUBLIC rad_abi ${CMAKE_DL_LIBS} Threads::Threads)
target_compile_definitions(rad_core PUBLIC RAD_VERSION="${PROJECT_VERSION}")
if(RAD_ENABLE_KV_ROLLBACK_TEST_HOOK)
# Scheduler is embedded in Engine and its test-only callback changes its class layout.
# Propagate the definition to every consumer to keep all translation units ABI-consistent.
target_compile_definitions(rad_core PUBLIC RAD_ENABLE_KV_ROLLBACK_TEST_HOOK=1)
endif()
target_include_directories(rad_core PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_SOURCE_DIR}/abi
+227
View File
@@ -44,8 +44,217 @@
#include <thread>
#include <unistd.h>
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
#include <string>
#endif
namespace rad {
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
namespace {
struct KVRollbackTestEvidence {
bool waiting_for_greedy = false;
std::string report_path;
uint64_t seq = 0;
int step = -1;
int proposals = 0;
int accepted = -1;
int32_t group = -1;
int64_t prefix_before = 0;
int64_t rollback_tokens_before = 0;
int64_t rollback_to_tokens = 0;
int64_t prefix_after_rollback = -1;
int64_t first_block_pos = 0;
int64_t block_size = 0;
int64_t n_layers = 0;
int64_t bytes_per_layer = 0;
std::vector<int32_t> logical_blocks;
std::vector<int32_t> physical_slots;
std::vector<uint8_t> before;
uint64_t after_hash = 0;
bool bytes_equal = false;
bool mapping_equal = false;
bool negative_control_detected = false;
};
uint64_t kv_test_hash(const std::vector<uint8_t>& bytes) {
uint64_t h = 14695981039346656037ull;
for (uint8_t b : bytes) h = (h ^ b) * 1099511628211ull;
return h;
}
bool kv_test_bytes_equal(const std::vector<uint8_t>& a, const std::vector<uint8_t>& b) {
return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin());
}
template<class RankT>
bool kv_test_snapshot(RankT& rank, uint64_t seq, int32_t group, int64_t prefix_tokens,
int64_t* first_block_pos, std::vector<int32_t>* logical,
std::vector<int32_t>* physical, std::vector<uint8_t>* bytes) {
const KVGroupPlan* p = rank.kv.plan(group);
if (!p || p->zero || !p->paged() || p->kind != RAD_KV_FULL || p->streamed() ||
p->n_layers <= 0 || p->block_size <= 0 || !p->base) return false;
const auto& table = rank.kv.block_table(seq, group);
const int64_t first_pos = rank.kv.first_block_pos(seq, group);
if (first_pos < 0 || prefix_tokens < first_pos) return false;
const int64_t complete = (prefix_tokens - first_pos) / p->block_size;
if (complete <= 0 || complete > (int64_t)table.size()) return false;
if (first_block_pos) *first_block_pos = first_pos;
/* Snapshot every complete block in the retained pre-verify prefix. The trailing partial
* block is omitted because accepted verify tokens may legitimately fill its unused slots. */
const int64_t nblocks = complete;
const int64_t layer_bytes = p->layer_bytes_per_block();
const int64_t block_bytes = p->n_layers * layer_bytes;
if (nblocks <= 0 || layer_bytes <= 0 || p->bytes_per_block != block_bytes) return false;
if (rad_dev_set(rank.device) < 0 || rad_stream_sync(rank.ctx.stream()) < 0) return false;
logical->clear();
physical->clear();
logical->reserve((size_t)nblocks);
physical->reserve((size_t)nblocks);
bytes->resize((size_t)nblocks * (size_t)block_bytes);
for (int64_t b = 0; b < nblocks; ++b) {
const int32_t id = table[(size_t)b];
if (id < 0 || id >= p->pool_blocks()) return false;
logical->push_back((int32_t)(first_pos / p->block_size + b));
physical->push_back(id);
for (int64_t layer = 0; layer < p->n_layers; ++layer) {
const auto* src = static_cast<const uint8_t*>(p->base) +
layer * p->layer_stride() + (int64_t)id * layer_bytes;
auto* dst = bytes->data() + b * block_bytes + layer * layer_bytes;
if (rad_memcpy_async(dst, src, layer_bytes, rank.ctx.stream()) < 0) return false;
}
}
return rad_stream_sync(rank.ctx.stream()) >= 0;
}
void kv_test_write_report(const KVRollbackTestEvidence& e, bool greedy, int greedy_token,
int64_t tokens_at_greedy) {
if (e.report_path.empty()) return;
std::ofstream f(e.report_path, std::ios::trunc);
if (!f) return;
f << "{\"partial_rejection_observed\":true,\"step\":" << e.step
<< ",\"sequence\":" << e.seq << ",\"proposals\":" << e.proposals
<< ",\"accepted\":" << e.accepted << ",\"group\":" << e.group
<< ",\"prefix_tokens_before_verify\":" << e.prefix_before
<< ",\"rollback_tokens_before\":" << e.rollback_tokens_before
<< ",\"rollback_to_tokens\":" << e.rollback_to_tokens
<< ",\"prefix_tokens_after\":" << e.prefix_after_rollback
<< ",\"first_block_pos\":" << e.first_block_pos
<< ",\"block_size\":" << e.block_size << ",\"layers\":" << e.n_layers
<< ",\"bytes_per_layer\":" << e.bytes_per_layer << ",\"logical_blocks\":[";
for (size_t i = 0; i < e.logical_blocks.size(); ++i) f << (i ? "," : "") << e.logical_blocks[i];
f << "],\"physical_slots\":[";
for (size_t i = 0; i < e.physical_slots.size(); ++i) f << (i ? "," : "") << e.physical_slots[i];
f << "],\"committed_prefix_bytes\":" << e.before.size()
<< ",\"before_hash\":" << kv_test_hash(e.before)
<< ",\"after_hash\":" << e.after_hash
<< ",\"bytes_equal\":" << (e.bytes_equal ? "true" : "false")
<< ",\"mapping_equal\":" << (e.mapping_equal ? "true" : "false")
<< ",\"negative_control_detected\":" << (e.negative_control_detected ? "true" : "false")
<< ",\"next_greedy_decode_observed\":" << (greedy ? "true" : "false")
<< ",\"tokens_at_next_greedy_decode\":" << (greedy ? tokens_at_greedy : -1)
<< ",\"next_greedy_token\":" << (greedy ? greedy_token : -1) << "}\n";
}
KVRollbackTestEvidence& kv_test_evidence() {
static KVRollbackTestEvidence e;
return e;
}
template<class Output, class Ranks>
void kv_test_before_commit(const StepPlan& plan, const Output& so, int step, Ranks& ranks) {
auto& e = kv_test_evidence();
if (!e.waiting_for_greedy && !e.report_path.empty() && e.accepted < 0) {
for (size_t i = 0; i < plan.e.size(); ++i) {
const StepEntry& entry = plan.e[i];
if (entry.seq == e.seq && step == e.step && entry.n_spec == e.proposals &&
(so.accepted[i] <= 0 || so.accepted[i] >= e.proposals)) {
e = KVRollbackTestEvidence{};
return;
}
}
}
if (!e.waiting_for_greedy) return;
for (size_t i = 0; i < plan.e.size(); ++i) {
const StepEntry& entry = plan.e[i];
if (entry.seq == e.seq && entry.req && entry.req->sp.greedy() &&
so.first_row[i] >= 0) {
kv_test_write_report(e, true, so.token[i], ranks[0]->kv.seq_tokens(e.seq));
e.waiting_for_greedy = false;
break;
}
}
}
template<class Ranks>
void kv_test_prepare(const StepPlan& plan, int step, Ranks& ranks) {
auto& e = kv_test_evidence();
if (!e.report_path.empty() || e.waiting_for_greedy) return;
const char* path = std::getenv("RADIANCE_TEST_KV_ROLLBACK_REPORT");
if (!path || !*path) return;
for (const StepEntry& entry : plan.e) {
if (!entry.req || entry.n_spec != 7) continue;
const int64_t prefix = entry.ctx_len;
for (int32_t g = 0; g < ranks[0]->kv.n_groups(); ++g) {
const KVGroupPlan* p = ranks[0]->kv.plan(g);
if (!p || p->kind != RAD_KV_FULL || p->zero || p->streamed() ||
prefix < p->block_size) continue;
KVRollbackTestEvidence candidate;
candidate.report_path = path;
candidate.seq = entry.seq;
candidate.step = step;
candidate.proposals = entry.n_spec;
candidate.group = g;
candidate.prefix_before = prefix;
candidate.block_size = p->block_size;
candidate.n_layers = p->n_layers;
candidate.bytes_per_layer = p->layer_bytes_per_block();
if (!kv_test_snapshot(*ranks[0], entry.seq, g, prefix, &candidate.first_block_pos,
&candidate.logical_blocks, &candidate.physical_slots,
&candidate.before)) continue;
e = std::move(candidate);
return;
}
}
}
template<class RankT>
void kv_test_rollback(uint64_t seq, int proposals, int accepted, int64_t valid,
bool before, RankT& rank) {
auto& e = kv_test_evidence();
if (e.report_path.empty() || e.waiting_for_greedy || seq != e.seq ||
proposals != e.proposals || proposals != 7 || accepted <= 0 || accepted >= proposals)
return;
if (before) {
e.accepted = accepted;
e.rollback_tokens_before = rank.kv.seq_tokens(seq);
e.rollback_to_tokens = valid;
return;
}
std::vector<int32_t> logical, physical;
std::vector<uint8_t> after;
int64_t first_block_pos = -1;
const bool copied = kv_test_snapshot(rank, seq, e.group, std::min(e.prefix_before, valid),
&first_block_pos, &logical, &physical, &after);
bool mapping_equal = copied && first_block_pos == e.first_block_pos &&
logical == e.logical_blocks && physical == e.physical_slots;
const bool bytes_equal = copied && kv_test_bytes_equal(after, e.before);
e.after_hash = copied ? kv_test_hash(after) : 0;
e.bytes_equal = bytes_equal;
std::vector<uint8_t> mutated = e.before;
if (!mutated.empty()) mutated[0] ^= 1;
e.negative_control_detected = !mutated.empty() && !kv_test_bytes_equal(e.before, mutated);
const int64_t after_tokens = rank.kv.seq_tokens(seq);
mapping_equal = mapping_equal && after_tokens == e.rollback_to_tokens;
e.mapping_equal = mapping_equal;
e.prefix_after_rollback = after_tokens;
kv_test_write_report(e, false, -1, -1);
e.waiting_for_greedy = true;
(void)valid; // rollback's requested length is emitted by the manager as after_tokens
}
} // namespace
#endif
/* The operator's RADIANCE_* names, captured at construction for the diagnostics report. */
Engine::Engine(Config cfg)
: cfg_(std::move(cfg)), env_set_(diag::env_names(environ, "RADIANCE_")) {}
@@ -507,6 +716,9 @@ int Engine::issue_ahead(const RadBatch** out) {
sched_.expect_draft(block_row_[(size_t)i].seq, block_steps_);
const RadBatch* nb = sched_.step_next();
if (!nb) return RAD_OK;
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
kv_test_prepare(sched_.plan(), nb->step, ranks_);
#endif
/* Its rows' tokens, positions and slots, advanced on the card behind this step's acceptance
* and drafts. */
RAD_TRY(advance_all(ADV_TRUNK, 0, false));
@@ -568,6 +780,15 @@ int Engine::step_loop() {
return fail_loop(RAD_E_UNSUPPORTED);
}
const bool t_on = (int)log_level() >= (int)Log::Debug;
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
if (std::getenv("RADIANCE_TEST_KV_ROLLBACK_REPORT")) {
sched_.set_kv_rollback_test_hook([this](uint64_t seq, int proposals, int accepted,
int64_t valid, bool before) {
if (!ranks_.empty()) kv_test_rollback(seq, proposals, accepted, valid, before,
*ranks_[0]);
});
}
#endif
/* The next step's forward pass when already issued behind the previous step, before its
* readback (Scheduler::step_next). */
const RadBatch* ahead = nullptr;
@@ -621,6 +842,9 @@ int Engine::step_loop() {
* produces_token, 1 + n_spec rows each. Row and sequence indices differ (a mid-prompt
* chunk produces no row). */
const StepPlan& plan = sched_.plan();
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
kv_test_prepare(plan, b->step, ranks_);
#endif
/* One entry per request; Sampler::build_step expands each into 1 + n_draft rows itself
* (giving each position its RNG coordinate), so one push per row would stage (1+n)^2 rows.
* `first_row` indexes sampled tokens, so it counts rows. */
@@ -884,6 +1108,9 @@ int Engine::step_loop() {
res.first_row = so.first_row.data();
}
res.path = so.path.empty() ? nullptr : so.path.data();
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
kv_test_before_commit(plan, so, b->step, ranks_);
#endif
st = sched_.commit(res);
if (t_on) phase_mark(PH_COMMIT);
if (st < 0) { RAD_ERR("commit: %s", rad_strerror(st)); return fail_loop(st); }
+7
View File
@@ -2571,7 +2571,14 @@ int Scheduler::commit(StepResult& res) {
/* Not while a step issued ahead writes past `valid`; that step's commit rolls back to
* the end it reaches. */
if (a < e.n_spec && !(next_open_ && s.entry_next >= 0)) {
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
if (kv_rollback_test_hook_) kv_rollback_test_hook_(r.id, e.n_spec, a, valid, true);
#endif
int st = kv_->rollback(r.id, valid);
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
if (st >= 0 && kv_rollback_test_hook_)
kv_rollback_test_hook_(r.id, e.n_spec, a, valid, false);
#endif
if (st < 0) RAD_WARN("kv rollback for request %llu: %s",
(unsigned long long)r.id, rad_strerror(st));
}
+13
View File
@@ -19,6 +19,9 @@
#include "ngram.h"
#include <chrono>
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
#include <functional>
#endif
#include <memory>
#include <mutex>
#include <unordered_map>
@@ -495,6 +498,13 @@ public:
int64_t chunk_end(const Request& r, int64_t n_target) const;
private:
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
friend class Engine;
/* Test-build-only observer at the concrete rollback operation. */
void set_kv_rollback_test_hook(std::function<void(uint64_t, int, int, int64_t, bool)> hook) {
kv_rollback_test_hook_ = std::move(hook);
}
#endif
Program* prog_ = nullptr;
Config cfg_{};
ChunkGeometry geo_{};
@@ -512,6 +522,9 @@ private:
* step, so plan_chunk called directly answers for a span. */
bool span_now_ = true;
IKVManager* kv_ = nullptr;
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
std::function<void(uint64_t, int, int, int64_t, bool)> kv_rollback_test_hook_;
#endif
IPrefixCache* pc_ = nullptr;
/* Does a prefix-cache hit leave a hole in a block drafter's own KV? Only if some paged group
+100
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
"""Exercise the compile-time-only direct KV rollback observer against a live Spark server.
Build the server with -DRAD_ENABLE_KV_ROLLBACK_TEST_HOOK=ON and set
RADIANCE_TEST_KV_ROLLBACK_REPORT in that server's environment to the same report path supplied
here. This script sends a real greedy completion; it does not synthesize KV data.
"""
import argparse
import json
from pathlib import Path
import sys
import time
import urllib.error
import urllib.request
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--url", required=True, help="server base URL, e.g. http://127.0.0.1:8080")
parser.add_argument("--model", required=True)
parser.add_argument("--report", required=True, type=Path,
help="same path configured in server's RADIANCE_TEST_KV_ROLLBACK_REPORT")
parser.add_argument("--prompt", default=("Write a detailed, varied explanation of why "
"forest ecosystems change over time. " * 20))
parser.add_argument("--max-tokens", type=int, default=128)
parser.add_argument("--timeout", type=float, default=180.0)
args = parser.parse_args()
if args.report.exists():
parser.error(f"report path already exists; choose a fresh path: {args.report}")
args.report.parent.mkdir(parents=True, exist_ok=True)
evidence = None
endpoint = args.url.rstrip("/") + "/v1/chat/completions"
for attempt in range(8):
prompt = args.prompt + f"\nVariation {attempt + 1}: use a distinct example."
body = json.dumps({"model": args.model, "messages": [{"role": "user", "content": prompt}],
"temperature": 0, "max_tokens": args.max_tokens,
"reasoning_effort": "none", "stream": False}).encode()
request = urllib.request.Request(endpoint, body, {"Content-Type": "application/json"})
try:
with urllib.request.urlopen(request, timeout=args.timeout) as response:
result = json.loads(response.read())
if not result.get("choices"):
raise RuntimeError("server returned no completion choices")
except (urllib.error.URLError, TimeoutError, RuntimeError, json.JSONDecodeError) as exc:
print(f"request {attempt + 1} failed: {exc}", file=sys.stderr)
return 1
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
if args.report.exists():
try:
candidate = json.loads(args.report.read_text())
except (OSError, json.JSONDecodeError):
time.sleep(0.05)
continue
if candidate.get("next_greedy_decode_observed"):
evidence = candidate
break
time.sleep(0.05)
if evidence is not None:
break
if evidence is None:
print("no completed direct KV observer report; a partial depth-7 rollback followed by "
"the next greedy decode was not observed", file=sys.stderr)
return 1
required = {
"partial_rejection_observed": evidence.get("partial_rejection_observed") is True,
"depth_7": evidence.get("proposals") == 7 and 0 < evidence.get("accepted", 0) < 7,
"rollback_length": evidence.get("prefix_tokens_after") == evidence.get("rollback_to_tokens"),
"bytes_equal": evidence.get("bytes_equal") is True,
"mapping_equal": evidence.get("mapping_equal") is True,
"physical_slot_mapping": len(evidence.get("logical_blocks", [])) > 0 and
len(evidence.get("logical_blocks", [])) ==
len(evidence.get("physical_slots", [])) and
evidence.get("logical_blocks") ==
sorted(set(evidence.get("logical_blocks", []))) and
len(evidence.get("physical_slots", [])) ==
len(set(evidence.get("physical_slots", []))),
"all_complete_prefix_blocks": evidence.get("block_size", 0) > 0 and
evidence.get("prefix_tokens_before_verify", 0) >=
evidence.get("first_block_pos", 0) and
len(evidence.get("logical_blocks", [])) ==
(evidence.get("prefix_tokens_before_verify", 0) -
evidence.get("first_block_pos", 0)) //
evidence.get("block_size", 1),
"snapshot_geometry": evidence.get("layers", 0) > 0 and
evidence.get("bytes_per_layer", 0) * evidence.get("layers", 0) *
len(evidence.get("logical_blocks", [])) ==
evidence.get("committed_prefix_bytes", 0),
"negative_control": evidence.get("negative_control_detected") is True,
"next_greedy_decode": evidence.get("next_greedy_decode_observed") is True and
isinstance(evidence.get("next_greedy_token"), int) and
evidence.get("next_greedy_token") >= 0,
}
print(json.dumps({"checks": required, "evidence": evidence}, indent=2))
return 0 if all(required.values()) else 1
if __name__ == "__main__":
raise SystemExit(main())
+32 -11
View File
@@ -252,6 +252,23 @@ def stop_sequence_observed(unstopped: dict[str, Any], stopped: dict[str, Any], m
return bool(found) and stopped["finish_reason"] == "stop" and stopped["content"] == before_marker
def observed_draft_token_total(trials: list[dict[str, Any]]) -> int:
return sum(int(trial["draft_tokens"]) for trial in trials)
def seeded_sample_reproduced(first: dict[str, Any], repeat: dict[str, Any]) -> bool:
"""Equal empty responses do not establish seeded sampling reproducibility."""
content = first.get("content")
count = first.get("completion_tokens")
repeat_count = repeat.get("completion_tokens")
finish = first.get("finish_reason")
return (isinstance(content, str) and bool(content.strip()) and
content == repeat.get("content") and
finish in ("stop", "length") and finish == repeat.get("finish_reason") and
type(count) is int and count > 0 and
type(repeat_count) is int and count == repeat_count)
def calibrated_rollover_prompt(base: str, model: str, api_key: str | None,
timeout: float, target: int = 480) -> tuple[str, int]:
"""Find a repeated prompt below the 512 boundary using response usage (no tokenizer guess)."""
@@ -392,14 +409,14 @@ def run(args: argparse.Namespace) -> dict[str, Any]:
eos = chat_request(on_url, args.model,
[{"role": "user", "content": "Reply with exactly OK and then end the turn."}],
api_key=args.api_key, timeout=args.timeout, temperature=0, seed=61,
max_tokens=24)
max_tokens=24, reasoning_effort="none")
stop_prompt = [{"role": "user", "content": "Write exactly DS_STOP_6f41 and nothing after it."}]
unstopped = chat_request(on_url, args.model, stop_prompt,
api_key=args.api_key, timeout=args.timeout, temperature=0, seed=67,
max_tokens=24)
max_tokens=24, reasoning_effort="none")
stopped = chat_request(on_url, args.model, stop_prompt,
api_key=args.api_key, timeout=args.timeout, temperature=0, seed=67,
max_tokens=24, stop=["DS_STOP_6f41"])
max_tokens=24, stop=["DS_STOP_6f41"], reasoning_effort="none")
result["scenarios"]["eos_and_stop"] = {"eos": eos, "without_stop": unstopped, "stop": stopped}
require(result, "natural_end_of_turn", eos["finish_reason"] == "stop",
f"finish_reason={eos['finish_reason']}")
@@ -425,13 +442,17 @@ def run(args: argparse.Namespace) -> dict[str, Any]:
seeded_body = [{"role": "user", "content": "Write a short, varied sentence about a comet."}]
seeded_a = chat_request(on_url, args.model, seeded_body, api_key=args.api_key, timeout=args.timeout,
temperature=0.75, seed=99173, max_tokens=32)
temperature=0.75, seed=99173, max_tokens=32, reasoning_effort="none")
seeded_b = chat_request(on_url, args.model, seeded_body, api_key=args.api_key, timeout=args.timeout,
temperature=0.75, seed=99173, max_tokens=32)
temperature=0.75, seed=99173, max_tokens=32, reasoning_effort="none")
same = seeded_a["content"] == seeded_b["content"]
result["scenarios"]["seeded_sampling"] = {"first": seeded_a, "repeat": seeded_b, "identical": same}
require(result, "seed_reproduces_sample", same,
f"first={seeded_a['content']!r}, repeat={seeded_b['content']!r}")
reproduced = seeded_sample_reproduced(seeded_a, seeded_b)
result["scenarios"]["seeded_sampling"] = {"first": seeded_a, "repeat": seeded_b,
"identical": same, "valid_reproduction": reproduced}
require(result, "seed_reproduces_sample", reproduced,
f"first={seeded_a['content']!r}, repeat={seeded_b['content']!r}, "
f"finish={seeded_a['finish_reason']!r}/{seeded_b['finish_reason']!r}, "
f"completion_tokens={seeded_a['completion_tokens']!r}/{seeded_b['completion_tokens']!r}")
# Exercise concurrent batching, then look for unaccepted proposals. Aggregate per-request
# counters cannot establish whether any single verify was partially accepted.
@@ -467,9 +488,9 @@ def run(args: argparse.Namespace) -> dict[str, Any]:
"draft_accepted": accepted, "unaccepted_proposals": rejected})
result["scenarios"]["unaccepted_proposals"] = {"trials": rejection_trials,
"observed": any_rejection}
require(result, "draft_proposals_are_observed",
any(t["draft_tokens"] > 0 for t in rejection_trials),
"no draft_tokens_total increase; confirm DSpark is enabled on this server")
draft_tokens_observed = observed_draft_token_total(rejection_trials)
require(result, "draft_proposals_are_observed", draft_tokens_observed > 0,
f"draft_tokens_total delta={draft_tokens_observed}")
if not args.allow_unobserved_rejection:
require(result, "unaccepted_proposals_are_observed", any_rejection,
f"trials={len(rejection_trials)}; per-trial deltas are recorded")
+33
View File
@@ -2,6 +2,7 @@
"""Host unit tests for the DSpark QoS harness's evidence checks (no server/GPU)."""
import importlib.util
import io
import json
from pathlib import Path
import unittest
from unittest.mock import patch
@@ -52,6 +53,38 @@ class HarnessChecks(unittest.TestCase):
r = qos.stream_request("", "", "test", api_key=None, timeout=1)
self.assertIsNotNone(r["first_text_s"])
def test_draft_token_total_reports_observed_trials(self):
self.assertEqual(qos.observed_draft_token_total([{"draft_tokens": 168}, {"draft_tokens": 189}]), 357)
self.assertEqual(qos.observed_draft_token_total([]), 0)
def test_seeded_repeat_requires_nonempty_matching_content_and_usage(self):
sample = {"content": "A bright comet crosses the sky.", "finish_reason": "stop",
"completion_tokens": 7}
self.assertTrue(qos.seeded_sample_reproduced(sample, dict(sample)))
for first, repeat in (
({**sample, "content": ""}, {**sample, "content": ""}),
({**sample, "content": " "}, {**sample, "content": " "}),
(sample, {**sample, "content": "A different comet."}),
(sample, {**sample, "finish_reason": "length"}),
(sample, {**sample, "completion_tokens": 8}),
(sample, {**sample, "completion_tokens": 7.0}),
(sample, {**sample, "completion_tokens": None}),
({**sample, "completion_tokens": 1}, {**sample, "completion_tokens": True}),
({**sample, "finish_reason": None}, {**sample, "finish_reason": None}),
):
with self.subTest(first=first, repeat=repeat):
self.assertFalse(qos.seeded_sample_reproduced(first, repeat))
def test_chat_request_forwards_reasoning_effort(self):
payload = {"choices": [{"finish_reason": "stop", "message": {"content": "OK"}}],
"usage": {"completion_tokens": 1}}
with patch.object(qos, "fetch", return_value=io.BytesIO(json.dumps(payload).encode())) as fetch:
result = qos.chat_request("http://localhost", "spark", [{"role": "user", "content": "test"}],
api_key=None, timeout=1, reasoning_effort="none")
self.assertEqual(result["content"], "OK")
sent = json.loads(fetch.call_args.kwargs["data"])
self.assertEqual(sent["reasoning_effort"], "none")
def test_stop_requires_control_and_exact_prefix(self):
marker = "STOP"
stopped = {"finish_reason": "stop", "content": "prefix "}