Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
Compare cache-disabled engines against untouched upstream
Jeremiah Ritchey573bb36baa91
diff --git a/src/program/generate.cpp b/src/program/generate.cppindex 7cadca36e..7e79f8402 100644--- a/src/program/generate.cpp+++ b/src/program/generate.cpp@@ -4375,6 +4375,7 @@ int main(int argc, char** argv) {uint64_t h_ple = hash_dev(ss.ple_hist, ss.ple_hist ? z.ple : 0, 1469598103934665603ull);uint64_t h_tail = 1469598103934665603ull, h_pool = h_tail, h_kv = h_tail, h_stale = h_tail;uint64_t h_dead = h_tail;+ uint64_t h_pool_complete = h_tail; // upstream's extent, without the moving spare rowconst int64_t kvb = qs.head_dim, scb = (qs.head_dim / 64) * 2;// a state's K/V arrays and their bytes per (cell, head) row: the host copy when it has oneauto kv_arrays = [&](const strata::core::QsaState& st) {@@ -4402,6 +4403,7 @@ int main(int argc, char** argv) {const strata::core::QsaState& st = ss.qsa_states[i];h_tail = hash_dev(st.idx_tail, z.tail, h_tail);h_dead = hash_dev(st.idx_dead, z.dead, h_dead);+ h_pool_complete = hash_dev(st.idx_pooled, (size_t) (L / qs.idx_block) * qs.idx_dim * 4, h_pool_complete);h_pool = hash_dev(st.idx_pooled, (size_t) (L > 0 ? L / qs.idx_block + 1 : 0) * qs.idx_dim * 4, h_pool);// KV streaming: the host copy is the identity layout and holds every cellfor (const auto& [pool, w] : kv_arrays(st)) {@@ -4419,10 +4421,11 @@ int main(int argc, char** argv) {return 1;}std::fprintf(stderr, "strata serve: STATE_HASH L=%lld gdn=%016llx ple=%016llx tail=%016llx pooled=%016llx "- "kv=%016llx mtp=%016llx stale=%016llx dead=%016llx ple_prev=%d,%d\n", (long long) L,+ "kv=%016llx mtp=%016llx stale=%016llx dead=%016llx pooled_complete=%016llx ple_prev=%d,%d\n", (long long) L,(unsigned long long) h_gdn, (unsigned long long) h_ple, (unsigned long long) h_tail,(unsigned long long) h_pool, (unsigned long long) h_kv, (unsigned long long) h_mtp,- (unsigned long long) h_stale, (unsigned long long) h_dead, ss.ple_prev[0], ss.ple_prev[1]);+ (unsigned long long) h_stale, (unsigned long long) h_dead,+ (unsigned long long) h_pool_complete, ss.ple_prev[0], ss.ple_prev[1]);}const int64_t req_hits = drive.d.cache_hits - decode_hits0;const int64_t req_look = (drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused) - decode_look0;diff --git a/tools/conversation_cache_disabled.py b/tools/conversation_cache_disabled.pynew file mode 100644index 000000000..db3c05f2b--- /dev/null+++ b/tools/conversation_cache_disabled.py@@ -0,0 +1,195 @@+"""Compare untouched upstream with cache-disabled engines; dry-run by default.++Private engines run sequentially in an exclusive GPU window. This is a correctness+gate, not a throughput benchmark: state fingerprinting adds diagnostic overhead.+"""+import argparse+import hashlib+import json+from pathlib import Path+import re+import sys+import threading+import time++ROOT = Path(__file__).resolve().parents[1]+sys.path[:0] = [str(ROOT), str(ROOT / 'tools')]+from conversation_cache_parity import load_tokenizer, require+from conversation_cache_soak import answer_text+from serve.frontend import ChatTemplate+from serve.server import StrataEngine, child_env++NAMES = ('short', 'A', 'A-live', 'A-checkpoint', 'B', 'A-return', 'B-return', 'A-return-again')+SETTINGS = ('version', 'context', 'kv', 'kv_resident', 'expert_slots', 'spec',+ 'mtp_max', 'lookup', 'cvec', 'pcie_frac', 'spec_min_p', 'pool_workers')+# Untouched 0.1.27 does not emit the indexer `dead` field added by this PR.+# Draft scratch and unused page padding are not comparable authoritative state.+STATE_KEYS = ('L', 'gdn', 'ple', 'tail', 'pooled', 'kv', 'ple_prev')+++def state_hashes(text, *, candidate=False):+ hashes = []+ for line in text.splitlines():+ if 'STATE_HASH L=' in line:+ fields = dict(re.findall(r'(\w+)=([0-9a-f,-]+)', line))+ require(set(STATE_KEYS) <= fields.keys(), 'missing upstream-compatible state fields')+ if candidate:+ # The PR's pooled hash includes the spare row. Require the+ # separately emitted upstream extent instead of comparing unlike bytes.+ require('pooled_complete' in fields, 'candidate lacks completed-row fingerprint')+ fields['pooled'] = fields['pooled_complete']+ hashes.append({key: fields[key] for key in STATE_KEYS})+ return hashes+++def common_args(cfg, spec):+ # Upstream has no conversation-cache options. Omit them from EVERY arm so+ # the candidates exercise their disabled default with identical arguments.+ args, i = [], 0+ while i < len(cfg['args']):+ arg = cfg['args'][i]+ if arg.startswith('--conversation-cache-'):+ require(i + 1 < len(cfg['args']), 'cache option lacks a value')+ i += 2+ else:+ args.append(arg)+ i += 1+ return args + ['--prompt-cache', '6', '--adapt-swaps', '0', '--spec', str(max(2, spec)),+ '--mtp-max-t', str(spec), '--suffix-draft', '0', '--spec-min-p', '0']+++def verify(results):+ arms = results['arms']+ require(len(arms) >= 2 and arms[0]['name'] == 'upstream', 'missing comparison arms')+ baseline = arms[0]+ requests = results['requests']+ require([r['name'] for r in requests] == list(NAMES), 'incomplete request sequence')+ require(all(r['ids'] and r['max_new'] > 0 for r in requests), 'empty request')+ digest = hashlib.sha256(json.dumps(requests, sort_keys=True).encode()).hexdigest()+ require(digest == results['request_digest'], 'request evidence changed')+ for arm in arms:+ require(arm['args'] == baseline['args'], 'engine arguments differ')+ require(arm['request_digest'] == results['request_digest'], 'input requests differ')+ require([r['name'] for r in arm['records']] == list(NAMES), 'incomplete output sequence')+ require(not arm['cache_events'], 'disabled cache performed snapshot operations')+ for key in SETTINGS:+ require(key in arm['info'] and arm['info'][key] == baseline['info'][key],+ f'{arm["name"]}: resolved setting differs: {key}')+ if arm['name'] != 'upstream':+ require(arm['info'].get('conversation_cache_mib') == 0, 'RAM cache not disabled')+ require(arm['info'].get('conversation_disk_mib', 0) == 0, 'disk cache not disabled')+ for request, reference, record in zip(requests, baseline['records'], arm['records']):+ require(record['ids'] and record['finish'] in ('stop', 'length'), 'incomplete generation')+ require(set(STATE_KEYS) <= record['state'].keys(), 'incomplete state fingerprint')+ require(record['ids'] == reference['ids'], f'{arm["name"]}/{record["name"]}: output differs')+ require(record['state'] == reference['state'], f'{arm["name"]}/{record["name"]}: state differs')+ require(record['reused'] == reference['reused'], 'prefix reuse differs')+ require(record['prompt_tokens'] == len(request['ids']), 'wrong prompt length')+ if request.get('expected'):+ require(answer_text(record['text']) == request['expected'].casefold(), 'known answer is wrong')+ records = {r['name']: r for r in arm['records']}+ require(records['A-live']['reused'] > 0 and records['A-checkpoint']['reused'] > 0,+ 'continuation/checkpoint path not exercised')+ require(records['A-return']['reused'] == records['A-return-again']['reused'] == 0,+ 'conversation switching did not force cold fallback')+++def main():+ ap = argparse.ArgumentParser(description=__doc__)+ ap.add_argument('--config', type=Path, required=True)+ ap.add_argument('--upstream', type=Path, required=True)+ ap.add_argument('--candidate', type=Path, action='append', required=True)+ ap.add_argument('--output', type=Path, required=True, help='new directory; existing paths refused')+ ap.add_argument('--paragraphs', type=int, default=128)+ ap.add_argument('--spec', type=int, choices=(1, 4), default=1)+ ap.add_argument('--run', action='store_true')+ a = ap.parse_args()+ if a.paragraphs < 1:+ ap.error('paragraphs must be positive')+ if not a.run:+ print('Dry run: upstream and disabled candidates; identical inputs/settings, known answers and state parity.')+ return+ cfg = json.loads(a.config.read_text())+ tok_path = Path(cfg['tokenizer'])+ tok = load_tokenizer(tok_path)+ tpl_path = tok_path / 'chat_template.jinja'+ tpl = ChatTemplate(tpl_path if tpl_path.exists() else ROOT / 'serve/chat_template.jinja')+ def encode(text):+ return tok.encode(text, parse_special=True)+ def prompt(text):+ return encode(tpl.render([{'role': 'user', 'content': text}], enable_thinking=False))+ text = 'Conversation A. Remember the exact code AZURE-314159.\n'+ text += '\n'.join(f'Record {i}: blue square, green triangle, red circle.' for i in range(a.paragraphs))+ A = prompt(text + '\nThe exact code to remember is AZURE-314159. Reply OK.')+ B = prompt('Unrelated conversation B. Remember BRONZE-271828. Reply OK.')+ suffix = encode('<|im_end|>\n<|im_start|>user\nWhat exact code did I ask you to remember? '+ 'Reply with only that code.<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n')+ args = common_args(cfg, a.spec)+ env = child_env(cfg)+ env.pop('STRATA_SNAPSHOT_VERIFY', None)+ env['STRATA_STATE_HASH'] = '1'+ env['STRATA_MTP_BATCH'] = '1'+ a.output.mkdir(mode=0o700, parents=False, exist_ok=False)+ results = {'config': cfg, 'paragraphs': a.paragraphs, 'spec': a.spec, 'arms': [], 'requests': [],+ 'compared_state_fields': STATE_KEYS,+ 'environment': {k: v for k, v in env.items() if k.startswith('STRATA_')}}+ for index, exe in enumerate([a.upstream, *a.candidate]):+ name = 'upstream' if index == 0 else f'candidate-{index}'+ log = a.output / f'{name}.log'+ print(f'START {name}: {exe}', flush=True)+ started = time.monotonic()+ engine = StrataEngine(str(exe.resolve()), args, cwd=cfg.get('cwd'), log=str(log), env=env)+ arm = {'name': name, 'exe': str(exe.resolve()), 'args': args, 'info': dict(engine.info),+ 'startup_seconds': time.monotonic() - started, 'records': []}+ with exe.open('rb') as source:+ arm['exe_sha256'] = hashlib.file_digest(source, 'sha256').hexdigest()+ def generate(request):+ ids = [t for t in engine.generate(request['ids'], request['max_new'], {'temperature': 0},+ threading.Event()) if t is not None]+ arm['records'].append({'name': request['name'], 'ids': ids, **engine.last,+ 'text': tok.decode(ids)})+ return ids+ try:+ if index == 0:+ def add(name, ids, max_new, expected=None):+ request = dict(name=name, ids=ids, max_new=max_new, expected=expected)+ results['requests'].append(request)+ return generate(request)+ add('short', prompt('What is 2 + 2? Reply with only the number.'), 16, '4')+ head = add('A', A, 1)+ require(len(head) == 1, 'A must produce one token')+ continuation = A + head + suffix+ add('A-live', continuation, 32, 'AZURE-314159')+ add('A-checkpoint', continuation, 32, 'AZURE-314159')+ add('B', B, 1)+ add('A-return', continuation, 32, 'AZURE-314159')+ add('B-return', B, 1)+ add('A-return-again', continuation, 32, 'AZURE-314159')+ payload = json.dumps(results['requests'], sort_keys=True).encode()+ results['request_digest'] = hashlib.sha256(payload).hexdigest()+ (a.output / 'requests.json').write_bytes(payload)+ else:+ for request in results['requests']:+ generate(request)+ finally:+ engine.close()+ engine.proc.wait(timeout=30)+ engine.log.close()+ arm['request_digest'] = hashlib.sha256(json.dumps(results['requests'], sort_keys=True).encode()).hexdigest()+ log_text = log.read_text()+ hashes = state_hashes(log_text, candidate=index != 0)+ require(len(hashes) == len(arm['records']), f'{name}: missing state hashes')+ for record, fingerprint in zip(arm['records'], hashes):+ record['state'] = fingerprint+ arm['cache_events'] = [line for line in log_text.splitlines() if any(mark in line for mark in+ ('conversation cache: parked', 'disk cache: spilled', 'SNAPSHOT_VERIFY'))]+ results['arms'].append(arm)+ (a.output / 'results.json').write_text(json.dumps(results, indent=2) + '\n')+ print(f'DONE {name}', flush=True)+ verify(results)+ (a.output / 'passed.json').write_text(json.dumps({'passed': True, 'request_digest': results['request_digest']}) + '\n')+ print('PASS: untouched upstream versus disabled engines; identical tokens, main state, reuse and known answers')+++if __name__ == '__main__':+ main()diff --git a/tools/test_conversation_cache_disabled.py b/tools/test_conversation_cache_disabled.pynew file mode 100644index 000000000..3eec19b25--- /dev/null+++ b/tools/test_conversation_cache_disabled.py@@ -0,0 +1,102 @@+"""The upstream comparison must reject mismatches and incomplete evidence."""+import copy+import hashlib+import json+from pathlib import Path+import subprocess+import sys+import tempfile+import unittest++from tools.conversation_cache_disabled import NAMES, SETTINGS, STATE_KEYS, common_args, state_hashes, verify+++def fixture():+ requests = [dict(name=n, ids=[1, 2], max_new=16, expected='4' if n == 'short' else None) for n in NAMES]+ digest = hashlib.sha256(json.dumps(requests, sort_keys=True).encode()).hexdigest()+ baseline = dict(name='upstream', args=['--kv', 'int8'], info={key: 1 for key in SETTINGS},+ request_digest=digest, cache_events=[], records=[])+ for name in NAMES:+ baseline['records'].append(dict(name=name, ids=[4], text='4', finish='stop', prompt_tokens=2,+ reused=2 if name in ('A-live', 'A-checkpoint') else 0,+ state={key: 'abc' for key in STATE_KEYS}))+ candidate = copy.deepcopy(baseline)+ candidate['name'] = 'candidate-1'+ candidate['info']['conversation_cache_mib'] = 0+ candidate['info']['conversation_disk_mib'] = 0+ return dict(arms=[baseline, candidate], requests=requests, request_digest=digest)+++class DisabledCacheGateTest(unittest.TestCase):+ def test_reference_fixture(self):+ verify(fixture())++ def test_upstream_hash_schema(self):+ line = 'strata serve: STATE_HASH L=2 gdn=ab ple=cd tail=ef pooled=12 kv=34 mtp=56 stale=78 ple_prev=1,2'+ self.assertEqual(set(state_hashes(line)[0]), set(STATE_KEYS))+ self.assertEqual(state_hashes(line), state_hashes(line + ' dead=99'))+ self.assertEqual(state_hashes(line), state_hashes(line.replace('pooled=12', 'pooled=ff') ++ ' pooled_complete=12', candidate=True))+ with self.assertRaises(AssertionError):+ state_hashes(line, candidate=True)+ with self.assertRaises(AssertionError):+ state_hashes(line.replace('kv=34 ', ''))++ def test_rejects_bad_evidence(self):+ mutations = [+ lambda r: r['arms'].pop(),+ lambda r: r['requests'].pop(),+ lambda r: r['requests'][0]['ids'].append(3),+ lambda r: r['arms'][1]['args'].append('--different'),+ lambda r: r['arms'][1].update(request_digest='different'),+ lambda r: r['arms'][1]['records'].pop(),+ lambda r: r['arms'][1]['info'].update(expert_slots=2),+ lambda r: r['arms'][1]['info'].pop('kv'),+ lambda r: r['arms'][1]['info'].update(conversation_cache_mib=8192),+ lambda r: r['arms'][1]['info'].pop('conversation_cache_mib'),+ lambda r: r['arms'][1]['info'].update(conversation_disk_mib=16384),+ lambda r: r['arms'][1]['cache_events'].append('disk cache: spilled'),+ lambda r: r['arms'][1]['records'][0].update(ids=[]),+ lambda r: r['arms'][1]['records'][0].update(ids=[5]),+ lambda r: r['arms'][1]['records'][0].update(finish='disconnect'),+ lambda r: r['arms'][1]['records'][0].update(prompt_tokens=1),+ lambda r: r['arms'][1]['records'][0]['state'].pop('gdn'),+ lambda r: r['arms'][1]['records'][0]['state'].update(kv='bad'),+ lambda r: r['arms'][1]['records'][0].update(reused=1),+ lambda r: [a['records'][0].update(text='5') for a in r['arms']],+ lambda r: [a['records'][2].update(reused=0) for a in r['arms']],+ lambda r: [a['records'][5].update(reused=2) for a in r['arms']],+ ]+ for mutation in mutations:+ with self.subTest(mutation=mutations.index(mutation)):+ result = fixture()+ mutation(result)+ with self.assertRaises(AssertionError):+ verify(result)++ def test_optimized_python_still_rejects(self):+ code = ('from tools.test_conversation_cache_disabled import fixture, verify; '+ 'r=fixture(); r["arms"][1]["records"][0]["ids"]=[5]; verify(r)')+ p = subprocess.run([sys.executable, '-O', '-c', code], capture_output=True, text=True)+ self.assertNotEqual(p.returncode, 0)+ self.assertIn('output differs', p.stderr)++ def test_cache_options_omitted_from_shared_arguments(self):+ cfg = {'args': ['--pack', '/model', '--conversation-cache-mib', '8192',+ '--conversation-cache-disk', '/cache', '--kv', 'int8']}+ args = common_args(cfg, 4)+ self.assertEqual(args[:4], ['--pack', '/model', '--kv', 'int8'])+ self.assertFalse(any(x.startswith('--conversation-cache-') for x in args))++ def test_dry_run_does_not_load_or_create_output(self):+ with tempfile.TemporaryDirectory() as tmp:+ out = Path(tmp) / 'absent'+ p = subprocess.run([sys.executable, 'tools/conversation_cache_disabled.py', '--config', '/absent',+ '--upstream', '/absent', '--candidate', '/absent', '--output', str(out)],+ capture_output=True, text=True)+ self.assertEqual(p.returncode, 0, p.stderr)+ self.assertFalse(out.exists())+++if __name__ == '__main__':+ unittest.main()