MetaCortex-Dynamics commited on
Commit
37cfe0e
Β·
verified Β·
1 Parent(s): 1a3c670

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +188 -83
app.py CHANGED
@@ -1,7 +1,11 @@
1
  """
2
  Axiom-Ref β€” HuggingFace Space / Gradio App
3
 
4
- Governed Language Model: every output ships its own proof.
 
 
 
 
5
  """
6
 
7
  import sys
@@ -23,7 +27,7 @@ from pipeline.mdlm.tokenizer import (
23
  G_OPEN, G_CLOSE, S_OPEN, S_CLOSE, F_OPEN, F_CLOSE,
24
  OP_OFFSET, WIT_OFFSET, ATTESTED, WITHHELD, BOS, EOS,
25
  )
26
- from pipeline.mdlm.model import StructureModel, MaskingSchedule, generate
27
  from pipeline.mdlm.decoder import ConstrainedDecoder
28
  from pipeline.mdlm.governed_pipeline import (
29
  propose, decide, promote, execute, tokens_to_example,
@@ -45,34 +49,29 @@ decoder = ConstrainedDecoder(
45
  gov_vocab=VOCAB_SIZE, prose_vocab=bpe_vocab, d_model=256, nhead=8,
46
  num_encoder_layers=3, num_decoder_layers=6, max_struct_len=40, max_prose_len=128,
47
  ).to(device)
48
- _dec_state = torch.load("models/axiom-ref/decoder_best.pt", weights_only=True, map_location=device)
49
- # Remap legacy weight names
50
- _dec_state = {k.replace("triad_embedding", "struct_embedding").replace("triad_pos", "struct_pos"): v for k, v in _dec_state.items()}
51
- decoder.load_state_dict(_dec_state)
52
  decoder.eval()
53
 
54
 
55
- def generate_governed(num_candidates=10, temperature=0.7):
56
- """Run the full 4-phase governed pipeline."""
 
57
 
58
- # Phase 1: PROPOSE
59
- candidates = propose(mdlm, num_candidates=num_candidates, g_slots=2, s_slots=2, f_slots=2)
60
 
61
- # Phase 2: DECIDE
62
  decided = decide(candidates)
63
-
64
  t_count = sum(1 for _, d, _ in decided if d.tig_status == "T")
65
  f_count = sum(1 for _, d, _ in decided if d.tig_status == "F")
66
-
67
  admitted = [(c, d, e) for c, d, e in decided if d.tig_status == "T" and e is not None]
68
-
69
- # Phase 3: PROMOTE
70
  promoted = promote(admitted)
71
 
72
  if not promoted:
73
- return "No candidates passed governance.", "", "{}", ""
74
 
75
- # Phase 4: EXECUTE
76
  outputs = execute(promoted)
77
  example, commitment = promoted[0]
78
  gov_dict = outputs[0].gov_structure
@@ -103,105 +102,211 @@ def generate_governed(num_candidates=10, temperature=0.7):
103
  gen.append(nxt.item())
104
 
105
  prose = tokenizer.decode(gen)
106
-
107
- # Build governance trace
108
  output_hash = sha256(prose.encode()).hexdigest()
109
 
110
- gate_html = ""
111
- gate_names = ["G1 Structural Integrity", "G2 Completeness", "G3 Witness Sufficiency",
112
- "G4 Authority Separation", "G5 Provenance Continuity",
113
- "G6 Semantic Stability", "G7 Behavioral Prediction"]
114
- for g in gate_names:
115
- gate_html += f'<div style="padding:4px 0"><span style="color:#4ade80;font-weight:bold">PASS</span> {g}</div>'
116
-
117
- witness_html = ""
118
- for w_name, w_data in commitment.witnesses.items():
119
- status = "ATTESTED" if w_data["attested"] else "WITHHELD"
120
- color = "#4ade80" if w_data["attested"] else "#e94560"
121
- witness_html += f'<div style="padding:2px 0"><span style="color:{color};font-weight:bold">{status}</span> {w_name}</div>'
122
-
123
  trace = {
124
- "output_hash": output_hash[:32] + "...",
125
- "commitment": commitment.witness_bundle_hash[:32] + "...",
126
  "gov_structure": {
127
  "G": [op["operator"] for op in gov_dict["G"]],
128
  "S": [op["operator"] for op in gov_dict["S"]],
129
  "F": [op["operator"] for op in gov_dict["F"]],
130
  },
131
  "gates_passed": 7,
132
- "witnesses_attested": 7,
133
- "admission": f"{t_count}/{num_candidates}",
 
134
  "timestamp": datetime.now(timezone.utc).isoformat(),
135
  }
136
 
137
- stats_html = f"""
138
- <div style="font-family:monospace;font-size:13px">
139
- <div style="margin-bottom:12px">
140
- <div style="color:#888;font-size:11px">PIPELINE STATS</div>
141
- <div>Proposed: {num_candidates} | Admitted: {t_count} | Rejected: {f_count}</div>
142
- </div>
143
- <div style="margin-bottom:12px">
144
- <div style="color:#888;font-size:11px">GATES</div>
145
- {gate_html}
146
- </div>
147
- <div style="margin-bottom:12px">
148
- <div style="color:#888;font-size:11px">WITNESSES</div>
149
- {witness_html}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  </div>
151
- <div>
152
- <div style="color:#888;font-size:11px">COMMITMENT</div>
153
- <div style="word-break:break-all;color:#666">{commitment.witness_bundle_hash[:48]}...</div>
154
- <div style="color:#4ade80;font-weight:bold;margin-top:4px">Irrevocable</div>
155
  </div>
156
  </div>
157
  """
158
 
159
- return prose, stats_html, json.dumps(trace, indent=2), f"G: {trace['gov_structure']['G']}\nS: {trace['gov_structure']['S']}\nF: {trace['gov_structure']['F']}"
160
 
 
 
 
161
 
162
- # ── Gradio Interface ──
163
  with gr.Blocks(
164
  title="Axiom-Ref: Governed Language Model",
165
  theme=gr.themes.Base(primary_hue="green", neutral_hue="slate"),
166
- css="""
167
- .output-prose { font-family: 'Courier New', monospace; font-size: 14px; }
168
- """
169
  ) as app:
170
 
171
  gr.Markdown("""
172
  # Axiom-Ref
173
- **Governed Language Model β€” every output ships its own proof.**
174
-
175
- Four phases: PROPOSE β†’ DECIDE β†’ PROMOTE β†’ EXECUTE.
176
- No other language model ships a machine-verifiable governance trace with its output.
177
  """)
178
 
179
- with gr.Row():
180
- with gr.Column(scale=2):
181
- num_candidates = gr.Slider(1, 50, value=10, step=1, label="Candidates to propose")
182
- temperature = gr.Slider(0.1, 1.5, value=0.7, step=0.1, label="Decoder temperature")
183
- generate_btn = gr.Button("Generate Governed Output", variant="primary", size="lg")
184
-
185
- gr.Markdown("### Generated Output")
186
- output_prose = gr.Code(label="Governed Prose", language="c", lines=12)
187
- output_structure = gr.Textbox(label="Governed Structure", lines=3)
188
-
189
- with gr.Column(scale=1):
190
- gr.Markdown("### Governance Trace")
191
- governance_panel = gr.HTML()
192
- trace_json = gr.Code(label="Machine-Verifiable Trace (JSON)", language="json", lines=15)
193
-
194
- generate_btn.click(
195
- fn=generate_governed,
196
- inputs=[num_candidates, temperature],
197
- outputs=[output_prose, governance_panel, trace_json, output_structure],
198
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
 
200
  gr.Markdown("""
201
  ---
202
  *[MetaCortex Dynamics DAO](https://github.com/MetaCortex-Dynamics) Β· [Source](https://github.com/MetaCortex-Dynamics/Axiom-Ref) Β· MIT License*
203
  """)
204
 
205
-
206
  if __name__ == "__main__":
207
  app.launch()
 
1
  """
2
  Axiom-Ref β€” HuggingFace Space / Gradio App
3
 
4
+ Two modes:
5
+ 1. GENERATE β€” produce governed output with proof
6
+ 2. VERIFY β€” submit output + trace, get pass/fail
7
+
8
+ The verifier is the product demo. The proof is the point.
9
  """
10
 
11
  import sys
 
27
  G_OPEN, G_CLOSE, S_OPEN, S_CLOSE, F_OPEN, F_CLOSE,
28
  OP_OFFSET, WIT_OFFSET, ATTESTED, WITHHELD, BOS, EOS,
29
  )
30
+ from pipeline.mdlm.model import StructureModel, MaskingSchedule, generate as mdlm_generate
31
  from pipeline.mdlm.decoder import ConstrainedDecoder
32
  from pipeline.mdlm.governed_pipeline import (
33
  propose, decide, promote, execute, tokens_to_example,
 
49
  gov_vocab=VOCAB_SIZE, prose_vocab=bpe_vocab, d_model=256, nhead=8,
50
  num_encoder_layers=3, num_decoder_layers=6, max_struct_len=40, max_prose_len=128,
51
  ).to(device)
52
+ _ds = torch.load("models/axiom-ref/decoder_best.pt", weights_only=True, map_location=device)
53
+ _ds = {k.replace("triad_embedding", "struct_embedding").replace("triad_pos", "struct_pos"): v for k, v in _ds.items()}
54
+ decoder.load_state_dict(_ds)
 
55
  decoder.eval()
56
 
57
 
58
+ # ═══════════════════════════════════════════════════════════════════════════════
59
+ # TAB 1: GENERATE
60
+ # ═══════════════════════════════════════════════════════════════════════════════
61
 
62
+ def generate_governed(num_candidates=10, temperature=0.7):
63
+ """Run the full 4-phase governed pipeline. Returns (prose, trace_panel, trace_json)."""
64
 
65
+ candidates = propose(mdlm, num_candidates=int(num_candidates), g_slots=2, s_slots=2, f_slots=2)
66
  decided = decide(candidates)
 
67
  t_count = sum(1 for _, d, _ in decided if d.tig_status == "T")
68
  f_count = sum(1 for _, d, _ in decided if d.tig_status == "F")
 
69
  admitted = [(c, d, e) for c, d, e in decided if d.tig_status == "T" and e is not None]
 
 
70
  promoted = promote(admitted)
71
 
72
  if not promoted:
73
+ return "No candidates passed governance.", "", "{}"
74
 
 
75
  outputs = execute(promoted)
76
  example, commitment = promoted[0]
77
  gov_dict = outputs[0].gov_structure
 
102
  gen.append(nxt.item())
103
 
104
  prose = tokenizer.decode(gen)
 
 
105
  output_hash = sha256(prose.encode()).hexdigest()
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  trace = {
108
+ "output_hash": output_hash,
 
109
  "gov_structure": {
110
  "G": [op["operator"] for op in gov_dict["G"]],
111
  "S": [op["operator"] for op in gov_dict["S"]],
112
  "F": [op["operator"] for op in gov_dict["F"]],
113
  },
114
  "gates_passed": 7,
115
+ "witnesses": {w: {"attested": d["attested"]} for w, d in commitment.witnesses.items()},
116
+ "commitment": commitment.witness_bundle_hash,
117
+ "admission": f"{t_count}/{int(num_candidates)}",
118
  "timestamp": datetime.now(timezone.utc).isoformat(),
119
  }
120
 
121
+ # Build panel
122
+ gate_names = ["G1 Structural Integrity", "G2 Completeness", "G3 Witness Sufficiency",
123
+ "G4 Authority Separation", "G5 Provenance Continuity",
124
+ "G6 Semantic Stability", "G7 Behavioral Prediction"]
125
+ gate_html = "".join(f'<div style="padding:3px 0"><span style="color:#4ade80;font-weight:bold">PASS</span> {g}</div>' for g in gate_names)
126
+ wit_html = "".join(
127
+ f'<div style="padding:2px 0"><span style="color:{"#4ade80" if d["attested"] else "#e94560"};font-weight:bold">{"ATTESTED" if d["attested"] else "WITHHELD"}</span> {w}</div>'
128
+ for w, d in commitment.witnesses.items()
129
+ )
130
+
131
+ panel = f"""<div style="font-family:monospace;font-size:12px">
132
+ <div style="margin-bottom:8px"><span style="color:#888">PIPELINE</span> Proposed: {int(num_candidates)} | Admitted: {t_count} | Rejected: {f_count}</div>
133
+ <div style="margin-bottom:8px"><span style="color:#888">GATES</span>{gate_html}</div>
134
+ <div style="margin-bottom:8px"><span style="color:#888">WITNESSES</span>{wit_html}</div>
135
+ <div><span style="color:#888">COMMITMENT</span><div style="word-break:break-all;color:#555;font-size:10px">{commitment.witness_bundle_hash}</div>
136
+ <div style="color:#4ade80;font-weight:bold;margin-top:4px">Irrevocable</div></div>
137
+ </div>"""
138
+
139
+ return prose, panel, json.dumps(trace, indent=2)
140
+
141
+
142
+ # ═══════════════════════════════════════════════════════════════════════════════
143
+ # TAB 2: VERIFY
144
+ # ═══════════════════════════════════════════════════════════════════════════════
145
+
146
+ def verify_governance(output_text, trace_json_str):
147
+ """Verify a governance trace against its claimed output."""
148
+ try:
149
+ trace = json.loads(trace_json_str)
150
+ except json.JSONDecodeError as e:
151
+ return f'<div style="color:#e94560;font-weight:bold;font-size:16px">INVALID JSON: {e}</div>'
152
+
153
+ checks = []
154
+ all_pass = True
155
+
156
+ # Check 1: Output hash matches
157
+ claimed_hash = trace.get("output_hash", "")
158
+ actual_hash = sha256(output_text.encode()).hexdigest()
159
+ hash_match = claimed_hash == actual_hash
160
+ if not hash_match:
161
+ all_pass = False
162
+ checks.append(("Output hash integrity", hash_match,
163
+ f"Claimed: {claimed_hash[:24]}...<br>Computed: {actual_hash[:24]}..."))
164
+
165
+ # Check 2: Structure present and complete
166
+ gov = trace.get("gov_structure", {})
167
+ has_g = bool(gov.get("G"))
168
+ has_s = bool(gov.get("S"))
169
+ has_f = bool(gov.get("F"))
170
+ complete = has_g and has_s and has_f
171
+ if not complete:
172
+ all_pass = False
173
+ checks.append(("Structure completeness", complete,
174
+ f"G: {'present' if has_g else 'MISSING'} | S: {'present' if has_s else 'MISSING'} | F: {'present' if has_f else 'MISSING'}"))
175
+
176
+ # Check 3: All 7 gates claimed passed
177
+ gates = trace.get("gates_passed", 0)
178
+ gates_ok = gates == 7
179
+ if not gates_ok:
180
+ all_pass = False
181
+ checks.append(("Gates passed (7 required)", gates_ok, f"{gates}/7"))
182
+
183
+ # Check 4: All 7 witnesses attested
184
+ witnesses = trace.get("witnesses", {})
185
+ attested_count = sum(1 for w in witnesses.values() if w.get("attested"))
186
+ total_witnesses = len(witnesses)
187
+ wit_ok = attested_count == 7 and total_witnesses == 7
188
+ if not wit_ok:
189
+ all_pass = False
190
+ checks.append(("Witness unanimity (7/7)", wit_ok, f"{attested_count}/{total_witnesses} attested"))
191
+
192
+ # Check 5: Commitment hash present
193
+ commitment = trace.get("commitment", "")
194
+ commit_ok = len(commitment) >= 32
195
+ if not commit_ok:
196
+ all_pass = False
197
+ checks.append(("Commitment hash present", commit_ok,
198
+ f"{commitment[:32]}..." if commitment else "MISSING"))
199
+
200
+ # Check 6: Operators are valid
201
+ all_ops = (gov.get("G", []) + gov.get("S", []) + gov.get("F", []))
202
+ valid_op_names = {TOKEN_NAMES[i] for i in range(OP_OFFSET, OP_OFFSET + 15)}
203
+ invalid_ops = [op for op in all_ops if op not in valid_op_names]
204
+ ops_ok = len(invalid_ops) == 0 and len(all_ops) > 0
205
+ if not ops_ok:
206
+ all_pass = False
207
+ checks.append(("Valid operators only", ops_ok,
208
+ f"{len(all_ops)} operators, {len(invalid_ops)} invalid" + (f": {invalid_ops}" if invalid_ops else "")))
209
+
210
+ # Check 7: Timestamp present and parseable
211
+ ts = trace.get("timestamp", "")
212
+ try:
213
+ datetime.fromisoformat(ts.replace("Z", "+00:00"))
214
+ ts_ok = True
215
+ except (ValueError, AttributeError):
216
+ ts_ok = False
217
+ if not ts_ok:
218
+ all_pass = False
219
+ checks.append(("Timestamp valid", ts_ok, ts if ts else "MISSING"))
220
+
221
+ # Build result HTML
222
+ verdict_color = "#4ade80" if all_pass else "#e94560"
223
+ verdict_text = "GOVERNANCE VERIFIED" if all_pass else "VERIFICATION FAILED"
224
+
225
+ rows = ""
226
+ for name, passed, detail in checks:
227
+ color = "#4ade80" if passed else "#e94560"
228
+ icon = "PASS" if passed else "FAIL"
229
+ rows += f'<tr><td style="padding:6px 12px;color:{color};font-weight:bold">{icon}</td><td style="padding:6px 12px;color:#ccc">{name}</td><td style="padding:6px 12px;color:#888;font-size:11px">{detail}</td></tr>'
230
+
231
+ return f"""
232
+ <div style="padding:16px">
233
+ <div style="font-size:24px;font-weight:bold;color:{verdict_color};margin-bottom:16px;text-align:center;padding:12px;border:2px solid {verdict_color};border-radius:8px">
234
+ {verdict_text}
235
  </div>
236
+ <table style="width:100%;border-collapse:collapse">{rows}</table>
237
+ <div style="margin-top:16px;color:#555;font-size:11px;text-align:center">
238
+ 7 checks performed. All must pass for governance verification.
 
239
  </div>
240
  </div>
241
  """
242
 
 
243
 
244
+ # ═══════════════════════════════════════════════════════════════════════════════
245
+ # GRADIO APP
246
+ # ═══════════════════════════════════════════════════════════════════════════════
247
 
 
248
  with gr.Blocks(
249
  title="Axiom-Ref: Governed Language Model",
250
  theme=gr.themes.Base(primary_hue="green", neutral_hue="slate"),
 
 
 
251
  ) as app:
252
 
253
  gr.Markdown("""
254
  # Axiom-Ref
255
+ **Every output ships its own proof of governance.**
 
 
 
256
  """)
257
 
258
+ with gr.Tabs():
259
+
260
+ # ── Tab 1: Generate ──
261
+ with gr.Tab("Generate"):
262
+ gr.Markdown("Generate governed output with a machine-verifiable governance trace.")
263
+
264
+ with gr.Row():
265
+ with gr.Column(scale=2):
266
+ num_candidates = gr.Slider(1, 50, value=10, step=1, label="Candidates to propose")
267
+ temperature = gr.Slider(0.1, 1.5, value=0.7, step=0.1, label="Temperature")
268
+ generate_btn = gr.Button("Generate", variant="primary", size="lg")
269
+
270
+ output_prose = gr.Code(label="Governed Output", language="c", lines=10)
271
+
272
+ with gr.Column(scale=1):
273
+ governance_panel = gr.HTML(label="Governance")
274
+ trace_json = gr.Code(label="Trace (JSON) β€” copy this to verify", language="json", lines=12)
275
+
276
+ generate_btn.click(
277
+ fn=generate_governed,
278
+ inputs=[num_candidates, temperature],
279
+ outputs=[output_prose, governance_panel, trace_json],
280
+ )
281
+
282
+ # ── Tab 2: Verify ──
283
+ with gr.Tab("Verify"):
284
+ gr.Markdown("""
285
+ **Submit any output + its governance trace. Get pass or fail.**
286
+
287
+ Paste the generated output and the JSON trace from the Generate tab (or from any Axiom model).
288
+ The verifier checks 7 governance conditions. All must pass.
289
+ """)
290
+
291
+ with gr.Row():
292
+ with gr.Column():
293
+ verify_output = gr.Textbox(label="Output text", lines=8, placeholder="Paste the generated output here...")
294
+ verify_trace = gr.Code(label="Governance trace (JSON)", language="json", lines=12, value='{\n "output_hash": "",\n "gov_structure": {"G": [], "S": [], "F": []},\n "gates_passed": 7,\n "witnesses": {},\n "commitment": "",\n "timestamp": ""\n}')
295
+ verify_btn = gr.Button("Verify Governance", variant="primary", size="lg")
296
+
297
+ with gr.Column():
298
+ verify_result = gr.HTML()
299
+
300
+ verify_btn.click(
301
+ fn=verify_governance,
302
+ inputs=[verify_output, verify_trace],
303
+ outputs=[verify_result],
304
+ )
305
 
306
  gr.Markdown("""
307
  ---
308
  *[MetaCortex Dynamics DAO](https://github.com/MetaCortex-Dynamics) Β· [Source](https://github.com/MetaCortex-Dynamics/Axiom-Ref) Β· MIT License*
309
  """)
310
 
 
311
  if __name__ == "__main__":
312
  app.launch()