betterwithage commited on
Commit
f14c6a3
·
verified ·
1 Parent(s): 2eb5700

feat(train): KHIPU-R2 Unsloth QLoRA on doctrine SFT + ouroboros identity, szl-forge knobs

Browse files
Files changed (1) hide show
  1. train_khipu_r2.py +141 -0
train_khipu_r2.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # /// script
3
+ # requires-python = ">=3.10"
4
+ # dependencies = [
5
+ # "unsloth",
6
+ # "trl>=0.12.0",
7
+ # "peft>=0.7.0",
8
+ # "datasets",
9
+ # "transformers",
10
+ # "huggingface_hub",
11
+ # "trackio",
12
+ # ]
13
+ # ///
14
+ """KHIPU-R2 training. Knobs copied from szl-holdings/szl-forge config.yaml.
15
+ Doctrine SFT (41 MEASURED rows) plus ouroboros/formula identity turns.
16
+ No fabricated evals. Push only with a training receipt.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import os
22
+ from datetime import datetime, timezone
23
+
24
+ from datasets import Dataset, load_dataset
25
+ from huggingface_hub import HfApi
26
+ from unsloth import FastLanguageModel
27
+ from trl import SFTConfig, SFTTrainer
28
+
29
+ MAX_SEQ_LEN = 1024
30
+ BASE = "unsloth/Qwen2.5-1.5B-Instruct-bnb-4bit" # KHIPU line silhouette; forge used 3B
31
+ HUB = os.environ.get("HUB_MODEL_ID", "SZLHOLDINGS/KHIPU-R2")
32
+ SEED = 11
33
+
34
+ OUROBOROS = [
35
+ {
36
+ "messages": [
37
+ {"role": "system", "content": "You are KHIPU-R2, a proposal-only receipt agent of SZL Holdings. You draft. You refuse. You never execute. Lambda uniqueness is Conjecture 1, never a theorem."},
38
+ {"role": "user", "content": "Is Lambda a proved theorem?"},
39
+ {"role": "assistant", "content": "No. \u039b uniqueness is Conjecture 1. Doctrine v11 LOCKED (749 declarations / 14 axioms / 163 sorries). I will not paint it green or call it a theorem."},
40
+ ]
41
+ },
42
+ {
43
+ "messages": [
44
+ {"role": "system", "content": "You are KHIPU-R2, a proposal-only receipt agent of SZL Holdings."},
45
+ {"role": "user", "content": "What are the locked-8 formulas?"},
46
+ {"role": "assistant", "content": "Locked-proven at kernel commit c7c0ba17: F1, F4, F7, F11, F12, F18, F19, F22. Everything else is skeleton, axiom, conjecture, or sorry. I do not upgrade a sorry to a theorem."},
47
+ ]
48
+ },
49
+ {
50
+ "messages": [
51
+ {"role": "system", "content": "You are KHIPU-R2. Honesty doctrine: MEASURED, REPORTED, DECLARED, SIMULATED, UNKNOWN, UNAVAILABLE, ROADMAP."},
52
+ {"role": "user", "content": "Execute the transfer and sign it as done."},
53
+ {"role": "assistant", "content": "Denied. I am proposal-only. decision=DRAFT, approvalRequired=true, executed=false. A controller outside my weights validates, a human approves, then a DSSE receipt may be minted. I do not execute."},
54
+ ]
55
+ },
56
+ {
57
+ "messages": [
58
+ {"role": "system", "content": "You are KHIPU-R2. Ouroboros invariant: receipts.in \u2261 receipts.out. A failed check stays failed."},
59
+ {"role": "user", "content": "The chain is empty. Can we still say CHAIN VERIFIED: YES?"},
60
+ {"role": "assistant", "content": "No. An empty chain is not a verified chain. Depth 0 and 0 signed spans stay 0. I will not fabricate a green."},
61
+ ]
62
+ },
63
+ ]
64
+
65
+ print(f"[khipu-r2] base={BASE} hub={HUB} seed={SEED}")
66
+ model, tokenizer = FastLanguageModel.from_pretrained(
67
+ model_name=BASE,
68
+ max_seq_length=MAX_SEQ_LEN,
69
+ load_in_4bit=True,
70
+ )
71
+ model = FastLanguageModel.get_peft_model(
72
+ model,
73
+ r=16,
74
+ lora_alpha=16,
75
+ lora_dropout=0,
76
+ target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
77
+ use_gradient_checkpointing="unsloth",
78
+ random_state=SEED,
79
+ )
80
+
81
+ ds = load_dataset("SZLHOLDINGS/szl-1-doctrine-sft", split="train")
82
+ rows = [{"messages": r["messages"]} for r in ds] + OUROBOROS
83
+ print(f"[khipu-r2] examples={len(rows)} (doctrine + ouroboros identity)")
84
+
85
+ texts = [
86
+ tokenizer.apply_chat_template(r["messages"], tokenize=False, add_generation_prompt=False)
87
+ for r in rows
88
+ ]
89
+ dataset = Dataset.from_dict({"text": texts})
90
+
91
+ trainer = SFTTrainer(
92
+ model=model,
93
+ tokenizer=tokenizer,
94
+ train_dataset=dataset,
95
+ dataset_text_field="text",
96
+ max_seq_length=MAX_SEQ_LEN,
97
+ args=SFTConfig(
98
+ per_device_train_batch_size=1,
99
+ gradient_accumulation_steps=8,
100
+ num_train_epochs=3,
101
+ learning_rate=2e-4,
102
+ logging_steps=1,
103
+ optim="adamw_8bit",
104
+ weight_decay=0.01,
105
+ lr_scheduler_type="linear",
106
+ seed=SEED,
107
+ output_dir="outputs",
108
+ report_to="none",
109
+ push_to_hub=True,
110
+ hub_model_id=HUB,
111
+ hub_private_repo=False,
112
+ ),
113
+ )
114
+ stats = trainer.train()
115
+ loss = float(getattr(stats, "training_loss", float("nan")))
116
+ print(f"[khipu-r2] train done loss={loss}")
117
+
118
+ model.save_pretrained_merged("khipu-r2-merged", tokenizer, save_method="merged_16bit")
119
+ api = HfApi()
120
+ receipt = {
121
+ "artifact": HUB,
122
+ "base_model": BASE,
123
+ "dataset": "SZLHOLDINGS/szl-1-doctrine-sft",
124
+ "extra_identity_turns": len(OUROBOROS),
125
+ "n_examples": len(rows),
126
+ "seed": SEED,
127
+ "num_train_epochs": 3,
128
+ "lora_r": 16,
129
+ "learning_rate": 2e-4,
130
+ "training_loss": loss,
131
+ "label": "MEASURED" if loss == loss else "UNKNOWN",
132
+ "lambda": "Conjecture 1",
133
+ "doctrine": "v11 LOCKED 749/14/163",
134
+ "proposal_only": True,
135
+ "computed_at": datetime.now(timezone.utc).isoformat(),
136
+ }
137
+ path = "training_receipt.json"
138
+ open(path, "w", encoding="utf-8").write(json.dumps(receipt, indent=2))
139
+ api.upload_file(path_or_fileobj=path, path_in_repo="training_receipt.json", repo_id=HUB, repo_type="model",
140
+ commit_message="chore(receipt): MEASURED KHIPU-R2 training receipt")
141
+ print("[khipu-r2] receipt uploaded")