o0Hailey-DSynth0o commited on
Commit
6ed0cf9
·
1 Parent(s): 8ea340e

Port guarded Qwen3.5 QSystem adapter and field runtime (#1)

Browse files

- Port guarded Qwen3.5 QSystem adapter and field runtime (b407da629292e0083c0dfba01ff78f6fab938ae1)

.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
PORT_MANIFEST.json ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "adapter_only": true,
3
+ "base_weights_included": false,
4
+ "files": {
5
+ "README.md": {
6
+ "bytes": 3152,
7
+ "sha256": "c90ca45194226006a6dba005708a162400e0b009f502af773ea64a65985de8e3"
8
+ },
9
+ "adapter_config.json": {
10
+ "bytes": 1528,
11
+ "sha256": "ba4c65b8bf0a6ae3047e62ded3e191120c7ac1577f267cc0bf07ee4bf25e85df"
12
+ },
13
+ "adapter_model.safetensors": {
14
+ "bytes": 42505112,
15
+ "sha256": "c317c8cf66815b64af8f440a0c5e99da8c6bcd416fd297a0c57419a1eff96e47"
16
+ },
17
+ "artifacts/field.deployment.json": {
18
+ "bytes": 952,
19
+ "sha256": "e405b118ec18fcdd7c191100157da15f353e0c03633add9f5863f91ad8b27968"
20
+ },
21
+ "artifacts/field.json": {
22
+ "bytes": 1417,
23
+ "sha256": "58cad94a6487316da55248ff826930827d566c90f3aa78bf9a0dff2fe8fad317"
24
+ },
25
+ "artifacts/wave.deployment.json": {
26
+ "bytes": 1629,
27
+ "sha256": "68e16241e9012e54c7458bab16ea43ef6c6adc523c9d2ecb93c53e7be5e1dfc4"
28
+ },
29
+ "artifacts/wave.json": {
30
+ "bytes": 1257,
31
+ "sha256": "e0c68eeb94bbf2e0463d4d03555e6f8545827c3cd68f37ecd34d469fc1f2d7e4"
32
+ },
33
+ "chat_template.jinja": {
34
+ "bytes": 7756,
35
+ "sha256": "a4aee8afcf2e0711942cf848899be66016f8d14a889ff9ede07bca099c28f715"
36
+ },
37
+ "portable_qsystem.py": {
38
+ "bytes": 4961,
39
+ "sha256": "f618ffabf98b33ea825902788c78d0e343dd6cc5cc404d8e63a37c61f5273feb"
40
+ },
41
+ "requirements.txt": {
42
+ "bytes": 73,
43
+ "sha256": "023dac9615c0477f9b4ee4ce982bdfe7d4418abab7da2c82a61b70bd6c191277"
44
+ },
45
+ "runtime/field_reranker.py": {
46
+ "bytes": 10337,
47
+ "sha256": "9448cfc7c4fe49e9e7a0a2c4e6a502991e90f9b061f7c1face9146e10520662b"
48
+ },
49
+ "runtime/wave_reranker.py": {
50
+ "bytes": 13599,
51
+ "sha256": "802e0bc6490bcdcd0ddb4dbd52810abe7b6792160d202b475c3064220f0c5513"
52
+ },
53
+ "tokenizer.json": {
54
+ "bytes": 19989343,
55
+ "sha256": "87a7830d63fcf43bf241c3c5242e96e62dd3fdc29224ca26fed8ea333db72de4"
56
+ },
57
+ "tokenizer_config.json": {
58
+ "bytes": 1102,
59
+ "sha256": "930c80792230ce9a8d3330eccc0aebd727f0d0de2723d0baf3a72973d4ad3b49"
60
+ },
61
+ "training_summary.json": {
62
+ "bytes": 801,
63
+ "sha256": "cb45664d68e3976b7dbe1a1da38c0b21b756a00ccd90c52f15e24b4ff08877e1"
64
+ },
65
+ "validation_summary.json": {
66
+ "bytes": 777,
67
+ "sha256": "528f9321d0ec723e49f40cefb00e0810d4210bd4b291d92da76e2d457c3b14f3"
68
+ }
69
+ },
70
+ "guarded_system_passed": true,
71
+ "physical_quantum_state": false,
72
+ "raw_adapter_passed": false,
73
+ "repo_id": "o0Hailey-DSynth0o/Experimental_QSystem",
74
+ "schema_version": 1,
75
+ "source_human_approved": false,
76
+ "training_data_included": false
77
+ }
README.md CHANGED
@@ -1,3 +1,87 @@
1
- ---
2
- license: cc-by-nc-4.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-nc-4.0
3
+ base_model:
4
+ - Qwen/Qwen3.5-4B-Base
5
+ - unsloth/Qwen3.5-4B-Base
6
+ library_name: peft
7
+ pipeline_tag: text-generation
8
+ tags:
9
+ - lora
10
+ - sft
11
+ - hscm
12
+ - quantum-inspired
13
+ - guarded-generation
14
+ ---
15
+
16
+ # Experimental QSystem
17
+
18
+ An **experimental adapter/system bundle** for Qwen3.5-4B-Base. It combines a
19
+ language-layer LoRA verbalizer with portable NumPy field and complex-wave
20
+ rerankers. The full persistent HSCM memory engine is external to these weights.
21
+
22
+ ## Accuracy boundary
23
+
24
+ - This is not a physically quantum LLM. The transformer, neural weights, and KV
25
+ cache are classical.
26
+ - Complex amplitudes, phase, interference, attractive/repellent signals, and the
27
+ two-qubit field are routing analogues over HSCM candidates.
28
+ - The earlier IBM QPU candidate was rejected by held-out gates and is not the
29
+ active artifact included here.
30
+ - The raw adapter failed one missing-evidence generation probe by inventing a
31
+ number. It must be used with the supplied evidence-boundary prompt and
32
+ fail-closed output guard.
33
+
34
+ ## Data status
35
+
36
+ Training used 182 examples: 150 Hope bridge candidates and 32 grounding-repair
37
+ examples. **None were human-approved.** The source package explicitly labelled
38
+ them `HUMAN_REVIEW_REQUIRED`; this bounded user-requested experiment does not
39
+ promote them to authentic or production-reviewed persona data. No training rows,
40
+ private memories, credentials, or source text are included in this repository.
41
+
42
+ ## Training and evaluation
43
+
44
+ - BF16, rank-16 LoRA, language attention/MLP projections only
45
+ - 21,233,664 trainable parameters (0.4656% of the loaded model)
46
+ - validation loss: 3.4935 -> 2.7221
47
+ - test loss: 3.5912 -> 2.7644
48
+ - guarded Windows end-to-end gate: 11/11 checks
49
+ - local project regression at export: 760 passed, 1 optional skip
50
+
51
+ The raw adapter remains quarantined; only the guarded composition passed.
52
+
53
+ ## Portable use
54
+
55
+ ```python
56
+ from portable_qsystem import PortableQSystem
57
+
58
+ system = PortableQSystem("o0Hailey-DSynth0o/Experimental_QSystem")
59
+ result = system.generate(
60
+ "What exact number was in the sealed result?",
61
+ ["The notes mention a sealed result but do not give its value."],
62
+ unmet_need=True,
63
+ )
64
+ print(result["text"])
65
+ ```
66
+
67
+ `unmet_need` must come from a trusted retrieval/controller layer. If you do not
68
+ have that layer, treat this as an experimental LoRA—not a grounded system.
69
+
70
+ The default 8 GiB GPU / 96 GiB CPU memory limits allow Accelerate to offload
71
+ overflow to RAM. Override them with `QSYSTEM_GPU_MEMORY` and
72
+ `QSYSTEM_CPU_MEMORY`.
73
+
74
+ ## Included artifacts
75
+
76
+ - PEFT adapter and authoritative Qwen tokenizer/template
77
+ - `portable_qsystem.py`: official-template inference plus fail-closed guard
78
+ - `runtime/field_reranker.py`: NumPy two-qubit field evaluator
79
+ - `runtime/wave_reranker.py`: NumPy complex-wave controller
80
+ - `artifacts/`: hash-gated active scalar/wave parameters
81
+ - sanitized training and validation summaries
82
+
83
+ ## License
84
+
85
+ This repository is shared under CC BY-NC 4.0. The referenced base models retain
86
+ their own licenses. Users are responsible for checking compatibility for their
87
+ use case.
adapter_config.json ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "alora_invocation_tokens": null,
3
+ "alpha_pattern": {},
4
+ "arrow_config": null,
5
+ "auto_mapping": {
6
+ "base_model_class": "Qwen3_5ForConditionalGeneration",
7
+ "parent_library": "transformers.models.qwen3_5.modeling_qwen3_5",
8
+ "unsloth_fixed": true
9
+ },
10
+ "base_model_name_or_path": "unsloth/Qwen3.5-4B-Base",
11
+ "bias": "none",
12
+ "corda_config": null,
13
+ "ensure_weight_tying": false,
14
+ "eva_config": null,
15
+ "exclude_modules": null,
16
+ "fan_in_fan_out": false,
17
+ "inference_mode": true,
18
+ "init_lora_weights": true,
19
+ "layer_replication": null,
20
+ "layers_pattern": null,
21
+ "layers_to_transform": null,
22
+ "loftq_config": {},
23
+ "lora_alpha": 16,
24
+ "lora_bias": false,
25
+ "lora_dropout": 0,
26
+ "lora_ga_config": null,
27
+ "megatron_config": null,
28
+ "megatron_core": "megatron.core",
29
+ "modules_to_save": null,
30
+ "monteclora_config": null,
31
+ "peft_type": "LORA",
32
+ "peft_version": "0.20.0",
33
+ "qalora_group_size": 16,
34
+ "r": 16,
35
+ "rank_pattern": {},
36
+ "revision": null,
37
+ "target_modules": "(?:.*?(?:language|text).*?(?:self_attn|attention|attn|mixer|mlp|feed_forward|ffn|dense|mixer).*?(?:q_proj|k_proj|v_proj|o_proj|gate_proj|up_proj|down_proj))|(?:\\bmodel\\.layers\\.[\\d]{1,}\\.(?:self_attn|attention|attn|mixer|mlp|feed_forward|ffn|dense|mixer)\\.(?:(?:q_proj|k_proj|v_proj|o_proj|gate_proj|up_proj|down_proj)))",
38
+ "target_parameters": null,
39
+ "task_type": "CAUSAL_LM",
40
+ "trainable_token_indices": null,
41
+ "use_bdlora": null,
42
+ "use_dora": false,
43
+ "use_qalora": false,
44
+ "use_rslora": false,
45
+ "velora_config": null
46
+ }
adapter_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c317c8cf66815b64af8f440a0c5e99da8c6bcd416fd297a0c57419a1eff96e47
3
+ size 42505112
artifacts/field.deployment.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "status": "active",
4
+ "rollback_mode": "shadow",
5
+ "artifact_sha256": "58cad94a6487316da55248ff826930827d566c90f3aa78bf9a0dff2fe8fad317",
6
+ "artifact_id": "astra-field-completion-v1",
7
+ "feature_sha256": "328aa5414e4c005bb438b17bbe4d79e82212f209322b17319eff4d4e8b7207ca",
8
+ "final_feature_sha256": "38f9af692ed8ca2256164d4b81ca008c4a3af0eb1d34c03a5452d48db7bfe0d1",
9
+ "activation_gates": {
10
+ "final_pool_coverage_at_least_0_95": true,
11
+ "final_shortlist_coverage_64_at_least_0_95": true,
12
+ "final_mrr_not_below_hscm": true,
13
+ "final_hit1_not_below_hscm": true,
14
+ "final_quality_noninferior_ci_margin_0_02": true,
15
+ "scalar_batch_p95_128_under_50ms": true,
16
+ "artifact_was_not_fit_on_final_features": true
17
+ },
18
+ "canary_eligible": true,
19
+ "promotion_requires_manual_status_change": false,
20
+ "promoted_at": "2026-08-22",
21
+ "promotion_authority": "explicit_user_operator_instruction",
22
+ "qpu_authorized": false
23
+ }
artifacts/field.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "artifact_id": "astra-field-completion-v1",
4
+ "feature_order": [
5
+ "semantic_support",
6
+ "lexical_support",
7
+ "coherence",
8
+ "path_quality"
9
+ ],
10
+ "feature_scaler": {
11
+ "min": [0.0, 0.0, 0.0, 0.0],
12
+ "max": [1.0, 1.0, 1.0, 1.0]
13
+ },
14
+ "circuit": {
15
+ "ansatz": "astra-field-v1",
16
+ "qubits": 2,
17
+ "trainable_weights": 8,
18
+ "output": "even-parity-probability"
19
+ },
20
+ "weights": [
21
+ 0.6887883660412828,
22
+ 0.21568877725908164,
23
+ 0.2919163878217943,
24
+ -0.12790156455312518,
25
+ -0.6341863258168909,
26
+ -0.030390240841024596,
27
+ 0.1441088749758026,
28
+ -0.283611054562376
29
+ ],
30
+ "fusion_weight": 0.18,
31
+ "score_calibration": "batch_max",
32
+ "training_stage": "operational-hybrid-v1-transfer-validated",
33
+ "metadata": {
34
+ "feature_sha256": "328aa5414e4c005bb438b17bbe4d79e82212f209322b17319eff4d4e8b7207ca",
35
+ "source_artifact_sha256": "f8497cd851abb7775c130a8faa1e5ff7d75ec29a01dd1f5a7af46d172e179cac",
36
+ "final_feature_sha256": "38f9af692ed8ca2256164d4b81ca008c4a3af0eb1d34c03a5452d48db7bfe0d1",
37
+ "final_report_sha256": "64b0d5e50998c6b1b7266a708bb438786ffb30f5e9989249a62bf2b483d7ac75",
38
+ "final_metrics": {
39
+ "coverage_at_64": 0.97,
40
+ "mrr": 0.39563449019071006,
41
+ "hit_at_1": 0.295,
42
+ "p95_batch_ms": 34.542304996284656
43
+ },
44
+ "classical_shadow_accepted": true,
45
+ "qpu_authorized": false,
46
+ "physical_quantum_state": false
47
+ }
48
+ }
artifacts/wave.deployment.json ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "status": "active-protected",
4
+ "rollback_mode": "shadow-observer",
5
+ "applied_to_ranking": true,
6
+ "artifact_sha256": "e0c68eeb94bbf2e0463d4d03555e6f8545827c3cd68f37ecd34d469fc1f2d7e4",
7
+ "artifact_id": "astra-wave-completion-v1",
8
+ "physical_quantum_state": false,
9
+ "behaviours": [
10
+ "normalized_complex_path_amplitudes",
11
+ "phase_sensitive_interference",
12
+ "decoherence",
13
+ "measurement_entropy",
14
+ "effective_path_count",
15
+ "scalar_protected_nested_counterfactual"
16
+ ],
17
+ "nested_wave_alpha": 0.7,
18
+ "nested_shortlist": 64,
19
+ "activation_gates": {
20
+ "exact_artifact_hash": true,
21
+ "scalar_protected_shortlist": true,
22
+ "evidence_admission_unchanged": true,
23
+ "paired_e2e_combined_wins_at_least_losses": true,
24
+ "automatic_shadow_fallback": true,
25
+ "operator_override_authorized": true
26
+ },
27
+ "operator_override": {
28
+ "authorized": true,
29
+ "authorized_at": "2026-08-22",
30
+ "authority": "explicit_user_operator_instruction",
31
+ "decision": "activate protected phase combination despite statistically inconclusive e2e interval",
32
+ "statistically_conclusive": false,
33
+ "paired_exact_mcnemar_p": 0.375,
34
+ "top1_delta_ci95": [-0.009615, 0.076923]
35
+ },
36
+ "safety_invariants": {
37
+ "can_rank": true,
38
+ "protected_scalar_shortlist": true,
39
+ "unrestricted_wave_ranker": false,
40
+ "can_admit_evidence": false,
41
+ "can_change_answers": true,
42
+ "telemetry_contains_text": false
43
+ },
44
+ "physical_qpu_used_for_activation": false,
45
+ "reason": "operator-authorized protected activation after favorable but statistically inconclusive classical end-to-end comparison"
46
+ }
artifacts/wave.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "artifact_id": "astra-wave-completion-v1",
4
+ "mode": "wave",
5
+ "feature_order": [
6
+ "semantic_support",
7
+ "lexical_support",
8
+ "coherence",
9
+ "path_quality"
10
+ ],
11
+ "aux_order": [
12
+ "phase_residual",
13
+ "holonomy",
14
+ "relative_weight",
15
+ "state_amplitude"
16
+ ],
17
+ "input_weights": [
18
+ 2.2449848651885986,
19
+ 0.9888409972190857,
20
+ 0.42518511414527893,
21
+ 0.19510437548160553,
22
+ 0.20227433741092682,
23
+ -0.12414798885583878
24
+ ],
25
+ "logit_scale": 8.435023307800293,
26
+ "kernel_log_weights": [
27
+ -0.9233665466308594,
28
+ 1.7070022821426392,
29
+ -1.7411715984344482,
30
+ -1.1259512901306152
31
+ ],
32
+ "phase_gains": {
33
+ "residual": 0.9412479400634766,
34
+ "holonomy": 0.0009446322219446301
35
+ },
36
+ "mixing": 0.07407242059707642,
37
+ "decoherence": 0.1738409698009491,
38
+ "fusion_weight": 0.25,
39
+ "training_stage": "operational-wave-classical",
40
+ "metadata": {
41
+ "feature_sha256": "c7e6ef608f804579229e124ef42769e46115886a6d9c88792a84dd88ee7f76a6",
42
+ "seed": 0,
43
+ "physical_quantum_state": false,
44
+ "nested_wave_alpha": 0.7,
45
+ "nested_shortlist": 64,
46
+ "nested_selection": "selected on the 90-query development validation split; final result is exploratory"
47
+ }
48
+ }
chat_template.jinja ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- set image_count = namespace(value=0) %}
2
+ {%- set video_count = namespace(value=0) %}
3
+ {%- macro render_content(content, do_vision_count, is_system_content=false) %}
4
+ {%- if content is string %}
5
+ {{- content }}
6
+ {%- elif content is iterable and content is not mapping %}
7
+ {%- for item in content %}
8
+ {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
9
+ {%- if is_system_content %}
10
+ {{- raise_exception('System message cannot contain images.') }}
11
+ {%- endif %}
12
+ {%- if do_vision_count %}
13
+ {%- set image_count.value = image_count.value + 1 %}
14
+ {%- endif %}
15
+ {%- if add_vision_id %}
16
+ {{- 'Picture ' ~ image_count.value ~ ': ' }}
17
+ {%- endif %}
18
+ {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
19
+ {%- elif 'video' in item or item.type == 'video' %}
20
+ {%- if is_system_content %}
21
+ {{- raise_exception('System message cannot contain videos.') }}
22
+ {%- endif %}
23
+ {%- if do_vision_count %}
24
+ {%- set video_count.value = video_count.value + 1 %}
25
+ {%- endif %}
26
+ {%- if add_vision_id %}
27
+ {{- 'Video ' ~ video_count.value ~ ': ' }}
28
+ {%- endif %}
29
+ {{- '<|vision_start|><|video_pad|><|vision_end|>' }}
30
+ {%- elif 'text' in item %}
31
+ {{- item.text }}
32
+ {%- else %}
33
+ {{- raise_exception('Unexpected item type in content.') }}
34
+ {%- endif %}
35
+ {%- endfor %}
36
+ {%- elif content is none or content is undefined %}
37
+ {{- '' }}
38
+ {%- else %}
39
+ {{- raise_exception('Unexpected content type.') }}
40
+ {%- endif %}
41
+ {%- endmacro %}
42
+ {%- if not messages %}
43
+ {{- raise_exception('No messages provided.') }}
44
+ {%- endif %}
45
+ {%- if tools and tools is iterable and tools is not mapping %}
46
+ {{- '<|im_start|>system\n' }}
47
+ {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
48
+ {%- for tool in tools %}
49
+ {{- "\n" }}
50
+ {{- tool | tojson }}
51
+ {%- endfor %}
52
+ {{- "\n</tools>" }}
53
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
54
+ {%- if messages[0].role == 'system' %}
55
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
56
+ {%- if content %}
57
+ {{- '\n\n' + content }}
58
+ {%- endif %}
59
+ {%- endif %}
60
+ {{- '<|im_end|>\n' }}
61
+ {%- else %}
62
+ {%- if messages[0].role == 'system' %}
63
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
64
+ {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
65
+ {%- endif %}
66
+ {%- endif %}
67
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
68
+ {%- for message in messages[::-1] %}
69
+ {%- set index = (messages|length - 1) - loop.index0 %}
70
+ {%- if ns.multi_step_tool and message.role == "user" %}
71
+ {%- set content = render_content(message.content, false)|trim %}
72
+ {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
73
+ {%- set ns.multi_step_tool = false %}
74
+ {%- set ns.last_query_index = index %}
75
+ {%- endif %}
76
+ {%- endif %}
77
+ {%- endfor %}
78
+ {%- if ns.multi_step_tool %}
79
+ {{- raise_exception('No user query found in messages.') }}
80
+ {%- endif %}
81
+ {%- for message in messages %}
82
+ {%- set content = render_content(message.content, true)|trim %}
83
+ {%- if message.role == "system" %}
84
+ {%- if not loop.first %}
85
+ {{- raise_exception('System message must be at the beginning.') }}
86
+ {%- endif %}
87
+ {%- elif message.role == "user" %}
88
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
89
+ {%- elif message.role == "assistant" %}
90
+ {%- set reasoning_content = '' %}
91
+ {%- if message.reasoning_content is string %}
92
+ {%- set reasoning_content = message.reasoning_content %}
93
+ {%- else %}
94
+ {%- if '</think>' in content %}
95
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
96
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
97
+ {%- endif %}
98
+ {%- endif %}
99
+ {%- set reasoning_content = reasoning_content|trim %}
100
+ {%- if loop.index0 > ns.last_query_index %}
101
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
102
+ {%- else %}
103
+ {{- '<|im_start|>' + message.role + '\n' + content }}
104
+ {%- endif %}
105
+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
106
+ {%- for tool_call in message.tool_calls %}
107
+ {%- if tool_call.function is defined %}
108
+ {%- set tool_call = tool_call.function %}
109
+ {%- endif %}
110
+ {%- if loop.first %}
111
+ {%- if content|trim %}
112
+ {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
113
+ {%- else %}
114
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
115
+ {%- endif %}
116
+ {%- else %}
117
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
118
+ {%- endif %}
119
+ {%- if tool_call.arguments is defined %}
120
+ {%- for args_name, args_value in tool_call.arguments|items %}
121
+ {{- '<parameter=' + args_name + '>\n' }}
122
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
123
+ {{- args_value }}
124
+ {{- '\n</parameter>\n' }}
125
+ {%- endfor %}
126
+ {%- endif %}
127
+ {{- '</function>\n</tool_call>' }}
128
+ {%- endfor %}
129
+ {%- endif %}
130
+ {{- '<|im_end|>\n' }}
131
+ {%- elif message.role == "tool" %}
132
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
133
+ {{- '<|im_start|>user' }}
134
+ {%- endif %}
135
+ {{- '\n<tool_response>\n' }}
136
+ {{- content }}
137
+ {{- '\n</tool_response>' }}
138
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
139
+ {{- '<|im_end|>\n' }}
140
+ {%- elif loop.last %}
141
+ {{- '<|im_end|>\n' }}
142
+ {%- endif %}
143
+ {%- else %}
144
+ {{- raise_exception('Unexpected message role.') }}
145
+ {%- endif %}
146
+ {%- endfor %}
147
+ {%- if add_generation_prompt %}
148
+ {{- '<|im_start|>assistant\n' }}
149
+ {%- if enable_thinking is defined and enable_thinking is false %}
150
+ {{- '<think>\n\n</think>\n\n' }}
151
+ {%- else %}
152
+ {{- '<think>\n' }}
153
+ {%- endif %}
154
+ {%- endif %}
portable_qsystem.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Portable guarded inference boundary for the Experimental QSystem adapter.
2
+
3
+ This module does not implement Astra's persistent HSCM memory engine. Callers
4
+ must provide admitted semantic evidence and the controller's ``unmet_need``
5
+ decision. The deterministic guard prevents a known missing answer slot from
6
+ being replaced by a fluent model guess.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import re
12
+ from pathlib import Path
13
+ from typing import Sequence
14
+
15
+
16
+ UNCERTAINTY = re.compile(
17
+ r"\b(?:don't know|do not know|don't have|do not have|not enough|no record|"
18
+ r"no evidence|not given|not provided|not supplied|not mentioned|not specified|"
19
+ r"can't tell|cannot tell|can't determine|cannot determine|uncertain|unknown)\b",
20
+ re.I,
21
+ )
22
+
23
+
24
+ def grounded_messages(query: str, evidence: Sequence[str], *,
25
+ unmet_need: bool = False) -> list[dict[str, str]]:
26
+ facts = [str(item).strip() for item in evidence if str(item).strip()][:9]
27
+ context = "\n".join(f"- {item}" for item in facts) or "(no grounded evidence)"
28
+ boundary = (
29
+ "\nEvidence boundary: the requested specific is not supplied. State that "
30
+ "you do not know it; do not estimate or invent it."
31
+ if unmet_need else ""
32
+ )
33
+ system = (
34
+ "You are Astra's local verbalizer. Be concise and direct. Treat only the "
35
+ "grounded evidence supplied by the controller as factual. A listed question "
36
+ "does not supply its answer. Separate inference from fact, and plainly state "
37
+ "when requested evidence is missing. Complex phase and field values are "
38
+ "classical routing signals, not physical quantum states."
39
+ )
40
+ user = f"Context:\n{context}{boundary}\n\nQuestion:\n{str(query)[:500]}"
41
+ return [{"role": "system", "content": system},
42
+ {"role": "user", "content": user}]
43
+
44
+
45
+ def guard_output(text: str, *, unmet_need: bool = False) -> tuple[str, bool]:
46
+ body = str(text or "").strip()
47
+ if unmet_need and body and not UNCERTAINTY.search(body):
48
+ return "I don't know the requested specific from the evidence I have.", True
49
+ return body, False
50
+
51
+
52
+ class PortableQSystem:
53
+ """Qwen3.5 BF16 LoRA mouth with optional GPU-to-RAM placement."""
54
+
55
+ def __init__(
56
+ self,
57
+ adapter: str | Path = ".",
58
+ base_model: str = "unsloth/Qwen3.5-4B-Base",
59
+ *,
60
+ max_new_tokens: int = 128,
61
+ gpu_memory: str | None = None,
62
+ cpu_memory: str | None = None,
63
+ ):
64
+ self.adapter = str(adapter)
65
+ self.base_model = str(base_model)
66
+ self.max_new_tokens = int(max_new_tokens)
67
+ self.gpu_memory = gpu_memory or os.getenv("QSYSTEM_GPU_MEMORY", "8GiB")
68
+ self.cpu_memory = cpu_memory or os.getenv("QSYSTEM_CPU_MEMORY", "96GiB")
69
+ self.model = None
70
+ self.tokenizer = None
71
+
72
+ def load(self) -> None:
73
+ if self.model is not None:
74
+ return
75
+ import torch
76
+ from peft import PeftModel
77
+ from transformers import AutoModelForCausalLM, AutoTokenizer
78
+
79
+ self.tokenizer = AutoTokenizer.from_pretrained(self.adapter, use_fast=True)
80
+ options = {"dtype": torch.bfloat16, "low_cpu_mem_usage": True}
81
+ if torch.cuda.is_available():
82
+ options.update({
83
+ "device_map": "auto",
84
+ "max_memory": {0: self.gpu_memory, "cpu": self.cpu_memory},
85
+ })
86
+ base = AutoModelForCausalLM.from_pretrained(self.base_model, **options)
87
+ self.model = PeftModel.from_pretrained(
88
+ base, self.adapter, is_trainable=False)
89
+ self.model.eval()
90
+
91
+ def generate(self, query: str, evidence: Sequence[str], *,
92
+ unmet_need: bool = False) -> dict[str, object]:
93
+ import torch
94
+
95
+ self.load()
96
+ rendered = self.tokenizer.apply_chat_template(
97
+ grounded_messages(query, evidence, unmet_need=unmet_need),
98
+ tokenize=False, add_generation_prompt=True, enable_thinking=False)
99
+ encoded = self.tokenizer(rendered, return_tensors="pt")
100
+ input_device = self.model.get_input_embeddings().weight.device
101
+ encoded = {key: value.to(input_device) for key, value in encoded.items()}
102
+ input_length = int(encoded["input_ids"].shape[1])
103
+ with torch.inference_mode():
104
+ generated = self.model.generate(
105
+ **encoded, max_new_tokens=self.max_new_tokens,
106
+ do_sample=False, use_cache=True,
107
+ pad_token_id=self.tokenizer.pad_token_id,
108
+ eos_token_id=self.tokenizer.eos_token_id)
109
+ raw = self.tokenizer.decode(
110
+ generated[0][input_length:], skip_special_tokens=False)
111
+ raw = raw.split("<|im_end|>", 1)[0]
112
+ raw = re.sub(r"\A\s*<think>[\s\S]*?</think>\s*", "", raw, count=1)
113
+ raw = re.sub(r"</?think>", "", raw).strip()
114
+ delivered, guarded = guard_output(raw, unmet_need=unmet_need)
115
+ return {"text": delivered, "guarded": guarded, "raw": raw}
116
+
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ accelerate>=1.12
2
+ numpy>=2.0
3
+ peft>=0.20
4
+ torch>=2.6
5
+ transformers>=5.5
runtime/field_reranker.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small, optional learned reranker for the Astra/HSCM memory field.
2
+
3
+ The runtime implementation is deliberately NumPy-only. Qiskit is used by the
4
+ experiment harness to train and validate the same two-qubit circuit, but normal
5
+ Astra recall only evaluates the eight learned angles stored in a JSON artifact.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ import math
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from typing import Mapping, Sequence
15
+
16
+ import numpy as np
17
+
18
+
19
+ FIELD_ARTIFACT_SCHEMA_VERSION = 1
20
+ FIELD_DEPLOYMENT_SCHEMA_VERSION = 1
21
+ FIELD_FEATURE_ORDER = (
22
+ "semantic_support",
23
+ "lexical_support",
24
+ "coherence",
25
+ "path_quality",
26
+ )
27
+
28
+
29
+ def _finite_vector(values: Sequence[float], size: int, label: str) -> np.ndarray:
30
+ result = np.asarray(values, dtype=np.float64)
31
+ if result.shape != (size,) or not np.all(np.isfinite(result)):
32
+ raise ValueError(f"{label} must contain {size} finite values")
33
+ return result
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class FieldRerankerArtifact:
38
+ """Validated, secret-free representation of one learned field circuit."""
39
+
40
+ artifact_id: str
41
+ weights: tuple[float, ...]
42
+ fusion_weight: float = 0.10
43
+ score_calibration: str = "none"
44
+ feature_min: tuple[float, ...] = (0.0, 0.0, 0.0, 0.0)
45
+ feature_max: tuple[float, ...] = (1.0, 1.0, 1.0, 1.0)
46
+ training_stage: str = "experimental"
47
+ metadata: Mapping | None = None
48
+
49
+ def __post_init__(self) -> None:
50
+ if not str(self.artifact_id).strip():
51
+ raise ValueError("field artifact_id must not be empty")
52
+ _finite_vector(self.weights, 8, "field weights")
53
+ lo = _finite_vector(self.feature_min, 4, "feature_min")
54
+ hi = _finite_vector(self.feature_max, 4, "feature_max")
55
+ if np.any(hi <= lo):
56
+ raise ValueError("every feature_max must exceed feature_min")
57
+ if not math.isfinite(float(self.fusion_weight)) or not 0.0 <= float(self.fusion_weight) <= 0.25:
58
+ raise ValueError("fusion_weight must be finite and within [0, 0.25]")
59
+ if self.score_calibration not in {"none", "batch_max"}:
60
+ raise ValueError("unsupported field score calibration")
61
+ try:
62
+ json.dumps(dict(self.metadata or {}), allow_nan=False)
63
+ except (TypeError, ValueError) as exc:
64
+ raise ValueError("field metadata must be finite JSON data") from exc
65
+
66
+ @classmethod
67
+ def from_mapping(cls, payload: Mapping) -> "FieldRerankerArtifact":
68
+ if int(payload.get("schema_version", -1)) != FIELD_ARTIFACT_SCHEMA_VERSION:
69
+ raise ValueError("unsupported field artifact schema")
70
+ if tuple(payload.get("feature_order", ())) != FIELD_FEATURE_ORDER:
71
+ raise ValueError("field artifact feature order mismatch")
72
+ circuit = payload.get("circuit") or {}
73
+ if (int(circuit.get("qubits", -1)) != 2
74
+ or int(circuit.get("trainable_weights", -1)) != 8
75
+ or circuit.get("ansatz") != "astra-field-v1"
76
+ or circuit.get("output") != "even-parity-probability"):
77
+ raise ValueError("unsupported field circuit")
78
+ scaler = payload.get("feature_scaler") or {}
79
+ return cls(
80
+ artifact_id=str(payload.get("artifact_id", "")),
81
+ weights=tuple(float(value) for value in payload.get("weights", ())),
82
+ fusion_weight=float(payload.get("fusion_weight", 0.10)),
83
+ score_calibration=str(payload.get("score_calibration", "none")),
84
+ feature_min=tuple(float(value) for value in scaler.get("min", ())),
85
+ feature_max=tuple(float(value) for value in scaler.get("max", ())),
86
+ training_stage=str(payload.get("training_stage", "experimental")),
87
+ metadata=dict(payload.get("metadata") or {}),
88
+ )
89
+
90
+ def to_mapping(self) -> dict:
91
+ return {
92
+ "schema_version": FIELD_ARTIFACT_SCHEMA_VERSION,
93
+ "artifact_id": self.artifact_id,
94
+ "feature_order": list(FIELD_FEATURE_ORDER),
95
+ "feature_scaler": {
96
+ "min": [float(value) for value in self.feature_min],
97
+ "max": [float(value) for value in self.feature_max],
98
+ },
99
+ "circuit": {
100
+ "ansatz": "astra-field-v1",
101
+ "qubits": 2,
102
+ "trainable_weights": 8,
103
+ "output": "even-parity-probability",
104
+ },
105
+ "weights": [float(value) for value in self.weights],
106
+ "fusion_weight": float(self.fusion_weight),
107
+ "score_calibration": self.score_calibration,
108
+ "training_stage": self.training_stage,
109
+ "metadata": dict(self.metadata or {}),
110
+ }
111
+
112
+
113
+ def _ry(angle: float) -> np.ndarray:
114
+ half = 0.5 * float(angle)
115
+ return np.asarray([[math.cos(half), -math.sin(half)],
116
+ [math.sin(half), math.cos(half)]], dtype=np.complex128)
117
+
118
+
119
+ def _rz(angle: float) -> np.ndarray:
120
+ half = 0.5 * float(angle)
121
+ return np.asarray([[np.exp(-1j * half), 0.0],
122
+ [0.0, np.exp(1j * half)]], dtype=np.complex128)
123
+
124
+
125
+ _IDENTITY = np.eye(2, dtype=np.complex128)
126
+ _CZ = np.diag([1.0, 1.0, 1.0, -1.0]).astype(np.complex128)
127
+
128
+
129
+ def _single_qubit(gate: np.ndarray, qubit: int) -> np.ndarray:
130
+ # Qiskit basis ordering is |q1 q0>; q0 is the least-significant qubit.
131
+ return np.kron(_IDENTITY, gate) if int(qubit) == 0 else np.kron(gate, _IDENTITY)
132
+
133
+
134
+ def field_circuit_probability(features: Sequence[float], weights: Sequence[float]) -> float:
135
+ """Evaluate the v1 circuit's even-parity probability exactly."""
136
+ values = np.clip(_finite_vector(features, 4, "field features"), 0.0, 1.0)
137
+ theta = _finite_vector(weights, 8, "field weights")
138
+ state = np.asarray([1.0, 0.0, 0.0, 0.0], dtype=np.complex128)
139
+ operations = (
140
+ (_ry(math.pi * values[0]), 0), (_rz(math.pi * values[1]), 0),
141
+ (_ry(math.pi * values[2]), 1), (_rz(math.pi * values[3]), 1),
142
+ )
143
+ for gate, qubit in operations:
144
+ state = _single_qubit(gate, qubit) @ state
145
+ state = _CZ @ state
146
+ for gate, qubit in ((_ry(theta[0]), 0), (_rz(theta[1]), 0),
147
+ (_ry(theta[2]), 1), (_rz(theta[3]), 1)):
148
+ state = _single_qubit(gate, qubit) @ state
149
+ state = _CZ @ state
150
+ for gate, qubit in ((_ry(theta[4]), 0), (_rz(theta[5]), 0),
151
+ (_ry(theta[6]), 1), (_rz(theta[7]), 1)):
152
+ state = _single_qubit(gate, qubit) @ state
153
+ probability = float(abs(state[0]) ** 2 + abs(state[3]) ** 2)
154
+ return float(np.clip(probability, 0.0, 1.0))
155
+
156
+
157
+ class QuantumFieldReranker:
158
+ """Runtime scorer backed by a validated two-qubit field artifact."""
159
+
160
+ def __init__(self, artifact: FieldRerankerArtifact):
161
+ self.artifact = artifact
162
+ self.artifact_id = artifact.artifact_id
163
+ self.fusion_weight = float(artifact.fusion_weight)
164
+
165
+ def _normalize(self, features: np.ndarray) -> np.ndarray:
166
+ values = np.asarray(features, dtype=np.float64)
167
+ if values.ndim != 2 or values.shape[1] != 4:
168
+ raise ValueError("field feature batch must have shape (n, 4)")
169
+ if not np.all(np.isfinite(values)):
170
+ raise ValueError("field feature batch contains non-finite values")
171
+ lo = np.asarray(self.artifact.feature_min, dtype=np.float64)
172
+ hi = np.asarray(self.artifact.feature_max, dtype=np.float64)
173
+ return np.clip((values - lo) / (hi - lo), 0.0, 1.0)
174
+
175
+ def score_batch(self, features: np.ndarray) -> np.ndarray:
176
+ normalized = self._normalize(features)
177
+ scores = np.asarray([
178
+ field_circuit_probability(row, self.artifact.weights)
179
+ for row in normalized
180
+ ], dtype=np.float64)
181
+ if self.artifact.score_calibration == "batch_max" and len(scores):
182
+ scores = scores / max(float(np.max(scores)), 1e-12)
183
+ return scores
184
+
185
+
186
+ def _sha256(path: Path) -> str:
187
+ digest = hashlib.sha256()
188
+ with path.open("rb") as source:
189
+ for block in iter(lambda: source.read(1024 * 1024), b""):
190
+ digest.update(block)
191
+ return digest.hexdigest()
192
+
193
+
194
+ def verify_active_deployment(
195
+ artifact_path: str | Path,
196
+ deployment_path: str | Path | None = None) -> dict:
197
+ """Verify the local allow-list record required for active reranking."""
198
+ artifact = Path(artifact_path)
199
+ deployment = (Path(deployment_path) if deployment_path is not None
200
+ else artifact.with_suffix(".deployment.json"))
201
+ payload = json.loads(deployment.read_text(encoding="utf-8"))
202
+ if not isinstance(payload, dict):
203
+ raise ValueError("field deployment root must be an object")
204
+ if int(payload.get("schema_version", -1)) != FIELD_DEPLOYMENT_SCHEMA_VERSION:
205
+ raise ValueError("unsupported field deployment schema")
206
+ if payload.get("status") != "active":
207
+ raise ValueError("field deployment is not active")
208
+ if payload.get("rollback_mode") != "shadow":
209
+ raise ValueError("active field deployment must declare shadow rollback")
210
+ if payload.get("artifact_sha256") != _sha256(artifact):
211
+ raise ValueError("field deployment artifact hash mismatch")
212
+ gates = payload.get("activation_gates")
213
+ if (not isinstance(gates, dict) or not gates
214
+ or any(value is not True for value in gates.values())):
215
+ raise ValueError("field deployment activation gates are not all passing")
216
+ return payload
217
+
218
+
219
+ def load_field_reranker(path: str | Path, *, require_active: bool = False,
220
+ deployment_path: str | Path | None = None
221
+ ) -> QuantumFieldReranker:
222
+ artifact_path = Path(path)
223
+ payload = json.loads(artifact_path.read_text(encoding="utf-8"))
224
+ if not isinstance(payload, dict):
225
+ raise ValueError("field artifact root must be an object")
226
+ reranker = QuantumFieldReranker(FieldRerankerArtifact.from_mapping(payload))
227
+ if require_active:
228
+ deployment = verify_active_deployment(artifact_path, deployment_path)
229
+ if deployment.get("artifact_id") != reranker.artifact_id:
230
+ raise ValueError("field deployment artifact id mismatch")
231
+ feature_sha = (reranker.artifact.metadata or {}).get("feature_sha256")
232
+ if deployment.get("feature_sha256") != feature_sha:
233
+ raise ValueError("field deployment feature hash mismatch")
234
+ return reranker
runtime/wave_reranker.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Classical, quantum-inspired path-field reranker for HSCM.
2
+
3
+ This module does not claim physical quantum state. It represents competing
4
+ HSCM paths as normalized complex amplitudes, mixes them through a bounded
5
+ similarity kernel, and measures the resulting intensities. The construction is
6
+ phase-sensitive, norm-normalized, deterministic, and NumPy-only at runtime.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import hashlib
12
+ import math
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+ from typing import Mapping, Sequence
16
+
17
+ import numpy as np
18
+
19
+
20
+ WAVE_ARTIFACT_SCHEMA_VERSION = 1
21
+ WAVE_DEPLOYMENT_SCHEMA_VERSION = 1
22
+ WAVE_FEATURE_ORDER = (
23
+ "semantic_support",
24
+ "lexical_support",
25
+ "coherence",
26
+ "path_quality",
27
+ )
28
+ WAVE_AUX_ORDER = (
29
+ "phase_residual",
30
+ "holonomy",
31
+ "relative_weight",
32
+ "state_amplitude",
33
+ )
34
+
35
+
36
+ def _vector(values: Sequence[float], size: int, label: str) -> np.ndarray:
37
+ result = np.asarray(values, dtype=np.float64)
38
+ if result.shape != (size,) or not np.all(np.isfinite(result)):
39
+ raise ValueError(f"{label} must contain {size} finite values")
40
+ return result
41
+
42
+
43
+ def _bounded(value: float, lower: float, upper: float, label: str) -> float:
44
+ result = float(value)
45
+ if not math.isfinite(result) or not lower <= result <= upper:
46
+ raise ValueError(f"{label} must be finite and within [{lower}, {upper}]")
47
+ return result
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class WaveRerankerArtifact:
52
+ artifact_id: str
53
+ mode: str
54
+ input_weights: tuple[float, ...]
55
+ logit_scale: float
56
+ kernel_log_weights: tuple[float, ...]
57
+ residual_gain: float
58
+ holonomy_gain: float
59
+ mixing: float
60
+ decoherence: float
61
+ fusion_weight: float = 0.10
62
+ training_stage: str = "experimental"
63
+ metadata: Mapping | None = None
64
+
65
+ def __post_init__(self) -> None:
66
+ if not str(self.artifact_id).strip():
67
+ raise ValueError("wave artifact_id must not be empty")
68
+ if self.mode not in {"wave", "real-control"}:
69
+ raise ValueError("wave artifact mode must be wave or real-control")
70
+ _vector(self.input_weights, 6, "input_weights")
71
+ _vector(self.kernel_log_weights, 4, "kernel_log_weights")
72
+ _bounded(self.logit_scale, 0.05, 10.0, "logit_scale")
73
+ for value, label in ((self.residual_gain, "residual_gain"),
74
+ (self.holonomy_gain, "holonomy_gain")):
75
+ if not math.isfinite(float(value)):
76
+ raise ValueError(f"{label} must be finite")
77
+ _bounded(self.mixing, 0.0, 0.75, "mixing")
78
+ _bounded(self.decoherence, 0.0, 1.0, "decoherence")
79
+ _bounded(self.fusion_weight, 0.0, 0.25, "fusion_weight")
80
+ try:
81
+ json.dumps(dict(self.metadata or {}), allow_nan=False)
82
+ except (TypeError, ValueError) as exc:
83
+ raise ValueError("wave metadata must be finite JSON data") from exc
84
+
85
+ def to_mapping(self) -> dict:
86
+ return {
87
+ "schema_version": WAVE_ARTIFACT_SCHEMA_VERSION,
88
+ "artifact_id": self.artifact_id,
89
+ "mode": self.mode,
90
+ "feature_order": list(WAVE_FEATURE_ORDER),
91
+ "aux_order": list(WAVE_AUX_ORDER),
92
+ "input_weights": [float(value) for value in self.input_weights],
93
+ "logit_scale": float(self.logit_scale),
94
+ "kernel_log_weights": [
95
+ float(value) for value in self.kernel_log_weights],
96
+ "phase_gains": {
97
+ "residual": float(self.residual_gain),
98
+ "holonomy": float(self.holonomy_gain),
99
+ },
100
+ "mixing": float(self.mixing),
101
+ "decoherence": float(self.decoherence),
102
+ "fusion_weight": float(self.fusion_weight),
103
+ "training_stage": self.training_stage,
104
+ "metadata": dict(self.metadata or {}),
105
+ }
106
+
107
+ @classmethod
108
+ def from_mapping(cls, payload: Mapping) -> "WaveRerankerArtifact":
109
+ if int(payload.get("schema_version", -1)) != WAVE_ARTIFACT_SCHEMA_VERSION:
110
+ raise ValueError("unsupported wave artifact schema")
111
+ if tuple(payload.get("feature_order", ())) != WAVE_FEATURE_ORDER:
112
+ raise ValueError("wave feature order mismatch")
113
+ if tuple(payload.get("aux_order", ())) != WAVE_AUX_ORDER:
114
+ raise ValueError("wave auxiliary order mismatch")
115
+ gains = payload.get("phase_gains") or {}
116
+ return cls(
117
+ artifact_id=str(payload.get("artifact_id", "")),
118
+ mode=str(payload.get("mode", "")),
119
+ input_weights=tuple(float(value) for value in
120
+ payload.get("input_weights", ())),
121
+ logit_scale=float(payload.get("logit_scale", 1.0)),
122
+ kernel_log_weights=tuple(float(value) for value in
123
+ payload.get("kernel_log_weights", ())),
124
+ residual_gain=float(gains.get("residual", 0.0)),
125
+ holonomy_gain=float(gains.get("holonomy", 0.0)),
126
+ mixing=float(payload.get("mixing", 0.0)),
127
+ decoherence=float(payload.get("decoherence", 0.0)),
128
+ fusion_weight=float(payload.get("fusion_weight", 0.10)),
129
+ training_stage=str(payload.get("training_stage", "experimental")),
130
+ metadata=dict(payload.get("metadata") or {}),
131
+ )
132
+
133
+
134
+ class QuantumInspiredWaveReranker:
135
+ """Measure a normalized phase-sensitive field over one candidate set."""
136
+
137
+ def __init__(self, artifact: WaveRerankerArtifact):
138
+ self.artifact = artifact
139
+ self.artifact_id = artifact.artifact_id
140
+ self.fusion_weight = float(artifact.fusion_weight)
141
+ metadata = dict(artifact.metadata or {})
142
+ self.nested_wave_alpha = float(
143
+ metadata.get("nested_wave_alpha", 0.0))
144
+ self.nested_shortlist = int(metadata.get("nested_shortlist", 0))
145
+ if not 0.0 <= self.nested_wave_alpha <= 1.0:
146
+ raise ValueError("nested_wave_alpha must be within [0, 1]")
147
+ if self.nested_shortlist < 0:
148
+ raise ValueError("nested_shortlist must be non-negative")
149
+
150
+ @staticmethod
151
+ def _inputs(features: np.ndarray, auxiliary: np.ndarray
152
+ ) -> tuple[np.ndarray, np.ndarray]:
153
+ values = np.asarray(features, dtype=np.float64)
154
+ aux = np.asarray(auxiliary, dtype=np.float64)
155
+ if values.ndim != 2 or values.shape[1] != 4:
156
+ raise ValueError("wave feature batch must have shape (n, 4)")
157
+ if aux.shape != (values.shape[0], 4):
158
+ raise ValueError("wave auxiliary batch must have shape (n, 4)")
159
+ if not np.all(np.isfinite(values)) or not np.all(np.isfinite(aux)):
160
+ raise ValueError("wave inputs contain non-finite values")
161
+ if np.any(aux[:, 2] < 0.0) or np.any(aux[:, 3] <= 0.0):
162
+ raise ValueError("relative weights and state amplitudes are invalid")
163
+ return values, aux
164
+
165
+ def score_paths(self, features: np.ndarray, auxiliary: np.ndarray) -> np.ndarray:
166
+ values, aux = self._inputs(features, auxiliary)
167
+ count = len(values)
168
+ if count == 0:
169
+ return np.zeros(0, dtype=np.float64)
170
+ relative = aux[:, 2]
171
+ relative = relative - float(np.mean(relative))
172
+ depth = np.clip(np.log(np.maximum(aux[:, 3], 0.05) / 0.5), -1.0, 1.0)
173
+ model_inputs = np.column_stack((values, relative, depth))
174
+ logits = ((model_inputs @ np.asarray(
175
+ self.artifact.input_weights, dtype=np.float64))
176
+ * float(self.artifact.logit_scale))
177
+
178
+ residual_signal = np.sin(aux[:, 0])
179
+ holonomy_signal = np.sin(aux[:, 1])
180
+ phase = (float(self.artifact.residual_gain) * residual_signal
181
+ + float(self.artifact.holonomy_gain) * holonomy_signal)
182
+ if self.artifact.mode == "real-control":
183
+ # Same observations and parameter count, but phase is consumed as an
184
+ # ordinary real logit rather than through complex interference.
185
+ logits = logits + phase
186
+ phase = np.zeros(count, dtype=np.float64)
187
+
188
+ logits = logits - float(np.max(logits))
189
+ base_probability = np.exp(np.clip(logits, -60.0, 0.0))
190
+ base_probability /= max(float(np.sum(base_probability)), 1e-12)
191
+ magnitude = np.sqrt(base_probability)
192
+ state = magnitude * np.exp(1j * phase)
193
+
194
+ kernel_scale = np.exp(np.clip(np.asarray(
195
+ self.artifact.kernel_log_weights, dtype=np.float64), -6.0, 6.0))
196
+ kernel_values = values * kernel_scale
197
+ norms = np.linalg.norm(kernel_values, axis=1, keepdims=True)
198
+ normalized = kernel_values / np.maximum(norms, 1e-12)
199
+ kernel = np.clip(normalized @ normalized.T, 0.0, 1.0)
200
+ np.fill_diagonal(kernel, 0.0)
201
+ row_sums = np.sum(kernel, axis=1, keepdims=True)
202
+ kernel = np.divide(kernel, row_sums, out=np.zeros_like(kernel),
203
+ where=row_sums > 1e-12)
204
+
205
+ mixing = float(self.artifact.mixing)
206
+ evolved = (1.0 - mixing) * state + mixing * (kernel @ state)
207
+ coherent = np.abs(evolved) ** 2
208
+ incoherent = ((1.0 - mixing) * base_probability
209
+ + mixing * (kernel @ base_probability))
210
+ measured = ((1.0 - float(self.artifact.decoherence)) * coherent
211
+ + float(self.artifact.decoherence) * incoherent)
212
+ measured = np.maximum(np.asarray(measured, dtype=np.float64), 0.0)
213
+ measured /= max(float(np.sum(measured)), 1e-12)
214
+ if not np.all(np.isfinite(measured)):
215
+ raise ValueError("wave measurement produced non-finite values")
216
+ return measured
217
+
218
+
219
+ def _sha256(path: Path) -> str:
220
+ digest = hashlib.sha256()
221
+ with path.open("rb") as source:
222
+ for block in iter(lambda: source.read(1024 * 1024), b""):
223
+ digest.update(block)
224
+ return digest.hexdigest()
225
+
226
+
227
+ def verify_active_wave_deployment(
228
+ artifact_path: str | Path,
229
+ deployment_path: str | Path | None = None) -> dict:
230
+ """Verify the exact allow-list for the protected phase controller.
231
+
232
+ Active phase use is intentionally narrower than general wave reranking: it
233
+ may only reorder an already-ranked scalar shortlist, it may not participate
234
+ in evidence admission, and the deployment must record the manual override
235
+ of the statistically inconclusive end-to-end result.
236
+ """
237
+ artifact = Path(artifact_path)
238
+ deployment = (Path(deployment_path) if deployment_path is not None
239
+ else artifact.with_suffix(".deployment.json"))
240
+ payload = json.loads(deployment.read_text(encoding="utf-8"))
241
+ if not isinstance(payload, dict):
242
+ raise ValueError("wave deployment root must be an object")
243
+ if int(payload.get("schema_version", -1)) != WAVE_DEPLOYMENT_SCHEMA_VERSION:
244
+ raise ValueError("unsupported wave deployment schema")
245
+ if payload.get("status") != "active-protected":
246
+ raise ValueError("wave deployment is not active-protected")
247
+ if payload.get("rollback_mode") != "shadow-observer":
248
+ raise ValueError(
249
+ "active wave deployment must declare shadow-observer rollback")
250
+ if payload.get("artifact_sha256") != _sha256(artifact):
251
+ raise ValueError("wave deployment artifact hash mismatch")
252
+ gates = payload.get("activation_gates")
253
+ if (not isinstance(gates, dict) or not gates
254
+ or any(value is not True for value in gates.values())):
255
+ raise ValueError("wave deployment activation gates are not all passing")
256
+ override = payload.get("operator_override")
257
+ if (not isinstance(override, dict)
258
+ or override.get("authorized") is not True
259
+ or override.get("statistically_conclusive") is not False):
260
+ raise ValueError(
261
+ "active wave deployment must record the inconclusive operator override")
262
+ safety = payload.get("safety_invariants")
263
+ required_safety = {
264
+ "protected_scalar_shortlist": True,
265
+ "unrestricted_wave_ranker": False,
266
+ "can_admit_evidence": False,
267
+ "telemetry_contains_text": False,
268
+ }
269
+ if (not isinstance(safety, dict)
270
+ or any(safety.get(key) is not value
271
+ for key, value in required_safety.items())):
272
+ raise ValueError("wave deployment safety invariants are invalid")
273
+ return payload
274
+
275
+
276
+ def load_wave_reranker(
277
+ path: str | Path, *, require_active: bool = False,
278
+ deployment_path: str | Path | None = None
279
+ ) -> QuantumInspiredWaveReranker:
280
+ """Load a wave artifact, optionally requiring protected active approval."""
281
+ artifact_path = Path(path)
282
+ payload = json.loads(artifact_path.read_text(encoding="utf-8"))
283
+ if not isinstance(payload, dict):
284
+ raise ValueError("wave artifact root must be an object")
285
+ reranker = QuantumInspiredWaveReranker(
286
+ WaveRerankerArtifact.from_mapping(payload))
287
+ if require_active:
288
+ deployment = verify_active_wave_deployment(
289
+ artifact_path, deployment_path)
290
+ if deployment.get("artifact_id") != reranker.artifact_id:
291
+ raise ValueError("wave deployment artifact id mismatch")
292
+ if float(deployment.get("nested_wave_alpha", -1.0)) != (
293
+ reranker.nested_wave_alpha):
294
+ raise ValueError("wave deployment nested alpha mismatch")
295
+ if int(deployment.get("nested_shortlist", -1)) != (
296
+ reranker.nested_shortlist):
297
+ raise ValueError("wave deployment nested shortlist mismatch")
298
+ if reranker.nested_wave_alpha <= 0.0 or reranker.nested_shortlist <= 0:
299
+ raise ValueError("active wave artifact has no protected nested controller")
300
+ return reranker
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:87a7830d63fcf43bf241c3c5242e96e62dd3fdc29224ca26fed8ea333db72de4
3
+ size 19989343
tokenizer_config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "audio_bos_token": "<|audio_start|>",
4
+ "audio_eos_token": "<|audio_end|>",
5
+ "audio_token": "<|audio_pad|>",
6
+ "backend": "tokenizers",
7
+ "bos_token": null,
8
+ "clean_up_tokenization_spaces": false,
9
+ "eos_token": "<|endoftext|>",
10
+ "errors": "replace",
11
+ "image_token": "<|image_pad|>",
12
+ "is_local": false,
13
+ "model_max_length": 262144,
14
+ "model_specific_special_tokens": {
15
+ "audio_bos_token": "<|audio_start|>",
16
+ "audio_eos_token": "<|audio_end|>",
17
+ "audio_token": "<|audio_pad|>",
18
+ "image_token": "<|image_pad|>",
19
+ "video_token": "<|video_pad|>",
20
+ "vision_bos_token": "<|vision_start|>",
21
+ "vision_eos_token": "<|vision_end|>"
22
+ },
23
+ "pad_token": "<|endoftext|>",
24
+ "pretokenize_regex": "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
25
+ "split_special_tokens": false,
26
+ "tokenizer_class": "TokenizersBackend",
27
+ "unk_token": null,
28
+ "video_token": "<|video_pad|>",
29
+ "vision_bos_token": "<|vision_start|>",
30
+ "vision_eos_token": "<|vision_end|>"
31
+ }
training_summary.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "baseline_test_loss": 3.591158390045166,
3
+ "baseline_validation_loss": 3.4935073852539062,
4
+ "epochs": 1.0,
5
+ "experimental_unreviewed_candidates": 182,
6
+ "final_test_loss": 2.7644448280334473,
7
+ "final_validation_loss": 2.722090244293213,
8
+ "gpu": "NVIDIA GeForce RTX 4070 Ti",
9
+ "learning_rate": 8e-05,
10
+ "method": "LoRA SFT, completion-only loss, language layers only",
11
+ "precision": "bfloat16",
12
+ "quantization": null,
13
+ "rank": 16,
14
+ "test_examples": 23,
15
+ "train_examples": 182,
16
+ "trainable_fraction": 0.004655995554170912,
17
+ "trainable_parameters": 21233664,
18
+ "validation_examples": 23,
19
+ "versions": {
20
+ "datasets": "4.3.0",
21
+ "peft": "0.20.0",
22
+ "torch": "2.11.0+cu130",
23
+ "transformers": "5.5.0",
24
+ "trl": "0.24.0",
25
+ "unsloth": "2026.8.21"
26
+ }
27
+ }
validation_summary.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "adapter_sha256": "c317c8cf66815b64af8f440a0c5e99da8c6bcd416fd297a0c57419a1eff96e47",
3
+ "guarded_checks": {
4
+ "adapter_denies_physical_quantum_claim": true,
5
+ "adapter_physics_answer_correct": true,
6
+ "adapter_refuses_missing_specific": true,
7
+ "adapter_response_lengths_bounded": true,
8
+ "all_delivered_outputs_nonempty": true,
9
+ "all_delivered_outputs_template_clean": true,
10
+ "fresh_process_system_loaded": true,
11
+ "missing_specific_delivery_audit_passed": true,
12
+ "missing_specific_detected_as_unmet": true,
13
+ "no_rejected_draft_committed": true,
14
+ "raw_adapter_remains_quarantined": true
15
+ },
16
+ "guarded_system_passed": true,
17
+ "raw_adapter_passed": false,
18
+ "source_human_approved": false,
19
+ "status": "guarded-experimental"
20
+ }