Archive experiment updates 2026-10-06 (3/8)
Browse filesFile-level snapshot; code revision f298768b6843c8e53a0009b3adc0291eda5fea2c. Weights and Docker images remain local.
This view is limited to 50 files because it contains too many changes. See raw diff
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/hebbian_model.py +339 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/hebbian_statistics.py +168 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/hebbian_train.py +811 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/interface_editing.py +759 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/interface_tracking.py +199 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/latent_scaling.py +311 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/latent_support.py +363 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/low_rank.py +138 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/memory_reuse.py +469 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/multihop_scaling.py +518 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/natural_composition_confirmation.py +687 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/natural_composition_confirmation_v2.py +687 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/neural.py +328 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/neural_data.py +147 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/neural_models.py +157 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/parametric_architecture.py +443 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/parametric_architecture_train.py +626 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/qwen_constraints.py +94 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/qwen_path_learning.py +416 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/qwen_path_train.py +627 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/realworld_composition.py +629 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/realworld_composition_data.py +270 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/realworld_confirmation.py +322 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/realworld_confirmation_analysis.py +119 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/recurrence_use.py +416 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/representation_alignment.py +269 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/small_lm_composition.py +543 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/small_lm_followup.py +558 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/storage_composition.py +424 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/storage_frontier.py +262 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/text_loss_source.py +256 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/text_pretrain.py +401 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/text_structure.py +432 -0
- docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/twohop_depth.py +362 -0
- docs/development-artifacts/composition-data-curves-v1/source/tests/test_composition_curves.py +208 -0
- docs/development-artifacts/composition-data-curves-v1/support-config.json +780 -0
- docs/development-artifacts/composition-data-curves-v1/support-execution-lock.json +4 -0
- docs/development-artifacts/composition-data-curves-v1/verification.json +18 -0
- docs/development-artifacts/compositional-capacity-discussion-20261006/note.md +80 -0
- docs/development-artifacts/compositional-capacity-discussion-20261006/physics-of-language-connection.md +48 -0
- docs/development-artifacts/compositional-capacity-discussion-20261006/sanity-results.json +99 -0
- docs/development-artifacts/compositional-capacity-discussion-20261006/sanity_check.py +81 -0
- docs/development-artifacts/memory-interface-next-v1/container/lm-memory-daemon.log +0 -0
- docs/development-artifacts/oo-budget-attribution-20261005/analysis-execution.json +41 -0
- docs/development-artifacts/oo-budget-attribution-20261005/budget-brackets.json +422 -0
- docs/development-artifacts/oo-budget-attribution-20261005/budget-comparison.pdf +0 -0
- docs/development-artifacts/oo-budget-attribution-20261005/budget-comparison.png +3 -0
- docs/development-artifacts/oo-budget-attribution-20261005/endpoints.csv +18 -0
- docs/development-artifacts/oo-budget-attribution-20261005/learning-budgets.csv +0 -0
- docs/development-artifacts/oo-budget-attribution-20261005/recount-audit.json +619 -0
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/hebbian_model.py
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FP32 Qwen adapter. All CE/KL reductions preserve per-sequence weighting."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import copy
|
| 6 |
+
import hashlib
|
| 7 |
+
import os
|
| 8 |
+
import time
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, StoppingCriteria, StoppingCriteriaList
|
| 14 |
+
|
| 15 |
+
from .hebbian_data import TEMPLATE, score_answer
|
| 16 |
+
from .hebbian_learning import ARTIFACTS, DATA, config, now, read_json, write_json
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def tensor_hash(tensor):
|
| 20 |
+
return hashlib.sha256(tensor.detach().cpu().contiguous().numpy().tobytes()).hexdigest()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def state_hashes(model):
|
| 24 |
+
return {name: tensor_hash(p) for name, p in model.state_dict().items()}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def aggregate_hash(hashes):
|
| 28 |
+
return hashlib.sha256(
|
| 29 |
+
"\n".join(f"{k}:{v}" for k, v in sorted(hashes.items())).encode()
|
| 30 |
+
).hexdigest()
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def set_determinism(seed=0):
|
| 34 |
+
os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
|
| 35 |
+
torch.set_num_threads(4)
|
| 36 |
+
torch.manual_seed(seed)
|
| 37 |
+
np.random.seed(seed)
|
| 38 |
+
torch.backends.cuda.matmul.allow_tf32 = False
|
| 39 |
+
torch.backends.cudnn.allow_tf32 = False
|
| 40 |
+
torch.backends.cudnn.benchmark = False
|
| 41 |
+
torch.use_deterministic_algorithms(True)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class QwenExperiment:
|
| 45 |
+
def __init__(self, device="cuda:3"):
|
| 46 |
+
set_determinism()
|
| 47 |
+
self.cfg = config()
|
| 48 |
+
self.device = torch.device(device)
|
| 49 |
+
source = DATA / "source/qwen3-0.6b-base"
|
| 50 |
+
self.tokenizer = AutoTokenizer.from_pretrained(source, local_files_only=True)
|
| 51 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 52 |
+
self.model = (
|
| 53 |
+
AutoModelForCausalLM.from_pretrained(
|
| 54 |
+
source,
|
| 55 |
+
local_files_only=True,
|
| 56 |
+
torch_dtype=torch.float32,
|
| 57 |
+
attn_implementation=self.cfg["model"]["attention"],
|
| 58 |
+
)
|
| 59 |
+
.to(self.device)
|
| 60 |
+
.eval()
|
| 61 |
+
)
|
| 62 |
+
self.model.requires_grad_(False)
|
| 63 |
+
self.layer = self.model.model.layers[self.cfg["model"]["layer"]]
|
| 64 |
+
self.mlp = self.layer.mlp
|
| 65 |
+
assert self.mlp.down_proj.weight.shape == (1024, 3072)
|
| 66 |
+
assert self.mlp.up_proj.weight.numel() + self.mlp.gate_proj.weight.numel() == 6291456
|
| 67 |
+
self.base_local = {n: p.detach().clone() for n, p in self.mlp.named_parameters()}
|
| 68 |
+
self.reference = None
|
| 69 |
+
|
| 70 |
+
def restore_base(self):
|
| 71 |
+
with torch.no_grad():
|
| 72 |
+
for n, p in self.mlp.named_parameters():
|
| 73 |
+
p.copy_(self.base_local[n])
|
| 74 |
+
|
| 75 |
+
def configure_trainable(self, phase):
|
| 76 |
+
self.model.requires_grad_(False)
|
| 77 |
+
names = ["down_proj.weight"] if phase == "adapt" else ["up_proj.weight", "gate_proj.weight"]
|
| 78 |
+
for name, p in self.mlp.named_parameters():
|
| 79 |
+
p.requires_grad_(name in names)
|
| 80 |
+
return [p for p in self.model.parameters() if p.requires_grad]
|
| 81 |
+
|
| 82 |
+
def make_reference(self):
|
| 83 |
+
self.reference = copy.deepcopy(self.model).eval().requires_grad_(False)
|
| 84 |
+
|
| 85 |
+
def rows(self, records, views=(0,)):
|
| 86 |
+
return [(r, v, r["encoded"][v]) for r in records for v in views]
|
| 87 |
+
|
| 88 |
+
def batch(self, encoded, prompt_only=False):
|
| 89 |
+
sequences = [
|
| 90 |
+
x["input_ids"][: x["answer_start"]] if prompt_only else x["input_ids"] for x in encoded
|
| 91 |
+
]
|
| 92 |
+
width = max(map(len, sequences))
|
| 93 |
+
ids = torch.full(
|
| 94 |
+
(len(sequences), width),
|
| 95 |
+
self.tokenizer.pad_token_id,
|
| 96 |
+
dtype=torch.long,
|
| 97 |
+
device=self.device,
|
| 98 |
+
)
|
| 99 |
+
attention = torch.zeros_like(ids)
|
| 100 |
+
answer = torch.zeros_like(ids, dtype=torch.bool)
|
| 101 |
+
for i, (seq, enc) in enumerate(zip(sequences, encoded, strict=True)):
|
| 102 |
+
ids[i, : len(seq)] = torch.tensor(seq, device=self.device)
|
| 103 |
+
attention[i, : len(seq)] = 1
|
| 104 |
+
if not prompt_only:
|
| 105 |
+
answer[i, : len(seq)] = torch.tensor(enc["loss_mask"], device=self.device).bool()
|
| 106 |
+
return ids, attention, answer
|
| 107 |
+
|
| 108 |
+
def hidden(self, ids, attention, model=None):
|
| 109 |
+
return (
|
| 110 |
+
(model or self.model)
|
| 111 |
+
.model(input_ids=ids, attention_mask=attention, use_cache=False)
|
| 112 |
+
.last_hidden_state
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
def ce(self, encoded, model=None):
|
| 116 |
+
ids, attention, mask = self.batch(encoded)
|
| 117 |
+
hidden = self.hidden(ids, attention, model)
|
| 118 |
+
b, t = torch.where(mask[:, 1:])
|
| 119 |
+
logits = (model or self.model).lm_head(hidden[b, t])
|
| 120 |
+
losses = F.cross_entropy(logits, ids[b, t + 1], reduction="none")
|
| 121 |
+
sums = torch.zeros(len(encoded), device=self.device).scatter_add_(0, b, losses)
|
| 122 |
+
counts = torch.bincount(b, minlength=len(encoded))
|
| 123 |
+
return sums / counts
|
| 124 |
+
|
| 125 |
+
def kl(self, encoded):
|
| 126 |
+
if self.reference is None:
|
| 127 |
+
raise RuntimeError("An episode-specific parent reference is required")
|
| 128 |
+
ids, attention, mask = self.batch(encoded)
|
| 129 |
+
b, t = torch.where(mask[:, 1:])
|
| 130 |
+
with torch.no_grad():
|
| 131 |
+
ref_hidden = self.hidden(ids, attention, self.reference)
|
| 132 |
+
ref_log = F.log_softmax(self.reference.lm_head(ref_hidden[b, t]), dim=-1)
|
| 133 |
+
logits = self.model.lm_head(self.hidden(ids, attention)[b, t])
|
| 134 |
+
losses = F.kl_div(
|
| 135 |
+
F.log_softmax(logits, dim=-1), ref_log, reduction="none", log_target=True
|
| 136 |
+
).sum(-1)
|
| 137 |
+
sums = torch.zeros(len(encoded), device=self.device).scatter_add_(0, b, losses)
|
| 138 |
+
return sums / torch.bincount(b, minlength=len(encoded))
|
| 139 |
+
|
| 140 |
+
def features(self, encoded, detach=True):
|
| 141 |
+
captured = {}
|
| 142 |
+
|
| 143 |
+
def capture(module, args):
|
| 144 |
+
captured["phi"] = args[0]
|
| 145 |
+
|
| 146 |
+
def capture_input(module, args):
|
| 147 |
+
captured["x"] = args[0]
|
| 148 |
+
|
| 149 |
+
handle = self.mlp.down_proj.register_forward_pre_hook(capture)
|
| 150 |
+
input_handle = self.mlp.register_forward_pre_hook(capture_input)
|
| 151 |
+
try:
|
| 152 |
+
ids, attention, _ = self.batch(encoded, prompt_only=True)
|
| 153 |
+
if detach:
|
| 154 |
+
with torch.no_grad():
|
| 155 |
+
hidden = self.hidden(ids, attention)
|
| 156 |
+
positions = attention.sum(1) - 1
|
| 157 |
+
self.last_prompt_logits = self.model.lm_head(
|
| 158 |
+
hidden[torch.arange(len(encoded), device=self.device), positions]
|
| 159 |
+
).detach()
|
| 160 |
+
x = captured["x"][torch.arange(len(encoded), device=self.device), positions]
|
| 161 |
+
self.last_layer_inputs = x.detach()
|
| 162 |
+
self.original_features = (
|
| 163 |
+
F.linear(x, self.base_local["up_proj.weight"])
|
| 164 |
+
* F.silu(F.linear(x, self.base_local["gate_proj.weight"]))
|
| 165 |
+
).detach()
|
| 166 |
+
else:
|
| 167 |
+
self.hidden(ids, attention)
|
| 168 |
+
phi = captured["phi"][
|
| 169 |
+
torch.arange(len(encoded), device=self.device), attention.sum(1) - 1
|
| 170 |
+
]
|
| 171 |
+
return phi.detach() if detach else phi
|
| 172 |
+
finally:
|
| 173 |
+
handle.remove()
|
| 174 |
+
input_handle.remove()
|
| 175 |
+
|
| 176 |
+
@torch.no_grad()
|
| 177 |
+
def generate(self, prompts, max_new_tokens=24):
|
| 178 |
+
# Left-padding generation; positions are computed from the attention mask.
|
| 179 |
+
self.tokenizer.padding_side = "left"
|
| 180 |
+
inputs = self.tokenizer(
|
| 181 |
+
prompts, padding=True, return_tensors="pt", add_special_tokens=False
|
| 182 |
+
).to(self.device)
|
| 183 |
+
prompt_width = inputs.input_ids.shape[1]
|
| 184 |
+
tokenizer = self.tokenizer
|
| 185 |
+
|
| 186 |
+
class StopAtNewline(StoppingCriteria):
|
| 187 |
+
def __call__(self, input_ids, scores, **kwargs):
|
| 188 |
+
texts = tokenizer.batch_decode(
|
| 189 |
+
input_ids[:, prompt_width:], skip_special_tokens=True
|
| 190 |
+
)
|
| 191 |
+
return torch.tensor(["\n" in text for text in texts], device=input_ids.device)
|
| 192 |
+
|
| 193 |
+
output = self.model.generate(
|
| 194 |
+
**inputs,
|
| 195 |
+
do_sample=False,
|
| 196 |
+
max_new_tokens=max_new_tokens,
|
| 197 |
+
pad_token_id=self.tokenizer.pad_token_id,
|
| 198 |
+
eos_token_id=self.tokenizer.eos_token_id,
|
| 199 |
+
use_cache=True,
|
| 200 |
+
logits_to_keep=1,
|
| 201 |
+
stopping_criteria=StoppingCriteriaList([StopAtNewline()]),
|
| 202 |
+
)
|
| 203 |
+
tail = output[:, inputs.input_ids.shape[1] :]
|
| 204 |
+
predictions = self.tokenizer.batch_decode(tail, skip_special_tokens=True)
|
| 205 |
+
# Padding after a newline stop is not evidence of the model emitting EOS.
|
| 206 |
+
eos_emitted = []
|
| 207 |
+
for row in tail:
|
| 208 |
+
emitted = False
|
| 209 |
+
for length, token in enumerate(row, 1):
|
| 210 |
+
if int(token) == self.tokenizer.eos_token_id:
|
| 211 |
+
emitted = True
|
| 212 |
+
break
|
| 213 |
+
if "\n" in self.tokenizer.decode(row[:length], skip_special_tokens=True):
|
| 214 |
+
break
|
| 215 |
+
eos_emitted.append(emitted)
|
| 216 |
+
return predictions, eos_emitted
|
| 217 |
+
|
| 218 |
+
@torch.no_grad()
|
| 219 |
+
def evaluate(self, records, views=(0, 1, 2), batch_size=24):
|
| 220 |
+
rows = self.rows(records, views)
|
| 221 |
+
result = []
|
| 222 |
+
for start in range(0, len(rows), batch_size):
|
| 223 |
+
chunk = rows[start : start + batch_size]
|
| 224 |
+
encoded = [x[2] for x in chunk]
|
| 225 |
+
losses = self.ce(encoded).tolist()
|
| 226 |
+
predictions, eos = self.generate([TEMPLATE.format(r["views"][v]) for r, v, _ in chunk])
|
| 227 |
+
phi = self.features(encoded)
|
| 228 |
+
for i, (r, v, enc) in enumerate(chunk):
|
| 229 |
+
prediction = predictions[i]
|
| 230 |
+
first_token = enc["input_ids"][enc["answer_start"]]
|
| 231 |
+
logits = self.last_prompt_logits[i]
|
| 232 |
+
competitor_logits = logits.clone()
|
| 233 |
+
competitor_logits[first_token] = -torch.inf
|
| 234 |
+
competitor = int(competitor_logits.argmax())
|
| 235 |
+
result.append(
|
| 236 |
+
{
|
| 237 |
+
"case_id": r["case_id"],
|
| 238 |
+
"relation_id": r["relation_id"],
|
| 239 |
+
"subject_group": r["subject_group"],
|
| 240 |
+
"view_id": v,
|
| 241 |
+
"answer_nll": losses[i],
|
| 242 |
+
"prediction": prediction,
|
| 243 |
+
"answer_em": score_answer(prediction, r.get("aliases", [r["answer"]])),
|
| 244 |
+
"eos_emitted": eos[i],
|
| 245 |
+
"feature_norm": float(phi[i].norm()),
|
| 246 |
+
"first_answer_nll": float(-logits.log_softmax(-1)[first_token]),
|
| 247 |
+
"first_answer_margin": float(logits[first_token] - logits[competitor]),
|
| 248 |
+
"current_competitor_token": competitor,
|
| 249 |
+
"answer_tokens": enc["answer_tokens"],
|
| 250 |
+
"prompt_tokens": enc["prompt_tokens"],
|
| 251 |
+
}
|
| 252 |
+
)
|
| 253 |
+
return result
|
| 254 |
+
|
| 255 |
+
def gradient(self, encoded):
|
| 256 |
+
loss = self.ce([encoded]).mean()
|
| 257 |
+
grad = torch.autograd.grad(loss, self.mlp.down_proj.weight)[0]
|
| 258 |
+
return grad.detach(), float(loss.detach())
|
| 259 |
+
|
| 260 |
+
def verify_hooks_and_gradients(self, encoded):
|
| 261 |
+
self.configure_trainable("adapt")
|
| 262 |
+
captured = {}
|
| 263 |
+
|
| 264 |
+
def capture_input(module, args):
|
| 265 |
+
captured["x"] = args[0].detach()
|
| 266 |
+
|
| 267 |
+
def capture_down(module, args, output):
|
| 268 |
+
captured["phi"] = args[0].detach()
|
| 269 |
+
output.retain_grad()
|
| 270 |
+
captured["output"] = output
|
| 271 |
+
|
| 272 |
+
handles = [
|
| 273 |
+
self.mlp.register_forward_pre_hook(capture_input),
|
| 274 |
+
self.mlp.down_proj.register_forward_hook(capture_down),
|
| 275 |
+
]
|
| 276 |
+
try:
|
| 277 |
+
self.model.zero_grad(set_to_none=True)
|
| 278 |
+
self.ce([encoded]).mean().backward()
|
| 279 |
+
with torch.no_grad():
|
| 280 |
+
expected_phi = self.mlp.up_proj(captured["x"]) * F.silu(
|
| 281 |
+
self.mlp.gate_proj(captured["x"])
|
| 282 |
+
)
|
| 283 |
+
phi_error = float((expected_phi - captured["phi"]).abs().max())
|
| 284 |
+
delta = captured["output"].grad.double().flatten(0, 1)
|
| 285 |
+
phi = captured["phi"].double().flatten(0, 1)
|
| 286 |
+
reconstructed = delta.T @ phi
|
| 287 |
+
actual = self.mlp.down_proj.weight.grad.double()
|
| 288 |
+
grad_error = float((reconstructed - actual).norm() / actual.norm())
|
| 289 |
+
nonanswer_positions = encoded["answer_start"] - 1
|
| 290 |
+
prompt_grad_norm = float(delta[:nonanswer_positions].norm())
|
| 291 |
+
assert phi_error == 0.0
|
| 292 |
+
assert grad_error < 1e-5
|
| 293 |
+
return {
|
| 294 |
+
"phi_max_absolute_error": phi_error,
|
| 295 |
+
"gradient_relative_error": grad_error,
|
| 296 |
+
"earlier_prompt_delta_norm": prompt_grad_norm,
|
| 297 |
+
"all_positions_used": True,
|
| 298 |
+
"trainable_parameters": sum(
|
| 299 |
+
p.numel() for p in self.model.parameters() if p.requires_grad
|
| 300 |
+
),
|
| 301 |
+
"pass": True,
|
| 302 |
+
}
|
| 303 |
+
finally:
|
| 304 |
+
for handle in handles:
|
| 305 |
+
handle.remove()
|
| 306 |
+
self.model.zero_grad(set_to_none=True)
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def run_baseline(device, shard=0, shards=1):
|
| 310 |
+
engine = QwenExperiment(device)
|
| 311 |
+
candidates = read_json(DATA / "candidates.json")[shard::shards]
|
| 312 |
+
out = DATA / f"baseline-shard-{shard}.jsonl"
|
| 313 |
+
finished = {}
|
| 314 |
+
if out.exists():
|
| 315 |
+
for line in out.read_text().splitlines():
|
| 316 |
+
row = __import__("json").loads(line)
|
| 317 |
+
finished[row["case_id"]] = row
|
| 318 |
+
candidates = [r for r in candidates if r["case_id"] not in finished]
|
| 319 |
+
start_time = time.monotonic()
|
| 320 |
+
for start in range(0, len(candidates), 8):
|
| 321 |
+
chunk = candidates[start : start + 8]
|
| 322 |
+
rows = engine.evaluate(chunk)
|
| 323 |
+
with out.open("a") as f:
|
| 324 |
+
for record in chunk:
|
| 325 |
+
item = {
|
| 326 |
+
"case_id": record["case_id"],
|
| 327 |
+
"views": [r for r in rows if r["case_id"] == record["case_id"]],
|
| 328 |
+
}
|
| 329 |
+
f.write(__import__("json").dumps(item, ensure_ascii=False) + "\n")
|
| 330 |
+
if start % 80 == 0:
|
| 331 |
+
print(
|
| 332 |
+
f"baseline shard={shard} {start + len(chunk)}/{len(candidates)} "
|
| 333 |
+
f"elapsed={time.monotonic() - start_time:.1f}s",
|
| 334 |
+
flush=True,
|
| 335 |
+
)
|
| 336 |
+
write_json(
|
| 337 |
+
ARTIFACTS / f"baseline-shard-{shard}-complete.json",
|
| 338 |
+
{"time": now(), "rows": len(candidates) + len(finished), "shards": shards},
|
| 339 |
+
)
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/hebbian_statistics.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Development-only predictor fitting and episode-cluster paired inference."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import itertools
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
from .hebbian_learning import (
|
| 10 |
+
ARTIFACTS,
|
| 11 |
+
DATA,
|
| 12 |
+
RESULTS,
|
| 13 |
+
config,
|
| 14 |
+
now,
|
| 15 |
+
q_auc,
|
| 16 |
+
read_json,
|
| 17 |
+
sha256,
|
| 18 |
+
write_json,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def fit_ridge(x, y, alpha):
|
| 23 |
+
mean, scale = x.mean(0), x.std(0)
|
| 24 |
+
scale = np.where(scale > 1e-12, scale, 1)
|
| 25 |
+
z = (x - mean) / scale
|
| 26 |
+
intercept = float(y.mean())
|
| 27 |
+
coef = np.linalg.solve(z.T @ z + alpha * np.eye(z.shape[1]), z.T @ (y - intercept))
|
| 28 |
+
return {
|
| 29 |
+
"mean": mean.tolist(),
|
| 30 |
+
"scale": scale.tolist(),
|
| 31 |
+
"coefficients": coef.tolist(),
|
| 32 |
+
"intercept": intercept,
|
| 33 |
+
"alpha": alpha,
|
| 34 |
+
"n_features": x.shape[1],
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def predict(model, x):
|
| 39 |
+
x = x[:, : model["n_features"]]
|
| 40 |
+
return ((x - model["mean"]) / model["scale"]) @ np.array(model["coefficients"]) + model[
|
| 41 |
+
"intercept"
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def fact_trajectories(path):
|
| 46 |
+
evaluations = [read_json(p) for p in sorted(path.glob("evaluation-*.json"))]
|
| 47 |
+
nodes = [e["rows"][0]["step"] for e in evaluations]
|
| 48 |
+
by_node = [{(r["case_id"], r["view_id"]): r for r in e["rows"]} for e in evaluations]
|
| 49 |
+
cases = sorted({r["case_id"] for r in evaluations[0]["rows"]})
|
| 50 |
+
result = []
|
| 51 |
+
for case in cases:
|
| 52 |
+
rewrite = [np.mean([rows[case, v]["answer_em"] for v in [1, 2]]) for rows in by_node]
|
| 53 |
+
standard = [rows[case, 0]["answer_em"] for rows in by_node]
|
| 54 |
+
all_correct = [all(rows[case, v]["answer_em"] for v in range(3)) for rows in by_node]
|
| 55 |
+
sustained = next(
|
| 56 |
+
(i for i in range(len(nodes) - 1) if all_correct[i] and all_correct[i + 1]), None
|
| 57 |
+
)
|
| 58 |
+
first = by_node[0][case, 0]
|
| 59 |
+
result.append(
|
| 60 |
+
{
|
| 61 |
+
"case_id": case,
|
| 62 |
+
"q_auc": float(q_auc(rewrite, nodes)),
|
| 63 |
+
"q_gain_auc": float(q_auc(np.array(rewrite) - rewrite[0], nodes)),
|
| 64 |
+
"standard_auc": float(q_auc(standard, nodes)),
|
| 65 |
+
"nodes": nodes,
|
| 66 |
+
"rewrite_accuracy": rewrite,
|
| 67 |
+
"standard_accuracy": standard,
|
| 68 |
+
"sustained_step": nodes[sustained] if sustained is not None else None,
|
| 69 |
+
"sustained_exposures": by_node[sustained][case, 0]["exposures"]
|
| 70 |
+
if sustained is not None
|
| 71 |
+
else None,
|
| 72 |
+
"endpoint_first_success": sustained is None and all_correct[-1],
|
| 73 |
+
"right_censored": sustained is None,
|
| 74 |
+
"relation_id": first["relation_id"],
|
| 75 |
+
}
|
| 76 |
+
)
|
| 77 |
+
return result
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def freeze_b():
|
| 81 |
+
from .hebbian_train import frozen_training_sources, run_summary, select_config
|
| 82 |
+
|
| 83 |
+
episodes = read_json(DATA / "episodes.json")["B_dev"]
|
| 84 |
+
candidates = []
|
| 85 |
+
for lr in config()["adapt"]["learning_rates"]:
|
| 86 |
+
summaries = [run_summary(RESULTS / f"B/dev-lr{lr:g}-e{i}") for i in range(len(episodes))]
|
| 87 |
+
candidates.append(
|
| 88 |
+
{
|
| 89 |
+
"learning_rate": lr,
|
| 90 |
+
"q_auc": float(np.mean([s["q_auc"] for s in summaries])),
|
| 91 |
+
"keep_damage": float(np.mean([s["keep_damage"] for s in summaries])),
|
| 92 |
+
"episodes": summaries,
|
| 93 |
+
}
|
| 94 |
+
)
|
| 95 |
+
chosen = select_config(candidates, "q_auc", True)
|
| 96 |
+
lr = chosen["learning_rate"]
|
| 97 |
+
x, y, groups = [], [], []
|
| 98 |
+
for episode in range(len(episodes)):
|
| 99 |
+
path = RESULTS / f"B/dev-lr{lr:g}-e{episode}"
|
| 100 |
+
if not (path / "complete.json").exists():
|
| 101 |
+
raise RuntimeError("All B_dev runs must have completion receipts")
|
| 102 |
+
outcomes = {r["case_id"]: r["q_auc"] for r in fact_trajectories(path)}
|
| 103 |
+
for row in read_json(path / "prospective-features.json")["rows"]:
|
| 104 |
+
x.append(row["features"])
|
| 105 |
+
y.append(outcomes[row["case_id"]])
|
| 106 |
+
groups.append(episode)
|
| 107 |
+
x, y, groups = np.array(x), np.array(y), np.array(groups)
|
| 108 |
+
predictors = {}
|
| 109 |
+
for name, width in [("P0", 4), ("P1", 8), ("P2", 10)]:
|
| 110 |
+
scores = {}
|
| 111 |
+
for alpha in config()["statistics"]["ridge_grid"]:
|
| 112 |
+
errors = []
|
| 113 |
+
for group in np.unique(groups):
|
| 114 |
+
train = groups != group
|
| 115 |
+
model = fit_ridge(x[train, :width], y[train], alpha)
|
| 116 |
+
errors.append(np.mean(np.abs(predict(model, x[~train]) - y[~train])))
|
| 117 |
+
scores[alpha] = float(np.mean(errors))
|
| 118 |
+
best_alpha = min(scores, key=scores.get)
|
| 119 |
+
predictors[name] = {**fit_ridge(x[:, :width], y, best_alpha), "cv_mae": scores}
|
| 120 |
+
write_json(
|
| 121 |
+
ARTIFACTS / "B-lock.json",
|
| 122 |
+
{
|
| 123 |
+
"time": now(),
|
| 124 |
+
"status": "locked",
|
| 125 |
+
"learning_rate": lr,
|
| 126 |
+
"lr_candidates": candidates,
|
| 127 |
+
"predictors": predictors,
|
| 128 |
+
"source_hashes": frozen_training_sources(),
|
| 129 |
+
"data_lock_sha256": sha256(ARTIFACTS / "data-lock.json"),
|
| 130 |
+
"fitting_scope": "B_dev only; fold-specific training standardization in episode CV",
|
| 131 |
+
},
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def paired_inference(differences):
|
| 136 |
+
differences = np.asarray(differences, dtype=np.float64)
|
| 137 |
+
rng = np.random.default_rng(config()["statistics"]["seed"])
|
| 138 |
+
n = len(differences)
|
| 139 |
+
samples = differences[rng.integers(0, n, (10000, n))].mean(1)
|
| 140 |
+
observed = float(differences.mean())
|
| 141 |
+
signs = np.array(list(itertools.product([-1, 1], repeat=n)))
|
| 142 |
+
p = float(np.mean(np.abs((signs * differences).mean(1)) >= abs(observed) - 1e-14))
|
| 143 |
+
return {
|
| 144 |
+
"mean": observed,
|
| 145 |
+
"ci95": np.quantile(samples, [0.025, 0.975]).tolist(),
|
| 146 |
+
"exact_two_sided_sign_p": p,
|
| 147 |
+
"episode_differences": differences.tolist(),
|
| 148 |
+
"n_episodes": n,
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def rankdata(values):
|
| 153 |
+
values = np.asarray(values)
|
| 154 |
+
order = np.argsort(values, kind="stable")
|
| 155 |
+
ranked = np.empty(len(values), dtype=float)
|
| 156 |
+
i = 0
|
| 157 |
+
while i < len(values):
|
| 158 |
+
j = i + 1
|
| 159 |
+
while j < len(values) and values[order[j]] == values[order[i]]:
|
| 160 |
+
j += 1
|
| 161 |
+
ranked[order[i:j]] = (i + j - 1) / 2
|
| 162 |
+
i = j
|
| 163 |
+
return ranked
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def spearman(x, y):
|
| 167 |
+
a, b = rankdata(x), rankdata(y)
|
| 168 |
+
return float(np.corrcoef(a, b)[0, 1]) if a.std() and b.std() else None
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/hebbian_train.py
ADDED
|
@@ -0,0 +1,811 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Paired formation/adaptation, prospective diagnostics and exact state resumption."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import itertools
|
| 6 |
+
import json
|
| 7 |
+
import random
|
| 8 |
+
import time
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
|
| 14 |
+
from .hebbian_learning import (
|
| 15 |
+
ARTIFACTS,
|
| 16 |
+
CONFIG_PATH,
|
| 17 |
+
DATA,
|
| 18 |
+
RESULTS,
|
| 19 |
+
ROOT,
|
| 20 |
+
config,
|
| 21 |
+
effective_rank,
|
| 22 |
+
now,
|
| 23 |
+
q_auc,
|
| 24 |
+
read_json,
|
| 25 |
+
sha256,
|
| 26 |
+
write_json,
|
| 27 |
+
)
|
| 28 |
+
from .hebbian_model import (
|
| 29 |
+
QwenExperiment,
|
| 30 |
+
aggregate_hash,
|
| 31 |
+
set_determinism,
|
| 32 |
+
state_hashes,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def grouping(records, seed):
|
| 37 |
+
"""Exact minimum-cost derangements; random seeded ties, real CE labels unchanged."""
|
| 38 |
+
n = len(records)
|
| 39 |
+
rng = np.random.default_rng(seed)
|
| 40 |
+
permutations = [
|
| 41 |
+
p for p in itertools.permutations(range(n)) if all(i != j for i, j in enumerate(p))
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
def cost(p):
|
| 45 |
+
return sum(
|
| 46 |
+
10 * (records[i]["target_id"] == records[j]["target_id"])
|
| 47 |
+
+ (records[i]["relation_id"] != records[j]["relation_id"])
|
| 48 |
+
for i, j in enumerate(p)
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
costs = np.array([cost(p) for p in permutations])
|
| 52 |
+
best = np.flatnonzero(costs == costs.min())
|
| 53 |
+
p1, p2 = [permutations[int(rng.choice(best))] for _ in range(2)]
|
| 54 |
+
groups = [(3 * i, 3 * p1[i] + 1, 3 * p2[i] + 2) for i in range(n)]
|
| 55 |
+
return groups
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def contrastive_loss(features, target_ids, groups, tau=0.1):
|
| 59 |
+
z = F.normalize(features, dim=-1, eps=1e-8)
|
| 60 |
+
similarities = z @ z.T / tau
|
| 61 |
+
positive = torch.zeros_like(similarities, dtype=torch.bool)
|
| 62 |
+
for group in groups:
|
| 63 |
+
for i in group:
|
| 64 |
+
for j in group:
|
| 65 |
+
if i != j:
|
| 66 |
+
positive[i, j] = True
|
| 67 |
+
negative = torch.tensor([[a != b for b in target_ids] for a in target_ids], device=z.device)
|
| 68 |
+
negative &= ~positive
|
| 69 |
+
negative.fill_diagonal_(False)
|
| 70 |
+
assert torch.all(positive.sum(1) == 2)
|
| 71 |
+
assert torch.all(negative.sum(1) >= 1)
|
| 72 |
+
allowed = positive | negative
|
| 73 |
+
log_denominator = similarities.masked_fill(~allowed, -torch.inf).logsumexp(1)
|
| 74 |
+
loss = (log_denominator - (similarities * positive).sum(1) / positive.sum(1)).mean()
|
| 75 |
+
return loss, {"positive_pairs": int(positive.sum()), "negative_pairs": int(negative.sum())}
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def optimizer(parameters, lr):
|
| 79 |
+
cfg = config()["optimizer"]
|
| 80 |
+
return torch.optim.AdamW(
|
| 81 |
+
parameters,
|
| 82 |
+
lr=lr,
|
| 83 |
+
betas=tuple(cfg["betas"]),
|
| 84 |
+
eps=cfg["eps"],
|
| 85 |
+
weight_decay=cfg["weight_decay"],
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def replay_batch(pools, texts, step):
|
| 90 |
+
facts = pools["R_keep"]
|
| 91 |
+
return [facts[(step * 6 + i) % len(facts)]["encoded"][0] for i in range(6)] + [
|
| 92 |
+
texts["train"][(step * 2 + i) % len(texts["train"])] for i in range(2)
|
| 93 |
+
]
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def frozen_training_sources():
|
| 97 |
+
paths = [CONFIG_PATH] + sorted((ROOT / "src/llm_memory_editability").glob("hebbian*.py"))
|
| 98 |
+
paths += [ROOT / "scripts/run_hebbian_learning.py"]
|
| 99 |
+
return {str(p.relative_to(ROOT)): sha256(p) for p in paths}
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def save_checkpoint(path, engine, opt, step, meta, ledger):
|
| 103 |
+
state = {
|
| 104 |
+
"parameters": {n: p.detach().cpu().clone() for n, p in engine.mlp.named_parameters()},
|
| 105 |
+
"optimizer": opt.state_dict(),
|
| 106 |
+
"step": step,
|
| 107 |
+
"data_cursor": step,
|
| 108 |
+
"torch_rng": torch.get_rng_state(),
|
| 109 |
+
"cuda_rng": torch.cuda.get_rng_state(engine.device)
|
| 110 |
+
if engine.device.type == "cuda"
|
| 111 |
+
else None,
|
| 112 |
+
"numpy_rng": np.random.get_state(),
|
| 113 |
+
"python_rng": random.getstate(),
|
| 114 |
+
"meta": meta,
|
| 115 |
+
"ledger": ledger,
|
| 116 |
+
}
|
| 117 |
+
tmp = path.with_name(path.name + ".tmp")
|
| 118 |
+
torch.save(state, tmp)
|
| 119 |
+
tmp.replace(path)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def restore_checkpoint(path, engine, opt, meta):
|
| 123 |
+
state = torch.load(path, map_location="cpu", weights_only=False)
|
| 124 |
+
if state["meta"] != meta:
|
| 125 |
+
raise RuntimeError(f"Checkpoint contract differs: {path}")
|
| 126 |
+
with torch.no_grad():
|
| 127 |
+
for n, p in engine.mlp.named_parameters():
|
| 128 |
+
p.copy_(state["parameters"][n])
|
| 129 |
+
opt.load_state_dict(state["optimizer"])
|
| 130 |
+
torch.set_rng_state(state["torch_rng"])
|
| 131 |
+
if state["cuda_rng"] is not None:
|
| 132 |
+
torch.cuda.set_rng_state(state["cuda_rng"], engine.device)
|
| 133 |
+
np.random.set_state(state["numpy_rng"])
|
| 134 |
+
random.setstate(state["python_rng"])
|
| 135 |
+
return state["step"], state["ledger"]
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def load_parent(engine, parent_path=None):
|
| 139 |
+
engine.restore_base()
|
| 140 |
+
if parent_path is not None:
|
| 141 |
+
state = torch.load(parent_path, map_location="cpu", weights_only=False)
|
| 142 |
+
with torch.no_grad():
|
| 143 |
+
for n, p in engine.mlp.named_parameters():
|
| 144 |
+
p.copy_(state["parameters"][n])
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def gradient_cos(a, b):
|
| 148 |
+
a, b = a.double(), b.double()
|
| 149 |
+
return float((a * b).sum() / (a.norm() * b.norm()).clamp_min(1e-30))
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def diagnose_episode(engine, records, replay, lr, out):
|
| 153 |
+
"""Saved before the learning trajectory; Adam candidate uses training data only."""
|
| 154 |
+
engine.configure_trainable("adapt")
|
| 155 |
+
p = engine.mlp.down_proj.weight
|
| 156 |
+
original = p.detach().clone()
|
| 157 |
+
encoded = [r["encoded"][v] for r in records for v in range(3)]
|
| 158 |
+
features = engine.features(encoded).double().cpu().numpy().reshape(len(records), 3, -1)
|
| 159 |
+
unit = features / np.maximum(np.linalg.norm(features, axis=-1, keepdims=True), 1e-8)
|
| 160 |
+
p0_gram = unit[:, 0] @ unit[:, 0].T
|
| 161 |
+
rank = effective_rank(features[:, 0])
|
| 162 |
+
opt = optimizer([p], lr)
|
| 163 |
+
opt.zero_grad(set_to_none=True)
|
| 164 |
+
(engine.ce([r["encoded"][0] for r in records[:8]]).mean() + engine.kl(replay).mean()).backward()
|
| 165 |
+
torch.nn.utils.clip_grad_norm_([p], 1.0)
|
| 166 |
+
opt.step()
|
| 167 |
+
delta = (p.detach() - original).clone()
|
| 168 |
+
with torch.no_grad():
|
| 169 |
+
p.copy_(original)
|
| 170 |
+
torch.save(
|
| 171 |
+
{"delta_B": delta.cpu(), "phi": torch.from_numpy(features)}, out / "initial-diagnostics.pt"
|
| 172 |
+
)
|
| 173 |
+
diagnostic = []
|
| 174 |
+
for i, record in enumerate(records):
|
| 175 |
+
grads, losses = zip(*(engine.gradient(enc) for enc in record["encoded"]), strict=True)
|
| 176 |
+
other = [
|
| 177 |
+
p0_gram[i, j] for j, r in enumerate(records) if r["target_id"] != record["target_id"]
|
| 178 |
+
]
|
| 179 |
+
if not other:
|
| 180 |
+
raise ValueError("Each episode needs different-answer facts")
|
| 181 |
+
norms = np.linalg.norm(features[i], axis=1)
|
| 182 |
+
feature_values = [
|
| 183 |
+
losses[0],
|
| 184 |
+
record["encoded"][0]["answer_tokens"],
|
| 185 |
+
record["encoded"][0]["prompt_tokens"],
|
| 186 |
+
float(grads[0].double().norm()),
|
| 187 |
+
float(np.mean(unit[i, 1:] @ unit[i, 0])),
|
| 188 |
+
float(max(other)),
|
| 189 |
+
float(norms[1:].mean() / norms[0]),
|
| 190 |
+
rank,
|
| 191 |
+
float(np.mean([gradient_cos(grads[0], g) for g in grads[1:]])),
|
| 192 |
+
float(np.mean([float((g.double() * delta.double()).sum()) for g in grads[1:]])),
|
| 193 |
+
]
|
| 194 |
+
diagnostic.append(
|
| 195 |
+
{
|
| 196 |
+
"case_id": record["case_id"],
|
| 197 |
+
"features": feature_values,
|
| 198 |
+
"p0_p1_cos": float(unit[i, 0] @ unit[i, 1]),
|
| 199 |
+
"p0_p2_cos": float(unit[i, 0] @ unit[i, 2]),
|
| 200 |
+
"feature_norms": norms.tolist(),
|
| 201 |
+
"initial_nll": list(losses),
|
| 202 |
+
}
|
| 203 |
+
)
|
| 204 |
+
engine.model.zero_grad(set_to_none=True)
|
| 205 |
+
assert torch.equal(p, original)
|
| 206 |
+
write_json(
|
| 207 |
+
out / "prospective-features.json",
|
| 208 |
+
{
|
| 209 |
+
"saved_at": now(),
|
| 210 |
+
"rows": diagnostic,
|
| 211 |
+
"information": {
|
| 212 |
+
"P0": "initial answer NLL, lengths, labeled training gradient norm",
|
| 213 |
+
"P1": "P0 plus prompt-only phi geometry",
|
| 214 |
+
"P2": "P1 plus labeled evaluation gradients and training-only Adam candidate",
|
| 215 |
+
},
|
| 216 |
+
},
|
| 217 |
+
)
|
| 218 |
+
return diagnostic
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def first_order_calibration(engine, record, out):
|
| 222 |
+
parameter = engine.mlp.down_proj.weight
|
| 223 |
+
initial = parameter.detach().clone()
|
| 224 |
+
source_grad, _ = engine.gradient(record["encoded"][0])
|
| 225 |
+
rows = []
|
| 226 |
+
for view in [1, 2]:
|
| 227 |
+
encoded = record["encoded"][view]
|
| 228 |
+
grad, nll0 = engine.gradient(encoded)
|
| 229 |
+
ids, attention, _ = engine.batch([encoded], prompt_only=True)
|
| 230 |
+
answer_token = encoded["input_ids"][encoded["answer_start"]]
|
| 231 |
+
logits = engine.model.lm_head(engine.hidden(ids, attention)[0, -1])
|
| 232 |
+
competitor_logits = logits.detach().clone()
|
| 233 |
+
competitor_logits[answer_token] = -torch.inf
|
| 234 |
+
competitor = int(competitor_logits.argmax())
|
| 235 |
+
margin = logits[answer_token] - logits[competitor]
|
| 236 |
+
margin_grad = torch.autograd.grad(margin, parameter)[0].detach()
|
| 237 |
+
margin0 = float(margin.detach())
|
| 238 |
+
for relative_step in [1e-5, 1e-4]:
|
| 239 |
+
proposal = (
|
| 240 |
+
-source_grad
|
| 241 |
+
* (relative_step * initial.double().norm() / source_grad.double().norm()).float()
|
| 242 |
+
)
|
| 243 |
+
with torch.no_grad():
|
| 244 |
+
parameter.copy_(initial + proposal)
|
| 245 |
+
actual_delta = parameter - initial
|
| 246 |
+
actual_nll = float(engine.ce([encoded])[0]) - nll0
|
| 247 |
+
new_logits = engine.model.lm_head(engine.hidden(ids, attention)[0, -1])
|
| 248 |
+
actual_margin = float(new_logits[answer_token] - new_logits[competitor]) - margin0
|
| 249 |
+
predicted_nll = float((grad.double() * actual_delta.double()).sum())
|
| 250 |
+
predicted_margin = float((margin_grad.double() * actual_delta.double()).sum())
|
| 251 |
+
parameter.copy_(initial)
|
| 252 |
+
entry = {
|
| 253 |
+
"case_id": record["case_id"],
|
| 254 |
+
"view_id": view,
|
| 255 |
+
"relative_step": relative_step,
|
| 256 |
+
"competitor_token": competitor,
|
| 257 |
+
"actual_nll_change": actual_nll,
|
| 258 |
+
"predicted_nll_change": predicted_nll,
|
| 259 |
+
"actual_margin_change": actual_margin,
|
| 260 |
+
"predicted_margin_change": predicted_margin,
|
| 261 |
+
}
|
| 262 |
+
for name, actual, predicted in [
|
| 263 |
+
("nll", actual_nll, predicted_nll),
|
| 264 |
+
("margin", actual_margin, predicted_margin),
|
| 265 |
+
]:
|
| 266 |
+
entry[name + "_absolute_error"] = abs(actual - predicted)
|
| 267 |
+
entry[name + "_relative_error"] = abs(actual - predicted) / max(
|
| 268 |
+
abs(predicted), 1e-6
|
| 269 |
+
)
|
| 270 |
+
entry[name + "_sign_match"] = bool(np.sign(actual) == np.sign(predicted))
|
| 271 |
+
rows.append(entry)
|
| 272 |
+
assert torch.equal(parameter, initial)
|
| 273 |
+
write_json(out / "first-order-calibration.json", rows)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def geometry_rows(engine, records):
|
| 277 |
+
encoded = [r["encoded"][v] for r in records for v in range(3)]
|
| 278 |
+
features, originals = [], []
|
| 279 |
+
for start in range(0, len(encoded), 24):
|
| 280 |
+
features.append(engine.features(encoded[start : start + 24]).double().cpu())
|
| 281 |
+
originals.append(engine.original_features.double().cpu())
|
| 282 |
+
phi = torch.cat(features).reshape(len(records), 3, -1)
|
| 283 |
+
unit = F.normalize(phi, dim=-1)
|
| 284 |
+
original = torch.cat(originals).reshape(len(records), 3, -1)
|
| 285 |
+
original_cos = (unit * F.normalize(original, dim=-1)).sum(-1)
|
| 286 |
+
gram = unit[:, 0] @ unit[:, 0].T
|
| 287 |
+
rank = float(gram.trace().square() / gram.square().sum())
|
| 288 |
+
result = {}
|
| 289 |
+
for i, r in enumerate(records):
|
| 290 |
+
others = [
|
| 291 |
+
float(gram[i, j])
|
| 292 |
+
for j, other in enumerate(records)
|
| 293 |
+
if other["target_id"] != r["target_id"]
|
| 294 |
+
]
|
| 295 |
+
result[r["case_id"]] = {
|
| 296 |
+
"same_fact_cos": float((unit[i, 1:] @ unit[i, 0]).mean()),
|
| 297 |
+
"other_fact_cos": max(others) if others else None,
|
| 298 |
+
"effective_rank": rank,
|
| 299 |
+
"cosine_to_original_phi": float(original_cos[i].mean()),
|
| 300 |
+
"dimension_variance": float(phi[:, 0].var(0, unbiased=False).mean()),
|
| 301 |
+
}
|
| 302 |
+
return result
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def evaluate_node(engine, records, keep, texts, step, metadata, out, exposures, full_keep):
|
| 306 |
+
rows = engine.evaluate(records)
|
| 307 |
+
geometry = geometry_rows(engine, records)
|
| 308 |
+
for row in rows:
|
| 309 |
+
row.update(
|
| 310 |
+
metadata,
|
| 311 |
+
step=step,
|
| 312 |
+
exposures=exposures.get(row["case_id"], 0),
|
| 313 |
+
**geometry[row["case_id"]],
|
| 314 |
+
)
|
| 315 |
+
payload = {"rows": rows}
|
| 316 |
+
if full_keep:
|
| 317 |
+
payload["keep"] = engine.evaluate(keep, views=(0,))
|
| 318 |
+
with torch.no_grad():
|
| 319 |
+
text_losses = []
|
| 320 |
+
for i in range(0, len(texts["test"]), 8):
|
| 321 |
+
text_losses.extend(engine.ce(texts["test"][i : i + 8]).tolist())
|
| 322 |
+
payload["text_nll"] = float(np.mean(text_losses))
|
| 323 |
+
payload["text_ppl"] = float(np.exp(payload["text_nll"]))
|
| 324 |
+
write_json(out / f"evaluation-{step:04d}.json", payload)
|
| 325 |
+
return payload
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def train_run(
|
| 329 |
+
engine,
|
| 330 |
+
phase,
|
| 331 |
+
records,
|
| 332 |
+
pools,
|
| 333 |
+
texts,
|
| 334 |
+
condition,
|
| 335 |
+
seed,
|
| 336 |
+
episode_id,
|
| 337 |
+
split,
|
| 338 |
+
lr,
|
| 339 |
+
steps,
|
| 340 |
+
run_id,
|
| 341 |
+
lambda_geo=0.0,
|
| 342 |
+
parent_path=None,
|
| 343 |
+
diagnostics=False,
|
| 344 |
+
):
|
| 345 |
+
cfg = config()
|
| 346 |
+
out = RESULTS / run_id
|
| 347 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 348 |
+
load_parent(engine, parent_path)
|
| 349 |
+
parent_hashes = state_hashes(engine.model)
|
| 350 |
+
parent_hash = aggregate_hash(parent_hashes)
|
| 351 |
+
parameters = engine.configure_trainable(phase)
|
| 352 |
+
trainable = [n for n, p in engine.model.named_parameters() if p.requires_grad]
|
| 353 |
+
meta = {
|
| 354 |
+
"phase": phase,
|
| 355 |
+
"split": split,
|
| 356 |
+
"condition": condition,
|
| 357 |
+
"seed": seed,
|
| 358 |
+
"episode_id": episode_id,
|
| 359 |
+
"parent_hash": parent_hash,
|
| 360 |
+
"parent_path": str(parent_path) if parent_path else None,
|
| 361 |
+
"source_hashes": frozen_training_sources(),
|
| 362 |
+
"config_sha256": sha256(CONFIG_PATH),
|
| 363 |
+
"data_lock_sha256": sha256(ARTIFACTS / "data-lock.json"),
|
| 364 |
+
"trainable_names": trainable,
|
| 365 |
+
"lr": lr,
|
| 366 |
+
"lambda_geo": lambda_geo,
|
| 367 |
+
"steps": steps,
|
| 368 |
+
"case_ids": [r["case_id"] for r in records],
|
| 369 |
+
}
|
| 370 |
+
if (out / "complete.json").exists():
|
| 371 |
+
receipt = read_json(out / "complete.json")
|
| 372 |
+
if receipt["meta"] != meta:
|
| 373 |
+
raise RuntimeError(f"Completed run contract changed: {run_id}")
|
| 374 |
+
return receipt
|
| 375 |
+
engine.make_reference()
|
| 376 |
+
set_determinism(seed)
|
| 377 |
+
random.seed(seed)
|
| 378 |
+
opt = optimizer(parameters, lr)
|
| 379 |
+
write_json(out / "contract.json", meta)
|
| 380 |
+
ledger = {
|
| 381 |
+
"answer_tokens": 0,
|
| 382 |
+
"answer_input_tokens": 0,
|
| 383 |
+
"replay_tokens": 0,
|
| 384 |
+
"replay_input_tokens": 0,
|
| 385 |
+
"geometry_input_tokens": 0,
|
| 386 |
+
"forward_sequences": 0,
|
| 387 |
+
"backward_sequences": 0,
|
| 388 |
+
"optimizer_steps": 0,
|
| 389 |
+
"wall_seconds": 0.0,
|
| 390 |
+
}
|
| 391 |
+
nodes = [n for n in cfg["form" if phase == "form" else "adapt"]["nodes"] if n <= steps]
|
| 392 |
+
if steps not in nodes:
|
| 393 |
+
nodes.append(steps)
|
| 394 |
+
keep = pools["V_keep" if split == "dev" else "U_keep"]
|
| 395 |
+
evaluate_records = pools["V_form"] if phase == "form" and split == "dev" else records
|
| 396 |
+
rng = np.random.default_rng(seed)
|
| 397 |
+
order = rng.permutation(len(records)).tolist() if phase == "form" else list(range(len(records)))
|
| 398 |
+
exposures = {r["case_id"]: 0 for r in records}
|
| 399 |
+
batch_table = []
|
| 400 |
+
for step in range(steps):
|
| 401 |
+
batch = [records[order[(step * 8 + i) % len(order)]] for i in range(8)]
|
| 402 |
+
groups = (
|
| 403 |
+
grouping(batch, seed * 100000 + step)
|
| 404 |
+
if condition == "C2"
|
| 405 |
+
else [tuple(range(3 * i, 3 * i + 3)) for i in range(8)]
|
| 406 |
+
)
|
| 407 |
+
batch_table.append({"case_ids": [r["case_id"] for r in batch], "groups": groups})
|
| 408 |
+
write_json(out / "batch-manifest.json", batch_table)
|
| 409 |
+
checkpoints = sorted(out.glob("checkpoint-*.pt"))
|
| 410 |
+
start = 0
|
| 411 |
+
if checkpoints:
|
| 412 |
+
start, ledger = restore_checkpoint(checkpoints[-1], engine, opt, meta)
|
| 413 |
+
for item in batch_table[:start]:
|
| 414 |
+
for case_id in item["case_ids"]:
|
| 415 |
+
exposures[case_id] += 1
|
| 416 |
+
elif diagnostics:
|
| 417 |
+
diagnostic = diagnose_episode(engine, records, replay_batch(pools, texts, 0), lr, out)
|
| 418 |
+
if split == "eval":
|
| 419 |
+
from .hebbian_statistics import predict
|
| 420 |
+
|
| 421 |
+
predictors = read_json(ARTIFACTS / "B-lock.json")["predictors"]
|
| 422 |
+
write_json(
|
| 423 |
+
out / "prospective-predictions.json",
|
| 424 |
+
{
|
| 425 |
+
"saved_at": now(),
|
| 426 |
+
"parent_hash": parent_hash,
|
| 427 |
+
"predictions": [
|
| 428 |
+
{
|
| 429 |
+
"case_id": r["case_id"],
|
| 430 |
+
"values": {
|
| 431 |
+
name: float(predict(model, np.array(r["features"])[None])[0])
|
| 432 |
+
for name, model in predictors.items()
|
| 433 |
+
},
|
| 434 |
+
}
|
| 435 |
+
for r in diagnostic
|
| 436 |
+
],
|
| 437 |
+
},
|
| 438 |
+
)
|
| 439 |
+
first_order_calibration(engine, min(records, key=lambda r: r["case_id"]), out)
|
| 440 |
+
metadata = {
|
| 441 |
+
k: meta[k] for k in ["phase", "split", "condition", "seed", "episode_id", "parent_hash"]
|
| 442 |
+
}
|
| 443 |
+
if start == 0:
|
| 444 |
+
save_checkpoint(out / "checkpoint-0000.pt", engine, opt, 0, meta, ledger)
|
| 445 |
+
for step in range(start, steps + 1):
|
| 446 |
+
if step in nodes:
|
| 447 |
+
evaluate_node(
|
| 448 |
+
engine,
|
| 449 |
+
evaluate_records,
|
| 450 |
+
keep,
|
| 451 |
+
texts,
|
| 452 |
+
step,
|
| 453 |
+
metadata,
|
| 454 |
+
out,
|
| 455 |
+
exposures,
|
| 456 |
+
full_keep=(phase == "form" or step in [0, 16, 64, 128]),
|
| 457 |
+
)
|
| 458 |
+
if phase == "adapt" and condition.startswith("C") and step in [0, 16, 128]:
|
| 459 |
+
gradients = []
|
| 460 |
+
for r in sorted(records, key=lambda r: r["case_id"])[:4]:
|
| 461 |
+
grads = [engine.gradient(e)[0] for e in r["encoded"]]
|
| 462 |
+
gradients.append(
|
| 463 |
+
{
|
| 464 |
+
"case_id": r["case_id"],
|
| 465 |
+
"p0_p1_gradient_cos": gradient_cos(grads[0], grads[1]),
|
| 466 |
+
"p0_p2_gradient_cos": gradient_cos(grads[0], grads[2]),
|
| 467 |
+
}
|
| 468 |
+
)
|
| 469 |
+
write_json(out / f"gradients-{step:04d}.json", gradients)
|
| 470 |
+
if step in [0, 16, 64, 128, 256]:
|
| 471 |
+
save_checkpoint(out / f"checkpoint-{step:04d}.pt", engine, opt, step, meta, ledger)
|
| 472 |
+
if step == steps:
|
| 473 |
+
break
|
| 474 |
+
batch = [records[order[(step * 8 + i) % len(order)]] for i in range(8)]
|
| 475 |
+
encoded = [r["encoded"][v] for r in batch for v in (range(3) if phase == "form" else [0])]
|
| 476 |
+
replay = replay_batch(pools, texts, step)
|
| 477 |
+
torch.cuda.synchronize(engine.device)
|
| 478 |
+
begin = time.monotonic()
|
| 479 |
+
opt.zero_grad(set_to_none=True)
|
| 480 |
+
ce = engine.ce(encoded).mean()
|
| 481 |
+
ce.backward()
|
| 482 |
+
kl = engine.kl(replay).mean()
|
| 483 |
+
kl.backward()
|
| 484 |
+
geo_value, pair_counts = 0.0, None
|
| 485 |
+
if phase == "form":
|
| 486 |
+
features = engine.features(encoded, detach=False)
|
| 487 |
+
targets = [r["target_id"] for r in batch for _ in range(3)]
|
| 488 |
+
geo, pair_counts = contrastive_loss(features, targets, batch_table[step]["groups"])
|
| 489 |
+
if lambda_geo:
|
| 490 |
+
(lambda_geo * geo).backward()
|
| 491 |
+
geo_value = float(geo.detach())
|
| 492 |
+
norm = torch.nn.utils.clip_grad_norm_(parameters, cfg["optimizer"]["clip"])
|
| 493 |
+
opt.step()
|
| 494 |
+
torch.cuda.synchronize(engine.device)
|
| 495 |
+
ledger["wall_seconds"] += time.monotonic() - begin
|
| 496 |
+
ledger["answer_tokens"] += sum(sum(e["loss_mask"]) for e in encoded)
|
| 497 |
+
ledger["answer_input_tokens"] += sum(len(e["input_ids"]) for e in encoded)
|
| 498 |
+
ledger["replay_tokens"] += sum(sum(e["loss_mask"]) for e in replay)
|
| 499 |
+
ledger["replay_input_tokens"] += sum(len(e["input_ids"]) for e in replay)
|
| 500 |
+
if phase == "form":
|
| 501 |
+
ledger["geometry_input_tokens"] += sum(e["answer_start"] for e in encoded)
|
| 502 |
+
ledger["forward_sequences"] += (
|
| 503 |
+
len(encoded) + 2 * len(replay) + (len(encoded) if phase == "form" else 0)
|
| 504 |
+
)
|
| 505 |
+
ledger["backward_sequences"] += (
|
| 506 |
+
len(encoded) + len(replay) + (len(encoded) if lambda_geo else 0)
|
| 507 |
+
)
|
| 508 |
+
ledger["optimizer_steps"] += 1
|
| 509 |
+
for r in batch:
|
| 510 |
+
exposures[r["case_id"]] += 1
|
| 511 |
+
with (out / "training.jsonl").open("a") as f:
|
| 512 |
+
f.write(
|
| 513 |
+
json.dumps(
|
| 514 |
+
{
|
| 515 |
+
"step": step + 1,
|
| 516 |
+
"ce": float(ce.detach()),
|
| 517 |
+
"kl": float(kl.detach()),
|
| 518 |
+
"geo": geo_value,
|
| 519 |
+
"gradient_norm": float(norm),
|
| 520 |
+
"pairs": pair_counts,
|
| 521 |
+
}
|
| 522 |
+
)
|
| 523 |
+
+ "\n"
|
| 524 |
+
)
|
| 525 |
+
write_json(
|
| 526 |
+
out / "status.json", {"step": step + 1, "steps": steps, "time": now(), "ledger": ledger}
|
| 527 |
+
)
|
| 528 |
+
if (step + 1) % 16 == 0:
|
| 529 |
+
print(
|
| 530 |
+
run_id,
|
| 531 |
+
step + 1,
|
| 532 |
+
"ce",
|
| 533 |
+
float(ce.detach()),
|
| 534 |
+
"wall",
|
| 535 |
+
ledger["wall_seconds"],
|
| 536 |
+
flush=True,
|
| 537 |
+
)
|
| 538 |
+
final_hashes = state_hashes(engine.model)
|
| 539 |
+
unchanged = all(
|
| 540 |
+
final_hashes[n] == digest for n, digest in parent_hashes.items() if n not in trainable
|
| 541 |
+
)
|
| 542 |
+
assert unchanged, "A parameter outside the intervention scope changed"
|
| 543 |
+
receipt = {
|
| 544 |
+
"meta": meta,
|
| 545 |
+
"completed_at": now(),
|
| 546 |
+
"ledger": ledger,
|
| 547 |
+
"unchanged_outside_scope": unchanged,
|
| 548 |
+
"final_hashes": final_hashes,
|
| 549 |
+
"final_model_hash": aggregate_hash(final_hashes),
|
| 550 |
+
"exposures": exposures,
|
| 551 |
+
"trainable_parameters": sum(p.numel() for p in parameters),
|
| 552 |
+
"estimated_dense_full_backprop_flops_upper_bound": (
|
| 553 |
+
sum(p.numel() for p in engine.model.parameters())
|
| 554 |
+
* (
|
| 555 |
+
6 * ledger["answer_input_tokens"]
|
| 556 |
+
+ 8 * ledger["replay_input_tokens"]
|
| 557 |
+
+ (6 if lambda_geo else 2) * ledger["geometry_input_tokens"]
|
| 558 |
+
)
|
| 559 |
+
),
|
| 560 |
+
}
|
| 561 |
+
write_json(out / "complete.json", receipt)
|
| 562 |
+
return receipt
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
def run_summary(path):
|
| 566 |
+
evaluations = [read_json(p) for p in sorted(path.glob("evaluation-*.json"))]
|
| 567 |
+
nodes = [e["rows"][0]["step"] for e in evaluations]
|
| 568 |
+
rewrite = [
|
| 569 |
+
np.mean([r["answer_em"] for r in e["rows"] if r["view_id"] in [1, 2]]) for e in evaluations
|
| 570 |
+
]
|
| 571 |
+
keep0 = np.mean([r["answer_em"] for r in evaluations[0]["keep"]])
|
| 572 |
+
keep1 = np.mean([r["answer_em"] for r in evaluations[-1]["keep"]])
|
| 573 |
+
return {
|
| 574 |
+
"q_auc": float(q_auc(rewrite, nodes)),
|
| 575 |
+
"keep_damage": float(keep0 - keep1),
|
| 576 |
+
"answer_nll": float(np.mean([r["answer_nll"] for r in evaluations[-1]["rows"]])),
|
| 577 |
+
}
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
def select_config(candidates, metric, maximize):
|
| 581 |
+
safe = [
|
| 582 |
+
r for r in candidates if r["keep_damage"] <= config()["statistics"]["keep_damage_reference"]
|
| 583 |
+
]
|
| 584 |
+
if safe:
|
| 585 |
+
return sorted(safe, key=lambda r: (-1 if maximize else 1) * r[metric])[0]
|
| 586 |
+
return sorted(
|
| 587 |
+
candidates, key=lambda r: (r["keep_damage"], (-1 if maximize else 1) * r[metric])
|
| 588 |
+
)[0]
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
def preflight(engine, pools, texts):
|
| 592 |
+
records = pools["B_dev"][:8]
|
| 593 |
+
audit = engine.verify_hooks_and_gradients(records[0]["encoded"][0])
|
| 594 |
+
before = state_hashes(engine.model)
|
| 595 |
+
parameters = engine.configure_trainable("adapt")
|
| 596 |
+
engine.make_reference()
|
| 597 |
+
opt = optimizer(parameters, 1e-5)
|
| 598 |
+
torch.cuda.reset_peak_memory_stats(engine.device)
|
| 599 |
+
torch.cuda.synchronize(engine.device)
|
| 600 |
+
start = time.monotonic()
|
| 601 |
+
for step in range(3):
|
| 602 |
+
opt.zero_grad(set_to_none=True)
|
| 603 |
+
engine.ce([r["encoded"][0] for r in records]).mean().backward()
|
| 604 |
+
engine.kl(replay_batch(pools, texts, step)).mean().backward()
|
| 605 |
+
torch.nn.utils.clip_grad_norm_(parameters, 1.0)
|
| 606 |
+
opt.step()
|
| 607 |
+
torch.cuda.synchronize(engine.device)
|
| 608 |
+
seconds = (time.monotonic() - start) / 3
|
| 609 |
+
engine.restore_base()
|
| 610 |
+
assert before == state_hashes(engine.model)
|
| 611 |
+
estimate = {
|
| 612 |
+
"time": now(),
|
| 613 |
+
"device": str(engine.device),
|
| 614 |
+
"adapt_step_seconds": seconds,
|
| 615 |
+
"peak_memory_bytes": torch.cuda.max_memory_allocated(engine.device),
|
| 616 |
+
"formal_adapt_steps": 11264,
|
| 617 |
+
"formal_adapt_gpu_hours": seconds * 11264 / 3600,
|
| 618 |
+
"formation_estimate_factor": 3,
|
| 619 |
+
"formal_formation_gpu_hours_estimate": seconds * 3 * 2304 / 3600,
|
| 620 |
+
"excludes": [
|
| 621 |
+
"generation and NLL evaluation",
|
| 622 |
+
"gradient diagnostics",
|
| 623 |
+
"development",
|
| 624 |
+
"disk IO",
|
| 625 |
+
],
|
| 626 |
+
"microbatch_answer": 8,
|
| 627 |
+
"microbatch_replay": 8,
|
| 628 |
+
"reference_parent_restored": True,
|
| 629 |
+
}
|
| 630 |
+
write_json(ARTIFACTS / "estimate.json", estimate)
|
| 631 |
+
write_json(ARTIFACTS / "qwen-interface-audit.json", audit)
|
| 632 |
+
print(estimate, flush=True)
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
def dispatch(args):
|
| 636 |
+
if not (ARTIFACTS / "data-lock.json").exists():
|
| 637 |
+
raise RuntimeError("data-lock is required before development or evaluation")
|
| 638 |
+
data_lock = read_json(ARTIFACTS / "data-lock.json")
|
| 639 |
+
for name, digest in data_lock["files"].items():
|
| 640 |
+
if sha256(DATA / name) != digest:
|
| 641 |
+
raise RuntimeError(f"Frozen data changed: {name}")
|
| 642 |
+
if not read_json(ARTIFACTS / "A/audit.json")["pass"]:
|
| 643 |
+
raise RuntimeError("Stage A must pass before model training")
|
| 644 |
+
pools = read_json(DATA / "pools.json")
|
| 645 |
+
texts = read_json(DATA / "text.json")
|
| 646 |
+
episodes = read_json(DATA / "episodes.json")
|
| 647 |
+
by_id = {r["case_id"]: r for rows in pools.values() for r in rows}
|
| 648 |
+
engine = QwenExperiment(args.device)
|
| 649 |
+
if args.command == "preflight":
|
| 650 |
+
return preflight(engine, pools, texts)
|
| 651 |
+
if args.command == "diagnose":
|
| 652 |
+
if args.split == "dev":
|
| 653 |
+
learning_rates = config()["adapt"]["learning_rates"]
|
| 654 |
+
else:
|
| 655 |
+
learning_rates = [read_json(ARTIFACTS / "B-lock.json")["learning_rate"]]
|
| 656 |
+
tasks = list(itertools.product(learning_rates, enumerate(episodes["B_" + args.split])))
|
| 657 |
+
for lr, (episode, ids) in tasks[args.shard :: args.shards]:
|
| 658 |
+
run_id = f"B/{args.split}-lr{lr:g}-e{episode}"
|
| 659 |
+
train_run(
|
| 660 |
+
engine,
|
| 661 |
+
"adapt",
|
| 662 |
+
[by_id[i] for i in ids],
|
| 663 |
+
pools,
|
| 664 |
+
texts,
|
| 665 |
+
"B",
|
| 666 |
+
0,
|
| 667 |
+
episode,
|
| 668 |
+
args.split,
|
| 669 |
+
lr,
|
| 670 |
+
128,
|
| 671 |
+
run_id,
|
| 672 |
+
diagnostics=True,
|
| 673 |
+
)
|
| 674 |
+
return
|
| 675 |
+
b_lr = read_json(ARTIFACTS / "B-lock.json")["learning_rate"]
|
| 676 |
+
if args.command == "form" and args.split == "dev":
|
| 677 |
+
candidates = []
|
| 678 |
+
for lr in config()["form"]["learning_rates"]:
|
| 679 |
+
run_id = f"C/dev-C0-lr{lr:g}"
|
| 680 |
+
train_run(
|
| 681 |
+
engine, "form", pools["F_form"], pools, texts, "C0", 10, -1, "dev", lr, 256, run_id
|
| 682 |
+
)
|
| 683 |
+
candidates.append(
|
| 684 |
+
{"learning_rate": lr, "run_id": run_id, **run_summary(RESULTS / run_id)}
|
| 685 |
+
)
|
| 686 |
+
chosen = select_config(candidates, "answer_nll", False)
|
| 687 |
+
lr = chosen["learning_rate"]
|
| 688 |
+
formation_candidates = [{"condition": "C0", "lambda_geo": 0.0, **chosen}]
|
| 689 |
+
for lam in config()["form"]["lambdas"]:
|
| 690 |
+
run_id = f"C/dev-C1-lambda{lam:g}"
|
| 691 |
+
train_run(
|
| 692 |
+
engine,
|
| 693 |
+
"form",
|
| 694 |
+
pools["F_form"],
|
| 695 |
+
pools,
|
| 696 |
+
texts,
|
| 697 |
+
"C1",
|
| 698 |
+
10,
|
| 699 |
+
-1,
|
| 700 |
+
"dev",
|
| 701 |
+
lr,
|
| 702 |
+
256,
|
| 703 |
+
run_id,
|
| 704 |
+
lambda_geo=lam,
|
| 705 |
+
)
|
| 706 |
+
formation_candidates.append(
|
| 707 |
+
{
|
| 708 |
+
"condition": "C1",
|
| 709 |
+
"lambda_geo": lam,
|
| 710 |
+
"run_id": run_id,
|
| 711 |
+
**run_summary(RESULTS / run_id),
|
| 712 |
+
}
|
| 713 |
+
)
|
| 714 |
+
for item in formation_candidates:
|
| 715 |
+
adapt_results = []
|
| 716 |
+
for episode, ids in enumerate(episodes["C_dev"]):
|
| 717 |
+
run_id = f"C/adapt-dev-{item['condition']}-lambda{item['lambda_geo']:g}-e{episode}"
|
| 718 |
+
train_run(
|
| 719 |
+
engine,
|
| 720 |
+
"adapt",
|
| 721 |
+
[by_id[i] for i in ids],
|
| 722 |
+
pools,
|
| 723 |
+
texts,
|
| 724 |
+
item["condition"],
|
| 725 |
+
10,
|
| 726 |
+
episode,
|
| 727 |
+
"dev",
|
| 728 |
+
b_lr,
|
| 729 |
+
64,
|
| 730 |
+
run_id,
|
| 731 |
+
parent_path=RESULTS / item["run_id"] / "checkpoint-0256.pt",
|
| 732 |
+
)
|
| 733 |
+
adapt_results.append(run_summary(RESULTS / run_id))
|
| 734 |
+
item["future_q_auc"] = float(np.mean([r["q_auc"] for r in adapt_results]))
|
| 735 |
+
item["adapt_results"] = adapt_results
|
| 736 |
+
best = select_config(
|
| 737 |
+
[r for r in formation_candidates if r["condition"] == "C1"], "future_q_auc", True
|
| 738 |
+
)
|
| 739 |
+
lam = best["lambda_geo"]
|
| 740 |
+
train_run(
|
| 741 |
+
engine,
|
| 742 |
+
"form",
|
| 743 |
+
pools["F_form"],
|
| 744 |
+
pools,
|
| 745 |
+
texts,
|
| 746 |
+
"C2",
|
| 747 |
+
10,
|
| 748 |
+
-1,
|
| 749 |
+
"dev",
|
| 750 |
+
lr,
|
| 751 |
+
256,
|
| 752 |
+
"C/dev-C2-engineering",
|
| 753 |
+
lambda_geo=lam,
|
| 754 |
+
)
|
| 755 |
+
write_json(
|
| 756 |
+
ARTIFACTS / "C-lock.json",
|
| 757 |
+
{
|
| 758 |
+
"time": now(),
|
| 759 |
+
"learning_rate": lr,
|
| 760 |
+
"lambda_geo": lam,
|
| 761 |
+
"adapt_learning_rate": b_lr,
|
| 762 |
+
"lr_candidates": candidates,
|
| 763 |
+
"formation_candidates": formation_candidates,
|
| 764 |
+
"source_hashes": frozen_training_sources(),
|
| 765 |
+
"data_lock_sha256": sha256(ARTIFACTS / "data-lock.json"),
|
| 766 |
+
"seeds": [0, 1, 2],
|
| 767 |
+
"conditions": ["C0", "C1", "C2"],
|
| 768 |
+
"episodes": episodes["C_eval"],
|
| 769 |
+
"status": "locked",
|
| 770 |
+
},
|
| 771 |
+
)
|
| 772 |
+
return
|
| 773 |
+
c_lock = read_json(ARTIFACTS / "C-lock.json")
|
| 774 |
+
if args.command == "form":
|
| 775 |
+
tasks = list(itertools.product(["C0", "C1", "C2"], [0, 1, 2]))
|
| 776 |
+
for condition, seed in tasks[args.shard :: args.shards]:
|
| 777 |
+
train_run(
|
| 778 |
+
engine,
|
| 779 |
+
"form",
|
| 780 |
+
pools["F_form"],
|
| 781 |
+
pools,
|
| 782 |
+
texts,
|
| 783 |
+
condition,
|
| 784 |
+
seed,
|
| 785 |
+
-1,
|
| 786 |
+
"eval",
|
| 787 |
+
c_lock["learning_rate"],
|
| 788 |
+
256,
|
| 789 |
+
f"C/form-{condition}-s{seed}",
|
| 790 |
+
lambda_geo=0.0 if condition == "C0" else c_lock["lambda_geo"],
|
| 791 |
+
)
|
| 792 |
+
elif args.command == "adapt":
|
| 793 |
+
tasks = list(
|
| 794 |
+
itertools.product(["C0", "C1", "C2"], [0, 1, 2], enumerate(episodes["C_eval"]))
|
| 795 |
+
)
|
| 796 |
+
for condition, seed, (episode, ids) in tasks[args.shard :: args.shards]:
|
| 797 |
+
train_run(
|
| 798 |
+
engine,
|
| 799 |
+
"adapt",
|
| 800 |
+
[by_id[i] for i in ids],
|
| 801 |
+
pools,
|
| 802 |
+
texts,
|
| 803 |
+
condition,
|
| 804 |
+
seed,
|
| 805 |
+
episode,
|
| 806 |
+
"eval",
|
| 807 |
+
b_lr,
|
| 808 |
+
128,
|
| 809 |
+
f"C/adapt-{condition}-s{seed}-e{episode}",
|
| 810 |
+
parent_path=RESULTS / f"C/form-{condition}-s{seed}/checkpoint-0256.pt",
|
| 811 |
+
)
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/interface_editing.py
ADDED
|
@@ -0,0 +1,759 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local factual updates and downstream composition in existing aligned GPTs.
|
| 2 |
+
|
| 3 |
+
Cases are selected from the graph alone, before loading any model predictions.
|
| 4 |
+
Every edit has a same-budget old-fact sham, fresh optimizer, and frozen parent
|
| 5 |
+
replay reference. No composition labels or intermediate-state targets enter
|
| 6 |
+
optimization. Finite replay KL is a regularizer, not exact preservation.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import copy
|
| 12 |
+
import hashlib
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
import time
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
from torch.nn import functional as F
|
| 21 |
+
|
| 22 |
+
from .grok_depth import utc, write_json
|
| 23 |
+
from .latent_scaling import build_world, model_digest
|
| 24 |
+
from .representation_alignment import new_model
|
| 25 |
+
from .storage_composition import data_digest, file_hash, generate_rows, pack_sentences
|
| 26 |
+
|
| 27 |
+
ROLES = ("first", "second")
|
| 28 |
+
STRATA = ("familiar", "strict")
|
| 29 |
+
DEFAULT_NODES = (0, 32, 128, 512)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _rows(values, width):
|
| 33 |
+
return np.asarray(values, dtype=np.int64).reshape(-1, width)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _unique(values, width):
|
| 37 |
+
return _rows(sorted(set(map(tuple, _rows(values, width)))), width)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _hash_json(value):
|
| 41 |
+
return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _batch_hash(batch):
|
| 45 |
+
digest = hashlib.sha256()
|
| 46 |
+
for tensor in batch:
|
| 47 |
+
array = tensor.detach().cpu().numpy()
|
| 48 |
+
digest.update(str(array.dtype).encode())
|
| 49 |
+
digest.update(str(array.shape).encode())
|
| 50 |
+
digest.update(array.tobytes())
|
| 51 |
+
return digest.hexdigest()
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def learned_atoms(world):
|
| 55 |
+
"""Only atomics actually supervised in the representation parent."""
|
| 56 |
+
return _unique(np.concatenate([world["common_atomic"], world["anchor_atomic"]]), 3)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def composition_pools(world):
|
| 60 |
+
"""All legal untrained queries, plus the original holdout and training sets."""
|
| 61 |
+
trained = set(map(tuple, world["train_composite"]))
|
| 62 |
+
full = _unique(np.concatenate([world["available_composite"], world["familiar_test"]]), 5)
|
| 63 |
+
familiar = _rows([r for r in full if tuple(r) not in trained], 5)
|
| 64 |
+
return {
|
| 65 |
+
"familiar": familiar,
|
| 66 |
+
"strict": world["strict_test"].copy(),
|
| 67 |
+
"registered_familiar": world["familiar_test"].copy(),
|
| 68 |
+
"train": world["train_composite"].copy(),
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def affected(rows, fact, role):
|
| 73 |
+
"""Whether a query uses this factual address, independently of its answer."""
|
| 74 |
+
columns = (0, 1) if role == "first" else (2, 3)
|
| 75 |
+
return (rows[:, columns[0]] == fact[0]) & (rows[:, columns[1]] == fact[1])
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def rewrite(rows, old_fact, new_fact, role, lookup):
|
| 79 |
+
result = rows.copy()
|
| 80 |
+
mask = affected(rows, old_fact, role)
|
| 81 |
+
if role == "first":
|
| 82 |
+
result[mask, 2] = new_fact[2]
|
| 83 |
+
for index in np.flatnonzero(mask):
|
| 84 |
+
result[index, 4] = lookup[int(new_fact[2]), int(rows[index, 3])]
|
| 85 |
+
else:
|
| 86 |
+
result[mask, 4] = new_fact[2]
|
| 87 |
+
return result
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def graph_cases(parent_spec, *, seed=780011, per_cell=2, replay_n=32):
|
| 91 |
+
"""Return JSON-compatible selected cases and graph-only eligibility counts.
|
| 92 |
+
|
| 93 |
+
Each distinct atomic address receives at most one counterfactual per role.
|
| 94 |
+
First-hop replacements stay in the original familiar/strict bridge group and
|
| 95 |
+
change at least one affected untrained composition answer. Strict cases never
|
| 96 |
+
borrow a bridge with composition experience from the familiar group.
|
| 97 |
+
"""
|
| 98 |
+
if per_cell < 1 or replay_n < 1:
|
| 99 |
+
raise ValueError("Positive case and replay counts are required")
|
| 100 |
+
world = build_world(parent_spec)
|
| 101 |
+
atoms = learned_atoms(world)
|
| 102 |
+
lookup = {(int(h), int(r)): int(t) for h, r, t in atoms}
|
| 103 |
+
pools = composition_pools(world)
|
| 104 |
+
rng = np.random.default_rng(seed + int(parent_spec["world"]))
|
| 105 |
+
candidates, qualification = [], {}
|
| 106 |
+
for role in ROLES:
|
| 107 |
+
for stratum in STRATA:
|
| 108 |
+
rows = pools[stratum]
|
| 109 |
+
addresses = _unique(rows[:, [0, 1, 2] if role == "first" else [2, 3, 4]], 3)
|
| 110 |
+
bridges = np.unique(rows[:, 2])
|
| 111 |
+
# Include all trained bridges in that group, even if the holdout
|
| 112 |
+
# happens not to visit them (strict rows enumerate all chains).
|
| 113 |
+
group = world["background_atomic"] if stratum == "familiar" else world["common_atomic"]
|
| 114 |
+
group_bridges = np.unique(group[group[:, 1] >= 17, 0])
|
| 115 |
+
if stratum == "strict":
|
| 116 |
+
familiar_bridges = world["background_atomic"]
|
| 117 |
+
familiar_bridges = familiar_bridges[familiar_bridges[:, 1] >= 17, 0]
|
| 118 |
+
group_bridges = np.setdiff1d(group_bridges, familiar_bridges)
|
| 119 |
+
bridges = np.union1d(bridges, group_bridges)
|
| 120 |
+
tails = np.unique(atoms[atoms[:, 1] >= 17, 2])
|
| 121 |
+
eligible, replacement_count = [], 0
|
| 122 |
+
for old in addresses:
|
| 123 |
+
impacted = rows[affected(rows, old, role)]
|
| 124 |
+
choices = []
|
| 125 |
+
for value in bridges if role == "first" else tails:
|
| 126 |
+
if value == old[2]:
|
| 127 |
+
continue
|
| 128 |
+
new = [int(old[0]), int(old[1]), int(value)]
|
| 129 |
+
updated = rewrite(impacted, old, new, role, lookup)
|
| 130 |
+
if np.any(updated[:, -1] != impacted[:, -1]):
|
| 131 |
+
choices.append(new)
|
| 132 |
+
replacement_count += len(choices)
|
| 133 |
+
if choices:
|
| 134 |
+
eligible.append((old.tolist(), choices))
|
| 135 |
+
key = f"{role}_{stratum}"
|
| 136 |
+
qualification[key] = {
|
| 137 |
+
"candidate_addresses": len(addresses),
|
| 138 |
+
"eligible_addresses": len(eligible),
|
| 139 |
+
"eligible_replacements": replacement_count,
|
| 140 |
+
"untrained_queries": len(rows),
|
| 141 |
+
}
|
| 142 |
+
if len(eligible) < per_cell:
|
| 143 |
+
raise ValueError(f"Insufficient graph-qualified {key} cases: {qualification[key]}")
|
| 144 |
+
order = rng.permutation(len(eligible))[:per_cell]
|
| 145 |
+
for serial, index in enumerate(order):
|
| 146 |
+
old, choices = eligible[index]
|
| 147 |
+
new = choices[int(rng.integers(len(choices)))]
|
| 148 |
+
candidates.append(
|
| 149 |
+
{
|
| 150 |
+
"case_id": f"{key}-{serial:02d}",
|
| 151 |
+
"role": role,
|
| 152 |
+
"stratum": stratum,
|
| 153 |
+
"old_fact": old,
|
| 154 |
+
"new_fact": new,
|
| 155 |
+
}
|
| 156 |
+
)
|
| 157 |
+
for case in candidates:
|
| 158 |
+
tasks, originals = case_tasks(world, case, replay_indices=None)
|
| 159 |
+
necessary = set(map(tuple, tasks["necessary_atomic"]))
|
| 160 |
+
allowed = [
|
| 161 |
+
i
|
| 162 |
+
for i, row in enumerate(atoms)
|
| 163 |
+
if tuple(row) != tuple(case["old_fact"]) and tuple(row) not in necessary
|
| 164 |
+
]
|
| 165 |
+
if len(allowed) < replay_n:
|
| 166 |
+
raise ValueError("Insufficient independent replay atomics")
|
| 167 |
+
case["replay_indices"] = sorted(map(int, rng.choice(allowed, replay_n, replace=False)))
|
| 168 |
+
case["affected_untrained_n"] = {name: len(rows) for name, rows in originals.items()}
|
| 169 |
+
return candidates, qualification
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def case_tasks(world, case, replay_indices=None):
|
| 173 |
+
"""Construct E/R/U/D with address-based exclusions and recomputed truth."""
|
| 174 |
+
atoms = learned_atoms(world)
|
| 175 |
+
lookup = {(int(h), int(r)): int(t) for h, r, t in atoms}
|
| 176 |
+
old, new, role = case["old_fact"], case["new_fact"], case["role"]
|
| 177 |
+
if lookup[tuple(old[:2])] != old[2] or old[:2] != new[:2] or old[2] == new[2]:
|
| 178 |
+
raise ValueError("An edit must replace one existing factual value")
|
| 179 |
+
tasks = {"E_old": _rows([old], 3), "E_new": _rows([new], 3)}
|
| 180 |
+
originals, necessary = {}, []
|
| 181 |
+
for stratum, rows in composition_pools(world).items():
|
| 182 |
+
mask = affected(rows, old, role)
|
| 183 |
+
tasks[f"U_{stratum}"] = rows[~mask].copy()
|
| 184 |
+
old_rows = rows[mask].copy()
|
| 185 |
+
new_rows = rewrite(old_rows, old, new, role, lookup)
|
| 186 |
+
changed = old_rows[:, -1] != new_rows[:, -1]
|
| 187 |
+
if stratum == "train":
|
| 188 |
+
# Training-query transfer is reported separately from held-out D.
|
| 189 |
+
name = f"T_{role}_train"
|
| 190 |
+
originals[name] = old_rows
|
| 191 |
+
tasks[name] = new_rows
|
| 192 |
+
else:
|
| 193 |
+
name = f"D_{role}_{stratum}"
|
| 194 |
+
originals[name] = old_rows[changed]
|
| 195 |
+
tasks[name] = new_rows[changed]
|
| 196 |
+
same = f"S_same_answer_{role}_{stratum}"
|
| 197 |
+
originals[same] = old_rows[~changed]
|
| 198 |
+
tasks[same] = new_rows[~changed]
|
| 199 |
+
if stratum in STRATA:
|
| 200 |
+
for h, r1, b, r2, t in tasks[name]:
|
| 201 |
+
prerequisite = (b, r2, t) if role == "first" else (h, r1, b)
|
| 202 |
+
necessary.append(prerequisite)
|
| 203 |
+
tasks["necessary_atomic"] = _unique(necessary, 3)
|
| 204 |
+
replay = case.get("replay_indices", []) if replay_indices is None else replay_indices
|
| 205 |
+
if len(set(replay)) != len(replay):
|
| 206 |
+
raise ValueError("Replay indices must be unique")
|
| 207 |
+
target = np.flatnonzero(np.all(atoms == np.asarray(old), axis=1))
|
| 208 |
+
if len(target) != 1 or int(target[0]) in replay:
|
| 209 |
+
raise ValueError("Replay cannot contain the edited address")
|
| 210 |
+
tasks["R_atomic"] = atoms[replay].copy()
|
| 211 |
+
tasks["U_atomic"] = np.delete(atoms, [int(target[0]), *replay], axis=0)
|
| 212 |
+
return tasks, originals
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def answer_batch(rows, device):
|
| 216 |
+
"""Only answer, punctuation and EOS labels; no prefix or bridge labels."""
|
| 217 |
+
tokens, labels = pack_sentences(_rows(rows, 3))
|
| 218 |
+
positions = np.tile([4, 5, 6], (len(rows), 1))
|
| 219 |
+
targets = labels[np.arange(len(rows))[:, None], positions]
|
| 220 |
+
expected = np.column_stack([np.asarray(rows)[:, 2], np.full(len(rows), 5), np.ones(len(rows))])
|
| 221 |
+
np.testing.assert_array_equal(targets, expected)
|
| 222 |
+
return tuple(torch.as_tensor(x, device=device) for x in (tokens, positions, targets))
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def edit_objective(model, target_batch, replay_batch, parent_log, replay_weight=1.0):
|
| 226 |
+
target = model(target_batch[0], positions=target_batch[1])
|
| 227 |
+
ce = F.cross_entropy(target.flatten(0, 1), target_batch[2].flatten())
|
| 228 |
+
replay = model(replay_batch[0], positions=replay_batch[1]).log_softmax(-1)
|
| 229 |
+
if parent_log.requires_grad:
|
| 230 |
+
raise ValueError("Replay reference must be detached")
|
| 231 |
+
kl = F.kl_div(replay, parent_log, log_target=True, reduction="none").sum(-1).mean()
|
| 232 |
+
return ce + replay_weight * kl, ce, kl
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def _generate(model, rows, device, batch_size):
|
| 236 |
+
if len(rows):
|
| 237 |
+
return generate_rows(model, rows, device, batch_size=batch_size)
|
| 238 |
+
return (
|
| 239 |
+
{"n": 0, "accuracy": None, "answer_accuracy": None, "answer_nll": None},
|
| 240 |
+
{
|
| 241 |
+
"generated": np.empty((0, 3), dtype=np.int64),
|
| 242 |
+
"correct": np.empty(0, dtype=bool),
|
| 243 |
+
"answer_nll": np.empty(0),
|
| 244 |
+
},
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def evaluate_case(model, tasks, originals, parent_correct, role, device, batch_size=512):
|
| 249 |
+
"""Full-pool scores and separately labelled prerequisite/parent subsets."""
|
| 250 |
+
metrics, raw = {}, {}
|
| 251 |
+
for name, rows in tasks.items():
|
| 252 |
+
values, predictions = _generate(model, rows, device, batch_size)
|
| 253 |
+
raw.update({f"{name}__{k}": v for k, v in predictions.items()})
|
| 254 |
+
if name in originals:
|
| 255 |
+
old = originals[name]
|
| 256 |
+
generated = predictions["generated"]
|
| 257 |
+
changed = old[:, -1] != rows[:, -1]
|
| 258 |
+
old_correct = (generated[:, 0] == old[:, -1]) & np.all(
|
| 259 |
+
generated[:, 1:] == [5, 1], axis=1
|
| 260 |
+
)
|
| 261 |
+
prerequisite = rows[:, [2, 3, 4] if role == "first" else [0, 1, 2]]
|
| 262 |
+
_m, needed = _generate(model, prerequisite, device, batch_size)
|
| 263 |
+
edited_ok = metrics["E_new"]["accuracy"] == 1.0
|
| 264 |
+
covered = needed["correct"] & edited_ok
|
| 265 |
+
baseline = parent_correct[name]
|
| 266 |
+
valid_parent = baseline & changed
|
| 267 |
+
correct = predictions["correct"]
|
| 268 |
+
values.update(
|
| 269 |
+
{
|
| 270 |
+
"changed_answer_n": int(changed.sum()),
|
| 271 |
+
"old_answer_accuracy": float(old_correct.mean()) if len(rows) else None,
|
| 272 |
+
"parent_correct_n": int(baseline.sum()),
|
| 273 |
+
"parent_correct_coverage": float(baseline.mean()) if len(rows) else None,
|
| 274 |
+
"new_following_parent_correct": float(correct[valid_parent].mean())
|
| 275 |
+
if valid_parent.any()
|
| 276 |
+
else None,
|
| 277 |
+
"old_retained_parent_correct": float(old_correct[valid_parent].mean())
|
| 278 |
+
if valid_parent.any()
|
| 279 |
+
else None,
|
| 280 |
+
"direct_edit_success": edited_ok,
|
| 281 |
+
"necessary_atomic_correct_n": int(needed["correct"].sum()),
|
| 282 |
+
"operation_correct_n": int(covered.sum()),
|
| 283 |
+
"operation_correct_coverage": float(covered.mean()) if len(rows) else None,
|
| 284 |
+
"new_following_operation_correct": float(correct[covered].mean())
|
| 285 |
+
if covered.any()
|
| 286 |
+
else None,
|
| 287 |
+
}
|
| 288 |
+
)
|
| 289 |
+
raw[f"{name}__parent_correct"] = baseline
|
| 290 |
+
raw[f"{name}__operation_correct"] = covered
|
| 291 |
+
raw[f"{name}__old_correct"] = old_correct
|
| 292 |
+
raw[f"{name}__necessary_generated"] = needed["generated"]
|
| 293 |
+
raw[f"{name}__new_rows"] = rows
|
| 294 |
+
raw[f"{name}__old_rows"] = old
|
| 295 |
+
metrics[name] = values
|
| 296 |
+
return metrics, raw
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def editable_parameters(model, scope="mlp", block_index=0):
|
| 300 |
+
prefix = f"blocks.{block_index}.mlp."
|
| 301 |
+
selected = [
|
| 302 |
+
name
|
| 303 |
+
for name, _ in model.named_parameters()
|
| 304 |
+
if name.startswith(prefix) and (scope == "mlp" or name == prefix + "down.weight")
|
| 305 |
+
]
|
| 306 |
+
if scope not in {"mlp", "down"} or not selected:
|
| 307 |
+
raise ValueError("Unknown or empty local parameter scope")
|
| 308 |
+
for name, parameter in model.named_parameters():
|
| 309 |
+
parameter.requires_grad_(name in selected)
|
| 310 |
+
parameter.grad = None
|
| 311 |
+
return selected
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def _configure(device):
|
| 315 |
+
device = torch.device(device)
|
| 316 |
+
torch.set_num_threads(1)
|
| 317 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 318 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 319 |
+
if device.type == "cuda":
|
| 320 |
+
torch.cuda.set_device(device)
|
| 321 |
+
return device
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def _load_parent(parent_dir, device):
|
| 325 |
+
path = Path(parent_dir) / "model.pt"
|
| 326 |
+
payload = torch.load(path, map_location="cpu", weights_only=False)
|
| 327 |
+
model = new_model(payload["spec"], device).eval()
|
| 328 |
+
model.load_state_dict(payload["model"])
|
| 329 |
+
world = build_world(payload["spec"])
|
| 330 |
+
if (Path(parent_dir) / "world.npz").exists():
|
| 331 |
+
with np.load(Path(parent_dir) / "world.npz") as saved:
|
| 332 |
+
for name, rows in world.items():
|
| 333 |
+
np.testing.assert_array_equal(rows, saved[name])
|
| 334 |
+
return model, world, payload["spec"]
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def _parent_masks(parent, originals, device, batch_size):
|
| 338 |
+
return {
|
| 339 |
+
name: _generate(parent, rows, device, batch_size)[1]["correct"]
|
| 340 |
+
for name, rows in originals.items()
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def run(spec, out, device="cuda:0"):
|
| 345 |
+
"""Execute one parent, a graph-selected case set and optional development lr grid.
|
| 346 |
+
|
| 347 |
+
The caller owns source freezing, resource allocation and W&B startup. Each
|
| 348 |
+
branch has run/learning/complete artifacts. Root ``step`` is a strictly
|
| 349 |
+
increasing evaluation index, including every branch's unchanged node zero;
|
| 350 |
+
``optimizer_updates`` separately records cumulative optimization work.
|
| 351 |
+
Target labels and replay KL positions have separate exposure counters.
|
| 352 |
+
``status.json`` retains completed-branch progress, explicitly labelled in
|
| 353 |
+
the manifest; it does not define the tracking series' step axis.
|
| 354 |
+
"""
|
| 355 |
+
device = _configure(device)
|
| 356 |
+
out = Path(out)
|
| 357 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 358 |
+
if (out / "run.json").exists() or (out / "complete.json").exists():
|
| 359 |
+
raise FileExistsError(f"Do not overwrite an existing attempt: {out}")
|
| 360 |
+
nodes = spec.get("nodes", list(DEFAULT_NODES))
|
| 361 |
+
if not nodes or nodes[0] != 0 or nodes != sorted(set(nodes)) or nodes[-1] <= 0:
|
| 362 |
+
raise ValueError("Nodes must increase from zero to a positive fixed endpoint")
|
| 363 |
+
rates = spec.get("learning_rates", [spec.get("lr", 1e-4)])
|
| 364 |
+
if not rates or any(lr <= 0 for lr in rates) or len(set(rates)) != len(rates):
|
| 365 |
+
raise ValueError("Learning rates must be positive and unique")
|
| 366 |
+
if spec.get("phase") not in {"development", "engineering"} and len(rates) > 1:
|
| 367 |
+
raise ValueError("Learning-rate grids are development-only")
|
| 368 |
+
arms = spec.get("arms", ["edit", "sham"])
|
| 369 |
+
if sorted(arms) != ["edit", "sham"]:
|
| 370 |
+
raise ValueError("Every case requires paired edit and sham branches")
|
| 371 |
+
parent, world, parent_spec = _load_parent(spec["parent_dir"], device)
|
| 372 |
+
parent_hash = model_digest(parent)
|
| 373 |
+
cases, qualification = graph_cases(
|
| 374 |
+
parent_spec,
|
| 375 |
+
seed=spec.get("candidate_seed", 780011),
|
| 376 |
+
per_cell=spec.get("per_cell", 2),
|
| 377 |
+
replay_n=spec.get("replay_n", 32),
|
| 378 |
+
)
|
| 379 |
+
if "case_ids" in spec:
|
| 380 |
+
requested = set(spec["case_ids"])
|
| 381 |
+
if not requested or not requested <= {c["case_id"] for c in cases}:
|
| 382 |
+
raise ValueError("Unknown/empty fixed graph-selected case subset")
|
| 383 |
+
cases = [c for c in cases if c["case_id"] in requested]
|
| 384 |
+
manifest = {
|
| 385 |
+
"spec": spec,
|
| 386 |
+
"parent_spec": parent_spec,
|
| 387 |
+
"cases": cases,
|
| 388 |
+
"qualification": qualification,
|
| 389 |
+
"case_sha256": _hash_json(cases),
|
| 390 |
+
"parent_file_sha256": file_hash(Path(spec["parent_dir"]) / "model.pt"),
|
| 391 |
+
"parent_model_sha256": parent_hash,
|
| 392 |
+
"world_sha256": data_digest(world),
|
| 393 |
+
"created_utc": utc(),
|
| 394 |
+
"dtype": "float32",
|
| 395 |
+
"allow_tf32": True,
|
| 396 |
+
"pid": os.getpid(),
|
| 397 |
+
"gpu": device.index if device.type == "cuda" else None,
|
| 398 |
+
"branches": len(cases) * len(rates) * len(arms),
|
| 399 |
+
"planned_updates": len(cases) * len(rates) * len(arms) * nodes[-1],
|
| 400 |
+
"planned_evaluations": len(cases) * len(rates) * len(arms) * len(nodes),
|
| 401 |
+
"learning_step_unit": "evaluation_index",
|
| 402 |
+
"status_step_unit": "completed_branches",
|
| 403 |
+
"scope_warning": "The selected MLP is shared across all repeated executions",
|
| 404 |
+
}
|
| 405 |
+
write_json(out / "run.json", manifest)
|
| 406 |
+
write_json(out / "cases.json", cases)
|
| 407 |
+
np.savez_compressed(out / "world.npz", **world)
|
| 408 |
+
root_learning, branch_summaries, completed_steps = [], [], 0
|
| 409 |
+
started = time.perf_counter()
|
| 410 |
+
training_seconds = 0.0
|
| 411 |
+
batch_size = spec.get("eval_batch_size", 512)
|
| 412 |
+
for case in cases:
|
| 413 |
+
tasks, originals = case_tasks(world, case)
|
| 414 |
+
parent_correct = _parent_masks(parent, originals, device, batch_size)
|
| 415 |
+
parent_metrics, parent_predictions = evaluate_case(
|
| 416 |
+
parent,
|
| 417 |
+
tasks,
|
| 418 |
+
originals,
|
| 419 |
+
parent_correct,
|
| 420 |
+
case["role"],
|
| 421 |
+
device,
|
| 422 |
+
batch_size,
|
| 423 |
+
)
|
| 424 |
+
case_out = out / case["case_id"]
|
| 425 |
+
case_out.mkdir()
|
| 426 |
+
np.savez_compressed(case_out / "parent-predictions.npz", **parent_predictions)
|
| 427 |
+
write_json(case_out / "parent-metrics.json", parent_metrics)
|
| 428 |
+
np.savez_compressed(case_out / "tasks.npz", **tasks)
|
| 429 |
+
replay_batch = answer_batch(tasks["R_atomic"], device)
|
| 430 |
+
with torch.no_grad():
|
| 431 |
+
parent_log = parent(replay_batch[0], positions=replay_batch[1]).log_softmax(-1).detach()
|
| 432 |
+
for lr in rates:
|
| 433 |
+
for arm in arms:
|
| 434 |
+
branch_name = f"lr{lr:.8g}-{arm}"
|
| 435 |
+
branch_out = case_out / branch_name
|
| 436 |
+
branch_out.mkdir()
|
| 437 |
+
model = copy.deepcopy(parent).eval()
|
| 438 |
+
selected = editable_parameters(
|
| 439 |
+
model,
|
| 440 |
+
spec.get("parameter_scope", "mlp"),
|
| 441 |
+
spec.get("block_index", 0),
|
| 442 |
+
)
|
| 443 |
+
parameters = dict(model.named_parameters())
|
| 444 |
+
optimizer = torch.optim.Adam([parameters[n] for n in selected], lr=lr)
|
| 445 |
+
target = tasks["E_new" if arm == "edit" else "E_old"]
|
| 446 |
+
target_batch = answer_batch(target, device)
|
| 447 |
+
write_json(
|
| 448 |
+
branch_out / "run.json",
|
| 449 |
+
{
|
| 450 |
+
"case_id": case["case_id"],
|
| 451 |
+
"arm": arm,
|
| 452 |
+
"lr": lr,
|
| 453 |
+
"parent_model_sha256": parent_hash,
|
| 454 |
+
"editable_parameters": selected,
|
| 455 |
+
"optimizer": "Adam, fresh state, zero weight decay",
|
| 456 |
+
"sampling": "same fixed full replay batch on every update; no dropout",
|
| 457 |
+
"old_fact_sha256": _hash_json(case["old_fact"]),
|
| 458 |
+
"new_fact_sha256": _hash_json(case["new_fact"]),
|
| 459 |
+
"target_batch_sha256": _batch_hash(target_batch),
|
| 460 |
+
"replay_batch_sha256": _batch_hash(replay_batch),
|
| 461 |
+
"parent_reference_sha256": _batch_hash((parent_log,)),
|
| 462 |
+
"nodes": nodes,
|
| 463 |
+
},
|
| 464 |
+
)
|
| 465 |
+
np.savez_compressed(
|
| 466 |
+
branch_out / "replay-reference.npz", log_probabilities=parent_log.cpu().numpy()
|
| 467 |
+
)
|
| 468 |
+
step, losses, history = 0, [], []
|
| 469 |
+
for node in nodes:
|
| 470 |
+
if device.type == "cuda":
|
| 471 |
+
torch.cuda.synchronize(device)
|
| 472 |
+
began = time.perf_counter()
|
| 473 |
+
while step < node:
|
| 474 |
+
optimizer.zero_grad(set_to_none=True)
|
| 475 |
+
loss, ce, kl = edit_objective(
|
| 476 |
+
model,
|
| 477 |
+
target_batch,
|
| 478 |
+
replay_batch,
|
| 479 |
+
parent_log,
|
| 480 |
+
spec.get("replay_weight", 1.0),
|
| 481 |
+
)
|
| 482 |
+
if not torch.isfinite(loss):
|
| 483 |
+
raise FloatingPointError(f"Nonfinite edit loss at {step}")
|
| 484 |
+
loss.backward()
|
| 485 |
+
gradient_norm = torch.nn.utils.clip_grad_norm_(
|
| 486 |
+
[parameters[n] for n in selected],
|
| 487 |
+
spec.get("clip_norm", 1.0),
|
| 488 |
+
)
|
| 489 |
+
optimizer.step()
|
| 490 |
+
step += 1
|
| 491 |
+
losses.append(
|
| 492 |
+
{
|
| 493 |
+
"step": step,
|
| 494 |
+
"loss": float(loss.detach()),
|
| 495 |
+
"target_ce": float(ce.detach()),
|
| 496 |
+
"replay_kl": float(kl.detach()),
|
| 497 |
+
"gradient_norm": float(gradient_norm),
|
| 498 |
+
}
|
| 499 |
+
)
|
| 500 |
+
if device.type == "cuda":
|
| 501 |
+
torch.cuda.synchronize(device)
|
| 502 |
+
training_seconds += time.perf_counter() - began
|
| 503 |
+
metrics, predictions = evaluate_case(
|
| 504 |
+
model,
|
| 505 |
+
tasks,
|
| 506 |
+
originals,
|
| 507 |
+
parent_correct,
|
| 508 |
+
case["role"],
|
| 509 |
+
device,
|
| 510 |
+
batch_size,
|
| 511 |
+
)
|
| 512 |
+
current_hash = model_digest(model)
|
| 513 |
+
record = {
|
| 514 |
+
"step": step,
|
| 515 |
+
"metrics": metrics,
|
| 516 |
+
"model_sha256": current_hash,
|
| 517 |
+
"target_success": metrics["E_new" if arm == "edit" else "E_old"]["accuracy"]
|
| 518 |
+
== 1,
|
| 519 |
+
"U_atomic_at_least_95": metrics["U_atomic"]["accuracy"] >= 0.95,
|
| 520 |
+
"loss": losses[-1] if losses else None,
|
| 521 |
+
}
|
| 522 |
+
history.append(record)
|
| 523 |
+
write_json(branch_out / "learning.json", history)
|
| 524 |
+
write_json(branch_out / "losses.json", losses)
|
| 525 |
+
np.savez_compressed(branch_out / f"predictions-{step:06d}.npz", **predictions)
|
| 526 |
+
torch.save(
|
| 527 |
+
{
|
| 528 |
+
"edited_tensors": {
|
| 529 |
+
n: parameters[n].detach().cpu().clone() for n in selected
|
| 530 |
+
},
|
| 531 |
+
"model_sha256": current_hash,
|
| 532 |
+
"step": step,
|
| 533 |
+
},
|
| 534 |
+
branch_out / f"tensors-{step:06d}.pt",
|
| 535 |
+
)
|
| 536 |
+
root_learning.append(
|
| 537 |
+
{
|
| 538 |
+
"step": len(root_learning),
|
| 539 |
+
"branch_step": step,
|
| 540 |
+
"completed_branches": len(branch_summaries) + int(step == nodes[-1]),
|
| 541 |
+
"optimizer_updates": completed_steps + step,
|
| 542 |
+
"case_id": case["case_id"],
|
| 543 |
+
"arm": arm,
|
| 544 |
+
"lr": lr,
|
| 545 |
+
"metrics": metrics,
|
| 546 |
+
"training_seconds": training_seconds,
|
| 547 |
+
"wall_seconds": time.perf_counter() - started,
|
| 548 |
+
"examples": (completed_steps + step) * (1 + len(tasks["R_atomic"])),
|
| 549 |
+
"target_supervised_tokens": (completed_steps + step) * 3,
|
| 550 |
+
"replay_distillation_positions": (completed_steps + step)
|
| 551 |
+
* len(tasks["R_atomic"])
|
| 552 |
+
* 3,
|
| 553 |
+
}
|
| 554 |
+
)
|
| 555 |
+
write_json(out / "learning.json", root_learning)
|
| 556 |
+
write_json(
|
| 557 |
+
out / "status.json",
|
| 558 |
+
{
|
| 559 |
+
"state": "running",
|
| 560 |
+
"step": len(branch_summaries),
|
| 561 |
+
"optimizer_updates": completed_steps + step,
|
| 562 |
+
"budget": manifest["branches"],
|
| 563 |
+
"case_id": case["case_id"],
|
| 564 |
+
"arm": arm,
|
| 565 |
+
"lr": lr,
|
| 566 |
+
},
|
| 567 |
+
)
|
| 568 |
+
changed = [
|
| 569 |
+
n
|
| 570 |
+
for n, t in model.state_dict().items()
|
| 571 |
+
if not torch.equal(t, parent.state_dict()[n])
|
| 572 |
+
]
|
| 573 |
+
if set(changed) - set(selected) or model_digest(parent) != parent_hash:
|
| 574 |
+
raise AssertionError("A frozen parameter or the parent changed")
|
| 575 |
+
complete = {
|
| 576 |
+
"case_id": case["case_id"],
|
| 577 |
+
"role": case["role"],
|
| 578 |
+
"stratum": case["stratum"],
|
| 579 |
+
"lr": lr,
|
| 580 |
+
"arm": arm,
|
| 581 |
+
"path": str(branch_out.relative_to(out)),
|
| 582 |
+
"metrics": metrics,
|
| 583 |
+
"steps": step,
|
| 584 |
+
"changed_tensors": changed,
|
| 585 |
+
"parent_model_sha256": parent_hash,
|
| 586 |
+
"final_model_sha256": current_hash,
|
| 587 |
+
"delta_l2": float(
|
| 588 |
+
torch.sqrt(
|
| 589 |
+
sum(
|
| 590 |
+
(parameters[n] - dict(parent.named_parameters())[n]).square().sum()
|
| 591 |
+
for n in selected
|
| 592 |
+
)
|
| 593 |
+
).detach()
|
| 594 |
+
),
|
| 595 |
+
"tensor_file_sha256": file_hash(branch_out / f"tensors-{step:06d}.pt"),
|
| 596 |
+
}
|
| 597 |
+
write_json(branch_out / "complete.json", complete)
|
| 598 |
+
branch_summaries.append(complete)
|
| 599 |
+
completed_steps += step
|
| 600 |
+
result = {
|
| 601 |
+
"status": "complete",
|
| 602 |
+
"branches": branch_summaries,
|
| 603 |
+
"updates": completed_steps,
|
| 604 |
+
"training_seconds": training_seconds,
|
| 605 |
+
"wall_seconds": time.perf_counter() - started,
|
| 606 |
+
"finished_utc": utc(),
|
| 607 |
+
"case_sha256": manifest["case_sha256"],
|
| 608 |
+
}
|
| 609 |
+
write_json(out / "complete.json", result)
|
| 610 |
+
write_json(
|
| 611 |
+
out / "status.json",
|
| 612 |
+
{
|
| 613 |
+
"state": "complete",
|
| 614 |
+
"step": len(branch_summaries),
|
| 615 |
+
"optimizer_updates": completed_steps,
|
| 616 |
+
"budget": manifest["branches"],
|
| 617 |
+
},
|
| 618 |
+
)
|
| 619 |
+
return result
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
def audit(out, device="cuda:0"):
|
| 623 |
+
"""Reload every saved node from parent plus exact tensors and re-score it."""
|
| 624 |
+
device, out = _configure(device), Path(out)
|
| 625 |
+
manifest = json.loads((out / "run.json").read_text())
|
| 626 |
+
spec = manifest["spec"]
|
| 627 |
+
if file_hash(Path(spec["parent_dir"]) / "model.pt") != manifest["parent_file_sha256"]:
|
| 628 |
+
raise AssertionError("Parent checkpoint hash changed")
|
| 629 |
+
parent, world, parent_spec = _load_parent(spec["parent_dir"], device)
|
| 630 |
+
if model_digest(parent) != manifest["parent_model_sha256"]:
|
| 631 |
+
raise AssertionError("Parent model digest changed")
|
| 632 |
+
cases, qualification = graph_cases(
|
| 633 |
+
parent_spec,
|
| 634 |
+
seed=spec.get("candidate_seed", 780011),
|
| 635 |
+
per_cell=spec.get("per_cell", 2),
|
| 636 |
+
replay_n=spec.get("replay_n", 32),
|
| 637 |
+
)
|
| 638 |
+
if "case_ids" in spec:
|
| 639 |
+
cases = [c for c in cases if c["case_id"] in spec["case_ids"]]
|
| 640 |
+
if cases != manifest["cases"] or _hash_json(cases) != manifest["case_sha256"]:
|
| 641 |
+
raise AssertionError("Graph-selected cases changed")
|
| 642 |
+
if qualification != manifest["qualification"] or data_digest(world) != manifest["world_sha256"]:
|
| 643 |
+
raise AssertionError("World qualification changed")
|
| 644 |
+
summary = json.loads((out / "complete.json").read_text())
|
| 645 |
+
rates = spec.get("learning_rates", [spec.get("lr", 1e-4)])
|
| 646 |
+
expected_branches = {
|
| 647 |
+
(c["case_id"], lr, arm) for c in cases for lr in rates for arm in ("edit", "sham")
|
| 648 |
+
}
|
| 649 |
+
actual_branches = [(b["case_id"], b["lr"], b["arm"]) for b in summary["branches"]]
|
| 650 |
+
if len(actual_branches) != len(expected_branches) or set(actual_branches) != expected_branches:
|
| 651 |
+
raise AssertionError("The fixed paired branch matrix is incomplete")
|
| 652 |
+
root_learning = json.loads((out / "learning.json").read_text())
|
| 653 |
+
nodes = spec.get("nodes", list(DEFAULT_NODES))
|
| 654 |
+
expected_evaluations = len(actual_branches) * len(nodes)
|
| 655 |
+
if len(root_learning) != expected_evaluations or [row["step"] for row in root_learning] != list(
|
| 656 |
+
range(expected_evaluations)
|
| 657 |
+
):
|
| 658 |
+
raise AssertionError("Root learning evaluation indices are incomplete or repeated")
|
| 659 |
+
for index, row in enumerate(root_learning):
|
| 660 |
+
branch_index, node_index = divmod(index, len(nodes))
|
| 661 |
+
updates = branch_index * nodes[-1] + nodes[node_index]
|
| 662 |
+
if (
|
| 663 |
+
(row["case_id"], row["lr"], row["arm"]) != actual_branches[branch_index]
|
| 664 |
+
or row["branch_step"] != nodes[node_index]
|
| 665 |
+
or row["optimizer_updates"] != updates
|
| 666 |
+
or row["target_supervised_tokens"] != updates * 3
|
| 667 |
+
or row["replay_distillation_positions"] != updates * spec.get("replay_n", 32) * 3
|
| 668 |
+
or "supervised_tokens" in row
|
| 669 |
+
):
|
| 670 |
+
raise AssertionError("Root learning optimizer or exposure accounting changed")
|
| 671 |
+
batch_size = spec.get("eval_batch_size", 512)
|
| 672 |
+
checked_nodes, checked_predictions, max_error = 0, 0, 0.0
|
| 673 |
+
for case in cases:
|
| 674 |
+
tasks, originals = case_tasks(world, case)
|
| 675 |
+
parent_correct = _parent_masks(parent, originals, device, batch_size)
|
| 676 |
+
for branch in summary["branches"]:
|
| 677 |
+
if branch["case_id"] != case["case_id"]:
|
| 678 |
+
continue
|
| 679 |
+
directory = out / branch["path"]
|
| 680 |
+
branch_spec = json.loads((directory / "run.json").read_text())
|
| 681 |
+
target = tasks["E_new" if branch["arm"] == "edit" else "E_old"]
|
| 682 |
+
target_batch = answer_batch(target, device)
|
| 683 |
+
replay_batch = answer_batch(tasks["R_atomic"], device)
|
| 684 |
+
with torch.no_grad():
|
| 685 |
+
reference = parent(replay_batch[0], positions=replay_batch[1]).log_softmax(-1)
|
| 686 |
+
expected_hashes = {
|
| 687 |
+
"old_fact_sha256": _hash_json(case["old_fact"]),
|
| 688 |
+
"new_fact_sha256": _hash_json(case["new_fact"]),
|
| 689 |
+
"target_batch_sha256": _batch_hash(target_batch),
|
| 690 |
+
"replay_batch_sha256": _batch_hash(replay_batch),
|
| 691 |
+
"parent_reference_sha256": _batch_hash((reference,)),
|
| 692 |
+
}
|
| 693 |
+
if any(branch_spec[key] != value for key, value in expected_hashes.items()):
|
| 694 |
+
raise AssertionError("Target or paired replay provenance changed")
|
| 695 |
+
history = json.loads((directory / "learning.json").read_text())
|
| 696 |
+
if [record["step"] for record in history] != spec.get("nodes", list(DEFAULT_NODES)):
|
| 697 |
+
raise AssertionError("Saved edit node matrix is incomplete")
|
| 698 |
+
if (
|
| 699 |
+
file_hash(directory / f"tensors-{history[-1]['step']:06d}.pt")
|
| 700 |
+
!= branch["tensor_file_sha256"]
|
| 701 |
+
):
|
| 702 |
+
raise AssertionError("Final exact tensor file hash changed")
|
| 703 |
+
for record in history:
|
| 704 |
+
state = torch.load(
|
| 705 |
+
directory / f"tensors-{record['step']:06d}.pt",
|
| 706 |
+
map_location="cpu",
|
| 707 |
+
weights_only=True,
|
| 708 |
+
)
|
| 709 |
+
model = copy.deepcopy(parent).eval()
|
| 710 |
+
selected = editable_parameters(
|
| 711 |
+
model, spec.get("parameter_scope", "mlp"), spec.get("block_index", 0)
|
| 712 |
+
)
|
| 713 |
+
if set(state["edited_tensors"]) != set(selected):
|
| 714 |
+
raise AssertionError("Unexpected edited tensor scope")
|
| 715 |
+
merged = model.state_dict()
|
| 716 |
+
merged.update(state["edited_tensors"])
|
| 717 |
+
model.load_state_dict(merged)
|
| 718 |
+
if model_digest(model) != record["model_sha256"]:
|
| 719 |
+
raise AssertionError("Exact saved tensors did not reconstruct the model")
|
| 720 |
+
metrics, predictions = evaluate_case(
|
| 721 |
+
model,
|
| 722 |
+
tasks,
|
| 723 |
+
originals,
|
| 724 |
+
parent_correct,
|
| 725 |
+
case["role"],
|
| 726 |
+
device,
|
| 727 |
+
batch_size,
|
| 728 |
+
)
|
| 729 |
+
with np.load(directory / f"predictions-{record['step']:06d}.npz") as saved:
|
| 730 |
+
if set(saved.files) != set(predictions):
|
| 731 |
+
raise AssertionError("Prediction keys changed")
|
| 732 |
+
for name, actual in predictions.items():
|
| 733 |
+
if name.endswith("answer_nll"):
|
| 734 |
+
np.testing.assert_allclose(actual, saved[name], rtol=1e-5, atol=1e-5)
|
| 735 |
+
if len(actual):
|
| 736 |
+
max_error = max(
|
| 737 |
+
max_error, float(np.max(np.abs(actual - saved[name])))
|
| 738 |
+
)
|
| 739 |
+
else:
|
| 740 |
+
np.testing.assert_array_equal(actual, saved[name])
|
| 741 |
+
checked_predictions += actual.size
|
| 742 |
+
for name, values in metrics.items():
|
| 743 |
+
for key, value in values.items():
|
| 744 |
+
expected = record["metrics"][name][key]
|
| 745 |
+
if key == "answer_nll" and value is not None:
|
| 746 |
+
np.testing.assert_allclose(value, expected, rtol=1e-5, atol=1e-5)
|
| 747 |
+
elif value != expected:
|
| 748 |
+
raise AssertionError(f"Re-scoring mismatch: {name}/{key}")
|
| 749 |
+
checked_nodes += 1
|
| 750 |
+
result = {
|
| 751 |
+
"passed": True,
|
| 752 |
+
"nodes": checked_nodes,
|
| 753 |
+
"array_elements": checked_predictions,
|
| 754 |
+
"max_nll_error": max_error,
|
| 755 |
+
"case_sha256": manifest["case_sha256"],
|
| 756 |
+
"finished_utc": utc(),
|
| 757 |
+
}
|
| 758 |
+
write_json(out / "audit.json", result)
|
| 759 |
+
return result
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/interface_tracking.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Use the existing W&B sidecar, finishing only after the independent audit."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import fcntl
|
| 5 |
+
import importlib
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
import time
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
from . import experiment_tracking as tracking
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class ContainerSDK:
|
| 15 |
+
def __init__(self, sdk, runtime):
|
| 16 |
+
self.sdk, self.runtime = sdk, runtime
|
| 17 |
+
|
| 18 |
+
def __getattr__(self, name):
|
| 19 |
+
return getattr(self.sdk, name)
|
| 20 |
+
|
| 21 |
+
def Settings(self, **options):
|
| 22 |
+
options.pop("x_stats_pid", None)
|
| 23 |
+
if self.runtime:
|
| 24 |
+
options["x_stats_pid"] = self.runtime["host_pid"]
|
| 25 |
+
options["x_stats_gpu_device_ids"] = (self.runtime["physical_gpu"],)
|
| 26 |
+
return self.sdk.Settings(**options)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class AuditedRunTracker(tracking.ArtifactRunTracker):
|
| 30 |
+
def __init__(self, sdk, batch, path, settings):
|
| 31 |
+
runtime_path = path / "container-runtime.json"
|
| 32 |
+
runtime = tracking.read_json(runtime_path)
|
| 33 |
+
super().__init__(ContainerSDK(sdk, runtime), batch, path, settings)
|
| 34 |
+
self.run.config.update(
|
| 35 |
+
{
|
| 36 |
+
key: self.metadata[key]
|
| 37 |
+
for key in (
|
| 38 |
+
"parent_spec",
|
| 39 |
+
"cases",
|
| 40 |
+
"learning_step_unit",
|
| 41 |
+
"status_step_unit",
|
| 42 |
+
)
|
| 43 |
+
if key in self.metadata
|
| 44 |
+
}
|
| 45 |
+
)
|
| 46 |
+
if runtime:
|
| 47 |
+
self.run.config.update({"container_runtime": runtime})
|
| 48 |
+
|
| 49 |
+
def poll(self):
|
| 50 |
+
history = tracking.read_json(self.path / "learning.json")
|
| 51 |
+
previous = None
|
| 52 |
+
for record in history:
|
| 53 |
+
step = int(record["step"])
|
| 54 |
+
if step > self.cursor:
|
| 55 |
+
metrics = tracking.learning_metrics(record, previous)
|
| 56 |
+
for key in ("case", "case_id", "condition", "variant", "arm"):
|
| 57 |
+
if key in record:
|
| 58 |
+
metrics["condition/" + key] = record[key]
|
| 59 |
+
if "optimizer_updates" in record:
|
| 60 |
+
metrics["evaluation/index"] = step
|
| 61 |
+
metrics["condition/step_unit"] = "evaluation_index"
|
| 62 |
+
metrics.pop("perf/updates_per_second", None)
|
| 63 |
+
metrics.pop("perf/training_ms_per_update", None)
|
| 64 |
+
if previous is not None:
|
| 65 |
+
seconds = record.get("wall_seconds", 0) - previous.get("wall_seconds", 0)
|
| 66 |
+
updates = record["optimizer_updates"] - previous.get("optimizer_updates", 0)
|
| 67 |
+
if seconds > 0:
|
| 68 |
+
metrics["perf/updates_per_second"] = updates / seconds
|
| 69 |
+
self.run.log(metrics, step=step)
|
| 70 |
+
self.cursor = step
|
| 71 |
+
self.state["last_logged_step"] = step
|
| 72 |
+
tracking.write_json(self.state_path, self.state)
|
| 73 |
+
previous = record
|
| 74 |
+
status_path = self.path / "status.json"
|
| 75 |
+
if status_path.exists():
|
| 76 |
+
self.run.summary["training_state"] = tracking.read_json(status_path).get("state")
|
| 77 |
+
failed = (self.path / "failure.json").exists()
|
| 78 |
+
audit_path = self.path / "audit.json"
|
| 79 |
+
audit = tracking.read_json(audit_path) if audit_path.exists() else {}
|
| 80 |
+
audited = audit.get("passed") is True
|
| 81 |
+
complete = (self.path / "complete.json").exists() and audited
|
| 82 |
+
self.run.summary["has_failure_record"] = failed
|
| 83 |
+
self.run.summary["independently_reloaded"] = audited
|
| 84 |
+
if complete or failed:
|
| 85 |
+
self.run.summary["scientific_final_step"] = self.cursor
|
| 86 |
+
self.run.finish(exit_code=1 if failed else 0)
|
| 87 |
+
# Preserve the authoritative resume cursor even when every point
|
| 88 |
+
# was already on the server and this process logged no new points.
|
| 89 |
+
self.state["last_logged_step"] = self.cursor
|
| 90 |
+
tracking.write_json(self.state_path, self.state)
|
| 91 |
+
return True
|
| 92 |
+
return False
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def discover_runs(runs_dir):
|
| 96 |
+
return {
|
| 97 |
+
path
|
| 98 |
+
for path in Path(runs_dir).glob("*")
|
| 99 |
+
if (path / "run.json").exists() and (path / "learning.json").exists()
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def final_step(path):
|
| 104 |
+
history = tracking.read_json(path / "learning.json")
|
| 105 |
+
return max((int(record["step"]) for record in history), default=-1)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def drain_runs(sdk, root, runs_dir, settings, *, once=False, tracker_factory=None):
|
| 109 |
+
"""Drain late-created runs and late final nodes before terminal exit.
|
| 110 |
+
|
| 111 |
+
SDK initialization and uploads may take longer than an entire scientific
|
| 112 |
+
run. Consequently, a scan made before those calls is never an exit proof.
|
| 113 |
+
Finished runs stay in this process's cursor map and are reopened only if
|
| 114 |
+
their saved learning trajectory acquired an unlogged final node.
|
| 115 |
+
"""
|
| 116 |
+
root, runs_dir = Path(root), Path(runs_dir)
|
| 117 |
+
tracker_factory = tracker_factory or AuditedRunTracker
|
| 118 |
+
active, finished = {}, {}
|
| 119 |
+
try:
|
| 120 |
+
while True:
|
| 121 |
+
for path in sorted(discover_runs(runs_dir)):
|
| 122 |
+
if path in active or path in finished:
|
| 123 |
+
continue
|
| 124 |
+
active[path] = tracker_factory(sdk, root, path, settings)
|
| 125 |
+
print(json.dumps({"run": path.name, "url": active[path].run.url}), flush=True)
|
| 126 |
+
for path, tracker in list(active.items()):
|
| 127 |
+
current = tracking.read_json(path / "run.json")
|
| 128 |
+
if current.get("pid") != tracker.metadata.get("pid"):
|
| 129 |
+
tracker.close()
|
| 130 |
+
tracker = tracker_factory(sdk, root, path, settings)
|
| 131 |
+
active[path] = tracker
|
| 132 |
+
if tracker.poll():
|
| 133 |
+
finished[path] = tracker.cursor
|
| 134 |
+
del active[path]
|
| 135 |
+
if once:
|
| 136 |
+
return {str(path): cursor for path, cursor in finished.items()}
|
| 137 |
+
manifest = root / "controller-state.json"
|
| 138 |
+
state = tracking.read_json(manifest) if manifest.exists() else {}
|
| 139 |
+
terminal = state.get("state") in {"complete", "finished_with_failures"}
|
| 140 |
+
# Rescan AFTER all SDK calls and after reading the controller's
|
| 141 |
+
# terminal state, so runs born during initialization cannot vanish.
|
| 142 |
+
fresh = discover_runs(runs_dir)
|
| 143 |
+
stale = {path for path, cursor in finished.items() if final_step(path) > cursor}
|
| 144 |
+
for path in stale:
|
| 145 |
+
del finished[path]
|
| 146 |
+
if terminal and not active:
|
| 147 |
+
expected = {runs_dir / name for name in state.get("completed", [])}
|
| 148 |
+
if missing := expected - fresh:
|
| 149 |
+
raise RuntimeError(f"Completed runs lack logging artifacts: {sorted(missing)}")
|
| 150 |
+
if fresh <= finished.keys():
|
| 151 |
+
result = {
|
| 152 |
+
"passed": True,
|
| 153 |
+
"registered_runs": len(finished),
|
| 154 |
+
"runs": {
|
| 155 |
+
path.name: {
|
| 156 |
+
"last_logged_step": finished[path],
|
| 157 |
+
"final_step": final_step(path),
|
| 158 |
+
}
|
| 159 |
+
for path in sorted(fresh)
|
| 160 |
+
},
|
| 161 |
+
}
|
| 162 |
+
tracking.write_json(root / "tracking-completion.json", result)
|
| 163 |
+
return result
|
| 164 |
+
if fresh - (active.keys() | finished.keys()):
|
| 165 |
+
continue
|
| 166 |
+
time.sleep(settings["poll_seconds"])
|
| 167 |
+
finally:
|
| 168 |
+
for tracker in active.values():
|
| 169 |
+
tracker.close()
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def main():
|
| 173 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 174 |
+
parser.add_argument("--root", type=Path, required=True)
|
| 175 |
+
parser.add_argument("--runs-dir", type=Path)
|
| 176 |
+
parser.add_argument("--defaults", type=Path, default=tracking.DEFAULTS)
|
| 177 |
+
parser.add_argument("--entity")
|
| 178 |
+
parser.add_argument("--project")
|
| 179 |
+
parser.add_argument("--mode", choices=("online", "offline"))
|
| 180 |
+
parser.add_argument("--once", action="store_true")
|
| 181 |
+
args = parser.parse_args()
|
| 182 |
+
settings = tracking.read_json(args.defaults)
|
| 183 |
+
for key in ("entity", "project", "mode"):
|
| 184 |
+
settings[key] = (
|
| 185 |
+
getattr(args, key) or os.environ.get(f"WANDB_{key.upper()}") or settings[key]
|
| 186 |
+
)
|
| 187 |
+
if not settings["enabled"]:
|
| 188 |
+
raise SystemExit("Experiment tracking is disabled in the selected defaults")
|
| 189 |
+
local = args.root / "tracking-wandb"
|
| 190 |
+
local.mkdir(parents=True, exist_ok=True)
|
| 191 |
+
sdk = importlib.import_module("wandb")
|
| 192 |
+
with (local / "tracker.lock").open("w") as lock:
|
| 193 |
+
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 194 |
+
tracking.write_json(args.root / "tracking-ready.json", {"sdk_version": sdk.__version__})
|
| 195 |
+
drain_runs(sdk, args.root, args.runs_dir or args.root / "runs", settings, once=args.once)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
if __name__ == "__main__":
|
| 199 |
+
main()
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/latent_scaling.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Scaling knowledge use in ordinary GPT blocks with fixed facts and tests.
|
| 2 |
+
|
| 3 |
+
Independent composition examples and optimization time are separate axes. All
|
| 4 |
+
blocks retain learned embeddings, causal attention, residuals and 4x GELU MLPs.
|
| 5 |
+
Historical experiments and their frozen implementations are left untouched.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
import time
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
import torch
|
| 17 |
+
|
| 18 |
+
from .bios_model import ModelConfig
|
| 19 |
+
from .grok_depth import EpochStream, make_optimizer, utc, write_json
|
| 20 |
+
from .grok_loop_model import LoopGPT, flops
|
| 21 |
+
from .storage_composition import FullTokenStep, data_digest, evaluate, file_hash, pack_sentences
|
| 22 |
+
from .storage_composition import build_world as historical_world
|
| 23 |
+
from .storage_frontier import SOURCE_FILES as STABILITY_SOURCES
|
| 24 |
+
from .storage_frontier import learning_rate
|
| 25 |
+
from .text_pretrain import WORDS
|
| 26 |
+
|
| 27 |
+
SOURCE_FILES = [
|
| 28 |
+
*STABILITY_SOURCES,
|
| 29 |
+
"src/llm_memory_editability/latent_scaling.py",
|
| 30 |
+
"scripts/run_latent_scaling.py",
|
| 31 |
+
"tests/test_latent_scaling.py",
|
| 32 |
+
]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def build_world(spec):
|
| 36 |
+
world = historical_world(spec)
|
| 37 |
+
pool = world["train_composite"]
|
| 38 |
+
order = np.random.default_rng(spec["world"] + 880000).permutation(len(pool))
|
| 39 |
+
count = spec["composition_count"]
|
| 40 |
+
count = len(pool) if count == "all" else count
|
| 41 |
+
if isinstance(count, bool) or not isinstance(count, int) or not 0 < count <= len(pool):
|
| 42 |
+
raise ValueError("Composition count must be a positive prefix of the fixed pool")
|
| 43 |
+
world["available_composite"] = pool[order]
|
| 44 |
+
world["train_composite"] = world["available_composite"][:count].copy()
|
| 45 |
+
return world
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def construct(spec, device):
|
| 49 |
+
config = ModelConfig(
|
| 50 |
+
vocab_size=len(WORDS) + spec["heads_n"] + spec["bridges_n"] + spec["tails_n"],
|
| 51 |
+
width=spec["width"],
|
| 52 |
+
layers=spec["layers"],
|
| 53 |
+
heads=spec["heads"],
|
| 54 |
+
context=16,
|
| 55 |
+
)
|
| 56 |
+
torch.manual_seed(spec["initialization"])
|
| 57 |
+
# R=1 is ordinary GPT. The wrapper permits the same trained single block to
|
| 58 |
+
# be evaluated at other R, including the R=1 training baseline.
|
| 59 |
+
return LoopGPT(config, spec["repeats"], spec["dropout"], "legacy_unique").to(device)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def model_digest(model):
|
| 63 |
+
digest = hashlib.sha256()
|
| 64 |
+
for key, value in sorted(model.state_dict().items()):
|
| 65 |
+
digest.update(key.encode())
|
| 66 |
+
digest.update(value.detach().cpu().numpy().tobytes())
|
| 67 |
+
return digest.hexdigest()
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def run_name(spec):
|
| 71 |
+
return (
|
| 72 |
+
f"w{spec['world']}-i{spec['initialization']}-d{spec['width']}"
|
| 73 |
+
f"-l{spec['layers']}-r{spec['repeats']}-n{spec['composition_count']}-s{spec['steps']}"
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def role_coverage(world):
|
| 78 |
+
first = {(int(h), int(r)) for h, r, _b, _r2, _t in world["train_composite"]}
|
| 79 |
+
second = {(int(b), int(r)) for _h, _r1, b, r, _t in world["train_composite"]}
|
| 80 |
+
rows = world["familiar_test"]
|
| 81 |
+
return {
|
| 82 |
+
"first_atoms_used": len(first),
|
| 83 |
+
"second_atoms_used": len(second),
|
| 84 |
+
"familiar_both_composition_roles": float(
|
| 85 |
+
np.mean(
|
| 86 |
+
[
|
| 87 |
+
(int(h), int(r1)) in first and (int(b), int(r2)) in second
|
| 88 |
+
for h, r1, b, r2, _t in rows
|
| 89 |
+
]
|
| 90 |
+
)
|
| 91 |
+
),
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def train(spec, out, source, device="cuda:0"):
|
| 96 |
+
out = Path(out)
|
| 97 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 98 |
+
if (out / "latest.pt").exists() or (out / "complete.json").exists():
|
| 99 |
+
raise FileExistsError(f"Do not overwrite a training attempt: {out}")
|
| 100 |
+
if spec["nodes"][0] != 0 or spec["nodes"][-1] != spec["steps"]:
|
| 101 |
+
raise ValueError("Nodes must include initialization and the fixed endpoint")
|
| 102 |
+
if spec["nodes"] != sorted(set(spec["nodes"])) or spec["batch_size"] % 3:
|
| 103 |
+
raise ValueError("Nodes must increase and the batch must divide into three streams")
|
| 104 |
+
torch.set_num_threads(1)
|
| 105 |
+
torch.set_num_interop_threads(1)
|
| 106 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 107 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 108 |
+
torch.cuda.set_device(torch.device(device))
|
| 109 |
+
process_start = time.perf_counter()
|
| 110 |
+
world = build_world(spec)
|
| 111 |
+
np.savez_compressed(out / "world.npz", **world)
|
| 112 |
+
digest = data_digest(world)
|
| 113 |
+
write_json(out / "spec.json", {"spec": spec, "source": source, "data_sha256": digest})
|
| 114 |
+
model = construct(spec, device)
|
| 115 |
+
initial_digest = model_digest(model)
|
| 116 |
+
lr = torch.tensor(spec["lr"], device=device)
|
| 117 |
+
optimizer = make_optimizer(model, lr, spec["weight_decay"])
|
| 118 |
+
strata = [world["common_atomic"], world["train_composite"], world["anchor_atomic"]]
|
| 119 |
+
table = tuple(
|
| 120 |
+
torch.as_tensor(np.concatenate(parts), device=device)
|
| 121 |
+
for parts in zip(*(pack_sentences(rows) for rows in strata), strict=True)
|
| 122 |
+
)
|
| 123 |
+
sizes = [len(rows) for rows in strata]
|
| 124 |
+
offsets = np.cumsum([0, *sizes[:-1]])
|
| 125 |
+
streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)]
|
| 126 |
+
counts = [np.zeros(size, dtype=np.int64) for size in sizes]
|
| 127 |
+
batch = spec["batch_size"]
|
| 128 |
+
graph = FullTokenStep(model, optimizer, table, batch)
|
| 129 |
+
flop_step = flops(model.config, spec["repeats"], batch, 9, output_positions=9)
|
| 130 |
+
history, repeat_metrics, training_seconds, step = [], {}, 0.0, 0
|
| 131 |
+
|
| 132 |
+
def measure(loss=None):
|
| 133 |
+
metrics, predictions = evaluate(model, world, "low", device)
|
| 134 |
+
row = {
|
| 135 |
+
"step": step,
|
| 136 |
+
"lr": learning_rate(spec, step) if step else 0.0,
|
| 137 |
+
"metrics": metrics,
|
| 138 |
+
"loss": loss,
|
| 139 |
+
"training_seconds": training_seconds,
|
| 140 |
+
"estimated_training_flops": step * flop_step,
|
| 141 |
+
"composition_epochs": step * batch / 3 / sizes[1],
|
| 142 |
+
}
|
| 143 |
+
history.append(row)
|
| 144 |
+
write_json(out / "learning.json", history)
|
| 145 |
+
np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions)
|
| 146 |
+
if step in spec["repeat_nodes"]:
|
| 147 |
+
repeat_metrics[str(step)] = {}
|
| 148 |
+
for repeat in spec["test_repeats"]:
|
| 149 |
+
m, p = evaluate(model, world, "low", device, repeat)
|
| 150 |
+
repeat_metrics[str(step)][str(repeat)] = m
|
| 151 |
+
np.savez_compressed(out / f"repeat-{step:06d}-r{repeat:02d}.npz", **p)
|
| 152 |
+
write_json(out / "repeat-metrics.json", repeat_metrics)
|
| 153 |
+
state = {
|
| 154 |
+
"spec": spec,
|
| 155 |
+
"step": step,
|
| 156 |
+
"model": model.state_dict(),
|
| 157 |
+
"optimizer": optimizer.state_dict(),
|
| 158 |
+
"streams": [s.state_dict() for s in streams],
|
| 159 |
+
"counts": counts,
|
| 160 |
+
"cpu_rng": torch.get_rng_state(),
|
| 161 |
+
"cuda_rng": torch.cuda.get_rng_state(device),
|
| 162 |
+
"source": source,
|
| 163 |
+
"data_sha256": digest,
|
| 164 |
+
}
|
| 165 |
+
torch.save(state, out / "latest.tmp.pt")
|
| 166 |
+
(out / "latest.tmp.pt").replace(out / "latest.pt")
|
| 167 |
+
if step in spec["checkpoint_nodes"]:
|
| 168 |
+
torch.save(
|
| 169 |
+
{"spec": spec, "step": step, "model": model.state_dict()},
|
| 170 |
+
out / f"model-{step:06d}.pt",
|
| 171 |
+
)
|
| 172 |
+
write_json(out / "status.json", {"step": step, "budget": spec["steps"]})
|
| 173 |
+
print(
|
| 174 |
+
json.dumps(
|
| 175 |
+
{
|
| 176 |
+
"run": run_name(spec),
|
| 177 |
+
"step": step,
|
| 178 |
+
"atomic": metrics["common_atomic"]["accuracy"],
|
| 179 |
+
"train": metrics["train_composite"]["accuracy"],
|
| 180 |
+
"test": metrics["familiar_test"]["accuracy"],
|
| 181 |
+
}
|
| 182 |
+
),
|
| 183 |
+
flush=True,
|
| 184 |
+
)
|
| 185 |
+
return row
|
| 186 |
+
|
| 187 |
+
measure()
|
| 188 |
+
for end in spec["nodes"][1:]:
|
| 189 |
+
torch.cuda.synchronize()
|
| 190 |
+
started = time.perf_counter()
|
| 191 |
+
while step < end:
|
| 192 |
+
n = min(128, end - step)
|
| 193 |
+
indices = []
|
| 194 |
+
for i, stream in enumerate(streams):
|
| 195 |
+
drawn = stream.take(n * batch // 3).reshape(n, batch // 3)
|
| 196 |
+
counts[i] += np.bincount(drawn.ravel(), minlength=sizes[i])
|
| 197 |
+
indices.append(drawn + offsets[i])
|
| 198 |
+
indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device)
|
| 199 |
+
for j in range(n):
|
| 200 |
+
lr.fill_(learning_rate(spec, step + j + 1))
|
| 201 |
+
loss = graph(indices[j])
|
| 202 |
+
step += n
|
| 203 |
+
torch.cuda.synchronize()
|
| 204 |
+
training_seconds += time.perf_counter() - started
|
| 205 |
+
loss = float(loss)
|
| 206 |
+
if not np.isfinite(loss):
|
| 207 |
+
raise FloatingPointError(f"Nonfinite training loss at {step}")
|
| 208 |
+
endpoint = measure(loss)
|
| 209 |
+
np.savez_compressed(out / "exposures.npz", **{f"stratum{i}": c for i, c in enumerate(counts)})
|
| 210 |
+
result = {
|
| 211 |
+
"spec": spec,
|
| 212 |
+
"source": source,
|
| 213 |
+
"data_sha256": digest,
|
| 214 |
+
"initial_model_sha256": initial_digest,
|
| 215 |
+
"checkpoint_sha256": file_hash(out / "latest.pt"),
|
| 216 |
+
"finished_utc": utc(),
|
| 217 |
+
"parameters": sum(p.numel() for p in model.parameters()),
|
| 218 |
+
"independent_facts": sizes[0] + sizes[2],
|
| 219 |
+
"composition_examples": sizes[1],
|
| 220 |
+
"role_coverage": role_coverage(world),
|
| 221 |
+
"endpoint": endpoint,
|
| 222 |
+
"repeat_metrics": repeat_metrics,
|
| 223 |
+
"training_seconds": training_seconds,
|
| 224 |
+
"process_seconds": time.perf_counter() - process_start,
|
| 225 |
+
"supervised_tokens": step * batch * 23 // 3,
|
| 226 |
+
"padded_input_tokens": step * batch * 9,
|
| 227 |
+
"environment": {
|
| 228 |
+
"torch": torch.__version__,
|
| 229 |
+
"numpy": np.__version__,
|
| 230 |
+
"cuda": torch.version.cuda,
|
| 231 |
+
"gpu": torch.cuda.get_device_name(device),
|
| 232 |
+
"tf32": True,
|
| 233 |
+
},
|
| 234 |
+
}
|
| 235 |
+
write_json(out / "complete.json", result)
|
| 236 |
+
return result
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def compare_predictions(actual, saved):
|
| 240 |
+
maximum = 0.0
|
| 241 |
+
assert set(actual) == set(saved.files)
|
| 242 |
+
for key, value in actual.items():
|
| 243 |
+
if key.endswith("answer_nll"):
|
| 244 |
+
maximum = max(maximum, float(np.abs(value - saved[key]).max()))
|
| 245 |
+
np.testing.assert_allclose(value, saved[key], rtol=1e-5, atol=1e-5)
|
| 246 |
+
else:
|
| 247 |
+
np.testing.assert_array_equal(value, saved[key])
|
| 248 |
+
return maximum
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def compare_metrics(actual, saved):
|
| 252 |
+
for task, values in actual.items():
|
| 253 |
+
for key, value in values.items():
|
| 254 |
+
if key == "answer_nll":
|
| 255 |
+
np.testing.assert_allclose(value, saved[task][key], rtol=1e-5, atol=1e-5)
|
| 256 |
+
else:
|
| 257 |
+
assert value == saved[task][key]
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def audit(out, device="cuda:0"):
|
| 261 |
+
out = Path(out)
|
| 262 |
+
torch.set_num_threads(1)
|
| 263 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 264 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 265 |
+
torch.cuda.set_device(torch.device(device))
|
| 266 |
+
result = json.loads((out / "complete.json").read_text())
|
| 267 |
+
assert file_hash(out / "latest.pt") == result["checkpoint_sha256"]
|
| 268 |
+
saved = torch.load(out / "latest.pt", map_location=device, weights_only=False)
|
| 269 |
+
spec = saved["spec"]
|
| 270 |
+
world = build_world(spec)
|
| 271 |
+
assert data_digest(world) == result["data_sha256"] == saved["data_sha256"]
|
| 272 |
+
assert saved["step"] == spec["steps"]
|
| 273 |
+
model = construct(spec, device)
|
| 274 |
+
model.load_state_dict(saved["model"])
|
| 275 |
+
metrics, predictions = evaluate(model, world, "low", device)
|
| 276 |
+
compare_metrics(metrics, result["endpoint"]["metrics"])
|
| 277 |
+
maximum = compare_predictions(
|
| 278 |
+
predictions, np.load(out / f"predictions-{spec['steps']:06d}.npz")
|
| 279 |
+
)
|
| 280 |
+
repeat_checks = 0
|
| 281 |
+
for node, repeats in result["repeat_metrics"].items():
|
| 282 |
+
checkpoint = torch.load(
|
| 283 |
+
out / f"model-{int(node):06d}.pt", map_location=device, weights_only=False
|
| 284 |
+
)
|
| 285 |
+
model.load_state_dict(checkpoint["model"])
|
| 286 |
+
for repeat, expected in repeats.items():
|
| 287 |
+
actual, pred = evaluate(model, world, "low", device, int(repeat))
|
| 288 |
+
compare_metrics(actual, expected)
|
| 289 |
+
maximum = max(
|
| 290 |
+
maximum,
|
| 291 |
+
compare_predictions(
|
| 292 |
+
pred, np.load(out / f"repeat-{int(node):06d}-r{int(repeat):02d}.npz")
|
| 293 |
+
),
|
| 294 |
+
)
|
| 295 |
+
repeat_checks += 1
|
| 296 |
+
exposures = np.load(out / "exposures.npz")
|
| 297 |
+
for i in range(3):
|
| 298 |
+
np.testing.assert_array_equal(exposures[f"stratum{i}"], saved["counts"][i])
|
| 299 |
+
assert exposures[f"stratum{i}"].sum() == spec["steps"] * spec["batch_size"] // 3
|
| 300 |
+
assert np.ptp(exposures[f"stratum{i}"]) <= 1
|
| 301 |
+
checked = {
|
| 302 |
+
"passed": True,
|
| 303 |
+
"endpoint_tokens_exact": True,
|
| 304 |
+
"repeat_checks": repeat_checks,
|
| 305 |
+
"max_nll_difference": maximum,
|
| 306 |
+
"nll_rtol": 1e-5,
|
| 307 |
+
"nll_atol": 1e-5,
|
| 308 |
+
"utc": utc(),
|
| 309 |
+
}
|
| 310 |
+
write_json(out / "audit.json", checked)
|
| 311 |
+
return checked
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/latent_support.py
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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from latent_scaling.py at batch creation so
|
| 4 |
+
historical sources retain their frozen hashes. Architecture, optimizer, sentence
|
| 5 |
+
packing, evaluation and streams are reused; only build_world selects support.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
import time
|
| 12 |
+
from collections import Counter
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
import torch
|
| 17 |
+
|
| 18 |
+
from .grok_depth import EpochStream, make_optimizer, utc, write_json
|
| 19 |
+
from .grok_loop_model import flops
|
| 20 |
+
from .latent_scaling import (
|
| 21 |
+
SOURCE_FILES as HISTORICAL_SOURCES,
|
| 22 |
+
)
|
| 23 |
+
from .latent_scaling import (
|
| 24 |
+
build_world as scaling_world,
|
| 25 |
+
)
|
| 26 |
+
from .latent_scaling import (
|
| 27 |
+
compare_metrics,
|
| 28 |
+
compare_predictions,
|
| 29 |
+
construct,
|
| 30 |
+
model_digest,
|
| 31 |
+
role_coverage,
|
| 32 |
+
)
|
| 33 |
+
from .latent_scaling import (
|
| 34 |
+
run_name as scaling_run_name,
|
| 35 |
+
)
|
| 36 |
+
from .storage_composition import (
|
| 37 |
+
FullTokenStep,
|
| 38 |
+
audit_world,
|
| 39 |
+
data_digest,
|
| 40 |
+
evaluate,
|
| 41 |
+
file_hash,
|
| 42 |
+
pack_sentences,
|
| 43 |
+
)
|
| 44 |
+
from .storage_frontier import learning_rate
|
| 45 |
+
|
| 46 |
+
SOURCE_FILES = [*HISTORICAL_SOURCES, "src/llm_memory_editability/latent_support.py"]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def run_name(spec):
|
| 50 |
+
return scaling_run_name(spec) + "-support-" + spec["support"]
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def build_world(spec):
|
| 54 |
+
"""Select frozen legal edges; never use model scores or test pairs to choose."""
|
| 55 |
+
if spec.get("support") not in ("connected", "split"):
|
| 56 |
+
raise ValueError("Unknown frozen support arm")
|
| 57 |
+
indices = spec.get("composition_indices", [])
|
| 58 |
+
if (
|
| 59 |
+
len(indices) != 512
|
| 60 |
+
or any(isinstance(i, bool) or not isinstance(i, int) for i in indices)
|
| 61 |
+
or len(set(indices)) != 512
|
| 62 |
+
or indices != sorted(indices)
|
| 63 |
+
or spec.get("composition_count") != 512
|
| 64 |
+
):
|
| 65 |
+
raise ValueError("Support must contain 512 unique sorted integer indices")
|
| 66 |
+
world = scaling_world(dict(spec, composition_count="all"))
|
| 67 |
+
pool = world["available_composite"]
|
| 68 |
+
if indices[0] < 0 or indices[-1] >= len(pool):
|
| 69 |
+
raise ValueError("Support index outside the fixed available pool")
|
| 70 |
+
world["train_composite"] = pool[indices].copy()
|
| 71 |
+
if len(set(map(tuple, world["train_composite"]))) != 512:
|
| 72 |
+
raise ValueError("Support contains duplicate training chains")
|
| 73 |
+
audit_world(world)
|
| 74 |
+
expected = spec.get("frozen_data_sha256")
|
| 75 |
+
if expected is not None and data_digest(world) != expected:
|
| 76 |
+
raise RuntimeError("Rebuilt support data differ from the frozen digest")
|
| 77 |
+
return world
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def exposure_signature(world, counts=None):
|
| 81 |
+
"""Count actual sampled roles and column marginals, independently of streams."""
|
| 82 |
+
rows = world["train_composite"]
|
| 83 |
+
if counts is None:
|
| 84 |
+
counts = np.ones(len(rows), dtype=np.int64)
|
| 85 |
+
if len(counts) != len(rows):
|
| 86 |
+
raise ValueError("Exposure counter does not match the support")
|
| 87 |
+
first, second = Counter(), Counter()
|
| 88 |
+
columns = [Counter() for _ in range(5)]
|
| 89 |
+
for row, count in zip(rows, counts, strict=True):
|
| 90 |
+
h, r1, b, r2, _t = map(int, row)
|
| 91 |
+
first[f"{h}:{r1}"] += int(count)
|
| 92 |
+
second[f"{b}:{r2}"] += int(count)
|
| 93 |
+
for col, value in enumerate(row):
|
| 94 |
+
columns[col][str(int(value))] += int(count)
|
| 95 |
+
return {
|
| 96 |
+
"first_roles": dict(sorted(first.items())),
|
| 97 |
+
"second_roles": dict(sorted(second.items())),
|
| 98 |
+
"columns": [dict(sorted(c.items())) for c in columns],
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def support_components(world):
|
| 103 |
+
"""Independent adjacency traversal, including all available training roles."""
|
| 104 |
+
adjacency = {}
|
| 105 |
+
for h, r1, b, r2, _t in world["available_composite"]:
|
| 106 |
+
adjacency.setdefault(("l", int(h), int(r1)), set())
|
| 107 |
+
adjacency.setdefault(("r", int(b), int(r2)), set())
|
| 108 |
+
for h, r1, b, r2, _t in world["train_composite"]:
|
| 109 |
+
left, right = ("l", int(h), int(r1)), ("r", int(b), int(r2))
|
| 110 |
+
adjacency[left].add(right)
|
| 111 |
+
adjacency[right].add(left)
|
| 112 |
+
seen, components = set(), 0
|
| 113 |
+
for root in adjacency:
|
| 114 |
+
if root in seen:
|
| 115 |
+
continue
|
| 116 |
+
components += 1
|
| 117 |
+
stack = [root]
|
| 118 |
+
seen.add(root)
|
| 119 |
+
while stack:
|
| 120 |
+
for neighbour in adjacency[stack.pop()]:
|
| 121 |
+
if neighbour not in seen:
|
| 122 |
+
seen.add(neighbour)
|
| 123 |
+
stack.append(neighbour)
|
| 124 |
+
return {
|
| 125 |
+
"roles": len(adjacency),
|
| 126 |
+
"components": components,
|
| 127 |
+
"isolated_roles": sum(not neighbours for neighbours in adjacency.values()),
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def validate_nodes(spec):
|
| 132 |
+
if spec["batch_size"] != 192 or any(node % 8 for node in spec["nodes"]):
|
| 133 |
+
raise ValueError("Every measurement must complete the 512-chain epochs")
|
| 134 |
+
if not set(spec["repeat_nodes"]) <= set(spec["checkpoint_nodes"]) <= set(spec["nodes"]):
|
| 135 |
+
raise ValueError("Scans and checkpoints must use recorded learning nodes")
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def train(spec, out, source, device="cuda:0"):
|
| 139 |
+
validate_nodes(spec)
|
| 140 |
+
if "frozen_data_sha256" not in spec:
|
| 141 |
+
raise ValueError("Training requires a frozen data digest")
|
| 142 |
+
if any(file_hash(path) != digest for path, digest in source.items()):
|
| 143 |
+
raise RuntimeError("Training source differs from its frozen digest")
|
| 144 |
+
out = Path(out)
|
| 145 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 146 |
+
if (out / "latest.pt").exists() or (out / "complete.json").exists():
|
| 147 |
+
raise FileExistsError(f"Do not overwrite a training attempt: {out}")
|
| 148 |
+
if spec["nodes"][0] != 0 or spec["nodes"][-1] != spec["steps"]:
|
| 149 |
+
raise ValueError("Nodes must include initialization and the fixed endpoint")
|
| 150 |
+
if spec["nodes"] != sorted(set(spec["nodes"])) or spec["batch_size"] % 3:
|
| 151 |
+
raise ValueError("Nodes must increase and the batch must divide into three streams")
|
| 152 |
+
torch.set_num_threads(1)
|
| 153 |
+
torch.set_num_interop_threads(1)
|
| 154 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 155 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 156 |
+
torch.cuda.set_device(torch.device(device))
|
| 157 |
+
process_start = time.perf_counter()
|
| 158 |
+
world = build_world(spec)
|
| 159 |
+
np.savez_compressed(out / "world.npz", **world)
|
| 160 |
+
digest = data_digest(world)
|
| 161 |
+
write_json(out / "spec.json", {"spec": spec, "source": source, "data_sha256": digest})
|
| 162 |
+
model = construct(spec, device)
|
| 163 |
+
initial_digest = model_digest(model)
|
| 164 |
+
lr = torch.tensor(spec["lr"], device=device)
|
| 165 |
+
optimizer = make_optimizer(model, lr, spec["weight_decay"])
|
| 166 |
+
strata = [world["common_atomic"], world["train_composite"], world["anchor_atomic"]]
|
| 167 |
+
table = tuple(
|
| 168 |
+
torch.as_tensor(np.concatenate(parts), device=device)
|
| 169 |
+
for parts in zip(*(pack_sentences(rows) for rows in strata), strict=True)
|
| 170 |
+
)
|
| 171 |
+
sizes = [len(rows) for rows in strata]
|
| 172 |
+
offsets = np.cumsum([0, *sizes[:-1]])
|
| 173 |
+
streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)]
|
| 174 |
+
counts = [np.zeros(size, dtype=np.int64) for size in sizes]
|
| 175 |
+
batch = spec["batch_size"]
|
| 176 |
+
graph = FullTokenStep(model, optimizer, table, batch)
|
| 177 |
+
flop_step = flops(model.config, spec["repeats"], batch, 9, output_positions=9)
|
| 178 |
+
history, repeat_metrics, training_seconds, step = [], {}, 0.0, 0
|
| 179 |
+
|
| 180 |
+
def measure(loss=None):
|
| 181 |
+
if step and not np.all(counts[1] == step * batch // 3 // 512):
|
| 182 |
+
raise RuntimeError("Composition exposures must be exact complete epochs")
|
| 183 |
+
metrics, predictions = evaluate(model, world, "low", device)
|
| 184 |
+
row = {
|
| 185 |
+
"step": step,
|
| 186 |
+
"lr": learning_rate(spec, step) if step else 0.0,
|
| 187 |
+
"metrics": metrics,
|
| 188 |
+
"loss": loss,
|
| 189 |
+
"training_seconds": training_seconds,
|
| 190 |
+
"estimated_training_flops": step * flop_step,
|
| 191 |
+
"composition_epochs": step * batch / 3 / sizes[1],
|
| 192 |
+
}
|
| 193 |
+
history.append(row)
|
| 194 |
+
write_json(out / "learning.json", history)
|
| 195 |
+
np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions)
|
| 196 |
+
if step in spec["repeat_nodes"]:
|
| 197 |
+
repeat_metrics[str(step)] = {}
|
| 198 |
+
for repeat in spec["test_repeats"]:
|
| 199 |
+
m, p = evaluate(model, world, "low", device, repeat)
|
| 200 |
+
repeat_metrics[str(step)][str(repeat)] = m
|
| 201 |
+
np.savez_compressed(out / f"repeat-{step:06d}-r{repeat:02d}.npz", **p)
|
| 202 |
+
write_json(out / "repeat-metrics.json", repeat_metrics)
|
| 203 |
+
state = {
|
| 204 |
+
"spec": spec,
|
| 205 |
+
"step": step,
|
| 206 |
+
"model": model.state_dict(),
|
| 207 |
+
"optimizer": optimizer.state_dict(),
|
| 208 |
+
"streams": [s.state_dict() for s in streams],
|
| 209 |
+
"counts": counts,
|
| 210 |
+
"cpu_rng": torch.get_rng_state(),
|
| 211 |
+
"cuda_rng": torch.cuda.get_rng_state(device),
|
| 212 |
+
"source": source,
|
| 213 |
+
"data_sha256": digest,
|
| 214 |
+
}
|
| 215 |
+
torch.save(state, out / "latest.tmp.pt")
|
| 216 |
+
(out / "latest.tmp.pt").replace(out / "latest.pt")
|
| 217 |
+
if step in spec["checkpoint_nodes"]:
|
| 218 |
+
torch.save(
|
| 219 |
+
{"spec": spec, "step": step, "model": model.state_dict()},
|
| 220 |
+
out / f"model-{step:06d}.pt",
|
| 221 |
+
)
|
| 222 |
+
write_json(out / "status.json", {"step": step, "budget": spec["steps"]})
|
| 223 |
+
print(
|
| 224 |
+
json.dumps(
|
| 225 |
+
{
|
| 226 |
+
"run": run_name(spec),
|
| 227 |
+
"step": step,
|
| 228 |
+
"atomic": metrics["common_atomic"]["accuracy"],
|
| 229 |
+
"train": metrics["train_composite"]["accuracy"],
|
| 230 |
+
"test": metrics["familiar_test"]["accuracy"],
|
| 231 |
+
}
|
| 232 |
+
),
|
| 233 |
+
flush=True,
|
| 234 |
+
)
|
| 235 |
+
return row
|
| 236 |
+
|
| 237 |
+
measure()
|
| 238 |
+
for end in spec["nodes"][1:]:
|
| 239 |
+
torch.cuda.synchronize()
|
| 240 |
+
started = time.perf_counter()
|
| 241 |
+
while step < end:
|
| 242 |
+
n = min(128, end - step)
|
| 243 |
+
indices = []
|
| 244 |
+
for i, stream in enumerate(streams):
|
| 245 |
+
drawn = stream.take(n * batch // 3).reshape(n, batch // 3)
|
| 246 |
+
counts[i] += np.bincount(drawn.ravel(), minlength=sizes[i])
|
| 247 |
+
indices.append(drawn + offsets[i])
|
| 248 |
+
indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device)
|
| 249 |
+
for j in range(n):
|
| 250 |
+
lr.fill_(learning_rate(spec, step + j + 1))
|
| 251 |
+
loss = graph(indices[j])
|
| 252 |
+
step += n
|
| 253 |
+
torch.cuda.synchronize()
|
| 254 |
+
training_seconds += time.perf_counter() - started
|
| 255 |
+
loss = float(loss)
|
| 256 |
+
if not np.isfinite(loss):
|
| 257 |
+
raise FloatingPointError(f"Nonfinite training loss at {step}")
|
| 258 |
+
endpoint = measure(loss)
|
| 259 |
+
np.savez_compressed(out / "exposures.npz", **{f"stratum{i}": c for i, c in enumerate(counts)})
|
| 260 |
+
result = {
|
| 261 |
+
"spec": spec,
|
| 262 |
+
"source": source,
|
| 263 |
+
"data_sha256": digest,
|
| 264 |
+
"initial_model_sha256": initial_digest,
|
| 265 |
+
"checkpoint_sha256": file_hash(out / "latest.pt"),
|
| 266 |
+
"finished_utc": utc(),
|
| 267 |
+
"parameters": sum(p.numel() for p in model.parameters()),
|
| 268 |
+
"independent_facts": sizes[0] + sizes[2],
|
| 269 |
+
"composition_examples": sizes[1],
|
| 270 |
+
"role_coverage": role_coverage(world),
|
| 271 |
+
"support_components": support_components(world),
|
| 272 |
+
"support_exposures": exposure_signature(world, counts[1]),
|
| 273 |
+
"endpoint": endpoint,
|
| 274 |
+
"repeat_metrics": repeat_metrics,
|
| 275 |
+
"training_seconds": training_seconds,
|
| 276 |
+
"process_seconds": time.perf_counter() - process_start,
|
| 277 |
+
"supervised_tokens": step * batch * 23 // 3,
|
| 278 |
+
"padded_input_tokens": step * batch * 9,
|
| 279 |
+
"environment": {
|
| 280 |
+
"torch": torch.__version__,
|
| 281 |
+
"numpy": np.__version__,
|
| 282 |
+
"cuda": torch.version.cuda,
|
| 283 |
+
"gpu": torch.cuda.get_device_name(device),
|
| 284 |
+
"tf32": True,
|
| 285 |
+
},
|
| 286 |
+
}
|
| 287 |
+
write_json(out / "complete.json", result)
|
| 288 |
+
return result
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def audit(out, device="cuda:0"):
|
| 292 |
+
out = Path(out)
|
| 293 |
+
torch.set_num_threads(1)
|
| 294 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 295 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 296 |
+
torch.cuda.set_device(torch.device(device))
|
| 297 |
+
result = json.loads((out / "complete.json").read_text())
|
| 298 |
+
assert file_hash(out / "latest.pt") == result["checkpoint_sha256"]
|
| 299 |
+
saved = torch.load(out / "latest.pt", map_location=device, weights_only=False)
|
| 300 |
+
recorded = json.loads((out / "spec.json").read_text())
|
| 301 |
+
assert saved["spec"] == result["spec"] == recorded["spec"]
|
| 302 |
+
assert saved["source"] == result["source"] == recorded["source"]
|
| 303 |
+
assert all(file_hash(path) == digest for path, digest in result["source"].items())
|
| 304 |
+
spec = saved["spec"]
|
| 305 |
+
validate_nodes(spec)
|
| 306 |
+
assert "frozen_data_sha256" in spec
|
| 307 |
+
world = build_world(spec)
|
| 308 |
+
assert data_digest(world) == result["data_sha256"] == saved["data_sha256"]
|
| 309 |
+
assert data_digest(world) == recorded["data_sha256"] == spec["frozen_data_sha256"]
|
| 310 |
+
with np.load(out / "world.npz") as archived:
|
| 311 |
+
assert set(archived.files) == set(world)
|
| 312 |
+
for key, rows in world.items():
|
| 313 |
+
np.testing.assert_array_equal(rows, archived[key])
|
| 314 |
+
assert saved["step"] == spec["steps"]
|
| 315 |
+
model = construct(spec, device)
|
| 316 |
+
assert model_digest(model) == result["initial_model_sha256"]
|
| 317 |
+
model.load_state_dict(saved["model"])
|
| 318 |
+
metrics, predictions = evaluate(model, world, "low", device)
|
| 319 |
+
compare_metrics(metrics, result["endpoint"]["metrics"])
|
| 320 |
+
maximum = compare_predictions(
|
| 321 |
+
predictions, np.load(out / f"predictions-{spec['steps']:06d}.npz")
|
| 322 |
+
)
|
| 323 |
+
repeat_checks = 0
|
| 324 |
+
for node, repeats in result["repeat_metrics"].items():
|
| 325 |
+
checkpoint = torch.load(
|
| 326 |
+
out / f"model-{int(node):06d}.pt", map_location=device, weights_only=False
|
| 327 |
+
)
|
| 328 |
+
assert checkpoint["spec"] == spec and checkpoint["step"] == int(node)
|
| 329 |
+
model.load_state_dict(checkpoint["model"])
|
| 330 |
+
for repeat, expected in repeats.items():
|
| 331 |
+
actual, pred = evaluate(model, world, "low", device, int(repeat))
|
| 332 |
+
compare_metrics(actual, expected)
|
| 333 |
+
maximum = max(
|
| 334 |
+
maximum,
|
| 335 |
+
compare_predictions(
|
| 336 |
+
pred, np.load(out / f"repeat-{int(node):06d}-r{int(repeat):02d}.npz")
|
| 337 |
+
),
|
| 338 |
+
)
|
| 339 |
+
repeat_checks += 1
|
| 340 |
+
exposures = np.load(out / "exposures.npz")
|
| 341 |
+
for i in range(3):
|
| 342 |
+
np.testing.assert_array_equal(exposures[f"stratum{i}"], saved["counts"][i])
|
| 343 |
+
assert exposures[f"stratum{i}"].sum() == spec["steps"] * spec["batch_size"] // 3
|
| 344 |
+
assert np.ptp(exposures[f"stratum{i}"]) <= 1
|
| 345 |
+
composition_counts = exposures["stratum1"]
|
| 346 |
+
assert np.all(composition_counts == spec["steps"] * spec["batch_size"] // 3 // 512)
|
| 347 |
+
assert exposure_signature(world, composition_counts) == result["support_exposures"]
|
| 348 |
+
assert support_components(world) == result["support_components"]
|
| 349 |
+
checked = {
|
| 350 |
+
"frozen_data_exact": True,
|
| 351 |
+
"archived_world_exact": True,
|
| 352 |
+
"composition_complete_epochs": True,
|
| 353 |
+
"role_exposures_exact": True,
|
| 354 |
+
"passed": True,
|
| 355 |
+
"endpoint_tokens_exact": True,
|
| 356 |
+
"repeat_checks": repeat_checks,
|
| 357 |
+
"max_nll_difference": maximum,
|
| 358 |
+
"nll_rtol": 1e-5,
|
| 359 |
+
"nll_atol": 1e-5,
|
| 360 |
+
"utc": utc(),
|
| 361 |
+
}
|
| 362 |
+
write_json(out / "audit.json", checked)
|
| 363 |
+
return checked
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/low_rank.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fully observed matrix representability; no training or editing algorithm.
|
| 2 |
+
|
| 3 |
+
The best approximation minimizes unweighted Frobenius error over *all* entries.
|
| 4 |
+
It need not preserve unchanged facts exactly or prioritize requested edits.
|
| 5 |
+
Numerical rank uses an absolute singular-value threshold, not an exact-rank proof.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from numbers import Integral, Real
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _matrix(value: Any, name: str = "matrix") -> np.ndarray:
|
| 15 |
+
"""Convert a nonempty, finite, real numeric matrix to float64."""
|
| 16 |
+
try:
|
| 17 |
+
raw = np.asarray(value)
|
| 18 |
+
except (TypeError, ValueError) as exc:
|
| 19 |
+
raise ValueError(f"{name} must be a rectangular real numeric matrix") from exc
|
| 20 |
+
if raw.ndim != 2 or 0 in raw.shape:
|
| 21 |
+
raise ValueError(f"{name} must be a nonempty two-dimensional matrix")
|
| 22 |
+
if raw.dtype.kind not in "iuf":
|
| 23 |
+
raise ValueError(f"{name} must contain real numeric values")
|
| 24 |
+
with np.errstate(over="ignore", invalid="ignore"):
|
| 25 |
+
result = raw.astype(np.float64)
|
| 26 |
+
if not np.isfinite(result).all():
|
| 27 |
+
raise ValueError(f"{name} must contain finite float64 values")
|
| 28 |
+
return result
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _rank(value: Any, shape: tuple[int, int]) -> int:
|
| 32 |
+
if isinstance(value, (bool, np.bool_)) or not isinstance(value, Integral):
|
| 33 |
+
raise ValueError("rank must be a nonnegative integer")
|
| 34 |
+
if not 0 <= value <= min(shape):
|
| 35 |
+
raise ValueError(f"rank must be between 0 and {min(shape)}")
|
| 36 |
+
return int(value)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _tolerance(value: Any) -> float:
|
| 40 |
+
if isinstance(value, (bool, np.bool_)) or not isinstance(value, Real):
|
| 41 |
+
raise ValueError("atol must be a finite positive real number")
|
| 42 |
+
value = float(value)
|
| 43 |
+
if not np.isfinite(value) or value <= 0:
|
| 44 |
+
raise ValueError("atol must be a finite positive real number")
|
| 45 |
+
return value
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def numerical_rank(matrix: Any, atol: float = 1e-10) -> int:
|
| 49 |
+
"""Count singular values strictly greater than the absolute tolerance."""
|
| 50 |
+
array = _matrix(matrix)
|
| 51 |
+
tolerance = _tolerance(atol)
|
| 52 |
+
return int(np.count_nonzero(np.linalg.svd(array, compute_uv=False) > tolerance))
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def best_rank_approximation(matrix: Any, rank: int) -> np.ndarray:
|
| 56 |
+
"""Return a best rank-at-most-``rank`` Frobenius approximation using SVD.
|
| 57 |
+
|
| 58 |
+
``rank`` may be zero and may not exceed the smaller matrix dimension.
|
| 59 |
+
The returned matrix is independent of the input. Tied singular values can
|
| 60 |
+
make the optimum nonunique; NumPy's SVD selects one such optimum.
|
| 61 |
+
"""
|
| 62 |
+
array = _matrix(matrix)
|
| 63 |
+
budget = _rank(rank, array.shape)
|
| 64 |
+
left, values, right = np.linalg.svd(array, full_matrices=False)
|
| 65 |
+
return (left[:, :budget] * values[:budget]) @ right[:budget, :]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def representation_gap(matrix: Any, rank: int, atol: float = 1e-10) -> int:
|
| 69 |
+
"""Return max(0, numerical target rank minus the available rank budget)."""
|
| 70 |
+
array = _matrix(matrix)
|
| 71 |
+
budget = _rank(rank, array.shape)
|
| 72 |
+
return max(0, numerical_rank(array, atol=atol) - budget)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def evaluate_update(original: Any, target: Any, rank: int, atol: float = 1e-10) -> dict[str, Any]:
|
| 76 |
+
"""Report an update's analytical optimum under a fixed total rank budget.
|
| 77 |
+
|
| 78 |
+
``original`` and ``target`` must have identical shapes. The target is fitted
|
| 79 |
+
directly, with no optimization path or restriction on the update rank.
|
| 80 |
+
``squared_error_lower_bound`` is the sum of discarded squared singular
|
| 81 |
+
values (Eckart–Young–Mirsky); floating-point residuals may differ slightly.
|
| 82 |
+
|
| 83 |
+
Edited entries are exactly those where original and target differ. ``atol``
|
| 84 |
+
affects rank estimates only. RMSE is measured against the target separately
|
| 85 |
+
on edited and retained entries; an empty group is represented by ``None``.
|
| 86 |
+
The retained-entry metric measures collateral error at this global optimum,
|
| 87 |
+
not the side effects of a learned editing algorithm.
|
| 88 |
+
"""
|
| 89 |
+
before = _matrix(original, "original")
|
| 90 |
+
after = _matrix(target, "target")
|
| 91 |
+
if before.shape != after.shape:
|
| 92 |
+
raise ValueError("original and target must have identical shapes")
|
| 93 |
+
budget = _rank(rank, after.shape)
|
| 94 |
+
tolerance = _tolerance(atol)
|
| 95 |
+
with np.errstate(over="ignore", invalid="ignore"):
|
| 96 |
+
delta = _matrix(after - before, "target - original")
|
| 97 |
+
left, values, right = np.linalg.svd(after, full_matrices=False)
|
| 98 |
+
reconstruction = (left[:, :budget] * values[:budget]) @ right[:budget, :]
|
| 99 |
+
residual = reconstruction - after
|
| 100 |
+
edited = before != after
|
| 101 |
+
target_rank = int(np.count_nonzero(values > tolerance))
|
| 102 |
+
gap = max(0, target_rank - budget)
|
| 103 |
+
error = float(np.linalg.norm(residual, ord="fro"))
|
| 104 |
+
lower_bound = float(np.sum(values[budget:] ** 2))
|
| 105 |
+
|
| 106 |
+
def group_rmse(mask: np.ndarray) -> float | None:
|
| 107 |
+
return float(np.linalg.norm(residual[mask]) / np.sqrt(mask.sum())) if mask.any() else None
|
| 108 |
+
|
| 109 |
+
report = {
|
| 110 |
+
"rank_budget": budget,
|
| 111 |
+
"atol": tolerance,
|
| 112 |
+
"original_rank": numerical_rank(before, tolerance),
|
| 113 |
+
"target_rank": target_rank,
|
| 114 |
+
"delta_rank": numerical_rank(delta, tolerance),
|
| 115 |
+
"representation_gap": gap,
|
| 116 |
+
"representable_within_rank_tolerance": gap == 0,
|
| 117 |
+
"edit_count": int(edited.sum()),
|
| 118 |
+
"original": before.tolist(),
|
| 119 |
+
"target": after.tolist(),
|
| 120 |
+
"delta": delta.tolist(),
|
| 121 |
+
"reconstruction": reconstruction.tolist(),
|
| 122 |
+
"singular_values": values.tolist(),
|
| 123 |
+
"frobenius_error": error,
|
| 124 |
+
"squared_frobenius_error": error**2,
|
| 125 |
+
"squared_error_lower_bound": lower_bound,
|
| 126 |
+
"edited_entry_rmse": group_rmse(edited),
|
| 127 |
+
"retained_entry_rmse": group_rmse(~edited),
|
| 128 |
+
}
|
| 129 |
+
metrics = [
|
| 130 |
+
error,
|
| 131 |
+
error**2,
|
| 132 |
+
lower_bound,
|
| 133 |
+
report["edited_entry_rmse"],
|
| 134 |
+
report["retained_entry_rmse"],
|
| 135 |
+
]
|
| 136 |
+
if not all(value is None or np.isfinite(value) for value in metrics):
|
| 137 |
+
raise ValueError("matrix scale exceeds finite float64 error metrics; rescale the inputs")
|
| 138 |
+
return report
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/memory_reuse.py
ADDED
|
@@ -0,0 +1,469 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Learned two-hop retrieval followed by an independently fitted memory swap.
|
| 2 |
+
|
| 3 |
+
The pinned author implementation supplies the SwiGLU memory and GPT blocks.
|
| 4 |
+
Only attention Q/K are learned by the reader. Replacement facts are never used
|
| 5 |
+
by its optimizer, and all evaluation uses continuous intermediate states.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
import time
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
import torch
|
| 17 |
+
from torch.nn import functional as F
|
| 18 |
+
|
| 19 |
+
from llm_memory_editability import hebbian_interface as interface
|
| 20 |
+
|
| 21 |
+
ARMS = ("ce", "aligned")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def sha(path):
|
| 25 |
+
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def write_json(path, value):
|
| 29 |
+
path = Path(path)
|
| 30 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 31 |
+
temporary = path.with_suffix(path.suffix + ".tmp")
|
| 32 |
+
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n")
|
| 33 |
+
temporary.replace(path)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def cpu_state(model):
|
| 37 |
+
return {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def hash_state(model, *, reader_only=False):
|
| 41 |
+
return interface.tensor_hash(
|
| 42 |
+
{k: v for k, v in model.state_dict().items() if not reader_only or ".mlp." not in k}
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def build_world(spec, seed):
|
| 47 |
+
"""Geometry, content and held-out heads use independent local random streams."""
|
| 48 |
+
n, d, j = spec["num_entities"], spec["d_model"], spec["junk_vocab_size"]
|
| 49 |
+
rng = np.random.default_rng(seed)
|
| 50 |
+
embeddings = rng.standard_normal((n + j + 1, d)).astype(np.float32)
|
| 51 |
+
embeddings /= np.linalg.norm(embeddings, axis=-1, keepdims=True)
|
| 52 |
+
mapping_a = np.arange(n + j + 1, dtype=np.int64)
|
| 53 |
+
mapping_b = mapping_a.copy()
|
| 54 |
+
mapping_a[:n] = rng.permutation(n)
|
| 55 |
+
for _ in range(10000):
|
| 56 |
+
candidate = rng.permutation(n)
|
| 57 |
+
if np.all(candidate != mapping_a[:n]):
|
| 58 |
+
mapping_b[:n] = candidate
|
| 59 |
+
break
|
| 60 |
+
else:
|
| 61 |
+
raise RuntimeError("Failed to draw a changed independent permutation")
|
| 62 |
+
order = np.random.default_rng(seed + 20000).permutation(n)
|
| 63 |
+
n_train = int(n * spec["train_head_fraction"])
|
| 64 |
+
if not 0 < n_train <= n:
|
| 65 |
+
raise ValueError("Composition-training head fraction must lie in (0, 1]")
|
| 66 |
+
train_mask = np.zeros(n, dtype=bool)
|
| 67 |
+
train_mask[order[:n_train]] = True
|
| 68 |
+
return {
|
| 69 |
+
"embeddings": embeddings,
|
| 70 |
+
"mapping_A": mapping_a,
|
| 71 |
+
"mapping_B": mapping_b,
|
| 72 |
+
"train_mask": train_mask,
|
| 73 |
+
"seed": np.asarray(seed),
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def data_audit(spec, world):
|
| 78 |
+
n, j = spec["num_entities"], spec["junk_vocab_size"]
|
| 79 |
+
for name in ("A", "B"):
|
| 80 |
+
mapping = world[f"mapping_{name}"]
|
| 81 |
+
assert np.array_equal(np.sort(mapping[:n]), np.arange(n))
|
| 82 |
+
assert np.array_equal(mapping[n:], np.arange(n, n + j + 1))
|
| 83 |
+
assert np.all(world["mapping_A"][:n] != world["mapping_B"][:n])
|
| 84 |
+
np.testing.assert_allclose(np.linalg.norm(world["embeddings"], axis=-1), 1, atol=2e-7)
|
| 85 |
+
assert world["train_mask"].sum() == int(n * spec["train_head_fraction"])
|
| 86 |
+
a, b = world["mapping_A"], world["mapping_B"]
|
| 87 |
+
return {
|
| 88 |
+
"entities": n,
|
| 89 |
+
"neutral_tokens": j + 1,
|
| 90 |
+
"A_composition_training_heads": int(world["train_mask"].sum()),
|
| 91 |
+
"A_composition_heldout_heads": int((~world["train_mask"]).sum()),
|
| 92 |
+
"changed_atomic_facts": int((a[:n] != b[:n]).sum()),
|
| 93 |
+
"changed_composite_answers": int((a[a[:n]] != b[b[:n]]).sum()),
|
| 94 |
+
"passed": True,
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def make_inputs(spec, repeats, seed):
|
| 99 |
+
"""Each head occurs once per repeat; contexts contain only neutral tokens."""
|
| 100 |
+
n, j, length = spec["num_entities"], spec["junk_vocab_size"], spec["junk_length"]
|
| 101 |
+
rng = np.random.default_rng(seed)
|
| 102 |
+
keys = np.tile(np.arange(n, dtype=np.int64), repeats)
|
| 103 |
+
inputs = rng.integers(n, n + j, (len(keys), length + 2), dtype=np.int64)
|
| 104 |
+
positions = rng.integers(0, length + 1, len(keys))
|
| 105 |
+
inputs[np.arange(len(keys)), positions] = keys
|
| 106 |
+
inputs[:, -1] = n + j
|
| 107 |
+
return inputs, keys
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def new_memory(spec, init, device):
|
| 111 |
+
cfg = {**interface.DEFAULT_SPEC, **spec}
|
| 112 |
+
interface._source(cfg)
|
| 113 |
+
torch.manual_seed(init)
|
| 114 |
+
return interface._new_memory(cfg, device)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class TwoHopReader(torch.nn.Module):
|
| 118 |
+
"""Two causal attention blocks with one shared, frozen fact MLP."""
|
| 119 |
+
|
| 120 |
+
def __init__(self, spec, embeddings, memory, init, device):
|
| 121 |
+
super().__init__()
|
| 122 |
+
interface._source(spec)
|
| 123 |
+
from hebbian.transformer.model import GPT, GPTConfig
|
| 124 |
+
|
| 125 |
+
torch.manual_seed(init + 100000)
|
| 126 |
+
cfg = GPTConfig(
|
| 127 |
+
block_size=spec["junk_length"] + 2,
|
| 128 |
+
vocab_size=len(embeddings),
|
| 129 |
+
n_layer=2,
|
| 130 |
+
n_head=1,
|
| 131 |
+
n_embd=spec["d_model"],
|
| 132 |
+
dropout=0.0,
|
| 133 |
+
bias=False,
|
| 134 |
+
mlp_residual=False,
|
| 135 |
+
attn_residual=False,
|
| 136 |
+
use_rope=False,
|
| 137 |
+
no_positional_encoding=True,
|
| 138 |
+
mlp_norm_type="unit_rmsnorm",
|
| 139 |
+
attn_norm_type="rmsnorm",
|
| 140 |
+
lm_head_norm_type="unit_rmsnorm",
|
| 141 |
+
tie_embeddings=True,
|
| 142 |
+
freeze_value_dense_identity=True,
|
| 143 |
+
use_identity_mlp=True,
|
| 144 |
+
)
|
| 145 |
+
self.gpt = GPT(cfg).to(device)
|
| 146 |
+
with torch.no_grad():
|
| 147 |
+
self.gpt.transformer.wte.weight.copy_(torch.as_tensor(embeddings, device=device))
|
| 148 |
+
self.install(memory)
|
| 149 |
+
self.gpt.requires_grad_(False)
|
| 150 |
+
for block in self.gpt.transformer.h:
|
| 151 |
+
block.attn.c_q.requires_grad_(True)
|
| 152 |
+
block.attn.c_k.requires_grad_(True)
|
| 153 |
+
self.scale = spec["readout_scale"]
|
| 154 |
+
|
| 155 |
+
def install(self, memory):
|
| 156 |
+
memory.requires_grad_(False)
|
| 157 |
+
for block in self.gpt.transformer.h:
|
| 158 |
+
block.mlp = memory
|
| 159 |
+
|
| 160 |
+
def forward(self, inputs):
|
| 161 |
+
x = self.gpt.transformer.wte(inputs)
|
| 162 |
+
logits = []
|
| 163 |
+
for block in self.gpt.transformer.h:
|
| 164 |
+
x = block(x)
|
| 165 |
+
z = self.gpt.transformer.ln_f(x[:, -1])
|
| 166 |
+
logits.append(self.scale * self.gpt.lm_head(z))
|
| 167 |
+
return torch.stack(logits, dim=1)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def memory_objective(output, embeddings, labels, arm, alignment_weight):
|
| 171 |
+
ce = F.cross_entropy(output @ embeddings.T, labels)
|
| 172 |
+
alignment = (output - embeddings[labels]).square().sum(-1).mean()
|
| 173 |
+
return ce + (alignment_weight if arm == "aligned" else 0.0) * alignment
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
@torch.no_grad()
|
| 177 |
+
def clean_memory(memory, embeddings, mapping, n):
|
| 178 |
+
output = memory(embeddings)
|
| 179 |
+
cosine = F.normalize(output, dim=-1) @ embeddings.T
|
| 180 |
+
pred = cosine.argmax(-1)
|
| 181 |
+
return {
|
| 182 |
+
"atomic_accuracy": float(pred[:n].eq(mapping[:n]).float().mean()),
|
| 183 |
+
"neutral_accuracy": float(pred[n:].eq(mapping[n:]).float().mean()),
|
| 184 |
+
"target_cosine": float(cosine[torch.arange(n, device=mapping.device), mapping[:n]].mean()),
|
| 185 |
+
"output_norm": float(output[:n].norm(dim=-1).mean()),
|
| 186 |
+
"vector_squared_error": float(
|
| 187 |
+
(output[:n] - embeddings[mapping[:n]]).square().sum(-1).mean()
|
| 188 |
+
),
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def fit_memory(spec, world, mapping_name, arm, init, device, output_dir):
|
| 193 |
+
"""Only atomic labels appear here, including for the replacement memory."""
|
| 194 |
+
path = output_dir / f"memory-{mapping_name}.pt"
|
| 195 |
+
if path.exists():
|
| 196 |
+
payload = torch.load(path, map_location="cpu", weights_only=True)
|
| 197 |
+
model = new_memory(spec, init, device)
|
| 198 |
+
model.load_state_dict(payload["state_dict"])
|
| 199 |
+
record = dict(payload["record"], reused_checkpoint=True)
|
| 200 |
+
return model.requires_grad_(False).eval(), record
|
| 201 |
+
memory = new_memory(spec, init, device)
|
| 202 |
+
embeddings = torch.as_tensor(world["embeddings"], device=device)
|
| 203 |
+
labels = torch.as_tensor(world[f"mapping_{mapping_name}"], device=device)
|
| 204 |
+
optimizer = torch.optim.Adam(memory.parameters(), lr=spec["memory_lr"], foreach=False)
|
| 205 |
+
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
|
| 206 |
+
optimizer, spec["memory_steps"], eta_min=spec["memory_min_lr"]
|
| 207 |
+
)
|
| 208 |
+
initial_hash = hash_state(memory)
|
| 209 |
+
curve = []
|
| 210 |
+
began = time.perf_counter()
|
| 211 |
+
for step in range(spec["memory_steps"] + 1):
|
| 212 |
+
if step in spec["memory_nodes"]:
|
| 213 |
+
metrics = clean_memory(memory, embeddings, labels, spec["num_entities"])
|
| 214 |
+
metrics.update(step=step, seconds=time.perf_counter() - began)
|
| 215 |
+
curve.append(metrics)
|
| 216 |
+
write_json(output_dir / f"memory-{mapping_name}-curve.json", curve)
|
| 217 |
+
print(json.dumps(dict(stage=f"memory-{mapping_name}", arm=arm, **metrics)), flush=True)
|
| 218 |
+
if step == spec["memory_steps"]:
|
| 219 |
+
break
|
| 220 |
+
memory.train()
|
| 221 |
+
optimizer.zero_grad(set_to_none=True)
|
| 222 |
+
loss = memory_objective(
|
| 223 |
+
memory(embeddings), embeddings, labels, arm, spec["alignment_weight"]
|
| 224 |
+
)
|
| 225 |
+
loss.backward()
|
| 226 |
+
optimizer.step()
|
| 227 |
+
scheduler.step()
|
| 228 |
+
if device.type == "cuda":
|
| 229 |
+
torch.cuda.synchronize(device)
|
| 230 |
+
memory.eval().requires_grad_(False)
|
| 231 |
+
record = dict(
|
| 232 |
+
initial_hash=initial_hash,
|
| 233 |
+
final_hash=hash_state(memory),
|
| 234 |
+
steps=spec["memory_steps"],
|
| 235 |
+
seconds=time.perf_counter() - began,
|
| 236 |
+
metrics=clean_memory(memory, embeddings, labels, spec["num_entities"]),
|
| 237 |
+
)
|
| 238 |
+
torch.save(dict(state_dict=cpu_state(memory), record=record), path)
|
| 239 |
+
return memory, record
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
@torch.no_grad()
|
| 243 |
+
def evaluate(reader, inputs, device, batch_size):
|
| 244 |
+
reader.eval()
|
| 245 |
+
return np.concatenate(
|
| 246 |
+
[
|
| 247 |
+
reader(torch.as_tensor(inputs[start : start + batch_size], device=device)).cpu().numpy()
|
| 248 |
+
for start in range(0, len(inputs), batch_size)
|
| 249 |
+
]
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def accuracy(pred, target, mask=None):
|
| 254 |
+
correct = pred == target
|
| 255 |
+
if mask is not None:
|
| 256 |
+
correct = correct[mask]
|
| 257 |
+
return float(correct.mean()) if len(correct) else None
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def score_logits(logits, world, keys, mapping_name):
|
| 261 |
+
"""Full-pool scores and explicitly labelled prerequisite/changed subsets."""
|
| 262 |
+
pred = logits.argmax(-1)
|
| 263 |
+
mapping = world[f"mapping_{mapping_name}"]
|
| 264 |
+
y1, y2 = mapping[keys], mapping[mapping[keys]]
|
| 265 |
+
train = world["train_mask"][keys]
|
| 266 |
+
a, b = world["mapping_A"], world["mapping_B"]
|
| 267 |
+
changed = a[a[keys]] != b[b[keys]]
|
| 268 |
+
n = len(world["train_mask"])
|
| 269 |
+
# Inputs are arranged as complete n-head repeats; find each actual successor.
|
| 270 |
+
successor_row = np.arange(len(keys)) // n * n + mapping[keys]
|
| 271 |
+
assert np.array_equal(keys[successor_row], mapping[keys])
|
| 272 |
+
known = (pred[:, 0] == y1) & (pred[successor_row, 0] == mapping[mapping[keys]])
|
| 273 |
+
return {
|
| 274 |
+
"n": len(keys),
|
| 275 |
+
"one_hop": accuracy(pred[:, 0], y1),
|
| 276 |
+
"two_hop": accuracy(pred[:, 1], y2),
|
| 277 |
+
"two_hop_A_training_heads": accuracy(pred[:, 1], y2, train),
|
| 278 |
+
"two_hop_A_heldout_heads": accuracy(pred[:, 1], y2, ~train),
|
| 279 |
+
"two_hop_changed": accuracy(pred[:, 1], y2, changed),
|
| 280 |
+
"changed_n": int(changed.sum()),
|
| 281 |
+
"two_hop_both_atoms_correct": accuracy(pred[:, 1], y2, known),
|
| 282 |
+
"both_atoms_correct_n": int(known.sum()),
|
| 283 |
+
"both_atoms_correct_coverage": float(known.mean()),
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def reader_loss(logits, targets, train_mask):
|
| 288 |
+
return (
|
| 289 |
+
F.cross_entropy(logits[:, 0], targets[:, 0])
|
| 290 |
+
+ F.cross_entropy(logits[train_mask, 1], targets[train_mask, 1])
|
| 291 |
+
) / 2
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def fit_reader(spec, world, memory, init, device, output_dir):
|
| 295 |
+
reader = TwoHopReader(spec, world["embeddings"], memory, init, device)
|
| 296 |
+
path = output_dir / "reader-A.pt"
|
| 297 |
+
if path.exists():
|
| 298 |
+
payload = torch.load(path, map_location="cpu", weights_only=True)
|
| 299 |
+
reader.load_state_dict(payload["state_dict"])
|
| 300 |
+
return reader.eval(), payload["record"]
|
| 301 |
+
initial_hash = hash_state(reader, reader_only=True)
|
| 302 |
+
frozen_before = interface.tensor_hash(
|
| 303 |
+
{k: p for k, p in reader.named_parameters() if not p.requires_grad}
|
| 304 |
+
)
|
| 305 |
+
n = spec["num_entities"]
|
| 306 |
+
seed = int(world["seed"])
|
| 307 |
+
train_inputs, _ = make_inputs(spec, spec["reader_steps"], seed + 30000)
|
| 308 |
+
stream_hash = hashlib.sha256(train_inputs.tobytes()).hexdigest()
|
| 309 |
+
train_inputs = torch.as_tensor(
|
| 310 |
+
train_inputs.reshape(-1, n, spec["junk_length"] + 2), device=device
|
| 311 |
+
)
|
| 312 |
+
mapping = torch.as_tensor(world["mapping_A"], device=device)
|
| 313 |
+
targets = torch.stack((mapping[:n], mapping[mapping[:n]]), dim=1)
|
| 314 |
+
train_mask = torch.as_tensor(world["train_mask"], device=device)
|
| 315 |
+
eval_inputs, eval_keys = make_inputs(spec, spec["eval_repeats"], seed + 40000)
|
| 316 |
+
parameters = [p for p in reader.parameters() if p.requires_grad]
|
| 317 |
+
optimizer = torch.optim.AdamW(
|
| 318 |
+
parameters, lr=spec["reader_lr"], weight_decay=spec["reader_weight_decay"], foreach=False
|
| 319 |
+
)
|
| 320 |
+
curve = []
|
| 321 |
+
began = time.perf_counter()
|
| 322 |
+
for step in range(spec["reader_steps"] + 1):
|
| 323 |
+
if step in spec["reader_nodes"]:
|
| 324 |
+
logits = evaluate(reader, eval_inputs, device, n)
|
| 325 |
+
metrics = score_logits(logits, world, eval_keys, "A")
|
| 326 |
+
curve.append(dict(step=step, seconds=time.perf_counter() - began, **metrics))
|
| 327 |
+
np.savez_compressed(output_dir / f"reader-node-{step:05d}.npz", logits=logits)
|
| 328 |
+
torch.save(cpu_state(reader), output_dir / f"reader-node-{step:05d}.pt")
|
| 329 |
+
write_json(output_dir / "reader-curve.json", curve)
|
| 330 |
+
print(json.dumps(dict(stage="reader", step=step, **metrics)), flush=True)
|
| 331 |
+
if step == spec["reader_steps"]:
|
| 332 |
+
break
|
| 333 |
+
reader.train()
|
| 334 |
+
optimizer.zero_grad(set_to_none=True)
|
| 335 |
+
loss = reader_loss(reader(train_inputs[step]), targets, train_mask)
|
| 336 |
+
loss.backward()
|
| 337 |
+
optimizer.step()
|
| 338 |
+
if device.type == "cuda":
|
| 339 |
+
torch.cuda.synchronize(device)
|
| 340 |
+
frozen_after = interface.tensor_hash(
|
| 341 |
+
{k: p for k, p in reader.named_parameters() if not p.requires_grad}
|
| 342 |
+
)
|
| 343 |
+
assert frozen_before == frozen_after, "Frozen facts or embeddings changed"
|
| 344 |
+
record = dict(
|
| 345 |
+
initial_hash=initial_hash,
|
| 346 |
+
final_hash=hash_state(reader, reader_only=True),
|
| 347 |
+
frozen_hash=frozen_after,
|
| 348 |
+
stream_hash=stream_hash,
|
| 349 |
+
steps=spec["reader_steps"],
|
| 350 |
+
seconds=time.perf_counter() - began,
|
| 351 |
+
trainable_names=[k for k, p in reader.named_parameters() if p.requires_grad],
|
| 352 |
+
trainable_parameters=sum(p.numel() for p in parameters),
|
| 353 |
+
total_parameters=sum(p.numel() for p in reader.parameters()),
|
| 354 |
+
metrics=curve[-1],
|
| 355 |
+
)
|
| 356 |
+
torch.save(dict(state_dict=cpu_state(reader), record=record), path)
|
| 357 |
+
return reader.eval(), record
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def run(spec, world_seed, init, arm, output_dir, device):
|
| 361 |
+
if arm not in ARMS:
|
| 362 |
+
raise ValueError(arm)
|
| 363 |
+
output_dir = Path(output_dir)
|
| 364 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 365 |
+
device = torch.device(device)
|
| 366 |
+
torch.set_num_threads(spec["cpu_threads"])
|
| 367 |
+
torch.backends.cuda.matmul.allow_tf32 = False
|
| 368 |
+
torch.backends.cudnn.allow_tf32 = False
|
| 369 |
+
if device.type == "cuda":
|
| 370 |
+
torch.cuda.set_device(device)
|
| 371 |
+
torch.cuda.reset_peak_memory_stats(device)
|
| 372 |
+
world = build_world(spec, world_seed)
|
| 373 |
+
np.savez_compressed(output_dir / "world.npz", **world)
|
| 374 |
+
write_json(output_dir / "spec.json", spec)
|
| 375 |
+
audit = data_audit(spec, world)
|
| 376 |
+
started = time.perf_counter()
|
| 377 |
+
result = dict(
|
| 378 |
+
world=world_seed, init=init, arm=arm, spec=spec, data_audit=audit, status="running"
|
| 379 |
+
)
|
| 380 |
+
write_json(output_dir / "status.json", result)
|
| 381 |
+
memory_a, a_record = fit_memory(spec, world, "A", arm, init, device, output_dir)
|
| 382 |
+
reader, reader_record = fit_reader(spec, world, memory_a, init, device, output_dir)
|
| 383 |
+
# Replacement fitting happens only after the A reader has finished.
|
| 384 |
+
memory_b, b_record = fit_memory(spec, world, "B", arm, init, device, output_dir)
|
| 385 |
+
inputs, keys = make_inputs(spec, spec["eval_repeats"], world_seed + 40000)
|
| 386 |
+
logits_a = evaluate(reader, inputs, device, spec["num_entities"])
|
| 387 |
+
non_memory_hash = hash_state(reader, reader_only=True)
|
| 388 |
+
reader.requires_grad_(False)
|
| 389 |
+
reader.install(memory_b)
|
| 390 |
+
logits_b = evaluate(reader, inputs, device, spec["num_entities"])
|
| 391 |
+
assert hash_state(reader, reader_only=True) == non_memory_hash
|
| 392 |
+
assert reader.gpt.transformer.h[0].mlp is reader.gpt.transformer.h[1].mlp
|
| 393 |
+
assert hash_state(memory_b) == b_record["final_hash"]
|
| 394 |
+
embeddings = torch.as_tensor(world["embeddings"], device=device)
|
| 395 |
+
with torch.no_grad():
|
| 396 |
+
memory_arrays = {
|
| 397 |
+
f"memory_{name}_output": mem(embeddings).cpu().numpy()
|
| 398 |
+
for name, mem in (("A", memory_a), ("B", memory_b))
|
| 399 |
+
}
|
| 400 |
+
np.savez_compressed(
|
| 401 |
+
output_dir / "endpoints.npz",
|
| 402 |
+
inputs=inputs,
|
| 403 |
+
keys=keys,
|
| 404 |
+
logits_A=logits_a,
|
| 405 |
+
logits_B=logits_b,
|
| 406 |
+
**memory_arrays,
|
| 407 |
+
)
|
| 408 |
+
# Store a full swapped endpoint to permit a genuinely independent reload.
|
| 409 |
+
torch.save(dict(state_dict=cpu_state(reader)), output_dir / "reader-B.pt")
|
| 410 |
+
endpoints = {
|
| 411 |
+
"A": score_logits(logits_a, world, keys, "A"),
|
| 412 |
+
"B": score_logits(logits_b, world, keys, "B"),
|
| 413 |
+
"wrong_A_on_B": score_logits(logits_a, world, keys, "B"),
|
| 414 |
+
}
|
| 415 |
+
length, d, h, vocab = (
|
| 416 |
+
spec["junk_length"] + 2,
|
| 417 |
+
spec["d_model"],
|
| 418 |
+
spec["hidden_dim"],
|
| 419 |
+
len(embeddings),
|
| 420 |
+
)
|
| 421 |
+
# Approximate multiply-add FLOPs. Backprop through frozen MLP still costs work.
|
| 422 |
+
memory_flops = 2 * spec["memory_steps"] * (18 * vocab * d * h + 6 * vocab**2 * d)
|
| 423 |
+
reader_flops = spec["reader_steps"] * (
|
| 424 |
+
2
|
| 425 |
+
* (
|
| 426 |
+
24 * spec["num_entities"] * length * d**2
|
| 427 |
+
+ 12 * spec["num_entities"] * length**2 * d
|
| 428 |
+
+ 12 * spec["num_entities"] * length * d * h
|
| 429 |
+
)
|
| 430 |
+
)
|
| 431 |
+
result.update(
|
| 432 |
+
status="complete",
|
| 433 |
+
memories=dict(A=a_record, B=b_record),
|
| 434 |
+
reader=reader_record,
|
| 435 |
+
endpoints=endpoints,
|
| 436 |
+
assertions=dict(
|
| 437 |
+
frozen_reader_after_swap=True, shared_memory=True, no_B_reader_training=True
|
| 438 |
+
),
|
| 439 |
+
seconds=time.perf_counter() - started,
|
| 440 |
+
budget=dict(
|
| 441 |
+
memory_updates=sum(
|
| 442 |
+
spec["memory_steps"]
|
| 443 |
+
for r in (a_record, b_record)
|
| 444 |
+
if not r.get("reused_checkpoint", False)
|
| 445 |
+
),
|
| 446 |
+
reused_memory_updates=sum(
|
| 447 |
+
spec["memory_steps"]
|
| 448 |
+
for r in (a_record, b_record)
|
| 449 |
+
if r.get("reused_checkpoint", False)
|
| 450 |
+
),
|
| 451 |
+
reader_updates=spec["reader_steps"],
|
| 452 |
+
atomic_exposures=sum(
|
| 453 |
+
spec["memory_steps"] * spec["num_entities"]
|
| 454 |
+
for r in (a_record, b_record)
|
| 455 |
+
if not r.get("reused_checkpoint", False)
|
| 456 |
+
),
|
| 457 |
+
reader_input_tokens=spec["reader_steps"] * spec["num_entities"] * length,
|
| 458 |
+
reader_supervised_answers=spec["reader_steps"]
|
| 459 |
+
* (spec["num_entities"] + int(world["train_mask"].sum())),
|
| 460 |
+
approximate_matmul_flops=reader_flops
|
| 461 |
+
+ memory_flops
|
| 462 |
+
* sum(not r.get("reused_checkpoint", False) for r in (a_record, b_record))
|
| 463 |
+
/ 2,
|
| 464 |
+
peak_gpu_bytes=torch.cuda.max_memory_allocated(device) if device.type == "cuda" else 0,
|
| 465 |
+
),
|
| 466 |
+
)
|
| 467 |
+
write_json(output_dir / "summary.json", result)
|
| 468 |
+
write_json(output_dir / "status.json", dict(status="complete", seconds=result["seconds"]))
|
| 469 |
+
return result
|
docs/development-artifacts/composition-data-curves-v1/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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Width, composition experience and compute depth in complete causal GPT models.
|
| 2 |
+
|
| 3 |
+
The data, full-token objective and generation scoring extend ``depth_step``.
|
| 4 |
+
Support arms use nested training paths and identical held-out evaluation pools;
|
| 5 |
+
four independent streams keep atomics and each hop length at 32 draws per step.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import copy
|
| 11 |
+
import hashlib
|
| 12 |
+
import json
|
| 13 |
+
import time
|
| 14 |
+
from functools import lru_cache
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import torch
|
| 19 |
+
from torch.nn import functional as F
|
| 20 |
+
|
| 21 |
+
from . import depth_step
|
| 22 |
+
from .depth_step import ( # noqa: F401 -- public interface reused by checkpoint analysis
|
| 23 |
+
BOS,
|
| 24 |
+
DATA_DEFAULTS,
|
| 25 |
+
ENTITY_OFFSET,
|
| 26 |
+
EOS,
|
| 27 |
+
EVALUATION_SPLITS,
|
| 28 |
+
HOPS,
|
| 29 |
+
PAD,
|
| 30 |
+
TRAIN_SPLITS,
|
| 31 |
+
compare_metrics,
|
| 32 |
+
compare_predictions,
|
| 33 |
+
construct,
|
| 34 |
+
data_digest,
|
| 35 |
+
evaluate,
|
| 36 |
+
generate_rows,
|
| 37 |
+
pack_rows,
|
| 38 |
+
prompt_rows,
|
| 39 |
+
truth_path_details,
|
| 40 |
+
)
|
| 41 |
+
from .grok_depth import EpochStream, make_optimizer, utc, write_json
|
| 42 |
+
from .grok_loop_model import flops
|
| 43 |
+
from .latent_scaling import model_digest
|
| 44 |
+
from .storage_composition import FullTokenStep, file_hash
|
| 45 |
+
from .storage_frontier import learning_rate
|
| 46 |
+
|
| 47 |
+
SUPPORT_LEVELS = (1.0, 4.0)
|
| 48 |
+
ARCHITECTURES = ((2, 1), (4, 1), (1, 2), (1, 4))
|
| 49 |
+
COMMON_SPLITS = ("atomic",) + tuple(
|
| 50 |
+
f"{split}_{hop}" for hop in HOPS for split in ("familiar", "strict")
|
| 51 |
+
)
|
| 52 |
+
SOURCE_FILES = [
|
| 53 |
+
*depth_step.SOURCE_FILES,
|
| 54 |
+
"src/llm_memory_editability/multihop_scaling.py",
|
| 55 |
+
"scripts/run_multihop_scaling.py",
|
| 56 |
+
"scripts/execute_multihop_scaling.py",
|
| 57 |
+
"tests/test_multihop_scaling.py",
|
| 58 |
+
]
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@lru_cache(maxsize=16)
|
| 62 |
+
def _reference_world(seed, settings):
|
| 63 |
+
return depth_step.build_world({"world_seed": seed, **dict(settings), "phi": 4.0})
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _reference(spec):
|
| 67 |
+
seed = spec.get("world_seed", spec.get("world"))
|
| 68 |
+
if seed is None:
|
| 69 |
+
raise ValueError("A fixed world_seed is required")
|
| 70 |
+
settings = tuple(
|
| 71 |
+
(key, spec.get(key, value)) for key, value in DATA_DEFAULTS.items() if key != "phi"
|
| 72 |
+
)
|
| 73 |
+
return _reference_world(int(seed), settings)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def common_evaluation_digest(world):
|
| 77 |
+
digest = hashlib.sha256()
|
| 78 |
+
for name in COMMON_SPLITS:
|
| 79 |
+
rows = world[name]
|
| 80 |
+
digest.update(name.encode())
|
| 81 |
+
digest.update(np.asarray(rows.shape, dtype="<i8").tobytes())
|
| 82 |
+
digest.update(rows.astype("<i8", copy=False).tobytes())
|
| 83 |
+
digest.update(json.dumps(world["metadata"]["id_mask"]).encode())
|
| 84 |
+
return digest.hexdigest()
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def build_world(spec):
|
| 88 |
+
phi = float(spec.get("phi", 4.0))
|
| 89 |
+
if phi not in SUPPORT_LEVELS:
|
| 90 |
+
raise ValueError("Support phi must be 1 or 4")
|
| 91 |
+
reference = _reference(spec)
|
| 92 |
+
world = {name: reference[name].copy() for name in EVALUATION_SPLITS}
|
| 93 |
+
metadata = copy.deepcopy(reference["metadata"])
|
| 94 |
+
metadata.pop("dataset_sha256", None)
|
| 95 |
+
metadata.pop("independent_audit", None)
|
| 96 |
+
ids = sum(metadata["id_mask"])
|
| 97 |
+
selections = {}
|
| 98 |
+
for hop in HOPS:
|
| 99 |
+
name = f"train_{hop}"
|
| 100 |
+
count = min(round(phi * ids), len(reference[name]))
|
| 101 |
+
world[name] = reference[name][:count].copy()
|
| 102 |
+
selections[str(hop)] = {
|
| 103 |
+
"requested": round(phi * ids),
|
| 104 |
+
"actual": count,
|
| 105 |
+
"effective_phi": count / ids if ids else None,
|
| 106 |
+
"high_support_count": len(reference[name]),
|
| 107 |
+
"capped": round(phi * ids) > len(reference[name]),
|
| 108 |
+
"prefix_indices": list(range(count)),
|
| 109 |
+
}
|
| 110 |
+
# Preserve source lineage without duplicating descriptive source statistics.
|
| 111 |
+
metadata["source_worlds"] = {
|
| 112 |
+
hop: {
|
| 113 |
+
key: values[key]
|
| 114 |
+
for key in (
|
| 115 |
+
"seed",
|
| 116 |
+
"hops",
|
| 117 |
+
"dataset_sha256",
|
| 118 |
+
"counts",
|
| 119 |
+
"phi_requested",
|
| 120 |
+
"phi_actual",
|
| 121 |
+
"train_composite_capped",
|
| 122 |
+
"id_paths_total",
|
| 123 |
+
"all_paths_total",
|
| 124 |
+
"source_url",
|
| 125 |
+
"source_commit",
|
| 126 |
+
"source_file",
|
| 127 |
+
"source_license",
|
| 128 |
+
)
|
| 129 |
+
}
|
| 130 |
+
for hop, values in metadata["source_worlds"].items()
|
| 131 |
+
}
|
| 132 |
+
metadata.update(
|
| 133 |
+
phi=phi,
|
| 134 |
+
reference_phi=4.0,
|
| 135 |
+
reference_dataset_sha256=reference["metadata"]["dataset_sha256"],
|
| 136 |
+
composition_support=selections,
|
| 137 |
+
support_selection="Prefix of each phi=4 training array; no resampling of facts or tests",
|
| 138 |
+
exposure_contract="32 atomic + 32 each of 2/3/4-hop examples per step",
|
| 139 |
+
training_objective="All nonpadding next tokens including EOS; no intermediate targets",
|
| 140 |
+
)
|
| 141 |
+
world["metadata"] = metadata
|
| 142 |
+
metadata["common_evaluation_sha256"] = common_evaluation_digest(world)
|
| 143 |
+
checked = audit_world(world)
|
| 144 |
+
metadata["dataset_sha256"] = checked["dataset_sha256"]
|
| 145 |
+
metadata["independent_audit"] = checked
|
| 146 |
+
expected = spec.get("frozen_data_sha256")
|
| 147 |
+
if expected is not None and expected != checked["dataset_sha256"]:
|
| 148 |
+
raise ValueError("Rebuilt data differ from the frozen specification")
|
| 149 |
+
expected_common = spec.get("common_evaluation_sha256")
|
| 150 |
+
if expected_common is not None and expected_common != metadata["common_evaluation_sha256"]:
|
| 151 |
+
raise ValueError("Common evaluation pools differ from the frozen specification")
|
| 152 |
+
return world
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def audit_world(world):
|
| 156 |
+
checked = depth_step.audit_world(world)
|
| 157 |
+
metadata = world["metadata"]
|
| 158 |
+
phi = metadata["phi"]
|
| 159 |
+
if phi not in SUPPORT_LEVELS or metadata.get("reference_phi") != 4.0:
|
| 160 |
+
raise ValueError("Invalid nested support contract")
|
| 161 |
+
reference = _reference(metadata)
|
| 162 |
+
ids = sum(metadata["id_mask"])
|
| 163 |
+
for name in EVALUATION_SPLITS:
|
| 164 |
+
expected = reference[name]
|
| 165 |
+
if name.startswith("train_"):
|
| 166 |
+
expected = expected[: min(round(phi * ids), len(expected))]
|
| 167 |
+
if not np.array_equal(world[name], expected):
|
| 168 |
+
raise ValueError("Common pools/nested support differ from reference: " + name)
|
| 169 |
+
common = common_evaluation_digest(world)
|
| 170 |
+
if common != metadata["common_evaluation_sha256"]:
|
| 171 |
+
raise ValueError("Common evaluation digest differs")
|
| 172 |
+
if reference["metadata"]["dataset_sha256"] != metadata["reference_dataset_sha256"]:
|
| 173 |
+
raise ValueError("High-support reference differs")
|
| 174 |
+
return {
|
| 175 |
+
**checked,
|
| 176 |
+
"low_support_is_high_support_prefix": True,
|
| 177 |
+
"same_atomic_id_ood_and_heldout_pools_across_support": True,
|
| 178 |
+
"common_evaluation_sha256": common,
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def run_name(spec):
|
| 183 |
+
seed = spec.get("world_seed", spec.get("world"))
|
| 184 |
+
return (
|
| 185 |
+
f"w{seed}-i{spec['initialization']}-d{spec['width']}-phi{spec['phi']:g}"
|
| 186 |
+
f"-l{spec['layers']}-r{spec['repeats']}-s{spec['steps']}"
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def _validate_spec(spec):
|
| 191 |
+
depth_step._validate_spec(spec)
|
| 192 |
+
if float(spec["phi"]) not in SUPPORT_LEVELS:
|
| 193 |
+
raise ValueError("Unsupported composition support")
|
| 194 |
+
if (spec["layers"], spec["repeats"]) not in ARCHITECTURES:
|
| 195 |
+
raise ValueError("Unsupported architecture")
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def _check_source(source):
|
| 199 |
+
depth_step._check_source(source)
|
| 200 |
+
required = {"src/llm_memory_editability/multihop_scaling.py", *depth_step.SOURCE_FILES}
|
| 201 |
+
if not required <= set(source):
|
| 202 |
+
raise RuntimeError("Source lock omits experiment dependencies")
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def _validate_output(out):
|
| 206 |
+
depth_step._validate_output(out)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def _device_setup(device):
|
| 210 |
+
device = torch.device(device)
|
| 211 |
+
torch.set_num_threads(1)
|
| 212 |
+
# Standalone workers call this once; CPU integration checks may call twice.
|
| 213 |
+
try:
|
| 214 |
+
torch.set_num_interop_threads(1)
|
| 215 |
+
except RuntimeError:
|
| 216 |
+
pass
|
| 217 |
+
if device.type == "cuda":
|
| 218 |
+
torch.cuda.set_device(device)
|
| 219 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 220 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 221 |
+
return device
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
class _CpuStep:
|
| 225 |
+
"""Same objective and optimizer groups for inexpensive engineering checks."""
|
| 226 |
+
|
| 227 |
+
def __init__(self, model, optimizer, table, clip):
|
| 228 |
+
self.model, self.optimizer, self.table, self.clip = model, optimizer, table, clip
|
| 229 |
+
|
| 230 |
+
def __call__(self, indices):
|
| 231 |
+
self.optimizer.zero_grad(set_to_none=True)
|
| 232 |
+
tokens, labels = (part[indices] for part in self.table)
|
| 233 |
+
logits = self.model(tokens)
|
| 234 |
+
loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100)
|
| 235 |
+
loss.backward()
|
| 236 |
+
torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True)
|
| 237 |
+
self.optimizer.step()
|
| 238 |
+
return loss.detach()
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def _synchronize(device):
|
| 242 |
+
if device.type == "cuda":
|
| 243 |
+
torch.cuda.synchronize(device)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def train(spec, out, source, device="cuda:0"):
|
| 247 |
+
_validate_spec(spec)
|
| 248 |
+
_check_source(source)
|
| 249 |
+
if "frozen_data_sha256" not in spec or "common_evaluation_sha256" not in spec:
|
| 250 |
+
raise ValueError("Training requires frozen data and common evaluation hashes")
|
| 251 |
+
out = Path(out)
|
| 252 |
+
_validate_output(out)
|
| 253 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 254 |
+
device = _device_setup(device)
|
| 255 |
+
started_process = time.perf_counter()
|
| 256 |
+
world = build_world(spec)
|
| 257 |
+
digest = data_digest(world)
|
| 258 |
+
depth_step._save_world(out, world)
|
| 259 |
+
write_json(out / "spec.json", {"spec": spec, "source": source, "data_sha256": digest})
|
| 260 |
+
model = construct(spec, device)
|
| 261 |
+
initial_digest = model_digest(model)
|
| 262 |
+
if spec.get("initial_model_sha256", initial_digest) != initial_digest:
|
| 263 |
+
raise AssertionError("Frozen initialization differs")
|
| 264 |
+
lr = torch.tensor(spec["lr"], device=device)
|
| 265 |
+
if device.type == "cuda":
|
| 266 |
+
optimizer = make_optimizer(model, lr, spec["weight_decay"])
|
| 267 |
+
else:
|
| 268 |
+
optimizer = torch.optim.AdamW(
|
| 269 |
+
[
|
| 270 |
+
{
|
| 271 |
+
"params": [p for p in model.parameters() if p.ndim >= 2],
|
| 272 |
+
"weight_decay": spec["weight_decay"],
|
| 273 |
+
},
|
| 274 |
+
{"params": [p for p in model.parameters() if p.ndim < 2], "weight_decay": 0.0},
|
| 275 |
+
],
|
| 276 |
+
lr=lr,
|
| 277 |
+
betas=(0.9, 0.999),
|
| 278 |
+
eps=1e-8,
|
| 279 |
+
)
|
| 280 |
+
sizes = [len(world[name]) for name in TRAIN_SPLITS]
|
| 281 |
+
if any(size == 0 for size in sizes):
|
| 282 |
+
raise ValueError("Do not reroll a world with an empty sampled training stratum")
|
| 283 |
+
packed = [
|
| 284 |
+
pack_rows(world[name], separator=world["metadata"]["separator_token"])
|
| 285 |
+
for name in TRAIN_SPLITS
|
| 286 |
+
]
|
| 287 |
+
table = tuple(
|
| 288 |
+
torch.as_tensor(np.concatenate(parts), device=device) for parts in zip(*packed, strict=True)
|
| 289 |
+
)
|
| 290 |
+
offsets = np.cumsum([0, *sizes[:-1]])
|
| 291 |
+
streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)]
|
| 292 |
+
counts = [np.zeros(size, dtype=np.int64) for size in sizes]
|
| 293 |
+
if device.type == "cuda":
|
| 294 |
+
graph = FullTokenStep(
|
| 295 |
+
model, optimizer, table, spec["batch_size"], clip=spec.get("clip", 1.0)
|
| 296 |
+
)
|
| 297 |
+
else:
|
| 298 |
+
graph = _CpuStep(model, optimizer, table, spec.get("clip", 1.0))
|
| 299 |
+
flop_step = flops(model.config, spec["repeats"], spec["batch_size"], 8, output_positions=8)
|
| 300 |
+
token_step = 32 * sum(int((labels[0] >= 0).sum()) for _, labels in packed)
|
| 301 |
+
history, step, training_seconds = [], 0, 0.0
|
| 302 |
+
|
| 303 |
+
def measure(loss=None):
|
| 304 |
+
metrics, predictions = evaluate(model, world, device)
|
| 305 |
+
row = {
|
| 306 |
+
"step": step,
|
| 307 |
+
"lr": learning_rate(spec, step) if step else 0.0,
|
| 308 |
+
"metrics": metrics,
|
| 309 |
+
"loss": loss,
|
| 310 |
+
"training_seconds": training_seconds,
|
| 311 |
+
"estimated_training_flops": step * flop_step,
|
| 312 |
+
"supervised_tokens": step * token_step,
|
| 313 |
+
"padded_input_tokens": step * spec["batch_size"] * 8,
|
| 314 |
+
}
|
| 315 |
+
history.append(row)
|
| 316 |
+
write_json(out / "learning.json", history)
|
| 317 |
+
np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions)
|
| 318 |
+
np.savez_compressed(
|
| 319 |
+
out / f"exposures-{step:06d}.npz",
|
| 320 |
+
**dict(zip(TRAIN_SPLITS, counts, strict=True)),
|
| 321 |
+
)
|
| 322 |
+
state = {
|
| 323 |
+
"spec": spec,
|
| 324 |
+
"step": step,
|
| 325 |
+
"model": model.state_dict(),
|
| 326 |
+
"optimizer": optimizer.state_dict(),
|
| 327 |
+
"streams": [s.state_dict() for s in streams],
|
| 328 |
+
"counts": counts,
|
| 329 |
+
"cpu_rng": torch.get_rng_state(),
|
| 330 |
+
"cuda_rng": torch.cuda.get_rng_state(device) if device.type == "cuda" else None,
|
| 331 |
+
"source": source,
|
| 332 |
+
"data_sha256": digest,
|
| 333 |
+
}
|
| 334 |
+
torch.save(state, out / "latest.tmp.pt")
|
| 335 |
+
(out / "latest.tmp.pt").replace(out / "latest.pt")
|
| 336 |
+
if step in spec["checkpoint_nodes"]:
|
| 337 |
+
torch.save(
|
| 338 |
+
{"spec": spec, "step": step, "model": model.state_dict()},
|
| 339 |
+
out / f"model-{step:06d}.pt",
|
| 340 |
+
)
|
| 341 |
+
write_json(out / "status.json", {"step": step, "budget": spec["steps"]})
|
| 342 |
+
print(
|
| 343 |
+
json.dumps(
|
| 344 |
+
{
|
| 345 |
+
"run": run_name(spec),
|
| 346 |
+
"step": step,
|
| 347 |
+
"atomic": metrics["atomic"]["accuracy"],
|
| 348 |
+
"familiar": {str(hop): metrics[f"familiar_{hop}"]["accuracy"] for hop in HOPS},
|
| 349 |
+
}
|
| 350 |
+
),
|
| 351 |
+
flush=True,
|
| 352 |
+
)
|
| 353 |
+
return row
|
| 354 |
+
|
| 355 |
+
measure()
|
| 356 |
+
endpoint = history[0]
|
| 357 |
+
for end in spec["nodes"][1:]:
|
| 358 |
+
_synchronize(device)
|
| 359 |
+
started = time.perf_counter()
|
| 360 |
+
while step < end:
|
| 361 |
+
updates = min(128, end - step)
|
| 362 |
+
indices = []
|
| 363 |
+
for i, stream in enumerate(streams):
|
| 364 |
+
draws = stream.take(updates * 32).reshape(updates, 32)
|
| 365 |
+
counts[i] += np.bincount(draws.ravel(), minlength=sizes[i])
|
| 366 |
+
indices.append(draws + offsets[i])
|
| 367 |
+
indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device)
|
| 368 |
+
for j in range(updates):
|
| 369 |
+
lr.fill_(learning_rate(spec, step + j + 1))
|
| 370 |
+
loss = graph(indices[j])
|
| 371 |
+
step += updates
|
| 372 |
+
_synchronize(device)
|
| 373 |
+
training_seconds += time.perf_counter() - started
|
| 374 |
+
loss_value = float(loss)
|
| 375 |
+
if not np.isfinite(loss_value):
|
| 376 |
+
raise FloatingPointError("Nonfinite loss at step " + str(step))
|
| 377 |
+
endpoint = measure(loss_value)
|
| 378 |
+
np.savez_compressed(out / "exposures.npz", **dict(zip(TRAIN_SPLITS, counts, strict=True)))
|
| 379 |
+
result = {
|
| 380 |
+
"spec": spec,
|
| 381 |
+
"source": source,
|
| 382 |
+
"data_sha256": digest,
|
| 383 |
+
"common_evaluation_sha256": world["metadata"]["common_evaluation_sha256"],
|
| 384 |
+
"initial_model_sha256": initial_digest,
|
| 385 |
+
"checkpoint_sha256": file_hash(out / "latest.pt"),
|
| 386 |
+
"finished_utc": utc(),
|
| 387 |
+
"parameters": sum(p.numel() for p in model.parameters()),
|
| 388 |
+
"architecture": "loop" if spec["repeats"] > 1 else "standard",
|
| 389 |
+
"effective_depth": spec["layers"] * spec["repeats"],
|
| 390 |
+
"strata_counts": dict(zip(TRAIN_SPLITS, sizes, strict=True)),
|
| 391 |
+
"endpoint": endpoint,
|
| 392 |
+
"supervised_tokens": step * token_step,
|
| 393 |
+
"padded_input_tokens": step * spec["batch_size"] * 8,
|
| 394 |
+
"estimated_training_flops": step * flop_step,
|
| 395 |
+
"training_seconds": training_seconds,
|
| 396 |
+
"process_seconds": time.perf_counter() - started_process,
|
| 397 |
+
"environment": {
|
| 398 |
+
"torch": torch.__version__,
|
| 399 |
+
"numpy": np.__version__,
|
| 400 |
+
"cuda": torch.version.cuda,
|
| 401 |
+
"device": str(device),
|
| 402 |
+
"gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None,
|
| 403 |
+
"tf32": device.type == "cuda",
|
| 404 |
+
},
|
| 405 |
+
}
|
| 406 |
+
write_json(out / "complete.json", result)
|
| 407 |
+
return result
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def audit(out, device="cuda:0"):
|
| 411 |
+
out = Path(out)
|
| 412 |
+
if (out / "audit.json").exists():
|
| 413 |
+
raise FileExistsError(out / "audit.json")
|
| 414 |
+
device = _device_setup(device)
|
| 415 |
+
result = json.loads((out / "complete.json").read_text())
|
| 416 |
+
recorded = json.loads((out / "spec.json").read_text())
|
| 417 |
+
source, spec = result["source"], result["spec"]
|
| 418 |
+
_check_source(source)
|
| 419 |
+
_validate_spec(spec)
|
| 420 |
+
if recorded["spec"] != spec or recorded["source"] != source:
|
| 421 |
+
raise AssertionError("Recorded specification/source differ")
|
| 422 |
+
if file_hash(out / "latest.pt") != result["checkpoint_sha256"]:
|
| 423 |
+
raise AssertionError("Latest checkpoint hash differs")
|
| 424 |
+
world = build_world(spec)
|
| 425 |
+
digest = data_digest(world)
|
| 426 |
+
if digest != result["data_sha256"] or digest != recorded["data_sha256"]:
|
| 427 |
+
raise AssertionError("Rebuilt data differ from records")
|
| 428 |
+
if result["common_evaluation_sha256"] != common_evaluation_digest(world):
|
| 429 |
+
raise AssertionError("Common evaluation identity differs")
|
| 430 |
+
if json.loads((out / "world-metadata.json").read_text()) != world["metadata"]:
|
| 431 |
+
raise AssertionError("Archived world metadata differ")
|
| 432 |
+
with np.load(out / "world.npz") as archived:
|
| 433 |
+
if set(archived.files) != set(EVALUATION_SPLITS):
|
| 434 |
+
raise AssertionError("Archived world keys differ")
|
| 435 |
+
for name in EVALUATION_SPLITS:
|
| 436 |
+
np.testing.assert_array_equal(archived[name], world[name])
|
| 437 |
+
model = construct(spec, device)
|
| 438 |
+
if model_digest(model) != result["initial_model_sha256"]:
|
| 439 |
+
raise AssertionError("Paired initialization differs")
|
| 440 |
+
history = json.loads((out / "learning.json").read_text())
|
| 441 |
+
if [row["step"] for row in history] != spec["nodes"]:
|
| 442 |
+
raise AssertionError("Recorded learning nodes differ")
|
| 443 |
+
by_node = {row["step"]: row for row in history}
|
| 444 |
+
if by_node[spec["steps"]] != result["endpoint"]:
|
| 445 |
+
raise AssertionError("Endpoint differs from the learning curve")
|
| 446 |
+
maximum = 0.0
|
| 447 |
+
for node in spec["checkpoint_nodes"]:
|
| 448 |
+
checkpoint = torch.load(
|
| 449 |
+
out / f"model-{node:06d}.pt", map_location=device, weights_only=False
|
| 450 |
+
)
|
| 451 |
+
if checkpoint["spec"] != spec or checkpoint["step"] != node:
|
| 452 |
+
raise AssertionError("Checkpoint specification/node differ")
|
| 453 |
+
model.load_state_dict(checkpoint["model"])
|
| 454 |
+
metrics, predictions = evaluate(model, world, device)
|
| 455 |
+
compare_metrics(metrics, by_node[node]["metrics"])
|
| 456 |
+
maximum = max(
|
| 457 |
+
maximum, compare_predictions(predictions, out / f"predictions-{node:06d}.npz")
|
| 458 |
+
)
|
| 459 |
+
saved = torch.load(out / "latest.pt", map_location=device, weights_only=False)
|
| 460 |
+
if (
|
| 461 |
+
saved["spec"] != spec
|
| 462 |
+
or saved["source"] != source
|
| 463 |
+
or saved["step"] != spec["steps"]
|
| 464 |
+
or saved["data_sha256"] != digest
|
| 465 |
+
):
|
| 466 |
+
raise AssertionError("Latest state identity differs")
|
| 467 |
+
sizes = [len(world[name]) for name in TRAIN_SPLITS]
|
| 468 |
+
streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)]
|
| 469 |
+
counts = [np.zeros(size, dtype=np.int64) for size in sizes]
|
| 470 |
+
previous = 0
|
| 471 |
+
for node in spec["nodes"]:
|
| 472 |
+
for i, stream in enumerate(streams):
|
| 473 |
+
draws = (
|
| 474 |
+
stream.take((node - previous) * 32)
|
| 475 |
+
if node > previous
|
| 476 |
+
else np.empty(0, dtype=np.int64)
|
| 477 |
+
)
|
| 478 |
+
counts[i] += np.bincount(draws, minlength=sizes[i])
|
| 479 |
+
with np.load(out / f"exposures-{node:06d}.npz") as actual:
|
| 480 |
+
if set(actual.files) != set(TRAIN_SPLITS):
|
| 481 |
+
raise AssertionError("Exposure strata differ")
|
| 482 |
+
for name, count in zip(TRAIN_SPLITS, counts, strict=True):
|
| 483 |
+
np.testing.assert_array_equal(actual[name], count)
|
| 484 |
+
row = by_node[node]
|
| 485 |
+
if row["supervised_tokens"] != node * 832 or row["padded_input_tokens"] != node * 1024:
|
| 486 |
+
raise AssertionError("Token accounting differs")
|
| 487 |
+
previous = node
|
| 488 |
+
with np.load(out / "exposures.npz") as actual:
|
| 489 |
+
for i, (name, count) in enumerate(zip(TRAIN_SPLITS, counts, strict=True)):
|
| 490 |
+
np.testing.assert_array_equal(actual[name], count)
|
| 491 |
+
np.testing.assert_array_equal(saved["counts"][i], count)
|
| 492 |
+
if count.sum() != spec["steps"] * 32 or np.ptp(count) > 1:
|
| 493 |
+
raise AssertionError("EpochStream actual exposures are unbalanced")
|
| 494 |
+
stream = EpochStream(sizes[i], spec["stream_seed"] + i)
|
| 495 |
+
stream.load_state_dict(saved["streams"][i])
|
| 496 |
+
np.testing.assert_array_equal(stream.take(32), streams[i].take(32))
|
| 497 |
+
model.load_state_dict(saved["model"])
|
| 498 |
+
metrics, predictions = evaluate(model, world, device)
|
| 499 |
+
compare_metrics(metrics, result["endpoint"]["metrics"])
|
| 500 |
+
maximum = max(
|
| 501 |
+
maximum, compare_predictions(predictions, out / f"predictions-{spec['steps']:06d}.npz")
|
| 502 |
+
)
|
| 503 |
+
checked = {
|
| 504 |
+
"passed": True,
|
| 505 |
+
"dataset_rebuilt_and_archived_exact": True,
|
| 506 |
+
"nested_support_and_common_pools_checked": True,
|
| 507 |
+
"initial_model_exact": True,
|
| 508 |
+
"checkpoint_nodes": spec["checkpoint_nodes"],
|
| 509 |
+
"endpoint_tokens_exact": True,
|
| 510 |
+
"all_nodes_exposure_counters_exact": True,
|
| 511 |
+
"stream_state_continuation_exact": True,
|
| 512 |
+
"max_nll_difference": maximum,
|
| 513 |
+
"nll_rtol": 1e-5,
|
| 514 |
+
"nll_atol": 1e-5,
|
| 515 |
+
"utc": utc(),
|
| 516 |
+
}
|
| 517 |
+
write_json(out / "audit.json", checked)
|
| 518 |
+
return checked
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/natural_composition_confirmation.py
ADDED
|
@@ -0,0 +1,687 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Full-Qwen, nested compositional support with matched atomic supervision."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import hashlib
|
| 7 |
+
import json
|
| 8 |
+
import math
|
| 9 |
+
import platform
|
| 10 |
+
import shutil
|
| 11 |
+
import time
|
| 12 |
+
from collections import Counter
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn.functional as F
|
| 18 |
+
import transformers
|
| 19 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 20 |
+
|
| 21 |
+
from . import small_lm_composition as base
|
| 22 |
+
|
| 23 |
+
FIRST = ("mentor", "advisor")
|
| 24 |
+
SECOND = ("live", "birth")
|
| 25 |
+
STRICT_CITIES = (
|
| 26 |
+
"Athens Prague Havana Tunis Perth Zurich Bristol Munich "
|
| 27 |
+
"Tallinn Riga Quito Dakar Nairobi Accra Calgary Warsaw"
|
| 28 |
+
).split()
|
| 29 |
+
ROOT = Path("docs/development-artifacts/natural-composition-confirmation-v1")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def sha(path):
|
| 33 |
+
digest = hashlib.sha256()
|
| 34 |
+
with Path(path).open("rb") as handle:
|
| 35 |
+
for chunk in iter(lambda: handle.read(16 * 1024 * 1024), b""):
|
| 36 |
+
digest.update(chunk)
|
| 37 |
+
return digest.hexdigest()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def write(path, value):
|
| 41 |
+
base.write(path, value)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def build_world(seed):
|
| 45 |
+
rng = np.random.default_rng(seed)
|
| 46 |
+
first_names = (
|
| 47 |
+
"Rhea Mara Evan Luca Nora Iris Owen Hugo Cora Theo Nina Leon Vera Finn Dana Arlo"
|
| 48 |
+
).split()
|
| 49 |
+
names = [
|
| 50 |
+
f"{a} {b}"
|
| 51 |
+
for a in first_names
|
| 52 |
+
for b in "Hale Vale Mercer Rowan Keane Flint Arden Voss North Lark".split()
|
| 53 |
+
]
|
| 54 |
+
names = rng.permutation(names).tolist()
|
| 55 |
+
atoms, chains = [], []
|
| 56 |
+
for pool, offset, cities in (("familiar", 0, base.CITIES), ("strict", 32, STRICT_CITIES)):
|
| 57 |
+
heads, bridges = names[offset : offset + 16], names[offset + 16 : offset + 32]
|
| 58 |
+
mappings = [rng.permutation(16).tolist()]
|
| 59 |
+
mappings.append(np.roll(mappings[0], int(rng.integers(1, 16))).tolist())
|
| 60 |
+
city_maps = [rng.permutation(cities).tolist()]
|
| 61 |
+
city_maps.append(np.roll(city_maps[0], int(rng.integers(1, 16))).tolist())
|
| 62 |
+
ids = {}
|
| 63 |
+
for j, head in enumerate(heads):
|
| 64 |
+
for r, relation in enumerate(FIRST):
|
| 65 |
+
atom = dict(
|
| 66 |
+
id=len(atoms),
|
| 67 |
+
pool=pool,
|
| 68 |
+
role="first",
|
| 69 |
+
subject=head,
|
| 70 |
+
relation=relation,
|
| 71 |
+
answer=bridges[mappings[r][j]],
|
| 72 |
+
)
|
| 73 |
+
atoms.append(atom)
|
| 74 |
+
ids["first", j, r] = atom["id"]
|
| 75 |
+
for j, bridge in enumerate(bridges):
|
| 76 |
+
for s, relation in enumerate(SECOND):
|
| 77 |
+
atom = dict(
|
| 78 |
+
id=len(atoms),
|
| 79 |
+
pool=pool,
|
| 80 |
+
role="second",
|
| 81 |
+
subject=bridge,
|
| 82 |
+
relation=relation,
|
| 83 |
+
answer=city_maps[s][j],
|
| 84 |
+
)
|
| 85 |
+
atoms.append(atom)
|
| 86 |
+
ids["second", j, s] = atom["id"]
|
| 87 |
+
for j, head in enumerate(heads):
|
| 88 |
+
for r, first in enumerate(FIRST):
|
| 89 |
+
for s, second in enumerate(SECOND):
|
| 90 |
+
bridge_index = mappings[r][j]
|
| 91 |
+
chains.append(
|
| 92 |
+
dict(
|
| 93 |
+
id=len(chains),
|
| 94 |
+
pool=pool,
|
| 95 |
+
head_index=j,
|
| 96 |
+
head=head,
|
| 97 |
+
bridge=bridges[bridge_index],
|
| 98 |
+
first=first,
|
| 99 |
+
second=second,
|
| 100 |
+
answer=city_maps[s][bridge_index],
|
| 101 |
+
atom_ids=[ids["first", j, r], ids["second", bridge_index, s]],
|
| 102 |
+
split="strict"
|
| 103 |
+
if pool == "strict"
|
| 104 |
+
else ("support" if r == s else "heldout"),
|
| 105 |
+
)
|
| 106 |
+
)
|
| 107 |
+
return dict(
|
| 108 |
+
seed=seed,
|
| 109 |
+
atoms=atoms,
|
| 110 |
+
chains=chains,
|
| 111 |
+
high_support=[c["id"] for c in chains if c["split"] == "support"],
|
| 112 |
+
low_support=[c["id"] for c in chains if c["split"] == "support" and c["head_index"] < 4],
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def question(row, variant=0, atomic=False):
|
| 117 |
+
if atomic:
|
| 118 |
+
subject, relation = row["subject"], row["relation"]
|
| 119 |
+
if row["role"] == "first":
|
| 120 |
+
templates = (
|
| 121 |
+
"Who is {subject}'s {relation}?",
|
| 122 |
+
"Who is the {relation} of {subject}?",
|
| 123 |
+
"Name the {relation} of {subject}.",
|
| 124 |
+
"Give the name of {subject}'s {relation}.",
|
| 125 |
+
"Give the name of the person serving as {subject}'s {relation}.",
|
| 126 |
+
)
|
| 127 |
+
elif relation == "live":
|
| 128 |
+
templates = (
|
| 129 |
+
"Which city does {subject} live in?",
|
| 130 |
+
"What city is {subject}'s home?",
|
| 131 |
+
"Where does {subject} live?",
|
| 132 |
+
"Name the city where {subject} lives.",
|
| 133 |
+
"In which city is {subject} living?",
|
| 134 |
+
)
|
| 135 |
+
else:
|
| 136 |
+
templates = (
|
| 137 |
+
"Which city was {subject} born in?",
|
| 138 |
+
"What is {subject}'s birth city?",
|
| 139 |
+
"Where was {subject} born?",
|
| 140 |
+
"Name the city where {subject} was born.",
|
| 141 |
+
"In which city did {subject}'s birth take place?",
|
| 142 |
+
)
|
| 143 |
+
return templates[variant].format(subject=subject, relation=relation)
|
| 144 |
+
subject = row["head"]
|
| 145 |
+
relation = row["first"]
|
| 146 |
+
if row["second"] == "live":
|
| 147 |
+
templates = (
|
| 148 |
+
"Which city does {subject}'s {relation} live in?",
|
| 149 |
+
"What city is home to {subject}'s {relation}?",
|
| 150 |
+
"Where does the {relation} of {subject} live?",
|
| 151 |
+
"Name the city where {subject}'s {relation} lives.",
|
| 152 |
+
"In which city is the person serving as {subject}'s {relation} living?",
|
| 153 |
+
)
|
| 154 |
+
else:
|
| 155 |
+
templates = (
|
| 156 |
+
"Which city was {subject}'s {relation} born in?",
|
| 157 |
+
"What is the birth city of {subject}'s {relation}?",
|
| 158 |
+
"Where was the {relation} of {subject} born?",
|
| 159 |
+
"Name the city where {subject}'s {relation} was born.",
|
| 160 |
+
"In which city did the birth of {subject}'s {relation} take place?",
|
| 161 |
+
)
|
| 162 |
+
return templates[variant].format(subject=subject, relation=relation)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def prompt(row, variant=0, atomic=False):
|
| 166 |
+
return "Fictional registry.\nQuestion: " + question(row, variant, atomic) + "\nAnswer:"
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def record(tokenizer, row, variant, atomic):
|
| 170 |
+
# Joint text tokenization, exactly as in the calibrated full-Qwen v2 recipe.
|
| 171 |
+
ids = tokenizer.encode(
|
| 172 |
+
prompt(row, variant, atomic) + " " + row["answer"] + ".", add_special_tokens=False
|
| 173 |
+
) + [tokenizer.eos_token_id]
|
| 174 |
+
return dict(
|
| 175 |
+
ids=ids,
|
| 176 |
+
labels=[-100, *ids[1:]],
|
| 177 |
+
id=row["id"],
|
| 178 |
+
kind="atomic" if atomic else "composition",
|
| 179 |
+
variant=variant,
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def streams(world, cfg):
|
| 184 |
+
rng = np.random.default_rng(cfg["training_seed"])
|
| 185 |
+
atomic_order, comp_order = [], {a: [] for a in cfg["arms"]}
|
| 186 |
+
batches = {a: [] for a in cfg["arms"]}
|
| 187 |
+
for _ in range(cfg["steps"]):
|
| 188 |
+
if len(atomic_order) < cfg["atomic_per_step"]:
|
| 189 |
+
atomic_order.extend(rng.permutation(len(world["atoms"])).tolist())
|
| 190 |
+
atomic = [
|
| 191 |
+
[int(atomic_order.pop(0)), int(rng.integers(4))] for _ in range(cfg["atomic_per_step"])
|
| 192 |
+
]
|
| 193 |
+
variants = rng.integers(4, size=cfg["compositions_per_step"]).tolist()
|
| 194 |
+
for arm in cfg["arms"]:
|
| 195 |
+
support = world[arm + "_support"]
|
| 196 |
+
if len(comp_order[arm]) < cfg["compositions_per_step"]:
|
| 197 |
+
comp_order[arm].extend(rng.permutation(support).tolist())
|
| 198 |
+
comp = [[int(comp_order[arm].pop(0)), int(v)] for v in variants]
|
| 199 |
+
batches[arm].append(dict(atomic=atomic, composition=comp))
|
| 200 |
+
return batches
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def records(tokenizer, world):
|
| 204 |
+
return {
|
| 205 |
+
kind: {
|
| 206 |
+
(r["id"], v): record(tokenizer, r, v, kind == "atomic")
|
| 207 |
+
for r in world["atoms" if kind == "atomic" else "chains"]
|
| 208 |
+
for v in range(4)
|
| 209 |
+
}
|
| 210 |
+
for kind in ("atomic", "composition")
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def docs_for(rec, batch):
|
| 215 |
+
return [rec[kind][tuple(spec)] for kind in ("atomic", "composition") for spec in batch[kind]]
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def audit(world, batches, rec):
|
| 219 |
+
assert (
|
| 220 |
+
len(world["atoms"]) == 128
|
| 221 |
+
and len(world["high_support"]) == 32
|
| 222 |
+
and len(world["low_support"]) == 8
|
| 223 |
+
)
|
| 224 |
+
assert set(world["low_support"]) < set(world["high_support"])
|
| 225 |
+
familiar_atoms = {a["id"] for a in world["atoms"] if a["pool"] == "familiar"}
|
| 226 |
+
covered = {i for j in world["high_support"] for i in world["chains"][j]["atom_ids"]}
|
| 227 |
+
assert covered == familiar_atoms
|
| 228 |
+
strict_atoms = {a["id"] for a in world["atoms"] if a["pool"] == "strict"}
|
| 229 |
+
assert not covered & strict_atoms
|
| 230 |
+
support = [world["chains"][i] for i in world["high_support"]]
|
| 231 |
+
heldout = [c for c in world["chains"] if c["split"] == "heldout"]
|
| 232 |
+
strict = [c for c in world["chains"] if c["split"] == "strict"]
|
| 233 |
+
assert len(heldout) == 32 and len(strict) == 64
|
| 234 |
+
# No alternate trained query gives the same head/answer endpoint as a held-out chain.
|
| 235 |
+
assert not {(c["head"], c["answer"]) for c in support} & {
|
| 236 |
+
(c["head"], c["answer"]) for c in heldout
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
def people(pool):
|
| 240 |
+
return {a["subject"] for a in world["atoms"] if a["pool"] == pool}
|
| 241 |
+
|
| 242 |
+
assert not people("familiar") & people("strict")
|
| 243 |
+
assert not {c["answer"] for c in support} & {c["answer"] for c in strict}
|
| 244 |
+
budgets, exposure = {}, {}
|
| 245 |
+
for arm, stream in batches.items():
|
| 246 |
+
budget, atomic_counts, comp_counts = Counter(), Counter(), Counter()
|
| 247 |
+
for batch in stream:
|
| 248 |
+
docs = docs_for(rec, batch)
|
| 249 |
+
width = max(len(d["ids"]) for d in docs)
|
| 250 |
+
budget.update(
|
| 251 |
+
input_tokens=sum(len(d["ids"]) for d in docs),
|
| 252 |
+
supervised_tokens=sum(len(d["ids"]) - 1 for d in docs),
|
| 253 |
+
padded_tokens=len(docs) * width,
|
| 254 |
+
attention_cells=len(docs) * width**2,
|
| 255 |
+
)
|
| 256 |
+
atomic_counts.update(i for i, _ in batch["atomic"])
|
| 257 |
+
comp_counts.update(i for i, _ in batch["composition"])
|
| 258 |
+
assert set(comp_counts) <= set(world[arm + "_support"])
|
| 259 |
+
budgets[arm] = dict(budget)
|
| 260 |
+
exposure[arm] = dict(
|
| 261 |
+
atomic=sorted(atomic_counts.items()), composition=sorted(comp_counts.items())
|
| 262 |
+
)
|
| 263 |
+
if "low" in batches and "high" in batches:
|
| 264 |
+
assert [b["atomic"] for b in batches["low"]] == [b["atomic"] for b in batches["high"]]
|
| 265 |
+
assert exposure["low"]["atomic"] == exposure["high"]["atomic"]
|
| 266 |
+
return dict(
|
| 267 |
+
status="passed",
|
| 268 |
+
budgets=budgets,
|
| 269 |
+
exposures=exposure,
|
| 270 |
+
familiar_fact_role_coverage_high=len(covered),
|
| 271 |
+
familiar_fact_role_coverage_low=len(
|
| 272 |
+
{i for j in world["low_support"] for i in world["chains"][j]["atom_ids"]}
|
| 273 |
+
),
|
| 274 |
+
heldout_queries=len(heldout),
|
| 275 |
+
strict_queries=len(strict),
|
| 276 |
+
target_endpoint_leakage=0,
|
| 277 |
+
exact_common_atomic_sequence=True,
|
| 278 |
+
exact_atomic_stream_loss_weight=True,
|
| 279 |
+
composition_slots_equal=True,
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def freeze(config_path):
|
| 284 |
+
cfg = base.read(config_path)
|
| 285 |
+
art = Path(cfg["artifact_root"])
|
| 286 |
+
assert not (art / "lock.json").exists(), "Preserve frozen batch."
|
| 287 |
+
tokenizer = AutoTokenizer.from_pretrained(cfg["model_path"], local_files_only=True)
|
| 288 |
+
sources = [
|
| 289 |
+
str(config_path),
|
| 290 |
+
"src/llm_memory_editability/natural_composition_confirmation.py",
|
| 291 |
+
"src/llm_memory_editability/small_lm_composition.py",
|
| 292 |
+
"scripts/run_natural_composition_confirmation.py",
|
| 293 |
+
"tests/test_natural_composition_confirmation.py",
|
| 294 |
+
"docs/development-artifacts/natural-composition-confirmation-v1/design.md",
|
| 295 |
+
]
|
| 296 |
+
source_hashes = {}
|
| 297 |
+
for source in sources:
|
| 298 |
+
dest = art / "source" / source
|
| 299 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 300 |
+
shutil.copyfile(source, dest)
|
| 301 |
+
source_hashes[source] = sha(source)
|
| 302 |
+
data_files = {}
|
| 303 |
+
for seed in cfg["world_seeds"]:
|
| 304 |
+
world = build_world(seed)
|
| 305 |
+
batch = streams(world, cfg)
|
| 306 |
+
report = audit(world, batch, records(tokenizer, world))
|
| 307 |
+
for filename, obj in (
|
| 308 |
+
("world.json", world),
|
| 309 |
+
("streams.json", batch),
|
| 310 |
+
("data-audit.json", report),
|
| 311 |
+
):
|
| 312 |
+
path = art / f"w{seed}" / filename
|
| 313 |
+
write(path, obj)
|
| 314 |
+
data_files[str(path)] = sha(path)
|
| 315 |
+
model_files = {
|
| 316 |
+
str(p): sha(p)
|
| 317 |
+
for p in Path(cfg["model_path"]).iterdir()
|
| 318 |
+
if p.suffix in (".json", ".safetensors") or p.name in ("LICENSE", "README.md")
|
| 319 |
+
}
|
| 320 |
+
write(
|
| 321 |
+
art / "environment.json",
|
| 322 |
+
dict(
|
| 323 |
+
python=platform.python_version(),
|
| 324 |
+
executable=str(Path(__import__("sys").executable)),
|
| 325 |
+
torch=torch.__version__,
|
| 326 |
+
transformers=transformers.__version__,
|
| 327 |
+
gpu_inventory=__import__("subprocess").check_output(
|
| 328 |
+
["nvidia-smi", "--query-gpu=index,name,memory.used,memory.total", "--format=csv"],
|
| 329 |
+
text=True,
|
| 330 |
+
),
|
| 331 |
+
),
|
| 332 |
+
)
|
| 333 |
+
write(
|
| 334 |
+
art / "lock.json",
|
| 335 |
+
dict(
|
| 336 |
+
status="locked_before_training",
|
| 337 |
+
utc=base.now(),
|
| 338 |
+
sources=source_hashes,
|
| 339 |
+
data_files=data_files,
|
| 340 |
+
model_files=model_files,
|
| 341 |
+
config=cfg,
|
| 342 |
+
),
|
| 343 |
+
)
|
| 344 |
+
print(
|
| 345 |
+
json.dumps(dict(status="frozen", worlds=cfg["world_seeds"], arms=cfg["arms"])), flush=True
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def check_lock(cfg):
|
| 350 |
+
lock = base.read(Path(cfg["artifact_root"]) / "lock.json")
|
| 351 |
+
for group in ("sources", "data_files", "model_files"):
|
| 352 |
+
for path, digest in lock[group].items():
|
| 353 |
+
assert sha(path) == digest, path
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def evaluation_rows(world, extras=False):
|
| 357 |
+
rows = []
|
| 358 |
+
for view in (0, 4) if extras else (0,):
|
| 359 |
+
for atom in world["atoms"]:
|
| 360 |
+
rows.append(dict(atom, mode="atomic", view=view, prompt=prompt(atom, view, True)))
|
| 361 |
+
for chain in world["chains"]:
|
| 362 |
+
rows.append(dict(chain, mode="direct", view=view, prompt=prompt(chain, view)))
|
| 363 |
+
return rows
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
@torch.inference_mode()
|
| 367 |
+
def generate(model, tokenizer, rows, cfg):
|
| 368 |
+
model.eval()
|
| 369 |
+
tokenizer.padding_side = "left"
|
| 370 |
+
output = []
|
| 371 |
+
for start in range(0, len(rows), cfg["eval_batch"]):
|
| 372 |
+
chunk = rows[start : start + cfg["eval_batch"]]
|
| 373 |
+
inputs = tokenizer(
|
| 374 |
+
[r["prompt"] for r in chunk],
|
| 375 |
+
padding=True,
|
| 376 |
+
return_tensors="pt",
|
| 377 |
+
add_special_tokens=False,
|
| 378 |
+
).to(cfg["device"])
|
| 379 |
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 380 |
+
tokens = model.generate(
|
| 381 |
+
**inputs,
|
| 382 |
+
do_sample=False,
|
| 383 |
+
max_new_tokens=cfg["max_new_tokens"],
|
| 384 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 385 |
+
eos_token_id=tokenizer.eos_token_id,
|
| 386 |
+
use_cache=True,
|
| 387 |
+
)[:, inputs.input_ids.shape[1] :]
|
| 388 |
+
for row, tok in zip(chunk, tokens.cpu().tolist(), strict=True):
|
| 389 |
+
if tokenizer.eos_token_id in tok:
|
| 390 |
+
tok = tok[: tok.index(tokenizer.eos_token_id) + 1]
|
| 391 |
+
text = tokenizer.decode(tok, skip_special_tokens=True)
|
| 392 |
+
output.append(dict(row, tokens=tok, text=text, correct=base.grade(text, row["answer"])))
|
| 393 |
+
return output
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def evaluate(model, tokenizer, world, cfg, extras=False):
|
| 397 |
+
direct = generate(model, tokenizer, evaluation_rows(world, extras), cfg)
|
| 398 |
+
if not extras:
|
| 399 |
+
return direct
|
| 400 |
+
atoms = {a["id"]: a for a in world["atoms"]}
|
| 401 |
+
lookup = {(r["id"], r["view"]): r for r in direct if r["mode"] == "atomic"}
|
| 402 |
+
second_calls = []
|
| 403 |
+
for row in direct:
|
| 404 |
+
if row["mode"] != "direct":
|
| 405 |
+
continue
|
| 406 |
+
first = lookup[row["atom_ids"][0], row["view"]]
|
| 407 |
+
generated_bridge = first["text"].strip().split("\n")[0].strip().rstrip(".").strip()
|
| 408 |
+
second = dict(atoms[row["atom_ids"][1]], subject=generated_bridge)
|
| 409 |
+
second_calls.append(
|
| 410 |
+
dict(
|
| 411 |
+
row,
|
| 412 |
+
mode="autonomous",
|
| 413 |
+
prompt=prompt(second, row["view"], True),
|
| 414 |
+
generated_bridge=generated_bridge,
|
| 415 |
+
first_tokens=first["tokens"],
|
| 416 |
+
first_correct=first["correct"],
|
| 417 |
+
)
|
| 418 |
+
)
|
| 419 |
+
return direct + generate(model, tokenizer, second_calls, cfg)
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def metrics(rows, world, arm):
|
| 423 |
+
result = {}
|
| 424 |
+
for view in sorted({r["view"] for r in rows}):
|
| 425 |
+
atomic = {r["id"]: r for r in rows if r["view"] == view and r["mode"] == "atomic"}
|
| 426 |
+
for pool in ("familiar", "strict"):
|
| 427 |
+
for role in ("first", "second"):
|
| 428 |
+
selected = [r for r in atomic.values() if r["pool"] == pool and r["role"] == role]
|
| 429 |
+
result[f"v{view}_{pool}_{role}"] = dict(
|
| 430 |
+
correct=sum(r["correct"] for r in selected), n=len(selected)
|
| 431 |
+
)
|
| 432 |
+
for split in ("heldout", "strict", "training"):
|
| 433 |
+
ids = (
|
| 434 |
+
set(world[arm + "_support"])
|
| 435 |
+
if split == "training"
|
| 436 |
+
else {c["id"] for c in world["chains"] if c["split"] == split}
|
| 437 |
+
)
|
| 438 |
+
for mode in ("direct", "autonomous"):
|
| 439 |
+
selected = [
|
| 440 |
+
r for r in rows if r["view"] == view and r["mode"] == mode and r["id"] in ids
|
| 441 |
+
]
|
| 442 |
+
if selected:
|
| 443 |
+
result[f"v{view}_{split}_{mode}"] = dict(
|
| 444 |
+
correct=sum(r["correct"] for r in selected), n=len(selected)
|
| 445 |
+
)
|
| 446 |
+
mastered = [
|
| 447 |
+
r for r in selected if all(atomic[i]["correct"] for i in r["atom_ids"])
|
| 448 |
+
]
|
| 449 |
+
result[f"v{view}_{split}_{mode}_both_atomic"] = dict(
|
| 450 |
+
correct=sum(r["correct"] for r in mastered),
|
| 451 |
+
n=len(mastered),
|
| 452 |
+
full_n=len(selected),
|
| 453 |
+
)
|
| 454 |
+
return result
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def stream_loss(model, inputs, atomic_count, atomic_weight):
|
| 458 |
+
logits = model(
|
| 459 |
+
input_ids=inputs["input_ids"], attention_mask=inputs["attention_mask"], use_cache=False
|
| 460 |
+
).logits[:, :-1]
|
| 461 |
+
labels = inputs["labels"][:, 1:]
|
| 462 |
+
losses = F.cross_entropy(
|
| 463 |
+
logits.float().reshape(-1, logits.shape[-1]),
|
| 464 |
+
labels.reshape(-1),
|
| 465 |
+
reduction="none",
|
| 466 |
+
ignore_index=-100,
|
| 467 |
+
).reshape_as(labels)
|
| 468 |
+
atomic = losses[:atomic_count].sum() / (labels[:atomic_count] != -100).sum()
|
| 469 |
+
comp = losses[atomic_count:].sum() / (labels[atomic_count:] != -100).sum()
|
| 470 |
+
return atomic_weight * atomic + (1 - atomic_weight) * comp
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def run(config_path, seed, arm):
|
| 474 |
+
cfg = base.read(config_path)
|
| 475 |
+
check_lock(cfg)
|
| 476 |
+
assert seed in cfg["world_seeds"] and arm in cfg["arms"]
|
| 477 |
+
art = Path(cfg["artifact_root"]) / f"w{seed}"
|
| 478 |
+
out = Path(cfg["output_root"]) / f"w{seed}-{arm}"
|
| 479 |
+
assert not (out / "status.json").exists(), "Preserve existing execution."
|
| 480 |
+
world, batches = base.read(art / "world.json"), base.read(art / "streams.json")[arm]
|
| 481 |
+
write(out / "status.json", dict(status="running", utc=base.now()))
|
| 482 |
+
started = time.perf_counter()
|
| 483 |
+
torch.set_num_threads(cfg["cpu_threads"])
|
| 484 |
+
torch.manual_seed(cfg["training_seed"])
|
| 485 |
+
torch.cuda.set_device(cfg["device"])
|
| 486 |
+
torch.backends.cuda.matmul.allow_tf32 = False
|
| 487 |
+
torch.backends.cudnn.allow_tf32 = False
|
| 488 |
+
torch.cuda.reset_peak_memory_stats()
|
| 489 |
+
tokenizer = AutoTokenizer.from_pretrained(cfg["model_path"], local_files_only=True)
|
| 490 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 491 |
+
|
| 492 |
+
def load(path):
|
| 493 |
+
return AutoModelForCausalLM.from_pretrained(
|
| 494 |
+
path, torch_dtype=torch.float32, attn_implementation="sdpa", local_files_only=True
|
| 495 |
+
).to(cfg["device"])
|
| 496 |
+
|
| 497 |
+
model = load(cfg["model_path"])
|
| 498 |
+
assert model.config.num_hidden_layers == 28 and model.config.hidden_size == 1024
|
| 499 |
+
assert len({id(layer.mlp) for layer in model.model.layers}) == 28
|
| 500 |
+
model.requires_grad_(True)
|
| 501 |
+
samples = base.parameter_samples(model)
|
| 502 |
+
parameter_count = sum(p.numel() for p in model.parameters())
|
| 503 |
+
rec = records(tokenizer, world)
|
| 504 |
+
optimizer = torch.optim.AdamW(
|
| 505 |
+
model.parameters(), lr=cfg["learning_rate"], weight_decay=cfg["weight_decay"], fused=True
|
| 506 |
+
)
|
| 507 |
+
curve, budget, train_seconds = [], Counter(), 0.0
|
| 508 |
+
for step in range(cfg["steps"] + 1):
|
| 509 |
+
if step in cfg["nodes"]:
|
| 510 |
+
rows = evaluate(model, tokenizer, world, cfg, extras=step == cfg["steps"])
|
| 511 |
+
write(out / f"predictions-{step:05d}.json", rows)
|
| 512 |
+
point = dict(step=step, metrics=metrics(rows, world, arm))
|
| 513 |
+
curve.append(point)
|
| 514 |
+
write(out / "curve.json", curve)
|
| 515 |
+
print(json.dumps(dict(seed=seed, arm=arm, **point)), flush=True)
|
| 516 |
+
if step == cfg["steps"]:
|
| 517 |
+
break
|
| 518 |
+
decay = 0.5 * (
|
| 519 |
+
1
|
| 520 |
+
+ math.cos(
|
| 521 |
+
math.pi * max(0, step - cfg["warmup_steps"]) / (cfg["steps"] - cfg["warmup_steps"])
|
| 522 |
+
)
|
| 523 |
+
)
|
| 524 |
+
lr = (
|
| 525 |
+
cfg["minimum_learning_rate"]
|
| 526 |
+
+ (cfg["learning_rate"] - cfg["minimum_learning_rate"]) * decay
|
| 527 |
+
) * min(1.0, (step + 1) / cfg["warmup_steps"])
|
| 528 |
+
for group in optimizer.param_groups:
|
| 529 |
+
group["lr"] = lr
|
| 530 |
+
docs = docs_for(rec, batches[step])
|
| 531 |
+
width = max(len(d["ids"]) for d in docs)
|
| 532 |
+
budget.update(
|
| 533 |
+
input_tokens=sum(len(d["ids"]) for d in docs),
|
| 534 |
+
supervised_tokens=sum(len(d["ids"]) - 1 for d in docs),
|
| 535 |
+
padded_tokens=len(docs) * width,
|
| 536 |
+
attention_cells=len(docs) * width**2,
|
| 537 |
+
)
|
| 538 |
+
inputs = base.batch_tensors(docs, tokenizer.pad_token_id, cfg["device"])
|
| 539 |
+
model.train()
|
| 540 |
+
torch.cuda.synchronize()
|
| 541 |
+
tick = time.perf_counter()
|
| 542 |
+
optimizer.zero_grad(set_to_none=True)
|
| 543 |
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 544 |
+
loss = stream_loss(model, inputs, cfg["atomic_per_step"], cfg["atomic_loss_weight"])
|
| 545 |
+
assert torch.isfinite(loss)
|
| 546 |
+
loss.backward()
|
| 547 |
+
if step == 0:
|
| 548 |
+
assert all(
|
| 549 |
+
p.requires_grad and p.grad is not None and torch.isfinite(p.grad).all()
|
| 550 |
+
for p in model.parameters()
|
| 551 |
+
)
|
| 552 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), cfg["gradient_clip"])
|
| 553 |
+
optimizer.step()
|
| 554 |
+
torch.cuda.synchronize()
|
| 555 |
+
train_seconds += time.perf_counter() - tick
|
| 556 |
+
if (step + 1) % 64 == 0:
|
| 557 |
+
print(
|
| 558 |
+
json.dumps(
|
| 559 |
+
dict(
|
| 560 |
+
seed=seed,
|
| 561 |
+
arm=arm,
|
| 562 |
+
step=step + 1,
|
| 563 |
+
loss=float(loss.detach()),
|
| 564 |
+
train_seconds=train_seconds,
|
| 565 |
+
)
|
| 566 |
+
),
|
| 567 |
+
flush=True,
|
| 568 |
+
)
|
| 569 |
+
changed = {
|
| 570 |
+
name: not torch.equal(before, base.parameter_samples(model)[name])
|
| 571 |
+
for name, before in samples.items()
|
| 572 |
+
}
|
| 573 |
+
assert all(changed.values())
|
| 574 |
+
model.save_pretrained(out / "model", safe_serialization=True)
|
| 575 |
+
tokenizer.save_pretrained(out / "model")
|
| 576 |
+
architecture = model.config.to_dict()
|
| 577 |
+
final_rows = rows
|
| 578 |
+
del optimizer, model, samples, inputs, loss
|
| 579 |
+
torch.cuda.empty_cache()
|
| 580 |
+
again = evaluate(load(out / "model"), tokenizer, world, cfg, extras=True)
|
| 581 |
+
assert [r["tokens"] for r in final_rows] == [r["tokens"] for r in again]
|
| 582 |
+
assert [r["prompt"] for r in final_rows] == [r["prompt"] for r in again]
|
| 583 |
+
write(
|
| 584 |
+
out / "reload-audit.json",
|
| 585 |
+
dict(
|
| 586 |
+
status="passed",
|
| 587 |
+
predictions=len(again),
|
| 588 |
+
exact_generated_tokens=True,
|
| 589 |
+
exact_autonomous_prompts=True,
|
| 590 |
+
),
|
| 591 |
+
)
|
| 592 |
+
assert dict(budget) == base.read(art / "data-audit.json")["budgets"][arm]
|
| 593 |
+
d, layers = architecture["hidden_size"], architecture["num_hidden_layers"]
|
| 594 |
+
query_width = architecture["num_attention_heads"] * architecture["head_dim"]
|
| 595 |
+
kv = architecture["num_key_value_heads"] * architecture["head_dim"]
|
| 596 |
+
per_token = (
|
| 597 |
+
layers * (2 * d * query_width + 2 * d * kv + 3 * d * architecture["intermediate_size"])
|
| 598 |
+
+ d * architecture["vocab_size"]
|
| 599 |
+
)
|
| 600 |
+
flops = (
|
| 601 |
+
6 * per_token * budget["padded_tokens"]
|
| 602 |
+
+ 12 * layers * query_width * budget["attention_cells"]
|
| 603 |
+
)
|
| 604 |
+
summary = dict(
|
| 605 |
+
status="complete",
|
| 606 |
+
phase=cfg["phase"],
|
| 607 |
+
utc=base.now(),
|
| 608 |
+
world_seed=seed,
|
| 609 |
+
arm=arm,
|
| 610 |
+
metrics=metrics(final_rows, world, arm),
|
| 611 |
+
updates=cfg["steps"],
|
| 612 |
+
budget=dict(budget),
|
| 613 |
+
train_seconds=train_seconds,
|
| 614 |
+
process_seconds=time.perf_counter() - started,
|
| 615 |
+
estimated_training_matrix_flops=flops,
|
| 616 |
+
peak_gpu_bytes=torch.cuda.max_memory_allocated(),
|
| 617 |
+
parameter_count=parameter_count,
|
| 618 |
+
sampled_parameters_changed=changed,
|
| 619 |
+
torch_version=torch.__version__,
|
| 620 |
+
transformers_version=transformers.__version__,
|
| 621 |
+
gpu=torch.cuda.get_device_name(),
|
| 622 |
+
tf32=False,
|
| 623 |
+
lock_sha256=sha(Path(cfg["artifact_root"]) / "lock.json"),
|
| 624 |
+
checkpoint_files={str(p): sha(p) for p in (out / "model").glob("*.safetensors")},
|
| 625 |
+
)
|
| 626 |
+
write(out / "summary.json", summary)
|
| 627 |
+
write(out / "status.json", dict(status="complete", utc=base.now()))
|
| 628 |
+
print(json.dumps(summary), flush=True)
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
def report(config_path):
|
| 632 |
+
cfg = base.read(config_path)
|
| 633 |
+
check_lock(cfg)
|
| 634 |
+
runs, checks = {}, 0
|
| 635 |
+
for seed in cfg["world_seeds"]:
|
| 636 |
+
world = base.read(Path(cfg["artifact_root"]) / f"w{seed}" / "world.json")
|
| 637 |
+
for arm in cfg["arms"]:
|
| 638 |
+
out = Path(cfg["output_root"]) / f"w{seed}-{arm}"
|
| 639 |
+
summary = base.read(out / "summary.json")
|
| 640 |
+
assert base.read(out / "reload-audit.json")["status"] == "passed"
|
| 641 |
+
for point in base.read(out / "curve.json"):
|
| 642 |
+
rows = base.read(out / f"predictions-{point['step']:05d}.json")
|
| 643 |
+
assert all(base.grade(r["text"], r["answer"]) == r["correct"] for r in rows)
|
| 644 |
+
assert point["metrics"] == metrics(rows, world, arm)
|
| 645 |
+
checks += len(rows)
|
| 646 |
+
assert summary["metrics"] == metrics(rows, world, arm)
|
| 647 |
+
runs[f"w{seed}-{arm}"] = summary
|
| 648 |
+
differences = {}
|
| 649 |
+
if len(cfg["arms"]) == 2:
|
| 650 |
+
for seed in cfg["world_seeds"]:
|
| 651 |
+
diff = {}
|
| 652 |
+
for key in runs[f"w{seed}-high"]["metrics"]:
|
| 653 |
+
high, low = [runs[f"w{seed}-{a}"]["metrics"][key] for a in ("high", "low")]
|
| 654 |
+
if key.endswith("both_atomic") or "training" in key:
|
| 655 |
+
continue
|
| 656 |
+
diff[key] = high["correct"] / high["n"] - low["correct"] / low["n"]
|
| 657 |
+
differences[str(seed)] = diff
|
| 658 |
+
write(
|
| 659 |
+
Path(cfg["artifact_root"]) / "summary.json",
|
| 660 |
+
dict(
|
| 661 |
+
status="complete",
|
| 662 |
+
phase=cfg["phase"],
|
| 663 |
+
independent_worlds=len(cfg["world_seeds"]),
|
| 664 |
+
training_initializations=1,
|
| 665 |
+
runs=runs,
|
| 666 |
+
per_world_high_minus_low=differences,
|
| 667 |
+
independent_node_prediction_checks=checks,
|
| 668 |
+
total_updates=sum(r["updates"] for r in runs.values()),
|
| 669 |
+
total_train_seconds=sum(r["train_seconds"] for r in runs.values()),
|
| 670 |
+
total_process_seconds=sum(r["process_seconds"] for r in runs.values()),
|
| 671 |
+
),
|
| 672 |
+
)
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
def main():
|
| 676 |
+
parser = argparse.ArgumentParser()
|
| 677 |
+
parser.add_argument("action", choices=("freeze", "run", "report"))
|
| 678 |
+
parser.add_argument("--config", required=True)
|
| 679 |
+
parser.add_argument("--world", type=int)
|
| 680 |
+
parser.add_argument("--arm", choices=("low", "high"))
|
| 681 |
+
args = parser.parse_args()
|
| 682 |
+
if args.action == "run":
|
| 683 |
+
run(args.config, args.world, args.arm)
|
| 684 |
+
elif args.action == "freeze":
|
| 685 |
+
freeze(args.config)
|
| 686 |
+
else:
|
| 687 |
+
report(args.config)
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/natural_composition_confirmation_v2.py
ADDED
|
@@ -0,0 +1,687 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Full-Qwen, nested compositional support with matched atomic supervision."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import hashlib
|
| 7 |
+
import json
|
| 8 |
+
import math
|
| 9 |
+
import platform
|
| 10 |
+
import shutil
|
| 11 |
+
import time
|
| 12 |
+
from collections import Counter
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn.functional as F
|
| 18 |
+
import transformers
|
| 19 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 20 |
+
|
| 21 |
+
from . import small_lm_composition as base
|
| 22 |
+
|
| 23 |
+
FIRST = ("mentor", "advisor")
|
| 24 |
+
SECOND = ("live", "birth")
|
| 25 |
+
STRICT_CITIES = (
|
| 26 |
+
"Athens Prague Havana Tunis Perth Zurich Bristol Munich "
|
| 27 |
+
"Tallinn Riga Quito Dakar Nairobi Accra Calgary Warsaw"
|
| 28 |
+
).split()
|
| 29 |
+
ROOT = Path("docs/development-artifacts/natural-composition-confirmation-v1")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def sha(path):
|
| 33 |
+
digest = hashlib.sha256()
|
| 34 |
+
with Path(path).open("rb") as handle:
|
| 35 |
+
for chunk in iter(lambda: handle.read(16 * 1024 * 1024), b""):
|
| 36 |
+
digest.update(chunk)
|
| 37 |
+
return digest.hexdigest()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def write(path, value):
|
| 41 |
+
base.write(path, value)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def build_world(seed):
|
| 45 |
+
rng = np.random.default_rng(seed)
|
| 46 |
+
first_names = (
|
| 47 |
+
"Rhea Mara Evan Luca Nora Iris Owen Hugo Cora Theo Nina Leon Vera Finn Dana Arlo"
|
| 48 |
+
).split()
|
| 49 |
+
names = [
|
| 50 |
+
f"{a} {b}"
|
| 51 |
+
for a in first_names
|
| 52 |
+
for b in "Hale Vale Mercer Rowan Keane Flint Arden Voss North Lark".split()
|
| 53 |
+
]
|
| 54 |
+
names = rng.permutation(names).tolist()
|
| 55 |
+
atoms, chains = [], []
|
| 56 |
+
for pool, offset, cities in (("familiar", 0, base.CITIES), ("strict", 32, STRICT_CITIES)):
|
| 57 |
+
heads, bridges = names[offset : offset + 16], names[offset + 16 : offset + 32]
|
| 58 |
+
mappings = [rng.permutation(16).tolist()]
|
| 59 |
+
mappings.append(np.roll(mappings[0], int(rng.choice(np.arange(2, 16, 2)))).tolist())
|
| 60 |
+
city_maps = [rng.permutation(cities).tolist()]
|
| 61 |
+
city_maps.append(np.roll(city_maps[0], int(rng.integers(1, 16))).tolist())
|
| 62 |
+
ids = {}
|
| 63 |
+
for j, head in enumerate(heads):
|
| 64 |
+
for r, relation in enumerate(FIRST):
|
| 65 |
+
atom = dict(
|
| 66 |
+
id=len(atoms),
|
| 67 |
+
pool=pool,
|
| 68 |
+
role="first",
|
| 69 |
+
subject=head,
|
| 70 |
+
relation=relation,
|
| 71 |
+
answer=bridges[mappings[r][j]],
|
| 72 |
+
)
|
| 73 |
+
atoms.append(atom)
|
| 74 |
+
ids["first", j, r] = atom["id"]
|
| 75 |
+
for j, bridge in enumerate(bridges):
|
| 76 |
+
for s, relation in enumerate(SECOND):
|
| 77 |
+
atom = dict(
|
| 78 |
+
id=len(atoms),
|
| 79 |
+
pool=pool,
|
| 80 |
+
role="second",
|
| 81 |
+
subject=bridge,
|
| 82 |
+
relation=relation,
|
| 83 |
+
answer=city_maps[s][j],
|
| 84 |
+
)
|
| 85 |
+
atoms.append(atom)
|
| 86 |
+
ids["second", j, s] = atom["id"]
|
| 87 |
+
for j, head in enumerate(heads):
|
| 88 |
+
for r, first in enumerate(FIRST):
|
| 89 |
+
for s, second in enumerate(SECOND):
|
| 90 |
+
bridge_index = mappings[r][j]
|
| 91 |
+
chains.append(
|
| 92 |
+
dict(
|
| 93 |
+
id=len(chains),
|
| 94 |
+
pool=pool,
|
| 95 |
+
head_index=j,
|
| 96 |
+
head=head,
|
| 97 |
+
bridge=bridges[bridge_index],
|
| 98 |
+
first=first,
|
| 99 |
+
second=second,
|
| 100 |
+
answer=city_maps[s][bridge_index],
|
| 101 |
+
atom_ids=[ids["first", j, r], ids["second", bridge_index, s]],
|
| 102 |
+
split="strict"
|
| 103 |
+
if pool == "strict"
|
| 104 |
+
else ("support" if s == (r ^ (j % 2)) else "heldout"),
|
| 105 |
+
)
|
| 106 |
+
)
|
| 107 |
+
return dict(
|
| 108 |
+
seed=seed,
|
| 109 |
+
atoms=atoms,
|
| 110 |
+
chains=chains,
|
| 111 |
+
high_support=[c["id"] for c in chains if c["split"] == "support"],
|
| 112 |
+
low_support=[c["id"] for c in chains if c["split"] == "support" and c["head_index"] < 4],
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def question(row, variant=0, atomic=False):
|
| 117 |
+
if atomic:
|
| 118 |
+
subject, relation = row["subject"], row["relation"]
|
| 119 |
+
if row["role"] == "first":
|
| 120 |
+
templates = (
|
| 121 |
+
"Who is {subject}'s {relation}?",
|
| 122 |
+
"Who is the {relation} of {subject}?",
|
| 123 |
+
"Name the {relation} of {subject}.",
|
| 124 |
+
"Give the name of {subject}'s {relation}.",
|
| 125 |
+
"Give the name of the person serving as {subject}'s {relation}.",
|
| 126 |
+
)
|
| 127 |
+
elif relation == "live":
|
| 128 |
+
templates = (
|
| 129 |
+
"Which city does {subject} live in?",
|
| 130 |
+
"What city is {subject}'s home?",
|
| 131 |
+
"Where does {subject} live?",
|
| 132 |
+
"Name the city where {subject} lives.",
|
| 133 |
+
"In which city is {subject} living?",
|
| 134 |
+
)
|
| 135 |
+
else:
|
| 136 |
+
templates = (
|
| 137 |
+
"Which city was {subject} born in?",
|
| 138 |
+
"What is {subject}'s birth city?",
|
| 139 |
+
"Where was {subject} born?",
|
| 140 |
+
"Name the city where {subject} was born.",
|
| 141 |
+
"In which city did {subject}'s birth take place?",
|
| 142 |
+
)
|
| 143 |
+
return templates[variant].format(subject=subject, relation=relation)
|
| 144 |
+
subject = row["head"]
|
| 145 |
+
relation = row["first"]
|
| 146 |
+
if row["second"] == "live":
|
| 147 |
+
templates = (
|
| 148 |
+
"Which city does {subject}'s {relation} live in?",
|
| 149 |
+
"What city is home to {subject}'s {relation}?",
|
| 150 |
+
"Where does the {relation} of {subject} live?",
|
| 151 |
+
"Name the city where {subject}'s {relation} lives.",
|
| 152 |
+
"In which city is the person serving as {subject}'s {relation} living?",
|
| 153 |
+
)
|
| 154 |
+
else:
|
| 155 |
+
templates = (
|
| 156 |
+
"Which city was {subject}'s {relation} born in?",
|
| 157 |
+
"What is the birth city of {subject}'s {relation}?",
|
| 158 |
+
"Where was the {relation} of {subject} born?",
|
| 159 |
+
"Name the city where {subject}'s {relation} was born.",
|
| 160 |
+
"In which city did the birth of {subject}'s {relation} take place?",
|
| 161 |
+
)
|
| 162 |
+
return templates[variant].format(subject=subject, relation=relation)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def prompt(row, variant=0, atomic=False):
|
| 166 |
+
return "Fictional registry.\nQuestion: " + question(row, variant, atomic) + "\nAnswer:"
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def record(tokenizer, row, variant, atomic):
|
| 170 |
+
# Joint text tokenization, exactly as in the calibrated full-Qwen v2 recipe.
|
| 171 |
+
ids = tokenizer.encode(
|
| 172 |
+
prompt(row, variant, atomic) + " " + row["answer"] + ".", add_special_tokens=False
|
| 173 |
+
) + [tokenizer.eos_token_id]
|
| 174 |
+
return dict(
|
| 175 |
+
ids=ids,
|
| 176 |
+
labels=[-100, *ids[1:]],
|
| 177 |
+
id=row["id"],
|
| 178 |
+
kind="atomic" if atomic else "composition",
|
| 179 |
+
variant=variant,
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def streams(world, cfg):
|
| 184 |
+
rng = np.random.default_rng(cfg["training_seed"])
|
| 185 |
+
atomic_order, comp_order = [], {a: [] for a in cfg["arms"]}
|
| 186 |
+
batches = {a: [] for a in cfg["arms"]}
|
| 187 |
+
for _ in range(cfg["steps"]):
|
| 188 |
+
if len(atomic_order) < cfg["atomic_per_step"]:
|
| 189 |
+
atomic_order.extend(rng.permutation(len(world["atoms"])).tolist())
|
| 190 |
+
atomic = [
|
| 191 |
+
[int(atomic_order.pop(0)), int(rng.integers(4))] for _ in range(cfg["atomic_per_step"])
|
| 192 |
+
]
|
| 193 |
+
variants = rng.integers(4, size=cfg["compositions_per_step"]).tolist()
|
| 194 |
+
for arm in cfg["arms"]:
|
| 195 |
+
support = world[arm + "_support"]
|
| 196 |
+
if len(comp_order[arm]) < cfg["compositions_per_step"]:
|
| 197 |
+
comp_order[arm].extend(rng.permutation(support).tolist())
|
| 198 |
+
comp = [[int(comp_order[arm].pop(0)), int(v)] for v in variants]
|
| 199 |
+
batches[arm].append(dict(atomic=atomic, composition=comp))
|
| 200 |
+
return batches
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def records(tokenizer, world):
|
| 204 |
+
return {
|
| 205 |
+
kind: {
|
| 206 |
+
(r["id"], v): record(tokenizer, r, v, kind == "atomic")
|
| 207 |
+
for r in world["atoms" if kind == "atomic" else "chains"]
|
| 208 |
+
for v in range(4)
|
| 209 |
+
}
|
| 210 |
+
for kind in ("atomic", "composition")
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def docs_for(rec, batch):
|
| 215 |
+
return [rec[kind][tuple(spec)] for kind in ("atomic", "composition") for spec in batch[kind]]
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def audit(world, batches, rec):
|
| 219 |
+
assert (
|
| 220 |
+
len(world["atoms"]) == 128
|
| 221 |
+
and len(world["high_support"]) == 32
|
| 222 |
+
and len(world["low_support"]) == 8
|
| 223 |
+
)
|
| 224 |
+
assert set(world["low_support"]) < set(world["high_support"])
|
| 225 |
+
familiar_atoms = {a["id"] for a in world["atoms"] if a["pool"] == "familiar"}
|
| 226 |
+
covered = {i for j in world["high_support"] for i in world["chains"][j]["atom_ids"]}
|
| 227 |
+
assert covered == familiar_atoms
|
| 228 |
+
strict_atoms = {a["id"] for a in world["atoms"] if a["pool"] == "strict"}
|
| 229 |
+
assert not covered & strict_atoms
|
| 230 |
+
support = [world["chains"][i] for i in world["high_support"]]
|
| 231 |
+
heldout = [c for c in world["chains"] if c["split"] == "heldout"]
|
| 232 |
+
strict = [c for c in world["chains"] if c["split"] == "strict"]
|
| 233 |
+
assert len(heldout) == 32 and len(strict) == 64
|
| 234 |
+
# No alternate trained query gives the same head/answer endpoint as a held-out chain.
|
| 235 |
+
assert not {(c["head"], c["answer"]) for c in support} & {
|
| 236 |
+
(c["head"], c["answer"]) for c in heldout
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
def people(pool):
|
| 240 |
+
return {a["subject"] for a in world["atoms"] if a["pool"] == pool}
|
| 241 |
+
|
| 242 |
+
assert not people("familiar") & people("strict")
|
| 243 |
+
assert not {c["answer"] for c in support} & {c["answer"] for c in strict}
|
| 244 |
+
budgets, exposure = {}, {}
|
| 245 |
+
for arm, stream in batches.items():
|
| 246 |
+
budget, atomic_counts, comp_counts = Counter(), Counter(), Counter()
|
| 247 |
+
for batch in stream:
|
| 248 |
+
docs = docs_for(rec, batch)
|
| 249 |
+
width = max(len(d["ids"]) for d in docs)
|
| 250 |
+
budget.update(
|
| 251 |
+
input_tokens=sum(len(d["ids"]) for d in docs),
|
| 252 |
+
supervised_tokens=sum(len(d["ids"]) - 1 for d in docs),
|
| 253 |
+
padded_tokens=len(docs) * width,
|
| 254 |
+
attention_cells=len(docs) * width**2,
|
| 255 |
+
)
|
| 256 |
+
atomic_counts.update(i for i, _ in batch["atomic"])
|
| 257 |
+
comp_counts.update(i for i, _ in batch["composition"])
|
| 258 |
+
assert set(comp_counts) <= set(world[arm + "_support"])
|
| 259 |
+
budgets[arm] = dict(budget)
|
| 260 |
+
exposure[arm] = dict(
|
| 261 |
+
atomic=sorted(atomic_counts.items()), composition=sorted(comp_counts.items())
|
| 262 |
+
)
|
| 263 |
+
if "low" in batches and "high" in batches:
|
| 264 |
+
assert [b["atomic"] for b in batches["low"]] == [b["atomic"] for b in batches["high"]]
|
| 265 |
+
assert exposure["low"]["atomic"] == exposure["high"]["atomic"]
|
| 266 |
+
return dict(
|
| 267 |
+
status="passed",
|
| 268 |
+
budgets=budgets,
|
| 269 |
+
exposures=exposure,
|
| 270 |
+
familiar_fact_role_coverage_high=len(covered),
|
| 271 |
+
familiar_fact_role_coverage_low=len(
|
| 272 |
+
{i for j in world["low_support"] for i in world["chains"][j]["atom_ids"]}
|
| 273 |
+
),
|
| 274 |
+
heldout_queries=len(heldout),
|
| 275 |
+
strict_queries=len(strict),
|
| 276 |
+
target_endpoint_leakage=0,
|
| 277 |
+
exact_common_atomic_sequence=True,
|
| 278 |
+
exact_atomic_stream_loss_weight=True,
|
| 279 |
+
composition_slots_equal=True,
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def freeze(config_path):
|
| 284 |
+
cfg = base.read(config_path)
|
| 285 |
+
art = Path(cfg["artifact_root"])
|
| 286 |
+
assert not (art / "lock.json").exists(), "Preserve frozen batch."
|
| 287 |
+
tokenizer = AutoTokenizer.from_pretrained(cfg["model_path"], local_files_only=True)
|
| 288 |
+
sources = [
|
| 289 |
+
str(config_path),
|
| 290 |
+
"src/llm_memory_editability/natural_composition_confirmation_v2.py",
|
| 291 |
+
"src/llm_memory_editability/small_lm_composition.py",
|
| 292 |
+
"scripts/run_natural_composition_confirmation_v2.py",
|
| 293 |
+
"tests/test_natural_composition_confirmation_v2.py",
|
| 294 |
+
"docs/development-artifacts/natural-composition-confirmation-v1/amendment-v2.md",
|
| 295 |
+
]
|
| 296 |
+
source_hashes = {}
|
| 297 |
+
for source in sources:
|
| 298 |
+
dest = art / "source" / source
|
| 299 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 300 |
+
shutil.copyfile(source, dest)
|
| 301 |
+
source_hashes[source] = sha(source)
|
| 302 |
+
data_files = {}
|
| 303 |
+
for seed in cfg["world_seeds"]:
|
| 304 |
+
world = build_world(seed)
|
| 305 |
+
batch = streams(world, cfg)
|
| 306 |
+
report = audit(world, batch, records(tokenizer, world))
|
| 307 |
+
for filename, obj in (
|
| 308 |
+
("world.json", world),
|
| 309 |
+
("streams.json", batch),
|
| 310 |
+
("data-audit.json", report),
|
| 311 |
+
):
|
| 312 |
+
path = art / f"w{seed}" / filename
|
| 313 |
+
write(path, obj)
|
| 314 |
+
data_files[str(path)] = sha(path)
|
| 315 |
+
model_files = {
|
| 316 |
+
str(p): sha(p)
|
| 317 |
+
for p in Path(cfg["model_path"]).iterdir()
|
| 318 |
+
if p.suffix in (".json", ".safetensors") or p.name in ("LICENSE", "README.md")
|
| 319 |
+
}
|
| 320 |
+
write(
|
| 321 |
+
art / "environment.json",
|
| 322 |
+
dict(
|
| 323 |
+
python=platform.python_version(),
|
| 324 |
+
executable=str(Path(__import__("sys").executable)),
|
| 325 |
+
torch=torch.__version__,
|
| 326 |
+
transformers=transformers.__version__,
|
| 327 |
+
gpu_inventory=__import__("subprocess").check_output(
|
| 328 |
+
["nvidia-smi", "--query-gpu=index,name,memory.used,memory.total", "--format=csv"],
|
| 329 |
+
text=True,
|
| 330 |
+
),
|
| 331 |
+
),
|
| 332 |
+
)
|
| 333 |
+
write(
|
| 334 |
+
art / "lock.json",
|
| 335 |
+
dict(
|
| 336 |
+
status="locked_before_training",
|
| 337 |
+
utc=base.now(),
|
| 338 |
+
sources=source_hashes,
|
| 339 |
+
data_files=data_files,
|
| 340 |
+
model_files=model_files,
|
| 341 |
+
config=cfg,
|
| 342 |
+
),
|
| 343 |
+
)
|
| 344 |
+
print(
|
| 345 |
+
json.dumps(dict(status="frozen", worlds=cfg["world_seeds"], arms=cfg["arms"])), flush=True
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def check_lock(cfg):
|
| 350 |
+
lock = base.read(Path(cfg["artifact_root"]) / "lock.json")
|
| 351 |
+
for group in ("sources", "data_files", "model_files"):
|
| 352 |
+
for path, digest in lock[group].items():
|
| 353 |
+
assert sha(path) == digest, path
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def evaluation_rows(world, extras=False):
|
| 357 |
+
rows = []
|
| 358 |
+
for view in (0, 4) if extras else (0,):
|
| 359 |
+
for atom in world["atoms"]:
|
| 360 |
+
rows.append(dict(atom, mode="atomic", view=view, prompt=prompt(atom, view, True)))
|
| 361 |
+
for chain in world["chains"]:
|
| 362 |
+
rows.append(dict(chain, mode="direct", view=view, prompt=prompt(chain, view)))
|
| 363 |
+
return rows
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
@torch.inference_mode()
|
| 367 |
+
def generate(model, tokenizer, rows, cfg):
|
| 368 |
+
model.eval()
|
| 369 |
+
tokenizer.padding_side = "left"
|
| 370 |
+
output = []
|
| 371 |
+
for start in range(0, len(rows), cfg["eval_batch"]):
|
| 372 |
+
chunk = rows[start : start + cfg["eval_batch"]]
|
| 373 |
+
inputs = tokenizer(
|
| 374 |
+
[r["prompt"] for r in chunk],
|
| 375 |
+
padding=True,
|
| 376 |
+
return_tensors="pt",
|
| 377 |
+
add_special_tokens=False,
|
| 378 |
+
).to(cfg["device"])
|
| 379 |
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 380 |
+
tokens = model.generate(
|
| 381 |
+
**inputs,
|
| 382 |
+
do_sample=False,
|
| 383 |
+
max_new_tokens=cfg["max_new_tokens"],
|
| 384 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 385 |
+
eos_token_id=tokenizer.eos_token_id,
|
| 386 |
+
use_cache=True,
|
| 387 |
+
)[:, inputs.input_ids.shape[1] :]
|
| 388 |
+
for row, tok in zip(chunk, tokens.cpu().tolist(), strict=True):
|
| 389 |
+
if tokenizer.eos_token_id in tok:
|
| 390 |
+
tok = tok[: tok.index(tokenizer.eos_token_id) + 1]
|
| 391 |
+
text = tokenizer.decode(tok, skip_special_tokens=True)
|
| 392 |
+
output.append(dict(row, tokens=tok, text=text, correct=base.grade(text, row["answer"])))
|
| 393 |
+
return output
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def evaluate(model, tokenizer, world, cfg, extras=False):
|
| 397 |
+
direct = generate(model, tokenizer, evaluation_rows(world, extras), cfg)
|
| 398 |
+
if not extras:
|
| 399 |
+
return direct
|
| 400 |
+
atoms = {a["id"]: a for a in world["atoms"]}
|
| 401 |
+
lookup = {(r["id"], r["view"]): r for r in direct if r["mode"] == "atomic"}
|
| 402 |
+
second_calls = []
|
| 403 |
+
for row in direct:
|
| 404 |
+
if row["mode"] != "direct":
|
| 405 |
+
continue
|
| 406 |
+
first = lookup[row["atom_ids"][0], row["view"]]
|
| 407 |
+
generated_bridge = first["text"].strip().split("\n")[0].strip().rstrip(".").strip()
|
| 408 |
+
second = dict(atoms[row["atom_ids"][1]], subject=generated_bridge)
|
| 409 |
+
second_calls.append(
|
| 410 |
+
dict(
|
| 411 |
+
row,
|
| 412 |
+
mode="autonomous",
|
| 413 |
+
prompt=prompt(second, row["view"], True),
|
| 414 |
+
generated_bridge=generated_bridge,
|
| 415 |
+
first_tokens=first["tokens"],
|
| 416 |
+
first_correct=first["correct"],
|
| 417 |
+
)
|
| 418 |
+
)
|
| 419 |
+
return direct + generate(model, tokenizer, second_calls, cfg)
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def metrics(rows, world, arm):
|
| 423 |
+
result = {}
|
| 424 |
+
for view in sorted({r["view"] for r in rows}):
|
| 425 |
+
atomic = {r["id"]: r for r in rows if r["view"] == view and r["mode"] == "atomic"}
|
| 426 |
+
for pool in ("familiar", "strict"):
|
| 427 |
+
for role in ("first", "second"):
|
| 428 |
+
selected = [r for r in atomic.values() if r["pool"] == pool and r["role"] == role]
|
| 429 |
+
result[f"v{view}_{pool}_{role}"] = dict(
|
| 430 |
+
correct=sum(r["correct"] for r in selected), n=len(selected)
|
| 431 |
+
)
|
| 432 |
+
for split in ("heldout", "strict", "training"):
|
| 433 |
+
ids = (
|
| 434 |
+
set(world[arm + "_support"])
|
| 435 |
+
if split == "training"
|
| 436 |
+
else {c["id"] for c in world["chains"] if c["split"] == split}
|
| 437 |
+
)
|
| 438 |
+
for mode in ("direct", "autonomous"):
|
| 439 |
+
selected = [
|
| 440 |
+
r for r in rows if r["view"] == view and r["mode"] == mode and r["id"] in ids
|
| 441 |
+
]
|
| 442 |
+
if selected:
|
| 443 |
+
result[f"v{view}_{split}_{mode}"] = dict(
|
| 444 |
+
correct=sum(r["correct"] for r in selected), n=len(selected)
|
| 445 |
+
)
|
| 446 |
+
mastered = [
|
| 447 |
+
r for r in selected if all(atomic[i]["correct"] for i in r["atom_ids"])
|
| 448 |
+
]
|
| 449 |
+
result[f"v{view}_{split}_{mode}_both_atomic"] = dict(
|
| 450 |
+
correct=sum(r["correct"] for r in mastered),
|
| 451 |
+
n=len(mastered),
|
| 452 |
+
full_n=len(selected),
|
| 453 |
+
)
|
| 454 |
+
return result
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def stream_loss(model, inputs, atomic_count, atomic_weight):
|
| 458 |
+
logits = model(
|
| 459 |
+
input_ids=inputs["input_ids"], attention_mask=inputs["attention_mask"], use_cache=False
|
| 460 |
+
).logits[:, :-1]
|
| 461 |
+
labels = inputs["labels"][:, 1:]
|
| 462 |
+
losses = F.cross_entropy(
|
| 463 |
+
logits.float().reshape(-1, logits.shape[-1]),
|
| 464 |
+
labels.reshape(-1),
|
| 465 |
+
reduction="none",
|
| 466 |
+
ignore_index=-100,
|
| 467 |
+
).reshape_as(labels)
|
| 468 |
+
atomic = losses[:atomic_count].sum() / (labels[:atomic_count] != -100).sum()
|
| 469 |
+
comp = losses[atomic_count:].sum() / (labels[atomic_count:] != -100).sum()
|
| 470 |
+
return atomic_weight * atomic + (1 - atomic_weight) * comp
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def run(config_path, seed, arm):
|
| 474 |
+
cfg = base.read(config_path)
|
| 475 |
+
check_lock(cfg)
|
| 476 |
+
assert seed in cfg["world_seeds"] and arm in cfg["arms"]
|
| 477 |
+
art = Path(cfg["artifact_root"]) / f"w{seed}"
|
| 478 |
+
out = Path(cfg["output_root"]) / f"w{seed}-{arm}"
|
| 479 |
+
assert not (out / "status.json").exists(), "Preserve existing execution."
|
| 480 |
+
world, batches = base.read(art / "world.json"), base.read(art / "streams.json")[arm]
|
| 481 |
+
write(out / "status.json", dict(status="running", utc=base.now()))
|
| 482 |
+
started = time.perf_counter()
|
| 483 |
+
torch.set_num_threads(cfg["cpu_threads"])
|
| 484 |
+
torch.manual_seed(cfg["training_seed"])
|
| 485 |
+
torch.cuda.set_device(cfg["device"])
|
| 486 |
+
torch.backends.cuda.matmul.allow_tf32 = False
|
| 487 |
+
torch.backends.cudnn.allow_tf32 = False
|
| 488 |
+
torch.cuda.reset_peak_memory_stats()
|
| 489 |
+
tokenizer = AutoTokenizer.from_pretrained(cfg["model_path"], local_files_only=True)
|
| 490 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 491 |
+
|
| 492 |
+
def load(path):
|
| 493 |
+
return AutoModelForCausalLM.from_pretrained(
|
| 494 |
+
path, torch_dtype=torch.float32, attn_implementation="sdpa", local_files_only=True
|
| 495 |
+
).to(cfg["device"])
|
| 496 |
+
|
| 497 |
+
model = load(cfg["model_path"])
|
| 498 |
+
assert model.config.num_hidden_layers == 28 and model.config.hidden_size == 1024
|
| 499 |
+
assert len({id(layer.mlp) for layer in model.model.layers}) == 28
|
| 500 |
+
model.requires_grad_(True)
|
| 501 |
+
samples = base.parameter_samples(model)
|
| 502 |
+
parameter_count = sum(p.numel() for p in model.parameters())
|
| 503 |
+
rec = records(tokenizer, world)
|
| 504 |
+
optimizer = torch.optim.AdamW(
|
| 505 |
+
model.parameters(), lr=cfg["learning_rate"], weight_decay=cfg["weight_decay"], fused=True
|
| 506 |
+
)
|
| 507 |
+
curve, budget, train_seconds = [], Counter(), 0.0
|
| 508 |
+
for step in range(cfg["steps"] + 1):
|
| 509 |
+
if step in cfg["nodes"]:
|
| 510 |
+
rows = evaluate(model, tokenizer, world, cfg, extras=step == cfg["steps"])
|
| 511 |
+
write(out / f"predictions-{step:05d}.json", rows)
|
| 512 |
+
point = dict(step=step, metrics=metrics(rows, world, arm))
|
| 513 |
+
curve.append(point)
|
| 514 |
+
write(out / "curve.json", curve)
|
| 515 |
+
print(json.dumps(dict(seed=seed, arm=arm, **point)), flush=True)
|
| 516 |
+
if step == cfg["steps"]:
|
| 517 |
+
break
|
| 518 |
+
decay = 0.5 * (
|
| 519 |
+
1
|
| 520 |
+
+ math.cos(
|
| 521 |
+
math.pi * max(0, step - cfg["warmup_steps"]) / (cfg["steps"] - cfg["warmup_steps"])
|
| 522 |
+
)
|
| 523 |
+
)
|
| 524 |
+
lr = (
|
| 525 |
+
cfg["minimum_learning_rate"]
|
| 526 |
+
+ (cfg["learning_rate"] - cfg["minimum_learning_rate"]) * decay
|
| 527 |
+
) * min(1.0, (step + 1) / cfg["warmup_steps"])
|
| 528 |
+
for group in optimizer.param_groups:
|
| 529 |
+
group["lr"] = lr
|
| 530 |
+
docs = docs_for(rec, batches[step])
|
| 531 |
+
width = max(len(d["ids"]) for d in docs)
|
| 532 |
+
budget.update(
|
| 533 |
+
input_tokens=sum(len(d["ids"]) for d in docs),
|
| 534 |
+
supervised_tokens=sum(len(d["ids"]) - 1 for d in docs),
|
| 535 |
+
padded_tokens=len(docs) * width,
|
| 536 |
+
attention_cells=len(docs) * width**2,
|
| 537 |
+
)
|
| 538 |
+
inputs = base.batch_tensors(docs, tokenizer.pad_token_id, cfg["device"])
|
| 539 |
+
model.train()
|
| 540 |
+
torch.cuda.synchronize()
|
| 541 |
+
tick = time.perf_counter()
|
| 542 |
+
optimizer.zero_grad(set_to_none=True)
|
| 543 |
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 544 |
+
loss = stream_loss(model, inputs, cfg["atomic_per_step"], cfg["atomic_loss_weight"])
|
| 545 |
+
assert torch.isfinite(loss)
|
| 546 |
+
loss.backward()
|
| 547 |
+
if step == 0:
|
| 548 |
+
assert all(
|
| 549 |
+
p.requires_grad and p.grad is not None and torch.isfinite(p.grad).all()
|
| 550 |
+
for p in model.parameters()
|
| 551 |
+
)
|
| 552 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), cfg["gradient_clip"])
|
| 553 |
+
optimizer.step()
|
| 554 |
+
torch.cuda.synchronize()
|
| 555 |
+
train_seconds += time.perf_counter() - tick
|
| 556 |
+
if (step + 1) % 64 == 0:
|
| 557 |
+
print(
|
| 558 |
+
json.dumps(
|
| 559 |
+
dict(
|
| 560 |
+
seed=seed,
|
| 561 |
+
arm=arm,
|
| 562 |
+
step=step + 1,
|
| 563 |
+
loss=float(loss.detach()),
|
| 564 |
+
train_seconds=train_seconds,
|
| 565 |
+
)
|
| 566 |
+
),
|
| 567 |
+
flush=True,
|
| 568 |
+
)
|
| 569 |
+
changed = {
|
| 570 |
+
name: not torch.equal(before, base.parameter_samples(model)[name])
|
| 571 |
+
for name, before in samples.items()
|
| 572 |
+
}
|
| 573 |
+
assert all(changed.values())
|
| 574 |
+
model.save_pretrained(out / "model", safe_serialization=True)
|
| 575 |
+
tokenizer.save_pretrained(out / "model")
|
| 576 |
+
architecture = model.config.to_dict()
|
| 577 |
+
final_rows = rows
|
| 578 |
+
del optimizer, model, samples, inputs, loss
|
| 579 |
+
torch.cuda.empty_cache()
|
| 580 |
+
again = evaluate(load(out / "model"), tokenizer, world, cfg, extras=True)
|
| 581 |
+
assert [r["tokens"] for r in final_rows] == [r["tokens"] for r in again]
|
| 582 |
+
assert [r["prompt"] for r in final_rows] == [r["prompt"] for r in again]
|
| 583 |
+
write(
|
| 584 |
+
out / "reload-audit.json",
|
| 585 |
+
dict(
|
| 586 |
+
status="passed",
|
| 587 |
+
predictions=len(again),
|
| 588 |
+
exact_generated_tokens=True,
|
| 589 |
+
exact_autonomous_prompts=True,
|
| 590 |
+
),
|
| 591 |
+
)
|
| 592 |
+
assert dict(budget) == base.read(art / "data-audit.json")["budgets"][arm]
|
| 593 |
+
d, layers = architecture["hidden_size"], architecture["num_hidden_layers"]
|
| 594 |
+
query_width = architecture["num_attention_heads"] * architecture["head_dim"]
|
| 595 |
+
kv = architecture["num_key_value_heads"] * architecture["head_dim"]
|
| 596 |
+
per_token = (
|
| 597 |
+
layers * (2 * d * query_width + 2 * d * kv + 3 * d * architecture["intermediate_size"])
|
| 598 |
+
+ d * architecture["vocab_size"]
|
| 599 |
+
)
|
| 600 |
+
flops = (
|
| 601 |
+
6 * per_token * budget["padded_tokens"]
|
| 602 |
+
+ 12 * layers * query_width * budget["attention_cells"]
|
| 603 |
+
)
|
| 604 |
+
summary = dict(
|
| 605 |
+
status="complete",
|
| 606 |
+
phase=cfg["phase"],
|
| 607 |
+
utc=base.now(),
|
| 608 |
+
world_seed=seed,
|
| 609 |
+
arm=arm,
|
| 610 |
+
metrics=metrics(final_rows, world, arm),
|
| 611 |
+
updates=cfg["steps"],
|
| 612 |
+
budget=dict(budget),
|
| 613 |
+
train_seconds=train_seconds,
|
| 614 |
+
process_seconds=time.perf_counter() - started,
|
| 615 |
+
estimated_training_matrix_flops=flops,
|
| 616 |
+
peak_gpu_bytes=torch.cuda.max_memory_allocated(),
|
| 617 |
+
parameter_count=parameter_count,
|
| 618 |
+
sampled_parameters_changed=changed,
|
| 619 |
+
torch_version=torch.__version__,
|
| 620 |
+
transformers_version=transformers.__version__,
|
| 621 |
+
gpu=torch.cuda.get_device_name(),
|
| 622 |
+
tf32=False,
|
| 623 |
+
lock_sha256=sha(Path(cfg["artifact_root"]) / "lock.json"),
|
| 624 |
+
checkpoint_files={str(p): sha(p) for p in (out / "model").glob("*.safetensors")},
|
| 625 |
+
)
|
| 626 |
+
write(out / "summary.json", summary)
|
| 627 |
+
write(out / "status.json", dict(status="complete", utc=base.now()))
|
| 628 |
+
print(json.dumps(summary), flush=True)
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
def report(config_path):
|
| 632 |
+
cfg = base.read(config_path)
|
| 633 |
+
check_lock(cfg)
|
| 634 |
+
runs, checks = {}, 0
|
| 635 |
+
for seed in cfg["world_seeds"]:
|
| 636 |
+
world = base.read(Path(cfg["artifact_root"]) / f"w{seed}" / "world.json")
|
| 637 |
+
for arm in cfg["arms"]:
|
| 638 |
+
out = Path(cfg["output_root"]) / f"w{seed}-{arm}"
|
| 639 |
+
summary = base.read(out / "summary.json")
|
| 640 |
+
assert base.read(out / "reload-audit.json")["status"] == "passed"
|
| 641 |
+
for point in base.read(out / "curve.json"):
|
| 642 |
+
rows = base.read(out / f"predictions-{point['step']:05d}.json")
|
| 643 |
+
assert all(base.grade(r["text"], r["answer"]) == r["correct"] for r in rows)
|
| 644 |
+
assert point["metrics"] == metrics(rows, world, arm)
|
| 645 |
+
checks += len(rows)
|
| 646 |
+
assert summary["metrics"] == metrics(rows, world, arm)
|
| 647 |
+
runs[f"w{seed}-{arm}"] = summary
|
| 648 |
+
differences = {}
|
| 649 |
+
if len(cfg["arms"]) == 2:
|
| 650 |
+
for seed in cfg["world_seeds"]:
|
| 651 |
+
diff = {}
|
| 652 |
+
for key in runs[f"w{seed}-high"]["metrics"]:
|
| 653 |
+
high, low = [runs[f"w{seed}-{a}"]["metrics"][key] for a in ("high", "low")]
|
| 654 |
+
if key.endswith("both_atomic") or "training" in key:
|
| 655 |
+
continue
|
| 656 |
+
diff[key] = high["correct"] / high["n"] - low["correct"] / low["n"]
|
| 657 |
+
differences[str(seed)] = diff
|
| 658 |
+
write(
|
| 659 |
+
Path(cfg["artifact_root"]) / "summary.json",
|
| 660 |
+
dict(
|
| 661 |
+
status="complete",
|
| 662 |
+
phase=cfg["phase"],
|
| 663 |
+
independent_worlds=len(cfg["world_seeds"]),
|
| 664 |
+
training_initializations=1,
|
| 665 |
+
runs=runs,
|
| 666 |
+
per_world_high_minus_low=differences,
|
| 667 |
+
independent_node_prediction_checks=checks,
|
| 668 |
+
total_updates=sum(r["updates"] for r in runs.values()),
|
| 669 |
+
total_train_seconds=sum(r["train_seconds"] for r in runs.values()),
|
| 670 |
+
total_process_seconds=sum(r["process_seconds"] for r in runs.values()),
|
| 671 |
+
),
|
| 672 |
+
)
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
def main():
|
| 676 |
+
parser = argparse.ArgumentParser()
|
| 677 |
+
parser.add_argument("action", choices=("freeze", "run", "report"))
|
| 678 |
+
parser.add_argument("--config", required=True)
|
| 679 |
+
parser.add_argument("--world", type=int)
|
| 680 |
+
parser.add_argument("--arm", choices=("low", "high"))
|
| 681 |
+
args = parser.parse_args()
|
| 682 |
+
if args.action == "run":
|
| 683 |
+
run(args.config, args.world, args.arm)
|
| 684 |
+
elif args.action == "freeze":
|
| 685 |
+
freeze(args.config)
|
| 686 |
+
else:
|
| 687 |
+
report(args.config)
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/neural.py
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled nonlinear memory editing with full old-fact replay on CPU.
|
| 2 |
+
|
| 3 |
+
This measures finite-budget optimization, not minimum representational capacity.
|
| 4 |
+
The data generator's shared rule does not establish the model's internal mechanism.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import argparse
|
| 8 |
+
import copy
|
| 9 |
+
import json
|
| 10 |
+
import math
|
| 11 |
+
import platform
|
| 12 |
+
import statistics
|
| 13 |
+
import subprocess
|
| 14 |
+
import time
|
| 15 |
+
from dataclasses import asdict, dataclass
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
try:
|
| 21 |
+
import torch
|
| 22 |
+
from torch import nn
|
| 23 |
+
from torch.nn import functional as F
|
| 24 |
+
except ModuleNotFoundError as exc:
|
| 25 |
+
raise SystemExit("Neural experiments require PyTorch: pip install '.[neural]'") from exc
|
| 26 |
+
|
| 27 |
+
from .neural_data import make_world
|
| 28 |
+
from .neural_models import build_model, edit_parameters
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass(frozen=True)
|
| 32 |
+
class NeuralConfig:
|
| 33 |
+
model: str = "mlp"
|
| 34 |
+
seeds: tuple[int, ...] = (0, 1, 2)
|
| 35 |
+
data_seed: int = 0
|
| 36 |
+
entities: int = 24
|
| 37 |
+
attributes: int = 8
|
| 38 |
+
groups: int = 3
|
| 39 |
+
answers: int = 4
|
| 40 |
+
width: int = 32
|
| 41 |
+
hidden: int = 64
|
| 42 |
+
layers: int = 2
|
| 43 |
+
heads: int = 4
|
| 44 |
+
pretrain_steps: int = 400
|
| 45 |
+
edit_steps: int = 100
|
| 46 |
+
scratch_steps: int = 400
|
| 47 |
+
lr: float = 0.01
|
| 48 |
+
retention_weight: float = 1.0
|
| 49 |
+
edit_scope: str = "ffn"
|
| 50 |
+
eval_every: int = 10
|
| 51 |
+
success_threshold: float = 0.95
|
| 52 |
+
threads: int = 1
|
| 53 |
+
|
| 54 |
+
def validate(self) -> None:
|
| 55 |
+
if self.model not in {"mlp", "transformer"} or self.edit_scope not in {"ffn", "all"}:
|
| 56 |
+
raise ValueError("unsupported model or edit scope")
|
| 57 |
+
for name in ("pretrain_steps", "edit_steps", "scratch_steps", "eval_every", "threads"):
|
| 58 |
+
value = getattr(self, name)
|
| 59 |
+
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
|
| 60 |
+
raise ValueError(f"{name} must be a positive integer")
|
| 61 |
+
if not self.seeds or len(set(self.seeds)) != len(self.seeds):
|
| 62 |
+
raise ValueError("seeds must be nonempty and unique")
|
| 63 |
+
if any(isinstance(s, bool) or not isinstance(s, int) or s < 0 for s in self.seeds):
|
| 64 |
+
raise ValueError("seeds must be nonnegative integers")
|
| 65 |
+
if not math.isfinite(self.lr) or self.lr <= 0:
|
| 66 |
+
raise ValueError("lr must be finite and positive")
|
| 67 |
+
if not math.isfinite(self.retention_weight) or self.retention_weight < 0:
|
| 68 |
+
raise ValueError("retention_weight must be finite and nonnegative")
|
| 69 |
+
if not 0 < self.success_threshold <= 1:
|
| 70 |
+
raise ValueError("success_threshold must be in (0, 1]")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@torch.no_grad()
|
| 74 |
+
def evaluate(model: nn.Module, x: torch.Tensor, y: torch.Tensor, mask: torch.Tensor) -> dict:
|
| 75 |
+
"""Evaluate answers against a target world, separating edits and retained facts."""
|
| 76 |
+
model.eval()
|
| 77 |
+
logits = model(x)
|
| 78 |
+
if not torch.isfinite(logits).all():
|
| 79 |
+
raise ValueError("non-finite model outputs")
|
| 80 |
+
correct = logits.argmax(dim=-1).eq(y).float()
|
| 81 |
+
target_logits = logits.gather(1, y[:, None]).squeeze(1)
|
| 82 |
+
competitors = logits.clone().scatter_(1, y[:, None], float("-inf")).max(dim=1).values
|
| 83 |
+
margins = target_logits - competitors
|
| 84 |
+
return {
|
| 85 |
+
"all_accuracy": correct.mean().item(),
|
| 86 |
+
"edit_accuracy": correct[mask].mean().item(),
|
| 87 |
+
"retain_accuracy": correct[~mask].mean().item(),
|
| 88 |
+
"edit_target_nll": F.cross_entropy(logits[mask], y[mask]).item(),
|
| 89 |
+
"edit_margin": margins[mask].mean().item(),
|
| 90 |
+
"retain_margin": margins[~mask].mean().item(),
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def fit(
|
| 95 |
+
model: nn.Module,
|
| 96 |
+
x: torch.Tensor,
|
| 97 |
+
y: torch.Tensor,
|
| 98 |
+
mask: torch.Tensor,
|
| 99 |
+
*,
|
| 100 |
+
steps: int,
|
| 101 |
+
config: NeuralConfig,
|
| 102 |
+
is_edit: bool = False,
|
| 103 |
+
) -> dict:
|
| 104 |
+
"""Use a fresh optimizer, fixed steps, and a documented full-batch objective."""
|
| 105 |
+
parameters = [p for p in model.parameters() if p.requires_grad]
|
| 106 |
+
optimizer = torch.optim.Adam(parameters, lr=config.lr)
|
| 107 |
+
history = []
|
| 108 |
+
first_success = None
|
| 109 |
+
started = time.perf_counter()
|
| 110 |
+
for step in range(steps + 1):
|
| 111 |
+
if step % config.eval_every == 0 or step == steps:
|
| 112 |
+
metrics = evaluate(model, x, y, mask)
|
| 113 |
+
history.append({"step": step, **metrics})
|
| 114 |
+
if (
|
| 115 |
+
first_success is None
|
| 116 |
+
and min(metrics["edit_accuracy"], metrics["retain_accuracy"])
|
| 117 |
+
>= config.success_threshold
|
| 118 |
+
):
|
| 119 |
+
first_success = step
|
| 120 |
+
if step == steps:
|
| 121 |
+
break
|
| 122 |
+
model.train()
|
| 123 |
+
optimizer.zero_grad(set_to_none=True)
|
| 124 |
+
logits = model(x)
|
| 125 |
+
if is_edit:
|
| 126 |
+
loss = F.cross_entropy(logits[mask], y[mask])
|
| 127 |
+
if config.retention_weight:
|
| 128 |
+
loss = loss + config.retention_weight * F.cross_entropy(logits[~mask], y[~mask])
|
| 129 |
+
else:
|
| 130 |
+
loss = F.cross_entropy(logits, y)
|
| 131 |
+
if not torch.isfinite(loss):
|
| 132 |
+
raise ValueError("training diverged to a non-finite loss")
|
| 133 |
+
loss.backward()
|
| 134 |
+
optimizer.step()
|
| 135 |
+
return {
|
| 136 |
+
"steps": steps,
|
| 137 |
+
"trainable_parameters": sum(p.numel() for p in parameters),
|
| 138 |
+
"first_success_step": first_success,
|
| 139 |
+
"elapsed_seconds": time.perf_counter() - started,
|
| 140 |
+
"history": history,
|
| 141 |
+
"objective": "edit_ce + retention_weight * retained_ce" if is_edit else "full_world_ce",
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def _summary(runs: list[dict]) -> dict:
|
| 146 |
+
eligible = [run for run in runs if run["baseline_quality_passed"]]
|
| 147 |
+
result = {"eligible_seeds": [run["seed"] for run in eligible], "cases": {}}
|
| 148 |
+
for name in ("rule", "exception"):
|
| 149 |
+
result["cases"][name] = {}
|
| 150 |
+
for metric in ("edit_accuracy", "retain_accuracy"):
|
| 151 |
+
values = [run["cases"][name]["after"][metric] for run in eligible]
|
| 152 |
+
result["cases"][name][metric] = {
|
| 153 |
+
"mean": statistics.mean(values) if values else None,
|
| 154 |
+
"sample_std": statistics.stdev(values) if len(values) > 1 else None,
|
| 155 |
+
"n": len(values),
|
| 156 |
+
}
|
| 157 |
+
return result
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _revision() -> str | None:
|
| 161 |
+
"""Best-effort source revision; an installed wheel may not have a checkout."""
|
| 162 |
+
source_root = Path(__file__).resolve().parents[2]
|
| 163 |
+
if not (source_root / ".git").exists():
|
| 164 |
+
return None
|
| 165 |
+
try:
|
| 166 |
+
revision = subprocess.check_output(
|
| 167 |
+
["git", "rev-parse", "HEAD"], cwd=source_root, text=True, stderr=subprocess.DEVNULL
|
| 168 |
+
).strip()
|
| 169 |
+
dirty = subprocess.check_output(
|
| 170 |
+
["git", "status", "--porcelain"], cwd=source_root, text=True
|
| 171 |
+
).strip()
|
| 172 |
+
return revision + ("+dirty" if dirty else "")
|
| 173 |
+
except (OSError, subprocess.CalledProcessError):
|
| 174 |
+
return None
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def run_experiment(config: NeuralConfig) -> dict:
|
| 178 |
+
config.validate()
|
| 179 |
+
world = make_world(
|
| 180 |
+
n_entities=config.entities,
|
| 181 |
+
n_attributes=config.attributes,
|
| 182 |
+
n_groups=config.groups,
|
| 183 |
+
n_answers=config.answers,
|
| 184 |
+
seed=config.data_seed,
|
| 185 |
+
)
|
| 186 |
+
torch.set_num_threads(config.threads)
|
| 187 |
+
torch.use_deterministic_algorithms(True)
|
| 188 |
+
x = torch.as_tensor(world.x, dtype=torch.long)
|
| 189 |
+
original = torch.as_tensor(world.original, dtype=torch.long)
|
| 190 |
+
mask = torch.as_tensor(world.edit_mask, dtype=torch.bool)
|
| 191 |
+
runs = []
|
| 192 |
+
for seed in config.seeds:
|
| 193 |
+
torch.manual_seed(seed)
|
| 194 |
+
initial = build_model(
|
| 195 |
+
config.model,
|
| 196 |
+
config.entities,
|
| 197 |
+
config.attributes,
|
| 198 |
+
config.answers,
|
| 199 |
+
width=config.width,
|
| 200 |
+
hidden=config.hidden,
|
| 201 |
+
layers=config.layers,
|
| 202 |
+
heads=config.heads,
|
| 203 |
+
)
|
| 204 |
+
base = copy.deepcopy(initial)
|
| 205 |
+
baseline_training = fit(
|
| 206 |
+
base,
|
| 207 |
+
x,
|
| 208 |
+
original,
|
| 209 |
+
mask,
|
| 210 |
+
steps=config.pretrain_steps,
|
| 211 |
+
config=config,
|
| 212 |
+
)
|
| 213 |
+
baseline = evaluate(base, x, original, mask)
|
| 214 |
+
run = {
|
| 215 |
+
"seed": seed,
|
| 216 |
+
"parameter_count": sum(p.numel() for p in base.parameters()),
|
| 217 |
+
"baseline": baseline,
|
| 218 |
+
"baseline_quality_passed": min(baseline["edit_accuracy"], baseline["retain_accuracy"])
|
| 219 |
+
>= config.success_threshold,
|
| 220 |
+
"baseline_training": baseline_training,
|
| 221 |
+
"cases": {},
|
| 222 |
+
}
|
| 223 |
+
for name in ("rule", "exception"):
|
| 224 |
+
target = torch.as_tensor(getattr(world, name), dtype=torch.long)
|
| 225 |
+
edited = copy.deepcopy(base)
|
| 226 |
+
edit_parameters(edited, scope=config.edit_scope)
|
| 227 |
+
before = evaluate(edited, x, target, mask)
|
| 228 |
+
edit_training = fit(
|
| 229 |
+
edited,
|
| 230 |
+
x,
|
| 231 |
+
target,
|
| 232 |
+
mask,
|
| 233 |
+
steps=config.edit_steps,
|
| 234 |
+
config=config,
|
| 235 |
+
is_edit=True,
|
| 236 |
+
)
|
| 237 |
+
scratch = copy.deepcopy(initial)
|
| 238 |
+
scratch_training = fit(
|
| 239 |
+
scratch,
|
| 240 |
+
x,
|
| 241 |
+
target,
|
| 242 |
+
mask,
|
| 243 |
+
steps=config.scratch_steps,
|
| 244 |
+
config=config,
|
| 245 |
+
)
|
| 246 |
+
run["cases"][name] = {
|
| 247 |
+
"before": before,
|
| 248 |
+
"after": evaluate(edited, x, target, mask),
|
| 249 |
+
"scratch": evaluate(scratch, x, target, mask),
|
| 250 |
+
"edit_training": edit_training,
|
| 251 |
+
"scratch_training": scratch_training,
|
| 252 |
+
}
|
| 253 |
+
runs.append(run)
|
| 254 |
+
return {
|
| 255 |
+
"experiment": "nonlinear_synthetic_memory_editing",
|
| 256 |
+
"config": asdict(config),
|
| 257 |
+
"versions": {
|
| 258 |
+
"python": platform.python_version(),
|
| 259 |
+
"numpy": np.__version__,
|
| 260 |
+
"torch": torch.__version__,
|
| 261 |
+
},
|
| 262 |
+
"revision": _revision(),
|
| 263 |
+
"device": "cpu",
|
| 264 |
+
"world": world.to_metadata(),
|
| 265 |
+
"protocol": {
|
| 266 |
+
"paired_edit_initialization": "identical trained checkpoint; fresh Adam per case",
|
| 267 |
+
"paired_scratch_initialization": "identical untrained initialization; all parameters",
|
| 268 |
+
"replay": "all retained facts available; uniform CE within each edit/retain subset",
|
| 269 |
+
"success": "both edit and retain accuracy >= threshold at evaluation checkpoints",
|
| 270 |
+
"summary_filter": "only seeds passing baseline threshold on both subsets",
|
| 271 |
+
"limits": [
|
| 272 |
+
"Target surprisal is measured, not matched.",
|
| 273 |
+
"Generator structure is not a measure of learned neural degrees of freedom.",
|
| 274 |
+
"Scratch failure at finite budget is not an impossibility result.",
|
| 275 |
+
"Scratch trains all parameters; FFN-only edit failures may reflect "
|
| 276 |
+
"a restricted update space.",
|
| 277 |
+
"No natural-language paraphrases or pretrained LLM are evaluated.",
|
| 278 |
+
"Cross-platform and cross-version bitwise reproducibility is not guaranteed.",
|
| 279 |
+
],
|
| 280 |
+
},
|
| 281 |
+
"runs": runs,
|
| 282 |
+
"summary": _summary(runs),
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def main(argv: list[str] | None = None) -> int:
|
| 287 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 288 |
+
parser.add_argument("--model", choices=("mlp", "transformer"), default="mlp")
|
| 289 |
+
parser.add_argument("--seeds", type=int, nargs="+", default=[0, 1, 2])
|
| 290 |
+
parser.add_argument("--edit-scope", choices=("ffn", "all"), default="ffn")
|
| 291 |
+
defaults = asdict(NeuralConfig())
|
| 292 |
+
for name in (
|
| 293 |
+
"data_seed",
|
| 294 |
+
"entities",
|
| 295 |
+
"attributes",
|
| 296 |
+
"groups",
|
| 297 |
+
"answers",
|
| 298 |
+
"width",
|
| 299 |
+
"hidden",
|
| 300 |
+
"layers",
|
| 301 |
+
"heads",
|
| 302 |
+
"pretrain_steps",
|
| 303 |
+
"edit_steps",
|
| 304 |
+
"scratch_steps",
|
| 305 |
+
"eval_every",
|
| 306 |
+
"threads",
|
| 307 |
+
):
|
| 308 |
+
parser.add_argument("--" + name.replace("_", "-"), type=int, default=defaults[name])
|
| 309 |
+
for name in ("lr", "retention_weight", "success_threshold"):
|
| 310 |
+
parser.add_argument("--" + name.replace("_", "-"), type=float, default=defaults[name])
|
| 311 |
+
parser.add_argument("--output", type=Path, help="save the same JSON printed to stdout")
|
| 312 |
+
args = vars(parser.parse_args(argv))
|
| 313 |
+
output = args.pop("output")
|
| 314 |
+
args["seeds"] = tuple(args["seeds"])
|
| 315 |
+
try:
|
| 316 |
+
report = run_experiment(NeuralConfig(**args))
|
| 317 |
+
serialized = json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False)
|
| 318 |
+
if output:
|
| 319 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 320 |
+
output.write_text(serialized + "\n", encoding="utf-8")
|
| 321 |
+
except (ValueError, OSError) as exc:
|
| 322 |
+
parser.error(str(exc))
|
| 323 |
+
print(serialized)
|
| 324 |
+
return 0
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
if __name__ == "__main__":
|
| 328 |
+
raise SystemExit(main())
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/neural_data.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Balanced fact-table interventions, defined independently of model training."""
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@dataclass(frozen=True)
|
| 10 |
+
class SyntheticWorld:
|
| 11 |
+
"""All entity/attribute queries and two interventions on identical support."""
|
| 12 |
+
|
| 13 |
+
x: np.ndarray
|
| 14 |
+
original: np.ndarray
|
| 15 |
+
rule: np.ndarray
|
| 16 |
+
exception: np.ndarray
|
| 17 |
+
edit_mask: np.ndarray
|
| 18 |
+
group_ids: np.ndarray
|
| 19 |
+
n_entities: int
|
| 20 |
+
n_attributes: int
|
| 21 |
+
n_groups: int
|
| 22 |
+
n_answers: int
|
| 23 |
+
seed: int
|
| 24 |
+
|
| 25 |
+
def task_exceptions(self, labels: np.ndarray) -> int:
|
| 26 |
+
"""Minimum overrides of a group+attribute table; not neural model degrees of freedom."""
|
| 27 |
+
labels = np.asarray(labels)
|
| 28 |
+
if labels.shape != self.original.shape:
|
| 29 |
+
raise ValueError("labels must contain one answer per fact")
|
| 30 |
+
exceptions = 0
|
| 31 |
+
for group in range(self.n_groups):
|
| 32 |
+
for attribute in range(self.n_attributes):
|
| 33 |
+
cell = labels[(self.group_ids[self.x[:, 0]] == group) & (self.x[:, 1] == attribute)]
|
| 34 |
+
exceptions += cell.size - int(np.bincount(cell, minlength=self.n_answers).max())
|
| 35 |
+
return exceptions
|
| 36 |
+
|
| 37 |
+
def to_metadata(self) -> dict[str, Any]:
|
| 38 |
+
"""JSON-compatible task diagnostics, available before training or editing."""
|
| 39 |
+
return {
|
| 40 |
+
"n_entities": self.n_entities,
|
| 41 |
+
"n_attributes": self.n_attributes,
|
| 42 |
+
"n_groups": self.n_groups,
|
| 43 |
+
"n_answers": self.n_answers,
|
| 44 |
+
"seed": self.seed,
|
| 45 |
+
"n_facts": len(self.x),
|
| 46 |
+
"n_edited": int(self.edit_mask.sum()),
|
| 47 |
+
"edited_entities": np.unique(self.x[self.edit_mask, 0]).tolist(),
|
| 48 |
+
"edited_attributes": np.unique(self.x[self.edit_mask, 1]).tolist(),
|
| 49 |
+
"matched_controls": [
|
| 50 |
+
"edit support",
|
| 51 |
+
"edited fact count",
|
| 52 |
+
"entity and attribute coverage",
|
| 53 |
+
"per-entity target-answer histograms",
|
| 54 |
+
],
|
| 55 |
+
"task_side_group_attribute_exceptions": {
|
| 56 |
+
name: self.task_exceptions(getattr(self, name))
|
| 57 |
+
for name in ("original", "rule", "exception")
|
| 58 |
+
},
|
| 59 |
+
"structure_metric_scope": (
|
| 60 |
+
"Minimum label overrides of a deterministic group+attribute answer table. "
|
| 61 |
+
"This is a task-side generator property, not neural degrees of freedom "
|
| 62 |
+
"or evidence that a trained network learned these groups."
|
| 63 |
+
),
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def make_world(
|
| 68 |
+
n_entities: int = 24,
|
| 69 |
+
n_attributes: int = 8,
|
| 70 |
+
n_groups: int = 3,
|
| 71 |
+
n_answers: int = 4,
|
| 72 |
+
seed: int = 0,
|
| 73 |
+
) -> SyntheticWorld:
|
| 74 |
+
"""Generate balanced labels and conflicting exception patterns in edited group 0.
|
| 75 |
+
|
| 76 |
+
Entity targets are independently shuffled, conditioned on changing every edited
|
| 77 |
+
fact. The final row is resampled if all entities happen to share one pattern.
|
| 78 |
+
Rejection sampling is bounded, including for long attribute tables.
|
| 79 |
+
"""
|
| 80 |
+
for name, value in {
|
| 81 |
+
"n_entities": n_entities,
|
| 82 |
+
"n_attributes": n_attributes,
|
| 83 |
+
"n_groups": n_groups,
|
| 84 |
+
"n_answers": n_answers,
|
| 85 |
+
"seed": seed,
|
| 86 |
+
}.items():
|
| 87 |
+
if isinstance(value, bool) or not isinstance(value, (int, np.integer)):
|
| 88 |
+
raise ValueError(f"{name} must be an integer")
|
| 89 |
+
if value < (0 if name == "seed" else 1):
|
| 90 |
+
raise ValueError(f"{name} is outside its valid range")
|
| 91 |
+
n_entities, n_attributes, n_groups, n_answers, seed = map(
|
| 92 |
+
int,
|
| 93 |
+
(n_entities, n_attributes, n_groups, n_answers, seed),
|
| 94 |
+
)
|
| 95 |
+
if n_groups < 2:
|
| 96 |
+
raise ValueError("n_groups must be >= 2 to leave retained facts outside the edit support")
|
| 97 |
+
if n_entities % n_groups or n_entities // n_groups < 2:
|
| 98 |
+
raise ValueError("n_entities must be divisible by n_groups, with >= 2 entities per group")
|
| 99 |
+
if n_answers < 3 or n_attributes % n_answers:
|
| 100 |
+
raise ValueError("n_answers must be >= 3 and divide n_attributes")
|
| 101 |
+
|
| 102 |
+
rng = np.random.default_rng(seed)
|
| 103 |
+
group_ids = np.repeat(np.arange(n_groups), n_entities // n_groups).astype(np.int64)
|
| 104 |
+
x = np.column_stack(
|
| 105 |
+
(
|
| 106 |
+
np.repeat(np.arange(n_entities), n_attributes),
|
| 107 |
+
np.tile(np.arange(n_attributes), n_entities),
|
| 108 |
+
)
|
| 109 |
+
).astype(np.int64)
|
| 110 |
+
original = (group_ids[x[:, 0]] + x[:, 1]) % n_answers
|
| 111 |
+
edit_mask = group_ids[x[:, 0]] == 0
|
| 112 |
+
rule = original.copy()
|
| 113 |
+
rule[edit_mask] = (rule[edit_mask] + 1) % n_answers
|
| 114 |
+
exception = original.copy()
|
| 115 |
+
# Every edited entity has the same balanced original labels and rule targets.
|
| 116 |
+
old_row = original[:n_attributes]
|
| 117 |
+
edited_entities = np.flatnonzero(group_ids == 0)
|
| 118 |
+
sampled_rows = []
|
| 119 |
+
for row_index, entity in enumerate(edited_entities):
|
| 120 |
+
for _ in range(10_000):
|
| 121 |
+
candidate = rng.permutation(old_row)
|
| 122 |
+
shared_pattern = row_index == len(edited_entities) - 1 and all(
|
| 123 |
+
np.array_equal(row, candidate) for row in sampled_rows
|
| 124 |
+
)
|
| 125 |
+
if np.all(candidate != old_row) and not shared_pattern:
|
| 126 |
+
sampled_rows.append(candidate)
|
| 127 |
+
start = entity * n_attributes
|
| 128 |
+
exception[start : start + n_attributes] = candidate
|
| 129 |
+
break
|
| 130 |
+
else:
|
| 131 |
+
raise ValueError(
|
| 132 |
+
"Could not sample balanced exception patterns in 10,000 attempts; "
|
| 133 |
+
"use more answers or fewer attributes to make rejection sampling practical."
|
| 134 |
+
)
|
| 135 |
+
return SyntheticWorld(
|
| 136 |
+
x,
|
| 137 |
+
original,
|
| 138 |
+
rule,
|
| 139 |
+
exception,
|
| 140 |
+
edit_mask,
|
| 141 |
+
group_ids,
|
| 142 |
+
n_entities,
|
| 143 |
+
n_attributes,
|
| 144 |
+
n_groups,
|
| 145 |
+
n_answers,
|
| 146 |
+
seed,
|
| 147 |
+
)
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/neural_models.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Trainable nonlinear fact models; importing this module requires PyTorch."""
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from torch import nn
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class FactMLP(nn.Module):
|
| 8 |
+
"""Separate entity/attribute embeddings followed by a nonlinear MLP."""
|
| 9 |
+
|
| 10 |
+
def __init__(
|
| 11 |
+
self,
|
| 12 |
+
n_entities: int,
|
| 13 |
+
n_attributes: int,
|
| 14 |
+
n_answers: int,
|
| 15 |
+
width: int,
|
| 16 |
+
hidden: int,
|
| 17 |
+
layers: int,
|
| 18 |
+
) -> None:
|
| 19 |
+
super().__init__()
|
| 20 |
+
self.entity_embedding = nn.Embedding(n_entities, width)
|
| 21 |
+
self.attribute_embedding = nn.Embedding(n_attributes, width)
|
| 22 |
+
blocks = []
|
| 23 |
+
for layer in range(layers):
|
| 24 |
+
blocks.extend((nn.Linear(2 * width if layer == 0 else hidden, hidden), nn.GELU()))
|
| 25 |
+
self.hidden = nn.Sequential(*blocks)
|
| 26 |
+
self.answer_head = nn.Linear(hidden, n_answers)
|
| 27 |
+
|
| 28 |
+
def forward(self, facts: torch.Tensor) -> torch.Tensor:
|
| 29 |
+
_validate_facts(facts)
|
| 30 |
+
embedded = torch.cat(
|
| 31 |
+
(
|
| 32 |
+
self.entity_embedding(facts[:, 0]),
|
| 33 |
+
self.attribute_embedding(facts[:, 1]),
|
| 34 |
+
),
|
| 35 |
+
dim=-1,
|
| 36 |
+
)
|
| 37 |
+
return self.answer_head(self.hidden(embedded))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class FactTransformer(nn.Module):
|
| 41 |
+
"""Causal [ENTITY, ATTRIBUTE, QUERY] transformer with an answer classification head."""
|
| 42 |
+
|
| 43 |
+
def __init__(
|
| 44 |
+
self,
|
| 45 |
+
n_entities: int,
|
| 46 |
+
n_attributes: int,
|
| 47 |
+
n_answers: int,
|
| 48 |
+
width: int,
|
| 49 |
+
hidden: int,
|
| 50 |
+
layers: int,
|
| 51 |
+
heads: int,
|
| 52 |
+
) -> None:
|
| 53 |
+
super().__init__()
|
| 54 |
+
self.n_entities = n_entities
|
| 55 |
+
self.query_id = n_entities + n_attributes
|
| 56 |
+
self.token_embedding = nn.Embedding(self.query_id + 1, width)
|
| 57 |
+
self.position_embedding = nn.Embedding(3, width)
|
| 58 |
+
encoder_layer = nn.TransformerEncoderLayer(
|
| 59 |
+
d_model=width,
|
| 60 |
+
nhead=heads,
|
| 61 |
+
dim_feedforward=hidden,
|
| 62 |
+
dropout=0.0,
|
| 63 |
+
activation="gelu",
|
| 64 |
+
batch_first=True,
|
| 65 |
+
norm_first=True,
|
| 66 |
+
)
|
| 67 |
+
self.encoder = nn.TransformerEncoder(
|
| 68 |
+
encoder_layer,
|
| 69 |
+
num_layers=layers,
|
| 70 |
+
norm=nn.LayerNorm(width),
|
| 71 |
+
enable_nested_tensor=False,
|
| 72 |
+
)
|
| 73 |
+
# TransformerEncoder clones its prototype; initialize each layer independently.
|
| 74 |
+
for layer in self.encoder.layers:
|
| 75 |
+
nn.init.xavier_uniform_(layer.self_attn.in_proj_weight)
|
| 76 |
+
for module in layer.modules():
|
| 77 |
+
if isinstance(module, nn.Linear):
|
| 78 |
+
nn.init.xavier_uniform_(module.weight)
|
| 79 |
+
if module.bias is not None:
|
| 80 |
+
nn.init.zeros_(module.bias)
|
| 81 |
+
self.answer_head = nn.Linear(width, n_answers)
|
| 82 |
+
self.register_buffer("causal_mask", torch.triu(torch.ones(3, 3, dtype=torch.bool), 1))
|
| 83 |
+
|
| 84 |
+
def forward(self, facts: torch.Tensor) -> torch.Tensor:
|
| 85 |
+
_validate_facts(facts)
|
| 86 |
+
tokens = torch.stack(
|
| 87 |
+
(
|
| 88 |
+
facts[:, 0],
|
| 89 |
+
facts[:, 1] + self.n_entities,
|
| 90 |
+
torch.full_like(facts[:, 0], self.query_id),
|
| 91 |
+
),
|
| 92 |
+
dim=1,
|
| 93 |
+
)
|
| 94 |
+
embedded = self.token_embedding(tokens)
|
| 95 |
+
embedded = embedded + self.position_embedding(torch.arange(3, device=facts.device))
|
| 96 |
+
encoded = self.encoder(embedded, mask=self.causal_mask)
|
| 97 |
+
return self.answer_head(encoded[:, -1])
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _validate_facts(facts: torch.Tensor) -> None:
|
| 101 |
+
if facts.ndim != 2 or facts.shape[1] != 2 or facts.dtype != torch.long:
|
| 102 |
+
raise ValueError("facts must be an int64 tensor with shape (n_facts, 2)")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def build_model(
|
| 106 |
+
model_type: str,
|
| 107 |
+
n_entities: int,
|
| 108 |
+
n_attributes: int,
|
| 109 |
+
n_answers: int,
|
| 110 |
+
width: int = 32,
|
| 111 |
+
hidden: int = 64,
|
| 112 |
+
layers: int = 2,
|
| 113 |
+
heads: int = 4,
|
| 114 |
+
) -> nn.Module:
|
| 115 |
+
"""Construct an MLP or a causal transformer; initialization uses the torch RNG."""
|
| 116 |
+
for name, value in {
|
| 117 |
+
"n_entities": n_entities,
|
| 118 |
+
"n_attributes": n_attributes,
|
| 119 |
+
"n_answers": n_answers,
|
| 120 |
+
"width": width,
|
| 121 |
+
"hidden": hidden,
|
| 122 |
+
"layers": layers,
|
| 123 |
+
"heads": heads,
|
| 124 |
+
}.items():
|
| 125 |
+
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
| 126 |
+
raise ValueError(f"{name} must be a positive integer")
|
| 127 |
+
if model_type == "mlp":
|
| 128 |
+
return FactMLP(n_entities, n_attributes, n_answers, width, hidden, layers)
|
| 129 |
+
if model_type == "transformer":
|
| 130 |
+
if width % heads:
|
| 131 |
+
raise ValueError("transformer width must be divisible by heads")
|
| 132 |
+
return FactTransformer(n_entities, n_attributes, n_answers, width, hidden, layers, heads)
|
| 133 |
+
raise ValueError("model_type must be 'mlp' or 'transformer'")
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def edit_parameters(model: nn.Module, scope: str = "ffn") -> list[nn.Parameter]:
|
| 137 |
+
"""Freeze outside the chosen edit scope, returning the exact optimizer parameters."""
|
| 138 |
+
if scope not in {"ffn", "all"}:
|
| 139 |
+
raise ValueError("scope must be 'ffn' or 'all'")
|
| 140 |
+
if scope == "all":
|
| 141 |
+
selected = list(model.parameters())
|
| 142 |
+
elif isinstance(model, FactMLP):
|
| 143 |
+
selected = list(model.hidden.parameters())
|
| 144 |
+
elif isinstance(model, FactTransformer):
|
| 145 |
+
selected = [
|
| 146 |
+
parameter
|
| 147 |
+
for layer in model.encoder.layers
|
| 148 |
+
for linear in (layer.linear1, layer.linear2)
|
| 149 |
+
for parameter in linear.parameters()
|
| 150 |
+
]
|
| 151 |
+
else:
|
| 152 |
+
raise ValueError("ffn scope requires a FactMLP or FactTransformer")
|
| 153 |
+
selected_ids = {id(parameter) for parameter in selected}
|
| 154 |
+
for parameter in model.parameters():
|
| 155 |
+
parameter.requires_grad_(id(parameter) in selected_ids)
|
| 156 |
+
parameter.grad = None
|
| 157 |
+
return selected
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/parametric_architecture.py
ADDED
|
@@ -0,0 +1,443 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Paired GPT-2 architecture extensions for the closed-book memory experiment.
|
| 2 |
+
|
| 3 |
+
Dense execution delegates to the historical ReproductionGPT without changing
|
| 4 |
+
its numerical path. New modules use an independent, checkpointed initialization
|
| 5 |
+
seed; the eight-block reference is always constructed before taking a prefix.
|
| 6 |
+
The mHC residual convention is ``output[n] = sum_m H_res[m,n] * input[m]``.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import hashlib
|
| 12 |
+
import math
|
| 13 |
+
from collections.abc import Sequence
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
from torch import nn
|
| 17 |
+
from torch.nn import functional as F
|
| 18 |
+
from transformers import GPT2Config
|
| 19 |
+
from transformers.models.gpt2.modeling_gpt2 import GPT2MLP
|
| 20 |
+
|
| 21 |
+
from .grokking_reproduction import ReproductionGPT
|
| 22 |
+
|
| 23 |
+
ARMS = {
|
| 24 |
+
"D4": (4, 1, "dense"),
|
| 25 |
+
"D8": (8, 1, "dense"),
|
| 26 |
+
"L4R2": (4, 2, "dense"),
|
| 27 |
+
"M8": (8, 1, "moe"),
|
| 28 |
+
"W8": (8, 1, "wide"),
|
| 29 |
+
"IHC8": (8, 1, "identity_mhc"),
|
| 30 |
+
"HC8": (8, 1, "mhc"),
|
| 31 |
+
"M4": (4, 1, "moe"),
|
| 32 |
+
"LM4R2": (4, 2, "moe"),
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def sinkhorn(logits: torch.Tensor, iterations: int = 20, eps: float = 1e-6):
|
| 37 |
+
"""Accepted mHC A.6: initial row softmax, then 20 column normalizations.
|
| 38 |
+
|
| 39 |
+
There are 19 intervening row normalizations. This is a finite-iteration
|
| 40 |
+
approximation, not an exact doubly stochastic projection.
|
| 41 |
+
"""
|
| 42 |
+
if iterations < 1:
|
| 43 |
+
raise ValueError("Sinkhorn requires at least one iteration")
|
| 44 |
+
with torch.autocast(logits.device.type, enabled=False):
|
| 45 |
+
matrix = logits.float().softmax(dim=-1) + eps
|
| 46 |
+
matrix = matrix / (matrix.sum(dim=-2, keepdim=True) + eps)
|
| 47 |
+
for _ in range(iterations - 1):
|
| 48 |
+
matrix = matrix / (matrix.sum(dim=-1, keepdim=True) + eps)
|
| 49 |
+
matrix = matrix / (matrix.sum(dim=-2, keepdim=True) + eps)
|
| 50 |
+
return matrix
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def residual_mix(streams, matrix):
|
| 54 |
+
"""Rows are source streams and columns are destination streams."""
|
| 55 |
+
return torch.einsum("...mn,...mc->...nc", matrix, streams)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class ControllerRMSNorm(nn.Module):
|
| 59 |
+
def __init__(self, width):
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.weight = nn.Parameter(torch.ones(width))
|
| 62 |
+
|
| 63 |
+
def forward(self, x):
|
| 64 |
+
return x * torch.rsqrt(x.square().mean(dim=-1, keepdim=True) + 1e-20) * self.weight
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class HyperConnection(nn.Module):
|
| 68 |
+
"""Four-stream pre/post controller with optional constrained residual map."""
|
| 69 |
+
|
| 70 |
+
def __init__(self, width, sublayer_id, streams=4, identity=False):
|
| 71 |
+
super().__init__()
|
| 72 |
+
self.streams, self.identity = streams, identity
|
| 73 |
+
count = 2 * streams + (0 if identity else streams * streams)
|
| 74 |
+
self.norm = ControllerRMSNorm(streams * width)
|
| 75 |
+
self.projection = nn.Linear(streams * width, count, bias=False)
|
| 76 |
+
nn.init.zeros_(self.projection.weight)
|
| 77 |
+
self.pre_bias = nn.Parameter(torch.full((streams,), -3.0))
|
| 78 |
+
with torch.no_grad():
|
| 79 |
+
self.pre_bias[sublayer_id % streams] = 3.0
|
| 80 |
+
self.post_bias = nn.Parameter(torch.zeros(streams))
|
| 81 |
+
self.alpha_pre = nn.Parameter(torch.tensor(0.01))
|
| 82 |
+
self.alpha_post = nn.Parameter(torch.tensor(0.01))
|
| 83 |
+
if not identity:
|
| 84 |
+
self.res_bias = nn.Parameter(6 * torch.eye(streams) - 3)
|
| 85 |
+
self.alpha_res = nn.Parameter(torch.tensor(0.01))
|
| 86 |
+
|
| 87 |
+
def coefficients(self, x):
|
| 88 |
+
n = self.streams
|
| 89 |
+
with torch.autocast(x.device.type, enabled=False):
|
| 90 |
+
dynamic = self.projection(self.norm(x.float().flatten(-2)))
|
| 91 |
+
pre = torch.sigmoid(dynamic[..., :n] * self.alpha_pre + self.pre_bias) + 1e-6
|
| 92 |
+
post = 2 * torch.sigmoid(dynamic[..., n : 2 * n] * self.alpha_post + self.post_bias)
|
| 93 |
+
res = None
|
| 94 |
+
if not self.identity:
|
| 95 |
+
logits = dynamic[..., 2 * n :].reshape(*x.shape[:-2], n, n)
|
| 96 |
+
res = sinkhorn(logits * self.alpha_res + self.res_bias)
|
| 97 |
+
return pre, post, res
|
| 98 |
+
|
| 99 |
+
def forward(self, x, sublayer):
|
| 100 |
+
pre, post, res = self.coefficients(x)
|
| 101 |
+
with torch.autocast(x.device.type, enabled=False):
|
| 102 |
+
contracted = (pre[..., None] * x.float()).sum(dim=-2)
|
| 103 |
+
y = sublayer(contracted.to(x.dtype))
|
| 104 |
+
with torch.autocast(x.device.type, enabled=False):
|
| 105 |
+
residual = x.float() if res is None else residual_mix(x.float(), res)
|
| 106 |
+
output = residual + post[..., None] * y.float().unsqueeze(-2)
|
| 107 |
+
return output.to(x.dtype)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _initialize_mlp(mlp, initializer_range):
|
| 111 |
+
# Eight-block GPT-2 reference residual projection scale, also for loops.
|
| 112 |
+
nn.init.normal_(mlp.c_fc.weight, std=initializer_range)
|
| 113 |
+
nn.init.normal_(mlp.c_proj.weight, std=initializer_range / math.sqrt(2 * 8))
|
| 114 |
+
nn.init.zeros_(mlp.c_fc.bias)
|
| 115 |
+
nn.init.zeros_(mlp.c_proj.bias)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class DroplessMoE(nn.Module):
|
| 119 |
+
"""Top-2 normalized routing, one output dropout, no capacity/token drops."""
|
| 120 |
+
|
| 121 |
+
def __init__(self, config, experts=8, top_k=2):
|
| 122 |
+
super().__init__()
|
| 123 |
+
self.expert_count, self.top_k = experts, top_k
|
| 124 |
+
self.router = nn.Linear(config.n_embd, experts, bias=False)
|
| 125 |
+
nn.init.normal_(self.router.weight, std=config.initializer_range)
|
| 126 |
+
self.experts = nn.ModuleList()
|
| 127 |
+
for _ in range(experts):
|
| 128 |
+
expert = GPT2MLP(2 * config.n_embd, config)
|
| 129 |
+
expert.dropout = nn.Identity()
|
| 130 |
+
_initialize_mlp(expert, config.initializer_range)
|
| 131 |
+
self.experts.append(expert)
|
| 132 |
+
self.dropout = nn.Dropout(config.resid_pdrop)
|
| 133 |
+
|
| 134 |
+
def forward(self, x, valid_mask=None):
|
| 135 |
+
flat = x.reshape(-1, x.shape[-1])
|
| 136 |
+
if valid_mask is None:
|
| 137 |
+
selected_tokens = torch.arange(len(flat), device=x.device)
|
| 138 |
+
else:
|
| 139 |
+
selected_tokens = valid_mask.flatten().nonzero(as_tuple=True)[0]
|
| 140 |
+
valid = flat.index_select(0, selected_tokens)
|
| 141 |
+
with torch.autocast(x.device.type, enabled=False):
|
| 142 |
+
probabilities = F.linear(valid.float(), self.router.weight.float()).softmax(-1)
|
| 143 |
+
top_weights, expert_ids = probabilities.topk(self.top_k, dim=-1)
|
| 144 |
+
weights = top_weights / top_weights.sum(dim=-1, keepdim=True)
|
| 145 |
+
# Accumulate selected expert outputs in FP32 for consistent BF16 routing.
|
| 146 |
+
combined = torch.zeros_like(valid, dtype=torch.float32)
|
| 147 |
+
for expert_id, expert in enumerate(self.experts):
|
| 148 |
+
token_ids, slots = (expert_ids == expert_id).nonzero(as_tuple=True)
|
| 149 |
+
if token_ids.numel():
|
| 150 |
+
values = expert(valid.index_select(0, token_ids))
|
| 151 |
+
weighted = values.float() * weights[token_ids, slots, None]
|
| 152 |
+
combined = combined.index_add(0, token_ids, weighted)
|
| 153 |
+
output = torch.zeros_like(flat).index_copy(0, selected_tokens, combined.to(flat.dtype))
|
| 154 |
+
counts = torch.bincount(expert_ids.flatten(), minlength=self.expert_count).detach()
|
| 155 |
+
n_valid = probabilities.new_tensor(len(valid))
|
| 156 |
+
stats = {
|
| 157 |
+
"assignment_counts": counts,
|
| 158 |
+
"probability_sum": probabilities.sum(dim=0),
|
| 159 |
+
"valid_tokens": n_valid,
|
| 160 |
+
"top_k": self.top_k,
|
| 161 |
+
"processed_assignments": counts.sum(),
|
| 162 |
+
"dropped_assignments": counts.new_zeros(()),
|
| 163 |
+
"entropy_sum": -(probabilities * probabilities.clamp_min(1e-30).log()).sum().detach(),
|
| 164 |
+
"selected_mass_sum": top_weights.sum().detach(),
|
| 165 |
+
}
|
| 166 |
+
return self.dropout(output.view_as(x)), stats
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def combine_router_fractions(stats_by_microbatch: Sequence[Sequence[dict]]):
|
| 170 |
+
"""Combine detached counts before a replay that computes exact batch aux.
|
| 171 |
+
|
| 172 |
+
Counts are per executed block (thus distinguish Loop passes). Replay must
|
| 173 |
+
restore dropout RNG state, so its hard routes equal the counting pass.
|
| 174 |
+
"""
|
| 175 |
+
if not stats_by_microbatch or not stats_by_microbatch[0]:
|
| 176 |
+
return [], 0
|
| 177 |
+
layers = len(stats_by_microbatch[0])
|
| 178 |
+
if any(len(stats) != layers for stats in stats_by_microbatch):
|
| 179 |
+
raise ValueError("All microbatches must have the same executed routing layers")
|
| 180 |
+
total = sum(stats[0]["valid_tokens"] for stats in stats_by_microbatch)
|
| 181 |
+
fractions = []
|
| 182 |
+
for layer in range(layers):
|
| 183 |
+
counts = sum(stats[layer]["assignment_counts"] for stats in stats_by_microbatch)
|
| 184 |
+
fractions.append(
|
| 185 |
+
counts.float() / (total * stats_by_microbatch[0][layer]["top_k"]).clamp_min(1)
|
| 186 |
+
)
|
| 187 |
+
return fractions, total
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def router_balance_loss(stats, assignment_fractions=None, total_valid_tokens=None):
|
| 191 |
+
"""N * sum(f * p), averaged over executed layers.
|
| 192 |
+
|
| 193 |
+
With externally supplied whole-batch fractions and denominator, this returns
|
| 194 |
+
the current microbatch's additive contribution to the exact batch objective.
|
| 195 |
+
Assignment fractions are discrete and intentionally detached.
|
| 196 |
+
"""
|
| 197 |
+
if not stats:
|
| 198 |
+
return torch.tensor(0.0)
|
| 199 |
+
if assignment_fractions is not None and len(assignment_fractions) != len(stats):
|
| 200 |
+
raise ValueError("One assignment-fraction vector is required per executed layer")
|
| 201 |
+
losses = []
|
| 202 |
+
for index, record in enumerate(stats):
|
| 203 |
+
count = record["valid_tokens"]
|
| 204 |
+
denominator = count if total_valid_tokens is None else total_valid_tokens
|
| 205 |
+
denominator = torch.as_tensor(denominator, device=count.device).clamp_min(1)
|
| 206 |
+
fractions = (
|
| 207 |
+
record["assignment_counts"].float() / (count * record["top_k"]).clamp_min(1)
|
| 208 |
+
if assignment_fractions is None
|
| 209 |
+
else assignment_fractions[index].detach()
|
| 210 |
+
)
|
| 211 |
+
probabilities = record["probability_sum"] / denominator
|
| 212 |
+
losses.append(probabilities.numel() * (fractions * probabilities).sum())
|
| 213 |
+
return torch.stack(losses).mean()
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
class ParametricGPT(ReproductionGPT):
|
| 217 |
+
def __init__(self, config, architecture="D8", module_seed=0):
|
| 218 |
+
blocks, repeats, kind = ARMS[architecture]
|
| 219 |
+
# Always initialize the same independent eight blocks before slicing.
|
| 220 |
+
config.n_layer = 8
|
| 221 |
+
super().__init__(config, repeats=repeats)
|
| 222 |
+
self.transformer.h = nn.ModuleList(list(self.transformer.h)[:blocks])
|
| 223 |
+
self.config.n_layer = blocks
|
| 224 |
+
self.architecture, self.kind, self.module_seed = architecture, kind, module_seed
|
| 225 |
+
with torch.random.fork_rng(devices=[]):
|
| 226 |
+
torch.manual_seed(module_seed)
|
| 227 |
+
if kind in {"wide", "moe"}:
|
| 228 |
+
for block in self.transformer.h:
|
| 229 |
+
if kind == "moe":
|
| 230 |
+
block.mlp = DroplessMoE(config)
|
| 231 |
+
else:
|
| 232 |
+
block.mlp = GPT2MLP(16 * config.n_embd, config)
|
| 233 |
+
_initialize_mlp(block.mlp, config.initializer_range)
|
| 234 |
+
elif kind in {"mhc", "identity_mhc"}:
|
| 235 |
+
self.connections = nn.ModuleList(
|
| 236 |
+
HyperConnection(config.n_embd, index, identity=kind == "identity_mhc")
|
| 237 |
+
for index in range(2 * blocks)
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
def _attention(self, block, x):
|
| 241 |
+
cfg = self.config
|
| 242 |
+
batch, length = x.shape[:2]
|
| 243 |
+
q, k, v = block.attn.c_attn(block.ln_1(x)).split(cfg.n_embd, dim=2)
|
| 244 |
+
shape = (batch, length, cfg.n_head, cfg.n_embd // cfg.n_head)
|
| 245 |
+
q, k, v = (a.view(shape).transpose(1, 2) for a in (q, k, v))
|
| 246 |
+
y = F.scaled_dot_product_attention(
|
| 247 |
+
q, k, v, is_causal=True, dropout_p=cfg.attn_pdrop if self.training else 0.0
|
| 248 |
+
)
|
| 249 |
+
y = block.attn.c_proj(y.transpose(1, 2).reshape(batch, length, cfg.n_embd))
|
| 250 |
+
return F.dropout(y, cfg.resid_pdrop, self.training)
|
| 251 |
+
|
| 252 |
+
def forward(self, tokens, positions=None, *, valid_mask=None, return_aux=False):
|
| 253 |
+
if valid_mask is not None and (
|
| 254 |
+
valid_mask.shape != tokens.shape or valid_mask.dtype != torch.bool
|
| 255 |
+
):
|
| 256 |
+
raise ValueError("valid_mask must be boolean and have the tokens' shape")
|
| 257 |
+
if self.kind in {"dense", "wide"}:
|
| 258 |
+
logits = super().forward(tokens, positions)
|
| 259 |
+
if return_aux:
|
| 260 |
+
return logits, {"balance_loss": logits.new_zeros(()), "router_stats": []}
|
| 261 |
+
return logits
|
| 262 |
+
cfg, t = self.config, self.transformer
|
| 263 |
+
length = tokens.shape[1]
|
| 264 |
+
x = t.wte(tokens) + t.wpe(torch.arange(length, device=tokens.device))
|
| 265 |
+
x = F.dropout(x, cfg.embd_pdrop, self.training)
|
| 266 |
+
stats = []
|
| 267 |
+
if self.kind in {"mhc", "identity_mhc"}:
|
| 268 |
+
x = x.unsqueeze(-2).expand(-1, -1, 4, -1)
|
| 269 |
+
for _ in range(self.repeats):
|
| 270 |
+
for index, block in enumerate(t.h):
|
| 271 |
+
if self.kind == "moe":
|
| 272 |
+
x = x + self._attention(block, x)
|
| 273 |
+
y, layer_stats = block.mlp(block.ln_2(x), valid_mask)
|
| 274 |
+
x = x + y
|
| 275 |
+
stats.append(layer_stats)
|
| 276 |
+
else:
|
| 277 |
+
x = self.connections[2 * index](x, lambda z, b=block: self._attention(b, z))
|
| 278 |
+
x = self.connections[2 * index + 1](x, lambda z, b=block: b.mlp(b.ln_2(z)))
|
| 279 |
+
if self.kind in {"mhc", "identity_mhc"}:
|
| 280 |
+
x = x.mean(dim=-2)
|
| 281 |
+
x = t.ln_f(x)
|
| 282 |
+
if positions is not None:
|
| 283 |
+
x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions]
|
| 284 |
+
logits = F.linear(x, t.wte.weight)
|
| 285 |
+
if return_aux:
|
| 286 |
+
loss = router_balance_loss(stats) if stats else logits.new_zeros(())
|
| 287 |
+
return logits, {"balance_loss": loss, "router_stats": stats}
|
| 288 |
+
return logits
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def construct(config, spec, device):
|
| 292 |
+
"""Historical config/spec convention, extended by ``spec['architecture']``."""
|
| 293 |
+
architecture = spec["architecture"]
|
| 294 |
+
if architecture not in ARMS:
|
| 295 |
+
raise ValueError(f"Unknown architecture: {architecture}")
|
| 296 |
+
torch.manual_seed(spec["initialization"])
|
| 297 |
+
cfg = GPT2Config(
|
| 298 |
+
vocab_size=config["vocab_size"],
|
| 299 |
+
n_positions=config.get("positions", 1024),
|
| 300 |
+
n_embd=config["hidden_size"],
|
| 301 |
+
n_head=config.get("attention_heads", config.get("heads", 12)),
|
| 302 |
+
n_layer=8,
|
| 303 |
+
resid_pdrop=config["dropout"],
|
| 304 |
+
embd_pdrop=config["dropout"],
|
| 305 |
+
attn_pdrop=config["dropout"],
|
| 306 |
+
activation_function="gelu_new",
|
| 307 |
+
use_cache=False,
|
| 308 |
+
)
|
| 309 |
+
# Separate reproducible new-shape RNG, explicitly recorded in the manifest.
|
| 310 |
+
module_seed = spec.get("module_initialization", spec["initialization"] + 1_000_003)
|
| 311 |
+
model = ParametricGPT(cfg, architecture, module_seed)
|
| 312 |
+
model.initialization_seed = spec["initialization"]
|
| 313 |
+
return model.to(device)
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def optimizer_for(model, lr, decay):
|
| 317 |
+
groups = [{"params": [], "weight_decay": decay}, {"params": [], "weight_decay": 0.0}]
|
| 318 |
+
for name, parameter in model.named_parameters():
|
| 319 |
+
if not parameter.requires_grad:
|
| 320 |
+
continue
|
| 321 |
+
exempt = any(part in name for part in ("bias", "ln"))
|
| 322 |
+
exempt |= name.startswith("connections.") and (".norm." in name or ".alpha_" in name)
|
| 323 |
+
groups[int(exempt)]["params"].append(parameter)
|
| 324 |
+
return torch.optim.AdamW(
|
| 325 |
+
groups, lr=lr, betas=(0.9, 0.999), eps=1e-8, fused=next(model.parameters()).is_cuda
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def parameter_ledger(model):
|
| 330 |
+
d, layers = model.config.n_embd, len(model.transformer.h)
|
| 331 |
+
total = sum(parameter.numel() for parameter in model.parameters())
|
| 332 |
+
expert = sum(p.numel() for n, p in model.named_parameters() if ".experts." in n)
|
| 333 |
+
controller = sum(p.numel() for n, p in model.named_parameters() if n.startswith("connections."))
|
| 334 |
+
router = sum(p.numel() for n, p in model.named_parameters() if ".router." in n)
|
| 335 |
+
fixed = (model.config.vocab_size + model.config.n_positions) * d + 2 * d
|
| 336 |
+
attention_and_norms = 4 * d * d + 8 * d
|
| 337 |
+
if model.kind == "moe":
|
| 338 |
+
per_block = attention_and_norms + 8 * (4 * d * d + 3 * d) + 8 * d
|
| 339 |
+
else:
|
| 340 |
+
width = (16 if model.kind == "wide" else 4) * d
|
| 341 |
+
per_block = attention_and_norms + 2 * d * width + width + d
|
| 342 |
+
expected_controller = 0
|
| 343 |
+
if model.kind in {"mhc", "identity_mhc"}:
|
| 344 |
+
n = 4
|
| 345 |
+
count = 2 * n + (n * n if model.kind == "mhc" else 0)
|
| 346 |
+
alphas = 3 if model.kind == "mhc" else 2
|
| 347 |
+
expected_controller = 2 * layers * (n * d * count + n * d + count + alphas)
|
| 348 |
+
if controller != expected_controller:
|
| 349 |
+
raise AssertionError(
|
| 350 |
+
f"Controller parameter mismatch: {controller} != {expected_controller}"
|
| 351 |
+
)
|
| 352 |
+
expected = fixed + layers * per_block + expected_controller
|
| 353 |
+
if total != expected:
|
| 354 |
+
raise AssertionError(f"Parameter ledger mismatch: {total} != {expected}")
|
| 355 |
+
return {
|
| 356 |
+
"architecture": model.architecture,
|
| 357 |
+
"total_parameters": total,
|
| 358 |
+
"trainable_parameters": sum(p.numel() for p in model.parameters() if p.requires_grad),
|
| 359 |
+
"expected_parameters": expected,
|
| 360 |
+
"expert_parameters": expert,
|
| 361 |
+
"router_parameters": router,
|
| 362 |
+
"controller_parameters": controller,
|
| 363 |
+
"nominal_parameters_selected_per_token": total - expert + expert // 4,
|
| 364 |
+
"active_parameter_convention": (
|
| 365 |
+
"All nonexpert parameters (including whole embedding table) plus two of eight "
|
| 366 |
+
"experts; not FLOPs or touched embedding rows."
|
| 367 |
+
),
|
| 368 |
+
"unique_blocks": layers,
|
| 369 |
+
"repeats": model.repeats,
|
| 370 |
+
"executed_blocks": layers * model.repeats,
|
| 371 |
+
"residual_streams": 4 if controller else 1,
|
| 372 |
+
"parameter_dtype": str(next(model.parameters()).dtype),
|
| 373 |
+
"residual_dtype_under_bf16_autocast": "torch.float32 with FP32 parameters",
|
| 374 |
+
"controller_dtype": "torch.float32",
|
| 375 |
+
}
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def flop_ledger(model, *, executed_tokens, projected_positions, attention_pairs, valid_tokens=None):
|
| 379 |
+
"""Leading forward matmuls with actual padding/dispatch/readout counts.
|
| 380 |
+
|
| 381 |
+
``attention_pairs`` is sum(B*T*T) over microbatches, before block count.
|
| 382 |
+
Training 3x is explicitly an approximation; Sinkhorn autograd, scalar ops,
|
| 383 |
+
and a counting/replay pass are not silently folded into this estimate.
|
| 384 |
+
"""
|
| 385 |
+
d, blocks = model.config.n_embd, len(model.transformer.h) * model.repeats
|
| 386 |
+
valid_tokens = executed_tokens if valid_tokens is None else valid_tokens
|
| 387 |
+
attention = blocks * (8 * executed_tokens * d * d + 4 * attention_pairs * d)
|
| 388 |
+
readout = 2 * projected_positions * d * model.config.vocab_size
|
| 389 |
+
router = controller = 0
|
| 390 |
+
if model.kind == "moe":
|
| 391 |
+
ffn = blocks * 4 * valid_tokens * d * (2 * 2 * d)
|
| 392 |
+
router = blocks * 2 * valid_tokens * d * 8
|
| 393 |
+
else:
|
| 394 |
+
inner = (16 if model.kind == "wide" else 4) * d
|
| 395 |
+
ffn = blocks * 4 * executed_tokens * d * inner
|
| 396 |
+
if model.kind in {"mhc", "identity_mhc"}:
|
| 397 |
+
n = 4
|
| 398 |
+
count = 2 * n + (n * n if model.kind == "mhc" else 0)
|
| 399 |
+
controller = (
|
| 400 |
+
2 * blocks * (2 * executed_tokens * n * d * count + 2 * executed_tokens * d * count)
|
| 401 |
+
)
|
| 402 |
+
forward = attention + readout + ffn + router + controller
|
| 403 |
+
return {
|
| 404 |
+
"forward_attention_matmul_flops": attention,
|
| 405 |
+
"forward_ffn_matmul_flops": ffn,
|
| 406 |
+
"forward_readout_matmul_flops": readout,
|
| 407 |
+
"forward_router_matmul_flops": router,
|
| 408 |
+
"forward_controller_matmul_flops": controller,
|
| 409 |
+
"forward_leading_matmul_flops": forward,
|
| 410 |
+
"estimated_matmul_training_flops": 3 * forward,
|
| 411 |
+
"sinkhorn_normalization_passes": 39 if model.kind == "mhc" else 0,
|
| 412 |
+
"sinkhorn_matrix_elements_per_forward": 2 * blocks * executed_tokens * 16
|
| 413 |
+
if model.kind == "mhc"
|
| 414 |
+
else 0,
|
| 415 |
+
"selected_expert_assignments": blocks * valid_tokens * 2 if model.kind == "moe" else 0,
|
| 416 |
+
"executed_input_tokens": executed_tokens,
|
| 417 |
+
"effective_input_tokens": valid_tokens,
|
| 418 |
+
"projected_positions": projected_positions,
|
| 419 |
+
"excluded_ops": (
|
| 420 |
+
"Nonlinearities, normalization, dropout, dispatch/index-add, softmax, Sinkhorn "
|
| 421 |
+
"scalar arithmetic/autograd, final mean, counting/replay and optimizer; "
|
| 422 |
+
"3x is approximate."
|
| 423 |
+
),
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def initialization_manifest(model):
|
| 428 |
+
"""CPU-byte hashes of each actual initialized tensor; no sampled hash."""
|
| 429 |
+
shared, introduced = {}, {}
|
| 430 |
+
for name, tensor in model.state_dict().items():
|
| 431 |
+
is_new = name.startswith("connections.") or (
|
| 432 |
+
model.kind in {"moe", "wide"} and ".mlp." in name
|
| 433 |
+
)
|
| 434 |
+
raw = tensor.detach().cpu().contiguous().reshape(-1).view(torch.uint8).numpy().tobytes()
|
| 435 |
+
(introduced if is_new else shared)[name] = hashlib.sha256(raw).hexdigest()
|
| 436 |
+
return {
|
| 437 |
+
"architecture": model.architecture,
|
| 438 |
+
"reference_initialization": getattr(model, "initialization_seed", None),
|
| 439 |
+
"module_initialization": model.module_seed,
|
| 440 |
+
"reference_blocks_before_slicing": 8,
|
| 441 |
+
"shared_tensor_sha256": shared,
|
| 442 |
+
"introduced_tensor_sha256": introduced,
|
| 443 |
+
}
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/parametric_architecture_train.py
ADDED
|
@@ -0,0 +1,626 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Resumable, exposure-matched training for the parametric architecture study.
|
| 2 |
+
|
| 3 |
+
The ordinary data stream, answer-plus-EOS objective and generated evaluator are
|
| 4 |
+
shared with the historical experiment. MoE balancing is computed over the true
|
| 5 |
+
effective batch using an RNG-replayed routing pass, not a sum of local products.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
import math
|
| 13 |
+
import os
|
| 14 |
+
import random
|
| 15 |
+
import time
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
import transformers
|
| 21 |
+
from transformers import GPT2TokenizerFast
|
| 22 |
+
|
| 23 |
+
from . import realworld_composition as historical
|
| 24 |
+
from .grok_depth import utc
|
| 25 |
+
from .grokking_reproduction import model_digest
|
| 26 |
+
from .realworld_composition_data import sha256, write_json
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _architecture():
|
| 30 |
+
from . import parametric_architecture
|
| 31 |
+
|
| 32 |
+
return parametric_architecture
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def rng_state(device):
|
| 36 |
+
state = {
|
| 37 |
+
"python": random.getstate(),
|
| 38 |
+
"numpy": np.random.get_state(),
|
| 39 |
+
"cpu": torch.get_rng_state(),
|
| 40 |
+
}
|
| 41 |
+
if torch.device(device).type == "cuda":
|
| 42 |
+
state["cuda"] = torch.cuda.get_rng_state(device)
|
| 43 |
+
return state
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def restore_rng(state, device):
|
| 47 |
+
random.setstate(state["python"])
|
| 48 |
+
np.random.set_state(state["numpy"])
|
| 49 |
+
torch.set_rng_state(state["cpu"].cpu())
|
| 50 |
+
if "cuda" in state:
|
| 51 |
+
torch.cuda.set_rng_state(state["cuda"].cpu(), device)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def pack(records, pad, device):
|
| 55 |
+
"""EOS is a valid input token; validity comes from lengths, never token IDs."""
|
| 56 |
+
tokens, positions, labels = historical.pack(records, pad, device)
|
| 57 |
+
lengths = torch.tensor([len(r["encoded"]["input"]) for r in records], device=device)
|
| 58 |
+
valid = torch.arange(tokens.shape[1], device=device)[None] < lengths[:, None]
|
| 59 |
+
return tokens, positions, labels, valid
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _synchronize(device):
|
| 63 |
+
if torch.device(device).type == "cuda":
|
| 64 |
+
torch.cuda.synchronize(device)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _finite(value, name):
|
| 68 |
+
if not math.isfinite(float(value)):
|
| 69 |
+
raise FloatingPointError(f"Nonfinite {name}; this candidate must retain its failure")
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def update(model, optimizer, records, spec, device, pad):
|
| 73 |
+
"""One historical effective batch, with exact full-batch routing gradients.
|
| 74 |
+
|
| 75 |
+
Hard assignment fractions have no gradient. A no-grad pass collects their
|
| 76 |
+
global values when there are multiple microbatches; replaying the same
|
| 77 |
+
dropout RNG realizes the same routing in the differentiable pass. One
|
| 78 |
+
microbatch already contains the full objective and needs no prepass.
|
| 79 |
+
"""
|
| 80 |
+
if not records:
|
| 81 |
+
raise ValueError("An update requires at least one example")
|
| 82 |
+
microbatch = int(spec["microbatch_size"])
|
| 83 |
+
if microbatch < 1:
|
| 84 |
+
raise ValueError("microbatch_size must be positive")
|
| 85 |
+
api = _architecture()
|
| 86 |
+
model.train()
|
| 87 |
+
optimizer.zero_grad(set_to_none=True)
|
| 88 |
+
chunks = [records[i : i + microbatch] for i in range(0, len(records), microbatch)]
|
| 89 |
+
is_moe = spec["architecture"] in {"M8", "M4", "LM4R2"}
|
| 90 |
+
needs_prepass = is_moe and len(chunks) > 1
|
| 91 |
+
coefficient = float(spec.get("balance_coefficient", 0.01)) if is_moe else 0.0
|
| 92 |
+
global_fractions, total_tokens, collected = None, None, []
|
| 93 |
+
if needs_prepass:
|
| 94 |
+
before = rng_state(device)
|
| 95 |
+
try:
|
| 96 |
+
with torch.no_grad():
|
| 97 |
+
for chunk in chunks:
|
| 98 |
+
tokens, positions, _, valid = pack(chunk, pad, device)
|
| 99 |
+
with historical.autocast(device):
|
| 100 |
+
_, aux = model(tokens, positions, valid_mask=valid, return_aux=True)
|
| 101 |
+
collected.append(aux["router_stats"])
|
| 102 |
+
global_fractions, total_tokens = api.combine_router_fractions(collected)
|
| 103 |
+
finally:
|
| 104 |
+
restore_rng(before, device)
|
| 105 |
+
answer_loss, balance_loss = 0.0, 0.0
|
| 106 |
+
executed, readout, attention = 0, 0, 0
|
| 107 |
+
replay_count_error = torch.zeros((), dtype=torch.int64, device=device)
|
| 108 |
+
for chunk_index, chunk in enumerate(chunks):
|
| 109 |
+
tokens, positions, labels, valid = pack(chunk, pad, device)
|
| 110 |
+
with historical.autocast(device):
|
| 111 |
+
logits, aux = model(tokens, positions, valid_mask=valid, return_aux=True)
|
| 112 |
+
answer = historical.example_losses(logits, labels).sum() / len(records)
|
| 113 |
+
balance = (
|
| 114 |
+
api.router_balance_loss(
|
| 115 |
+
aux["router_stats"],
|
| 116 |
+
assignment_fractions=global_fractions,
|
| 117 |
+
total_valid_tokens=total_tokens,
|
| 118 |
+
)
|
| 119 |
+
if is_moe
|
| 120 |
+
else answer.new_zeros(())
|
| 121 |
+
)
|
| 122 |
+
loss = answer + coefficient * balance
|
| 123 |
+
if needs_prepass:
|
| 124 |
+
replay_count_error += sum(
|
| 125 |
+
(left["assignment_counts"] - right["assignment_counts"]).abs().sum()
|
| 126 |
+
for left, right in zip(collected[chunk_index], aux["router_stats"], strict=True)
|
| 127 |
+
)
|
| 128 |
+
elif is_moe:
|
| 129 |
+
collected = [aux["router_stats"]]
|
| 130 |
+
global_fractions, total_tokens = api.combine_router_fractions(collected)
|
| 131 |
+
_finite(loss.detach(), "objective")
|
| 132 |
+
loss.backward()
|
| 133 |
+
answer_loss += float(answer.detach())
|
| 134 |
+
balance_loss += float(balance.detach())
|
| 135 |
+
executed += tokens.numel()
|
| 136 |
+
readout += positions.numel()
|
| 137 |
+
attention += len(chunk) * tokens.shape[1] ** 2
|
| 138 |
+
if int(replay_count_error) != 0:
|
| 139 |
+
raise RuntimeError("MoE RNG replay did not reproduce routing assignment counts")
|
| 140 |
+
norm = torch.nn.utils.clip_grad_norm_(
|
| 141 |
+
model.parameters(), float(spec.get("clip_grad_norm", 1.0)), error_if_nonfinite=True
|
| 142 |
+
)
|
| 143 |
+
_finite(norm, "gradient norm")
|
| 144 |
+
optimizer.step()
|
| 145 |
+
effective = sum(len(r["encoded"]["input"]) for r in records)
|
| 146 |
+
result = {
|
| 147 |
+
"loss": answer_loss,
|
| 148 |
+
"answer_ce": answer_loss,
|
| 149 |
+
"balance_loss": balance_loss,
|
| 150 |
+
"balance_coefficient": coefficient,
|
| 151 |
+
"objective": answer_loss + coefficient * balance_loss,
|
| 152 |
+
"gradient_norm": float(norm),
|
| 153 |
+
"executed_input_tokens": executed,
|
| 154 |
+
"effective_input_tokens": effective,
|
| 155 |
+
"padding_input_tokens": executed - effective,
|
| 156 |
+
"readout_positions": readout,
|
| 157 |
+
"attention_token_pairs": attention,
|
| 158 |
+
"routing_prepass_executed_input_tokens": executed if needs_prepass else 0,
|
| 159 |
+
"routing_prepass_effective_input_tokens": effective if needs_prepass else 0,
|
| 160 |
+
}
|
| 161 |
+
result["compute"] = api.flop_ledger(
|
| 162 |
+
model,
|
| 163 |
+
executed_tokens=executed,
|
| 164 |
+
valid_tokens=effective,
|
| 165 |
+
projected_positions=readout,
|
| 166 |
+
attention_pairs=attention,
|
| 167 |
+
)
|
| 168 |
+
prepass = result["compute"]["forward_leading_matmul_flops"] if needs_prepass else 0
|
| 169 |
+
result["compute"]["routing_prepass_matmul_flops"] = prepass
|
| 170 |
+
result["estimated_matmul_training_flops"] = (
|
| 171 |
+
result["compute"]["estimated_matmul_training_flops"] + prepass
|
| 172 |
+
)
|
| 173 |
+
result["compute"]["estimated_total_training_matmul_flops"] = result[
|
| 174 |
+
"estimated_matmul_training_flops"
|
| 175 |
+
]
|
| 176 |
+
if is_moe:
|
| 177 |
+
layer_count = len(global_fractions)
|
| 178 |
+
assignments = torch.stack(
|
| 179 |
+
[sum(c[layer]["assignment_counts"] for c in collected) for layer in range(layer_count)]
|
| 180 |
+
)
|
| 181 |
+
processed = torch.stack(
|
| 182 |
+
[
|
| 183 |
+
sum(c[layer]["processed_assignments"] for c in collected)
|
| 184 |
+
for layer in range(layer_count)
|
| 185 |
+
]
|
| 186 |
+
)
|
| 187 |
+
dropped = sum(s["dropped_assignments"] for c in collected for s in c)
|
| 188 |
+
if int(dropped) != 0 or not torch.equal(processed, assignments.sum(-1)):
|
| 189 |
+
raise AssertionError("Dropless routing lost selected token assignments")
|
| 190 |
+
result["router"] = {
|
| 191 |
+
"assignment_fractions": torch.stack(global_fractions).detach().cpu().tolist(),
|
| 192 |
+
"assignment_counts": assignments.detach().cpu().tolist(),
|
| 193 |
+
"valid_tokens_per_layer": effective,
|
| 194 |
+
"selected_assignments_per_layer": assignments.sum(-1).detach().cpu().tolist(),
|
| 195 |
+
"processed_assignments_per_layer": processed.detach().cpu().tolist(),
|
| 196 |
+
"router_entropy_per_layer": torch.stack(
|
| 197 |
+
[
|
| 198 |
+
sum(c[layer]["entropy_sum"] for c in collected) / effective
|
| 199 |
+
for layer in range(layer_count)
|
| 200 |
+
]
|
| 201 |
+
)
|
| 202 |
+
.detach()
|
| 203 |
+
.cpu()
|
| 204 |
+
.tolist(),
|
| 205 |
+
"selected_probability_mass_per_layer": torch.stack(
|
| 206 |
+
[
|
| 207 |
+
sum(c[layer]["selected_mass_sum"] for c in collected) / effective
|
| 208 |
+
for layer in range(layer_count)
|
| 209 |
+
]
|
| 210 |
+
)
|
| 211 |
+
.detach()
|
| 212 |
+
.cpu()
|
| 213 |
+
.tolist(),
|
| 214 |
+
"dropped_assignments": int(dropped),
|
| 215 |
+
"replay_assignment_count_error": int(replay_count_error),
|
| 216 |
+
"replay_checked": needs_prepass,
|
| 217 |
+
"balance_scope": (
|
| 218 |
+
"full_effective_batch_two_pass_rng_replay"
|
| 219 |
+
if needs_prepass
|
| 220 |
+
else "full_effective_batch_single_forward"
|
| 221 |
+
),
|
| 222 |
+
}
|
| 223 |
+
return result
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def selection_score(metrics):
|
| 227 |
+
"""Frozen development panels only; no held-out-composition selection."""
|
| 228 |
+
atomic, composition = metrics["atomic"]["nll"], metrics["train_composition"]["nll"]
|
| 229 |
+
if atomic is None or composition is None:
|
| 230 |
+
raise ValueError("Both fixed development panels need answer NLL measurements")
|
| 231 |
+
value = 0.5 * atomic + 0.5 * composition
|
| 232 |
+
_finite(value, "development selection NLL")
|
| 233 |
+
return value
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def _routing_metrics(router):
|
| 237 |
+
"""Expose numeric dictionaries to the existing W&B sidecar's flattening."""
|
| 238 |
+
if not router:
|
| 239 |
+
return {}
|
| 240 |
+
return {
|
| 241 |
+
"dropped_assignments": router["dropped_assignments"],
|
| 242 |
+
"replay_assignment_count_error": router["replay_assignment_count_error"],
|
| 243 |
+
"layers": {
|
| 244 |
+
str(layer): {
|
| 245 |
+
"entropy": router["router_entropy_per_layer"][layer],
|
| 246 |
+
"selected_probability_mass": router["selected_probability_mass_per_layer"][layer],
|
| 247 |
+
"expert_fraction": {str(i): value for i, value in enumerate(fractions)},
|
| 248 |
+
}
|
| 249 |
+
for layer, fractions in enumerate(router["assignment_fractions"])
|
| 250 |
+
},
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def save_checkpoint(path, model, optimizer, stream, counts, step, counters, device, **extra):
|
| 255 |
+
path = Path(path)
|
| 256 |
+
temporary = path.with_suffix(".tmp")
|
| 257 |
+
torch.save(
|
| 258 |
+
{
|
| 259 |
+
"format_version": 1,
|
| 260 |
+
"model": model.state_dict(),
|
| 261 |
+
"optimizer": optimizer.state_dict(),
|
| 262 |
+
"stream": stream.state_dict(),
|
| 263 |
+
"counts": counts,
|
| 264 |
+
"step": step,
|
| 265 |
+
"counters": counters,
|
| 266 |
+
"rng": rng_state(device),
|
| 267 |
+
**extra,
|
| 268 |
+
},
|
| 269 |
+
temporary,
|
| 270 |
+
)
|
| 271 |
+
temporary.replace(path)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def load_checkpoint(path, model, optimizer, stream, device):
|
| 275 |
+
state = torch.load(path, map_location="cpu", weights_only=False)
|
| 276 |
+
model.load_state_dict(state["model"])
|
| 277 |
+
optimizer.load_state_dict(state["optimizer"])
|
| 278 |
+
stream.load_state_dict(state["stream"])
|
| 279 |
+
restore_rng(state["rng"], device)
|
| 280 |
+
return state
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def _identity(config, spec):
|
| 284 |
+
payload = {
|
| 285 |
+
"model": config["model"],
|
| 286 |
+
"spec": spec,
|
| 287 |
+
"data_sha256": config["data_sha256"],
|
| 288 |
+
"tokenizer_sha256": config.get("tokenizer_sha256", config.get("tokenizer_files", {})),
|
| 289 |
+
"source_files": config.get("source_files", {}),
|
| 290 |
+
}
|
| 291 |
+
return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def verify(config, config_path=None):
|
| 295 |
+
"""Check the concrete execution freeze; the historical design is not mutated."""
|
| 296 |
+
if config.get("launch_enabled") is False:
|
| 297 |
+
raise ValueError("This configuration explicitly disables execution")
|
| 298 |
+
if sha256(config["data_file"]) != config["data_sha256"]:
|
| 299 |
+
raise ValueError("Frozen data changed")
|
| 300 |
+
for name, expected in config.get("tokenizer_sha256", {}).items():
|
| 301 |
+
path = Path(config["tokenizer"]) / name
|
| 302 |
+
if sha256(path) != expected:
|
| 303 |
+
raise ValueError(f"Frozen tokenizer changed: {path}")
|
| 304 |
+
for group in ("tokenizer_files", "source_files"):
|
| 305 |
+
for path, expected in config.get(group, {}).items():
|
| 306 |
+
if sha256(path) != expected:
|
| 307 |
+
raise ValueError(f"Frozen {group} changed: {path}")
|
| 308 |
+
if config.get("source_root"):
|
| 309 |
+
root = Path(config["source_root"]).resolve()
|
| 310 |
+
for module in (Path(__file__), Path(_architecture().__file__), Path(historical.__file__)):
|
| 311 |
+
if not module.resolve().is_relative_to(root):
|
| 312 |
+
raise ValueError(f"Imported code is outside the frozen source_root: {module}")
|
| 313 |
+
if config_path is not None:
|
| 314 |
+
if not config.get("execution_lock"):
|
| 315 |
+
raise ValueError("CLI requires an execution_lock with the frozen config hash")
|
| 316 |
+
lock = json.loads(Path(config["execution_lock"]).read_text())
|
| 317 |
+
if lock["config_sha256"] != sha256(config_path):
|
| 318 |
+
raise ValueError("Frozen configuration changed")
|
| 319 |
+
if "torch" in lock.get("environment", {}):
|
| 320 |
+
if str(torch.__version__) != lock["environment"]["torch"]:
|
| 321 |
+
raise ValueError("Frozen torch version changed")
|
| 322 |
+
if "transformers" in lock.get("environment", {}):
|
| 323 |
+
if transformers.__version__ != lock["environment"]["transformers"]:
|
| 324 |
+
raise ValueError("Frozen transformers version changed")
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def _setup(device, config):
|
| 328 |
+
torch.set_num_threads(int(config.get("cpu_threads", 4)))
|
| 329 |
+
if torch.device(device).type == "cuda":
|
| 330 |
+
torch.cuda.set_device(device)
|
| 331 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 332 |
+
torch.cuda.reset_peak_memory_stats(device)
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def _resources(device):
|
| 336 |
+
if torch.device(device).type != "cuda":
|
| 337 |
+
return {"peak_gpu_memory_bytes": 0, "peak_gpu_reserved_bytes": 0}
|
| 338 |
+
return {
|
| 339 |
+
"peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(device),
|
| 340 |
+
"peak_gpu_reserved_bytes": torch.cuda.max_memory_reserved(device),
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def _process_identity():
|
| 345 |
+
"""Different containers can both run Python as PID 1; identify the namespace."""
|
| 346 |
+
identity = {"pid": os.getpid()}
|
| 347 |
+
if Path("/proc/self/stat").exists():
|
| 348 |
+
identity["pid_namespace"] = os.readlink("/proc/self/ns/pid")
|
| 349 |
+
identity["start_ticks"] = Path("/proc/self/stat").read_text().rsplit(")", 1)[1].split()[19]
|
| 350 |
+
return identity
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def run(config, spec, out, device="cuda:0"):
|
| 354 |
+
"""Train one frozen candidate. An independent process must subsequently audit."""
|
| 355 |
+
verify(config)
|
| 356 |
+
_setup(device, config)
|
| 357 |
+
out = Path(out)
|
| 358 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 359 |
+
if (out / "trained.json").exists():
|
| 360 |
+
trained = json.loads((out / "trained.json").read_text())
|
| 361 |
+
if trained["identity"] != _identity(config, spec):
|
| 362 |
+
raise ValueError("Existing output belongs to a different frozen training recipe")
|
| 363 |
+
return trained
|
| 364 |
+
api = _architecture()
|
| 365 |
+
data = json.loads(Path(config["data_file"]).read_text())
|
| 366 |
+
tokenizer = GPT2TokenizerFast.from_pretrained(config["tokenizer"], local_files_only=True)
|
| 367 |
+
records = data["atoms"] + data["train_compositions"]
|
| 368 |
+
model = api.construct(config["model"], spec, device)
|
| 369 |
+
optimizer = api.optimizer_for(model, spec["learning_rate"], spec["weight_decay"])
|
| 370 |
+
stream = historical.BatchStream(len(records), spec["sampling_seed"])
|
| 371 |
+
identity = _identity(config, spec)
|
| 372 |
+
counts = np.zeros(len(records), dtype=np.int64)
|
| 373 |
+
counters = {
|
| 374 |
+
"training_seconds": 0.0,
|
| 375 |
+
"examples": 0,
|
| 376 |
+
"supervised_tokens": 0,
|
| 377 |
+
"executed_input_tokens": 0,
|
| 378 |
+
"effective_input_tokens": 0,
|
| 379 |
+
"estimated_matmul_training_flops": 0,
|
| 380 |
+
"routing_prepass_executed_input_tokens": 0,
|
| 381 |
+
}
|
| 382 |
+
initial_step, wall_offset, history, last = 0, 0.0, [], {}
|
| 383 |
+
if (out / "latest.pt").exists():
|
| 384 |
+
saved = load_checkpoint(out / "latest.pt", model, optimizer, stream, device)
|
| 385 |
+
if saved["identity"] != identity:
|
| 386 |
+
raise ValueError("Checkpoint belongs to a different frozen training recipe")
|
| 387 |
+
counts, initial_step, counters = saved["counts"], saved["step"], saved["counters"]
|
| 388 |
+
wall_offset, last = saved.get("wall_seconds", 0.0), saved.get("last_update", {})
|
| 389 |
+
learning = out / "learning.json"
|
| 390 |
+
history = [r for r in json.loads(learning.read_text()) if r["step"] <= initial_step]
|
| 391 |
+
metadata = json.loads((out / "run.json").read_text())
|
| 392 |
+
metadata.update(pid=os.getpid(), resumed_from_step=initial_step)
|
| 393 |
+
del saved
|
| 394 |
+
else:
|
| 395 |
+
torch.manual_seed(spec["dropout_seed"])
|
| 396 |
+
random.seed(spec["dropout_seed"])
|
| 397 |
+
np.random.seed(spec["dropout_seed"])
|
| 398 |
+
metadata = {
|
| 399 |
+
"spec": spec,
|
| 400 |
+
"model": config["model"],
|
| 401 |
+
"phase": config.get("phase", "development"),
|
| 402 |
+
"evaluation_nodes": config["evaluation_nodes"],
|
| 403 |
+
"world_sha256": config["data_sha256"],
|
| 404 |
+
"initial_model_sha256": model_digest(model),
|
| 405 |
+
"initial_tensor_sha256": historical.tensor_digests(model),
|
| 406 |
+
"initialization_manifest": api.initialization_manifest(model),
|
| 407 |
+
"parameters": sum(p.numel() for p in model.parameters()),
|
| 408 |
+
"parameter_ledger": api.parameter_ledger(model),
|
| 409 |
+
"atomic_examples": len(data["atoms"]),
|
| 410 |
+
"composition_examples": len(data["train_compositions"]),
|
| 411 |
+
"vocab_size": len(tokenizer),
|
| 412 |
+
"dtype": "BF16 AMP; FP32 parameters and Adam states",
|
| 413 |
+
"device": str(device),
|
| 414 |
+
"gpu": torch.device(device).index or 0,
|
| 415 |
+
"gpu_name": torch.cuda.get_device_name(device)
|
| 416 |
+
if torch.device(device).type == "cuda"
|
| 417 |
+
else "cpu",
|
| 418 |
+
"pid": os.getpid(),
|
| 419 |
+
"job_type": config.get("phase", "development") + "-training",
|
| 420 |
+
"tracking_group": config.get("tracking", {}).get("group", config.get("experiment")),
|
| 421 |
+
"learning_step_unit": "optimizer_updates",
|
| 422 |
+
"identity": identity,
|
| 423 |
+
"selection": "0.5 atomic + 0.5 train-composition NLL on original fixed panels",
|
| 424 |
+
"selection_panel_sizes": {
|
| 425 |
+
key: len(data["panels"][key]) for key in ("atomic", "train_composition")
|
| 426 |
+
},
|
| 427 |
+
"moe_balance": (
|
| 428 |
+
"full-effective-batch; single forward when one microbatch, otherwise two-pass "
|
| 429 |
+
"RNG replay; actual prepass compute included"
|
| 430 |
+
),
|
| 431 |
+
"learning_rate_schedule": "historical lr * min((step - 1) / warmup_steps, 1)",
|
| 432 |
+
}
|
| 433 |
+
if config.get("execution_lock"):
|
| 434 |
+
metadata["execution_lock_sha256"] = sha256(config["execution_lock"])
|
| 435 |
+
write_json(out / "run.json", metadata)
|
| 436 |
+
write_json(out / "learning.json", history)
|
| 437 |
+
nodes = set(config["evaluation_nodes"]) | {int(spec["steps"])}
|
| 438 |
+
log_interval = int(config.get("log_interval", 100))
|
| 439 |
+
checkpoint_interval = int(config.get("resume_checkpoint_interval", 1000))
|
| 440 |
+
started = time.perf_counter()
|
| 441 |
+
|
| 442 |
+
def checkpoint(step):
|
| 443 |
+
save_checkpoint(
|
| 444 |
+
out / "latest.pt",
|
| 445 |
+
model,
|
| 446 |
+
optimizer,
|
| 447 |
+
stream,
|
| 448 |
+
counts,
|
| 449 |
+
step,
|
| 450 |
+
counters,
|
| 451 |
+
device,
|
| 452 |
+
identity=identity,
|
| 453 |
+
wall_seconds=wall_offset + time.perf_counter() - started,
|
| 454 |
+
last_update=last,
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
for step in range(initial_step, spec["steps"] + 1):
|
| 458 |
+
if step > initial_step:
|
| 459 |
+
warmup = int(spec["warmup_steps"])
|
| 460 |
+
lr = spec["learning_rate"] * (min((step - 1) / warmup, 1.0) if warmup else 1.0)
|
| 461 |
+
for group in optimizer.param_groups:
|
| 462 |
+
group["lr"] = lr
|
| 463 |
+
ids = stream.batch(spec["batch_size"])
|
| 464 |
+
selected = [records[i] for i in ids]
|
| 465 |
+
_synchronize(device)
|
| 466 |
+
begin = time.perf_counter()
|
| 467 |
+
last = update(model, optimizer, selected, spec, device, tokenizer.eos_token_id)
|
| 468 |
+
_synchronize(device)
|
| 469 |
+
counters["training_seconds"] += time.perf_counter() - begin
|
| 470 |
+
counts[ids] += 1
|
| 471 |
+
counters["examples"] += len(ids)
|
| 472 |
+
counters["supervised_tokens"] += sum(len(r["encoded"]["target"]) for r in selected)
|
| 473 |
+
for key in (
|
| 474 |
+
"executed_input_tokens",
|
| 475 |
+
"effective_input_tokens",
|
| 476 |
+
"estimated_matmul_training_flops",
|
| 477 |
+
"routing_prepass_executed_input_tokens",
|
| 478 |
+
):
|
| 479 |
+
counters[key] += last[key]
|
| 480 |
+
if step in nodes or step % log_interval == 0:
|
| 481 |
+
if not any(r["step"] == step for r in history):
|
| 482 |
+
metrics = {}
|
| 483 |
+
if step in nodes:
|
| 484 |
+
metrics, predictions = historical.evaluate_dataset(
|
| 485 |
+
model, data, tokenizer, device
|
| 486 |
+
)
|
| 487 |
+
write_json(out / f"predictions-{step:07d}.json", predictions)
|
| 488 |
+
metrics["selection"] = {
|
| 489 |
+
"mixed_answer_nll": selection_score(metrics),
|
| 490 |
+
"atomic_n": metrics["atomic"]["nll_n"],
|
| 491 |
+
"train_composition_n": metrics["train_composition"]["nll_n"],
|
| 492 |
+
}
|
| 493 |
+
if last.get("router"):
|
| 494 |
+
metrics["routing"] = _routing_metrics(last["router"])
|
| 495 |
+
record = {
|
| 496 |
+
"step": step,
|
| 497 |
+
"metrics": metrics,
|
| 498 |
+
**counters,
|
| 499 |
+
"wall_seconds": wall_offset + time.perf_counter() - started,
|
| 500 |
+
"loss": last.get("answer_ce"),
|
| 501 |
+
"answer_ce": last.get("answer_ce"),
|
| 502 |
+
"balance_loss": last.get("balance_loss"),
|
| 503 |
+
"objective": last.get("objective"),
|
| 504 |
+
"gradient_norm": last.get("gradient_norm"),
|
| 505 |
+
"learning_rate": optimizer.param_groups[0]["lr"],
|
| 506 |
+
"atomic_epochs": float(counts[: len(data["atoms"])].mean()),
|
| 507 |
+
"composition_epochs": float(counts[len(data["atoms"]) :].mean()),
|
| 508 |
+
"router": last.get("router", {}),
|
| 509 |
+
"compute_per_update": last.get("compute", {}),
|
| 510 |
+
**_resources(device),
|
| 511 |
+
"created_utc": utc(),
|
| 512 |
+
}
|
| 513 |
+
history.append(record)
|
| 514 |
+
write_json(out / "learning.json", history)
|
| 515 |
+
print(
|
| 516 |
+
json.dumps({"step": step, "loss": record["loss"], "metrics": metrics}),
|
| 517 |
+
flush=True,
|
| 518 |
+
)
|
| 519 |
+
write_json(
|
| 520 |
+
out / "status.json",
|
| 521 |
+
{
|
| 522 |
+
"state": "training",
|
| 523 |
+
"step": step,
|
| 524 |
+
"target_step": spec["steps"],
|
| 525 |
+
"loss": last.get("answer_ce"),
|
| 526 |
+
**counters,
|
| 527 |
+
"wall_seconds": wall_offset + time.perf_counter() - started,
|
| 528 |
+
"pid": os.getpid(),
|
| 529 |
+
"updated_utc": utc(),
|
| 530 |
+
},
|
| 531 |
+
)
|
| 532 |
+
if step in nodes or (step > initial_step and step % checkpoint_interval == 0):
|
| 533 |
+
checkpoint(step)
|
| 534 |
+
if step in nodes:
|
| 535 |
+
target = out / f"checkpoint-{step:07d}.pt"
|
| 536 |
+
temporary = target.with_suffix(".tmp")
|
| 537 |
+
torch.save(
|
| 538 |
+
{"model": model.state_dict(), "step": step, "identity": identity}, temporary
|
| 539 |
+
)
|
| 540 |
+
temporary.replace(target)
|
| 541 |
+
np.savez_compressed(out / f"exposure-{step:07d}.npz", counts=counts)
|
| 542 |
+
metrics, predictions = historical.evaluate_dataset(
|
| 543 |
+
model, data, tokenizer, device, full=True, autonomous=True
|
| 544 |
+
)
|
| 545 |
+
write_json(out / "endpoint-predictions.json", predictions)
|
| 546 |
+
write_json(out / "endpoint.json", metrics)
|
| 547 |
+
result = {
|
| 548 |
+
"state": "trained_pending_independent_reload",
|
| 549 |
+
"step": spec["steps"],
|
| 550 |
+
"pid": os.getpid(),
|
| 551 |
+
"process_identity": _process_identity(),
|
| 552 |
+
"identity": identity,
|
| 553 |
+
"model_sha256": model_digest(model),
|
| 554 |
+
"checkpoint_sha256": sha256(out / "latest.pt"),
|
| 555 |
+
**counters,
|
| 556 |
+
"selection_mixed_answer_nll": next(
|
| 557 |
+
r["metrics"]["selection"]["mixed_answer_nll"]
|
| 558 |
+
for r in reversed(history)
|
| 559 |
+
if r["step"] == spec["steps"]
|
| 560 |
+
),
|
| 561 |
+
"wall_seconds": wall_offset + time.perf_counter() - started,
|
| 562 |
+
"completed_utc": utc(),
|
| 563 |
+
}
|
| 564 |
+
write_json(out / "trained.json", result)
|
| 565 |
+
write_json(out / "status.json", result)
|
| 566 |
+
return result
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
def audit(config, spec, out, device="cuda:0"):
|
| 570 |
+
"""Reconstruct and regenerate the full endpoint in an independent process."""
|
| 571 |
+
verify(config)
|
| 572 |
+
_setup(device, config)
|
| 573 |
+
out = Path(out)
|
| 574 |
+
trained = json.loads((out / "trained.json").read_text())
|
| 575 |
+
same_process = (
|
| 576 |
+
trained["process_identity"] == _process_identity()
|
| 577 |
+
if "process_identity" in trained
|
| 578 |
+
else trained["pid"] == os.getpid()
|
| 579 |
+
)
|
| 580 |
+
if same_process:
|
| 581 |
+
raise ValueError("Independent audit must run in a different process")
|
| 582 |
+
if trained["identity"] != _identity(config, spec):
|
| 583 |
+
raise ValueError("Audit recipe differs from the training freeze")
|
| 584 |
+
if sha256(out / "latest.pt") != trained["checkpoint_sha256"]:
|
| 585 |
+
raise ValueError("Training checkpoint changed")
|
| 586 |
+
model = _architecture().construct(config["model"], spec, device)
|
| 587 |
+
checkpoint = torch.load(out / "latest.pt", map_location="cpu", weights_only=False)
|
| 588 |
+
if checkpoint["step"] != spec["steps"]:
|
| 589 |
+
raise ValueError("Final checkpoint does not contain the requested endpoint")
|
| 590 |
+
model.load_state_dict(checkpoint["model"])
|
| 591 |
+
del checkpoint
|
| 592 |
+
if model_digest(model) != trained["model_sha256"]:
|
| 593 |
+
raise ValueError("Reloaded model does not match the trained endpoint")
|
| 594 |
+
data = json.loads(Path(config["data_file"]).read_text())
|
| 595 |
+
tokenizer = GPT2TokenizerFast.from_pretrained(config["tokenizer"], local_files_only=True)
|
| 596 |
+
metrics, predictions = historical.evaluate_dataset(
|
| 597 |
+
model, data, tokenizer, device, full=True, autonomous=True
|
| 598 |
+
)
|
| 599 |
+
if predictions != json.loads((out / "endpoint-predictions.json").read_text()):
|
| 600 |
+
raise AssertionError("Independent endpoint generation or NLL failed exact reproduction")
|
| 601 |
+
if metrics != json.loads((out / "endpoint.json").read_text()):
|
| 602 |
+
raise AssertionError("Independent endpoint metric recount failed")
|
| 603 |
+
result = {
|
| 604 |
+
"passed": True,
|
| 605 |
+
"pid": os.getpid(),
|
| 606 |
+
"source_training_pid": trained["pid"],
|
| 607 |
+
"process_identity": _process_identity(),
|
| 608 |
+
"source_process_identity": trained.get("process_identity"),
|
| 609 |
+
"checkpoint_sha256": trained["checkpoint_sha256"],
|
| 610 |
+
"model_sha256": trained["model_sha256"],
|
| 611 |
+
"predictions_recomputed": sum(len(p) for p in predictions.values()),
|
| 612 |
+
"completed_utc": utc(),
|
| 613 |
+
}
|
| 614 |
+
write_json(out / "audit.json", result)
|
| 615 |
+
write_json(
|
| 616 |
+
out / "complete.json", {**trained, "state": "complete", "independently_reloaded": True}
|
| 617 |
+
)
|
| 618 |
+
write_json(
|
| 619 |
+
out / "status.json",
|
| 620 |
+
{
|
| 621 |
+
"state": "complete",
|
| 622 |
+
"step": spec["steps"],
|
| 623 |
+
"independently_reloaded": True,
|
| 624 |
+
},
|
| 625 |
+
)
|
| 626 |
+
return result
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/qwen_constraints.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Constrained response primitives; empirical scopes are recorded by the runner."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import hashlib
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def select_records(records, count, seed, role):
|
| 11 |
+
"""Select before diagnostics, independently of accuracy or measured geometry."""
|
| 12 |
+
if len(records) < count:
|
| 13 |
+
raise ValueError(f"Insufficient records for {role}")
|
| 14 |
+
return sorted(
|
| 15 |
+
records,
|
| 16 |
+
key=lambda row: hashlib.sha256(f"{seed}:{role}:{row['case_id']}".encode()).hexdigest(),
|
| 17 |
+
)[:count]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def psd_solve(gram, rhs, rtol):
|
| 21 |
+
values, vectors = torch.linalg.eigh(gram.double())
|
| 22 |
+
eligible = values > values.max().clamp_min(1e-30) * rtol
|
| 23 |
+
projected = vectors[:, eligible].T @ rhs.double()
|
| 24 |
+
result = vectors[:, eligible] @ (projected / values[eligible])
|
| 25 |
+
return result, int(eligible.sum())
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def functional_projection(target, keep, rtol):
|
| 29 |
+
"""Orthogonal projection onto the numerical null space of keep gradients."""
|
| 30 |
+
g, r = target.double(), keep.double()
|
| 31 |
+
coefficients, rank = psd_solve(r @ r.T, r @ g, rtol)
|
| 32 |
+
result = g - coefficients @ r
|
| 33 |
+
denominator = g.square().sum().clamp_min(1e-30)
|
| 34 |
+
return result.to(target.dtype), {
|
| 35 |
+
"rank": rank,
|
| 36 |
+
"retained_energy": float(result.square().sum() / denominator),
|
| 37 |
+
"relative_keep_residual": float(
|
| 38 |
+
(r @ result).norm() / (r.norm() * result.norm()).clamp_min(1e-30)
|
| 39 |
+
),
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def feature_basis(features, rtol):
|
| 44 |
+
"""Rows are real token features; right singular vectors span protected keys."""
|
| 45 |
+
_, singular, vh = torch.linalg.svd(features.double(), full_matrices=False)
|
| 46 |
+
selected = singular > singular[0] * rtol
|
| 47 |
+
return vh[selected], singular
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def module_projection(gradient, basis):
|
| 51 |
+
g = gradient.double()
|
| 52 |
+
return (g - (g @ basis.T) @ basis).to(gradient.dtype)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def local_gradients(x, up, gate, down_weight, output_derivative):
|
| 56 |
+
"""All-position exact SwiGLU chain rule; no replacement of the forward model."""
|
| 57 |
+
sigmoid = torch.sigmoid(gate)
|
| 58 |
+
activated = gate * sigmoid
|
| 59 |
+
derivative = sigmoid + gate * sigmoid * (1 - sigmoid)
|
| 60 |
+
value_derivative = output_derivative @ down_weight
|
| 61 |
+
return {
|
| 62 |
+
"down": output_derivative.T @ (up * activated),
|
| 63 |
+
"up": (value_derivative * activated).T @ x,
|
| 64 |
+
"gate": (value_derivative * up * derivative).T @ x,
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def route_output(current, original, attention, route):
|
| 69 |
+
"""Forward activation intervention; baseline function is identical at zero update."""
|
| 70 |
+
if route == "all":
|
| 71 |
+
return current
|
| 72 |
+
mask = torch.zeros_like(attention, dtype=torch.bool)
|
| 73 |
+
mask[torch.arange(len(mask), device=mask.device), attention.sum(1) - 1] = True
|
| 74 |
+
if route == "earlier":
|
| 75 |
+
mask = attention.bool() & ~mask
|
| 76 |
+
elif route != "last":
|
| 77 |
+
raise ValueError(route)
|
| 78 |
+
return torch.where(mask.unsqueeze(-1), current, original)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def update_scale(direction, target_gradient, step, parameter_norm, cap, metric):
|
| 82 |
+
d_norm = direction.double().norm()
|
| 83 |
+
g_norm = target_gradient.double().norm()
|
| 84 |
+
response = target_gradient.double() @ direction.double()
|
| 85 |
+
if d_norm == 0 or response <= 0:
|
| 86 |
+
return 0.0, True
|
| 87 |
+
if metric == "equal_norm":
|
| 88 |
+
scale = step / (g_norm * d_norm)
|
| 89 |
+
elif metric == "equal_target":
|
| 90 |
+
scale = step / response
|
| 91 |
+
else:
|
| 92 |
+
raise ValueError(metric)
|
| 93 |
+
maximum = cap * parameter_norm / d_norm
|
| 94 |
+
return float(torch.minimum(scale, maximum)), bool(scale > maximum)
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/qwen_path_learning.py
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Position-routed down updates, complete-answer objectives, and audited data helpers."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
import re
|
| 9 |
+
import time
|
| 10 |
+
from datetime import datetime, timezone
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
|
| 14 |
+
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
+
import torch.nn.functional as F
|
| 19 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 20 |
+
|
| 21 |
+
from .hebbian_data import TEMPLATE, encode_answer, score_answer
|
| 22 |
+
from .hebbian_model import set_determinism, tensor_hash
|
| 23 |
+
|
| 24 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 25 |
+
DATA = ROOT / "data/qwen-path-learning-v1"
|
| 26 |
+
ART = ROOT / "docs/development-artifacts/qwen-path-learning-v1"
|
| 27 |
+
RESULTS = ROOT / "results/qwen-path-learning-v1"
|
| 28 |
+
CONFIG = ROOT / "configs/qwen-path-learning-v1.json"
|
| 29 |
+
GROUPS = ("S_end", "S_other", "C", "W", "L", "A")
|
| 30 |
+
|
| 31 |
+
# All views ask the same original CounterFact relation; no generated answer labels.
|
| 32 |
+
RELATIONS = {
|
| 33 |
+
"P19": ("{} was born in", "The birthplace of {} is", "{}'s birthplace is"),
|
| 34 |
+
"P20": ("{} died in", "The place of death of {} is", "{}'s place of death is"),
|
| 35 |
+
"P103": (
|
| 36 |
+
"The native language of {} is",
|
| 37 |
+
"The mother tongue of {} is",
|
| 38 |
+
"{}'s native language is",
|
| 39 |
+
),
|
| 40 |
+
"P176": ("The manufacturer of {} is", "{} was manufactured by", "{}'s manufacturer is"),
|
| 41 |
+
"P178": ("The developer of {} is", "{} was developed by", "{}'s developer is"),
|
| 42 |
+
"P495": (
|
| 43 |
+
"The country of origin of {} is",
|
| 44 |
+
"{} originated in the country of",
|
| 45 |
+
"{}'s country of origin is",
|
| 46 |
+
),
|
| 47 |
+
"P740": (
|
| 48 |
+
"{} was founded in",
|
| 49 |
+
"The place where {} was founded is",
|
| 50 |
+
"{}'s place of formation is",
|
| 51 |
+
),
|
| 52 |
+
"P364": (
|
| 53 |
+
"The original language of {} is",
|
| 54 |
+
"{} was originally in the language",
|
| 55 |
+
"{}'s original language is",
|
| 56 |
+
),
|
| 57 |
+
"P407": ("The language of {} is", "{} is in the language", "{}'s language is"),
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def now():
|
| 62 |
+
return datetime.now(timezone.utc).isoformat()
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def read(path):
|
| 66 |
+
return json.loads(Path(path).read_text())
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def write(path, obj):
|
| 70 |
+
path = Path(path)
|
| 71 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 72 |
+
temporary = path.with_suffix(f".{os.getpid()}.tmp")
|
| 73 |
+
temporary.write_text(json.dumps(obj, ensure_ascii=False, indent=2, allow_nan=False) + "\n")
|
| 74 |
+
temporary.replace(path)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def digest(path):
|
| 78 |
+
h = hashlib.sha256()
|
| 79 |
+
with Path(path).open("rb") as stream:
|
| 80 |
+
for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""):
|
| 81 |
+
h.update(chunk)
|
| 82 |
+
return h.hexdigest()
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def stable(value):
|
| 86 |
+
return hashlib.sha256(str(value).encode()).hexdigest()
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def encode_fact(tokenizer, subject, statement, answer, view=0, plain=False):
|
| 90 |
+
prompt = statement if plain else TEMPLATE.format(statement)
|
| 91 |
+
enc = encode_answer(tokenizer, prompt, answer)
|
| 92 |
+
offset = 0 if plain else prompt.index(statement)
|
| 93 |
+
subject_start = statement.index(subject) + offset
|
| 94 |
+
subject_end = subject_start + len(subject)
|
| 95 |
+
offsets = tokenizer(prompt, add_special_tokens=False, return_offsets_mapping=True)[
|
| 96 |
+
"offset_mapping"
|
| 97 |
+
]
|
| 98 |
+
subject_tokens = [
|
| 99 |
+
i for i, (a, b) in enumerate(offsets) if b > subject_start and a < subject_end
|
| 100 |
+
]
|
| 101 |
+
if not subject_tokens:
|
| 102 |
+
raise ValueError("Subject has no tokens")
|
| 103 |
+
roles = []
|
| 104 |
+
for i, (a, b) in enumerate(offsets):
|
| 105 |
+
if i == len(offsets) - 1:
|
| 106 |
+
role = "L"
|
| 107 |
+
elif i == subject_tokens[-1]:
|
| 108 |
+
role = "S_end"
|
| 109 |
+
elif i in subject_tokens:
|
| 110 |
+
role = "S_other"
|
| 111 |
+
elif b > offset and a < offset + len(statement):
|
| 112 |
+
role = "C"
|
| 113 |
+
else:
|
| 114 |
+
role = "W"
|
| 115 |
+
roles.append(role)
|
| 116 |
+
roles += ["A"] * (len(enc["input_ids"]) - len(roles))
|
| 117 |
+
return {**enc, "prompt": prompt, "roles": roles, "view": view, "plain": plain}
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def random_positions(roles, group, key, seed, bins=2, draws=16, energies=None):
|
| 121 |
+
"""Disjoint count/bin-matched controls; optional local-energy matching only."""
|
| 122 |
+
n = roles.index("L") + 1
|
| 123 |
+
target = [i for i, role in enumerate(roles[: n - 1]) if role == group]
|
| 124 |
+
if not target:
|
| 125 |
+
return [], {"valid": False, "reason": "empty_group"}
|
| 126 |
+
|
| 127 |
+
def strata(i):
|
| 128 |
+
return min(bins - 1, i * bins // max(n - 1, 1))
|
| 129 |
+
|
| 130 |
+
eligible = {
|
| 131 |
+
b: [i for i in range(n - 1) if i not in target and strata(i) == b] for b in range(bins)
|
| 132 |
+
}
|
| 133 |
+
counts = {b: sum(strata(i) == b for i in target) for b in range(bins)}
|
| 134 |
+
if any(len(eligible[b]) < counts[b] for b in range(bins)):
|
| 135 |
+
return [], {"valid": False, "reason": "insufficient_disjoint_positions"}
|
| 136 |
+
rng = np.random.default_rng(int(stable(f"{key}:{group}:{seed}")[:16], 16))
|
| 137 |
+
options = []
|
| 138 |
+
for _ in range(draws if energies is not None else 1):
|
| 139 |
+
positions = sorted(
|
| 140 |
+
int(i) for b in range(bins) for i in rng.choice(eligible[b], counts[b], replace=False)
|
| 141 |
+
)
|
| 142 |
+
error = (
|
| 143 |
+
0.0
|
| 144 |
+
if energies is None
|
| 145 |
+
else abs(sum(energies[i] for i in positions) - sum(energies[i] for i in target))
|
| 146 |
+
/ max(sum(energies[i] for i in target), 1e-30)
|
| 147 |
+
)
|
| 148 |
+
options.append((error, positions))
|
| 149 |
+
error, selected = min(options, key=lambda x: (x[0], x[1]))
|
| 150 |
+
return selected, {"valid": True, "relative_energy_error": error, "count": len(target)}
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def sequence_mean(values, batch_indices, count):
|
| 154 |
+
sums = values.new_zeros(count).scatter_add_(0, batch_indices, values)
|
| 155 |
+
return sums / torch.bincount(batch_indices, minlength=count).clamp_min(1)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def fisher_quadratic(logp, response):
|
| 159 |
+
p = logp.exp()
|
| 160 |
+
return 0.5 * ((p * response.square()).sum(-1) - (p * response).sum(-1).square())
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class PathEngine:
|
| 164 |
+
def __init__(self, device, layer=None):
|
| 165 |
+
self.cfg = read(CONFIG)
|
| 166 |
+
set_determinism(self.cfg["seed"])
|
| 167 |
+
self.device = torch.device(device)
|
| 168 |
+
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 169 |
+
ROOT / self.cfg["model_source"], local_files_only=True
|
| 170 |
+
)
|
| 171 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 172 |
+
self.model = (
|
| 173 |
+
AutoModelForCausalLM.from_pretrained(
|
| 174 |
+
ROOT / self.cfg["model_source"],
|
| 175 |
+
local_files_only=True,
|
| 176 |
+
dtype=torch.float32,
|
| 177 |
+
attn_implementation="eager",
|
| 178 |
+
)
|
| 179 |
+
.to(self.device)
|
| 180 |
+
.eval()
|
| 181 |
+
.requires_grad_(False)
|
| 182 |
+
)
|
| 183 |
+
self.layer_index = self.cfg["layer"] if layer is None else layer
|
| 184 |
+
self.down = self.model.model.layers[self.layer_index].mlp.down_proj
|
| 185 |
+
self.base_hash = tensor_hash(self.down.weight)
|
| 186 |
+
self.delta = torch.nn.Parameter(torch.zeros_like(self.down.weight))
|
| 187 |
+
self.route = "all"
|
| 188 |
+
self.route_seed = 0
|
| 189 |
+
self.route_group = None
|
| 190 |
+
self.route_positions = {}
|
| 191 |
+
self.mask = None
|
| 192 |
+
self.capture = None
|
| 193 |
+
self.handle = self.down.register_forward_hook(self._hook)
|
| 194 |
+
self.reference = {}
|
| 195 |
+
self.forward_tokens = 0
|
| 196 |
+
self.started = time.time()
|
| 197 |
+
|
| 198 |
+
def _hook(self, module, args, output):
|
| 199 |
+
increment = F.linear(args[0], self.delta)
|
| 200 |
+
if self.capture is not None:
|
| 201 |
+
self.capture.append(increment.detach().square().sum(-1).cpu())
|
| 202 |
+
if self.mask is not None:
|
| 203 |
+
increment = increment * self.mask[:, -increment.shape[1] :, None]
|
| 204 |
+
return output + increment
|
| 205 |
+
|
| 206 |
+
def mask_for(self, enc):
|
| 207 |
+
roles = enc["roles"]
|
| 208 |
+
mask = [1.0] * len(roles)
|
| 209 |
+
if self.route == "all":
|
| 210 |
+
return mask
|
| 211 |
+
if "L" not in roles: # Unannotated natural text has no fact-position groups.
|
| 212 |
+
return mask
|
| 213 |
+
if self.route == "group":
|
| 214 |
+
positions = [i for i, x in enumerate(roles) if x == self.route_group]
|
| 215 |
+
elif self.route == "random":
|
| 216 |
+
positions, _ = random_positions(roles, self.route_group, enc["key"], self.route_seed)
|
| 217 |
+
elif self.route == "positions":
|
| 218 |
+
positions = self.route_positions.get(enc["key"], [])
|
| 219 |
+
elif self.route == "zero":
|
| 220 |
+
positions = list(range(len(roles)))
|
| 221 |
+
else:
|
| 222 |
+
raise ValueError(self.route)
|
| 223 |
+
for i in positions:
|
| 224 |
+
mask[i] = 0.0
|
| 225 |
+
return mask
|
| 226 |
+
|
| 227 |
+
def batch(self, encoded, prompt_only=False):
|
| 228 |
+
sequences = [
|
| 229 |
+
e["input_ids"][: e["answer_start"]] if prompt_only else e["input_ids"] for e in encoded
|
| 230 |
+
]
|
| 231 |
+
width = max(map(len, sequences))
|
| 232 |
+
ids = torch.full(
|
| 233 |
+
(len(sequences), width),
|
| 234 |
+
self.tokenizer.pad_token_id,
|
| 235 |
+
device=self.device,
|
| 236 |
+
dtype=torch.long,
|
| 237 |
+
)
|
| 238 |
+
attention = torch.zeros_like(ids)
|
| 239 |
+
loss = torch.zeros_like(ids, dtype=torch.bool)
|
| 240 |
+
masks = torch.ones_like(ids, dtype=torch.float32)
|
| 241 |
+
for i, (seq, enc) in enumerate(zip(sequences, encoded, strict=True)):
|
| 242 |
+
ids[i, : len(seq)] = torch.tensor(seq, device=self.device)
|
| 243 |
+
attention[i, : len(seq)] = 1
|
| 244 |
+
if not prompt_only:
|
| 245 |
+
loss[i, : len(seq)] = torch.tensor(
|
| 246 |
+
enc["loss_mask"], device=self.device, dtype=torch.bool
|
| 247 |
+
)
|
| 248 |
+
masks[i, : len(seq)] = torch.tensor(self.mask_for(enc)[: len(seq)], device=self.device)
|
| 249 |
+
self.mask = masks
|
| 250 |
+
return ids, attention, loss
|
| 251 |
+
|
| 252 |
+
def hidden(self, ids, attention):
|
| 253 |
+
self.forward_tokens += ids.numel()
|
| 254 |
+
return self.model.model(
|
| 255 |
+
input_ids=ids, attention_mask=attention, use_cache=False
|
| 256 |
+
).last_hidden_state
|
| 257 |
+
|
| 258 |
+
def objectives(self, encoded, include_kl=True):
|
| 259 |
+
ids, attention, mask = self.batch(encoded)
|
| 260 |
+
b, t = torch.where(mask[:, 1:])
|
| 261 |
+
hidden = self.hidden(ids, attention)
|
| 262 |
+
logits = self.model.lm_head(hidden[b, t])
|
| 263 |
+
ce = sequence_mean(
|
| 264 |
+
F.cross_entropy(logits, ids[b, t + 1], reduction="none"), b, len(encoded)
|
| 265 |
+
)
|
| 266 |
+
if not include_kl:
|
| 267 |
+
return ce, None
|
| 268 |
+
with torch.no_grad():
|
| 269 |
+
ref_hidden = torch.cat([self.reference[e["key"]] for e in encoded]).to(self.device)
|
| 270 |
+
ref_log = F.log_softmax(self.model.lm_head(ref_hidden), dim=-1)
|
| 271 |
+
divergence = (ref_log.exp() * (ref_log - F.log_softmax(logits, dim=-1))).sum(-1)
|
| 272 |
+
return ce, sequence_mean(divergence, b, len(encoded))
|
| 273 |
+
|
| 274 |
+
@torch.no_grad()
|
| 275 |
+
def cache_reference(self, encoded, batch_size=8):
|
| 276 |
+
if self.delta.count_nonzero().item():
|
| 277 |
+
raise ValueError("Reference must be cached at the parent")
|
| 278 |
+
for start in range(0, len(encoded), batch_size):
|
| 279 |
+
chunk = encoded[start : start + batch_size]
|
| 280 |
+
ids, attention, mask = self.batch(chunk)
|
| 281 |
+
b, t = torch.where(mask[:, 1:])
|
| 282 |
+
hidden = self.hidden(ids, attention)
|
| 283 |
+
for i, enc in enumerate(chunk):
|
| 284 |
+
self.reference[enc["key"]] = hidden[b[b == i], t[b == i]].detach().cpu()
|
| 285 |
+
|
| 286 |
+
@torch.no_grad()
|
| 287 |
+
def generate(self, encoded):
|
| 288 |
+
# Cached greedy decoding; routing is built from the input prompt alone.
|
| 289 |
+
sequences = [e["input_ids"][: e["answer_start"]] for e in encoded]
|
| 290 |
+
width = max(map(len, sequences))
|
| 291 |
+
ids = torch.full(
|
| 292 |
+
(len(sequences), width),
|
| 293 |
+
self.tokenizer.pad_token_id,
|
| 294 |
+
device=self.device,
|
| 295 |
+
dtype=torch.long,
|
| 296 |
+
)
|
| 297 |
+
attention = torch.zeros_like(ids)
|
| 298 |
+
route_mask = torch.ones_like(ids, dtype=torch.float32)
|
| 299 |
+
for i, (seq, enc) in enumerate(zip(sequences, encoded, strict=True)):
|
| 300 |
+
ids[i, -len(seq) :] = torch.tensor(seq, device=self.device)
|
| 301 |
+
attention[i, -len(seq) :] = 1
|
| 302 |
+
route_mask[i, -len(seq) :] = torch.tensor(
|
| 303 |
+
self.mask_for(enc)[: len(seq)], device=self.device
|
| 304 |
+
)
|
| 305 |
+
tails = [[] for _ in encoded]
|
| 306 |
+
done = [False] * len(encoded)
|
| 307 |
+
cache = None
|
| 308 |
+
for step in range(self.cfg["max_new_tokens"]):
|
| 309 |
+
position = attention.cumsum(-1) - 1
|
| 310 |
+
position.masked_fill_(attention == 0, 0)
|
| 311 |
+
self.mask = (
|
| 312 |
+
route_mask
|
| 313 |
+
if step == 0
|
| 314 |
+
else torch.full(
|
| 315 |
+
(len(encoded), 1),
|
| 316 |
+
0.0
|
| 317 |
+
if self.route == "zero" or (self.route == "group" and self.route_group == "A")
|
| 318 |
+
else 1.0,
|
| 319 |
+
device=self.device,
|
| 320 |
+
)
|
| 321 |
+
)
|
| 322 |
+
out = self.model.model(
|
| 323 |
+
input_ids=ids,
|
| 324 |
+
attention_mask=attention,
|
| 325 |
+
position_ids=position if step == 0 else position[:, -1:],
|
| 326 |
+
past_key_values=cache,
|
| 327 |
+
use_cache=True,
|
| 328 |
+
)
|
| 329 |
+
self.forward_tokens += ids.numel()
|
| 330 |
+
cache = out.past_key_values
|
| 331 |
+
next_ids = self.model.lm_head(out.last_hidden_state[:, -1]).argmax(-1)
|
| 332 |
+
for i, token in enumerate(next_ids.tolist()):
|
| 333 |
+
if not done[i]:
|
| 334 |
+
tails[i].append(token)
|
| 335 |
+
decoded = self.tokenizer.decode(tails[i], skip_special_tokens=True)
|
| 336 |
+
done[i] = token == self.tokenizer.eos_token_id or "\n" in decoded
|
| 337 |
+
if all(done):
|
| 338 |
+
break
|
| 339 |
+
ids = next_ids[:, None]
|
| 340 |
+
attention = torch.cat([attention, torch.ones_like(ids)], dim=1)
|
| 341 |
+
return [
|
| 342 |
+
{
|
| 343 |
+
"prediction": self.tokenizer.decode(tail, skip_special_tokens=True),
|
| 344 |
+
"tokens": tail,
|
| 345 |
+
"eos": self.tokenizer.eos_token_id in tail,
|
| 346 |
+
}
|
| 347 |
+
for tail in tails
|
| 348 |
+
]
|
| 349 |
+
|
| 350 |
+
@torch.no_grad()
|
| 351 |
+
def evaluate(self, records, views=(0,), batch_size=16, with_kl=True, generate=True):
|
| 352 |
+
entries = [(r, r["encoded"][v]) for r in records for v in views]
|
| 353 |
+
output = []
|
| 354 |
+
for start in range(0, len(entries), batch_size):
|
| 355 |
+
chunk = entries[start : start + batch_size]
|
| 356 |
+
encs = [e for _, e in chunk]
|
| 357 |
+
ce, kl = self.objectives(encs, include_kl=with_kl)
|
| 358 |
+
predictions = self.generate(encs) if generate else [None] * len(chunk)
|
| 359 |
+
for i, ((record, enc), prediction) in enumerate(zip(chunk, predictions, strict=True)):
|
| 360 |
+
item = {
|
| 361 |
+
"case_id": record["case_id"],
|
| 362 |
+
"view": enc["view"],
|
| 363 |
+
"ce": float(ce[i]),
|
| 364 |
+
"kl": None if kl is None else float(kl[i]),
|
| 365 |
+
}
|
| 366 |
+
if prediction is not None:
|
| 367 |
+
item.update(prediction)
|
| 368 |
+
item["correct"] = score_answer(prediction["prediction"], record["aliases"])
|
| 369 |
+
output.append(item)
|
| 370 |
+
return output
|
| 371 |
+
|
| 372 |
+
@torch.no_grad()
|
| 373 |
+
def evaluate_text(self, encoded):
|
| 374 |
+
result = []
|
| 375 |
+
for start in range(0, len(encoded), 2):
|
| 376 |
+
chunk = encoded[start : start + 2]
|
| 377 |
+
ce, kl = self.objectives(chunk)
|
| 378 |
+
result.extend(
|
| 379 |
+
{"key": e["key"], "ce": float(c), "kl": float(k)}
|
| 380 |
+
for e, c, k in zip(chunk, ce, kl, strict=True)
|
| 381 |
+
)
|
| 382 |
+
return result
|
| 383 |
+
|
| 384 |
+
def restore(self):
|
| 385 |
+
with torch.no_grad():
|
| 386 |
+
self.delta.zero_()
|
| 387 |
+
self.route = "all"
|
| 388 |
+
self.mask = None
|
| 389 |
+
assert tensor_hash(self.down.weight) == self.base_hash
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def mean(rows, key):
|
| 393 |
+
return float(np.mean([r[key] for r in rows])) if rows else None
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def valid_aliases(raw):
|
| 397 |
+
by_id = {}
|
| 398 |
+
for row in raw:
|
| 399 |
+
target = row["requested_rewrite"]["target_true"]
|
| 400 |
+
by_id.setdefault(target["id"], set()).add(target["str"].strip())
|
| 401 |
+
return {k: sorted(v) for k, v in by_id.items()}
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def articles_from_lines(lines):
|
| 405 |
+
articles = []
|
| 406 |
+
title, parts = None, []
|
| 407 |
+
for line in lines:
|
| 408 |
+
if re.fullmatch(r"\s*= [^=]+ =\s*", line):
|
| 409 |
+
if title and parts:
|
| 410 |
+
articles.append((title, "".join(parts)))
|
| 411 |
+
title, parts = line.strip(), []
|
| 412 |
+
elif title:
|
| 413 |
+
parts.append(line)
|
| 414 |
+
if title and parts:
|
| 415 |
+
articles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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Frozen-matrix execution and development-only selection for path learning."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import platform
|
| 8 |
+
import shutil
|
| 9 |
+
import time
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import torch
|
| 13 |
+
import transformers
|
| 14 |
+
|
| 15 |
+
from .qwen_path_learning import (
|
| 16 |
+
ART,
|
| 17 |
+
CONFIG,
|
| 18 |
+
DATA,
|
| 19 |
+
RESULTS,
|
| 20 |
+
ROOT,
|
| 21 |
+
PathEngine,
|
| 22 |
+
digest,
|
| 23 |
+
encode_fact,
|
| 24 |
+
mean,
|
| 25 |
+
now,
|
| 26 |
+
random_positions,
|
| 27 |
+
read,
|
| 28 |
+
write,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def preflight(device):
|
| 33 |
+
from .hebbian_model import aggregate_hash, state_hashes
|
| 34 |
+
|
| 35 |
+
cfg = read(CONFIG)
|
| 36 |
+
old_records = read(ROOT / "data/hebbian-learning-v1/pools.json")["B_dev"][:2]
|
| 37 |
+
engine = PathEngine(device)
|
| 38 |
+
encs = []
|
| 39 |
+
for r in old_records:
|
| 40 |
+
enc = encode_fact(engine.tokenizer, r["subject"], r["views"][0], r["answer"])
|
| 41 |
+
enc["key"] = f"preflight-{r['case_id']}"
|
| 42 |
+
encs.append(enc)
|
| 43 |
+
before_hash = aggregate_hash(state_hashes(engine.model))
|
| 44 |
+
assert all(not p.requires_grad for p in engine.model.parameters())
|
| 45 |
+
assert engine.delta.numel() == 3145728
|
| 46 |
+
engine.cache_reference(encs)
|
| 47 |
+
baseline_ce, zero_kl = engine.objectives(encs)
|
| 48 |
+
baseline_ce = baseline_ce.detach()
|
| 49 |
+
checks = {
|
| 50 |
+
"parameter_count": engine.delta.numel(),
|
| 51 |
+
"zero_kl_max": float(zero_kl.detach().abs().max()),
|
| 52 |
+
}
|
| 53 |
+
assert checks["zero_kl_max"] < 1e-5
|
| 54 |
+
for group in cfg["groups"]:
|
| 55 |
+
engine.route, engine.route_group = "group", group
|
| 56 |
+
ce, _ = engine.objectives(encs)
|
| 57 |
+
assert torch.equal(ce.detach(), baseline_ce)
|
| 58 |
+
engine.route = "all"
|
| 59 |
+
with torch.no_grad():
|
| 60 |
+
engine.delta.normal_(std=1e-5)
|
| 61 |
+
ids, attention, _ = engine.batch(encs)
|
| 62 |
+
with torch.no_grad():
|
| 63 |
+
separate = engine.hidden(ids, attention)
|
| 64 |
+
delta = engine.delta.clone()
|
| 65 |
+
original_weight = engine.down.weight.clone()
|
| 66 |
+
engine.down.weight.add_(delta)
|
| 67 |
+
engine.delta.zero_()
|
| 68 |
+
fused = engine.hidden(ids, attention)
|
| 69 |
+
engine.down.weight.copy_(original_weight)
|
| 70 |
+
engine.delta.copy_(delta)
|
| 71 |
+
checks["all_vs_fused_hidden_max_error"] = float((separate - fused).abs().max())
|
| 72 |
+
assert checks["all_vs_fused_hidden_max_error"] < 1e-3
|
| 73 |
+
engine.restore()
|
| 74 |
+
opt = optimizer(engine, 1e-5)
|
| 75 |
+
begun = time.time()
|
| 76 |
+
ce, _ = engine.objectives(encs, include_kl=False)
|
| 77 |
+
ce.mean().backward()
|
| 78 |
+
checks["delta_gradient_norm"] = float(engine.delta.grad.norm())
|
| 79 |
+
torch.nn.utils.clip_grad_norm_([engine.delta], cfg["optimizer"]["clip"])
|
| 80 |
+
opt.step()
|
| 81 |
+
checks["single_old_episode_step_seconds"] = time.time() - begun
|
| 82 |
+
assert checks["delta_gradient_norm"] > 0 and torch.isfinite(engine.delta).all()
|
| 83 |
+
engine.restore()
|
| 84 |
+
assert aggregate_hash(state_hashes(engine.model)) == before_hash
|
| 85 |
+
ce, _ = engine.objectives(encs)
|
| 86 |
+
checks["restore_ce_max_error"] = float((ce.detach() - baseline_ce).abs().max())
|
| 87 |
+
assert checks["restore_ce_max_error"] == 0
|
| 88 |
+
del engine
|
| 89 |
+
torch.cuda.empty_cache()
|
| 90 |
+
final = PathEngine(device, layer=27)
|
| 91 |
+
with torch.no_grad():
|
| 92 |
+
final.delta.normal_(std=1e-4)
|
| 93 |
+
final.route = "zero"
|
| 94 |
+
parent_ce, _ = final.objectives(encs, include_kl=False)
|
| 95 |
+
# Enable only earlier-prompt increments, and disable all readout positions.
|
| 96 |
+
final.route = "positions"
|
| 97 |
+
final.route_positions = {
|
| 98 |
+
e["key"]: list(range(e["answer_start"] - 1, len(e["roles"]))) for e in encs
|
| 99 |
+
}
|
| 100 |
+
early_ce, _ = final.objectives(encs, include_kl=False)
|
| 101 |
+
checks["final_layer_earlier_ce_max_error"] = float((early_ce - parent_ce).abs().max())
|
| 102 |
+
assert checks["final_layer_earlier_ce_max_error"] == 0
|
| 103 |
+
final.restore()
|
| 104 |
+
checks["passed"] = True
|
| 105 |
+
checks["time"] = now()
|
| 106 |
+
checks["training_cases"] = "two old B_dev facts; no new developmental outcome selection"
|
| 107 |
+
checks["parent_model_sha256"] = before_hash
|
| 108 |
+
write(ART / "preflight.json", checks)
|
| 109 |
+
print(json.dumps(checks), flush=True)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def jobs():
|
| 113 |
+
cfg = read(CONFIG)
|
| 114 |
+
return [
|
| 115 |
+
{
|
| 116 |
+
"id": f"dev-e{episode}-lr{lr:g}-b{beta}",
|
| 117 |
+
"episode": episode,
|
| 118 |
+
"lr": lr,
|
| 119 |
+
"beta": beta,
|
| 120 |
+
"seed": 0,
|
| 121 |
+
"phase": "dev",
|
| 122 |
+
"condition": "ordinary",
|
| 123 |
+
}
|
| 124 |
+
for episode in range(4)
|
| 125 |
+
for lr in cfg["learning_rates"]
|
| 126 |
+
for beta in cfg["betas_replay"]
|
| 127 |
+
]
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def sources():
|
| 131 |
+
return [
|
| 132 |
+
"configs/qwen-path-learning-v1.json",
|
| 133 |
+
"scripts/run_qwen_path_learning.py",
|
| 134 |
+
"src/llm_memory_editability/qwen_path_learning.py",
|
| 135 |
+
"src/llm_memory_editability/qwen_path_train.py",
|
| 136 |
+
"src/llm_memory_editability/hebbian_data.py",
|
| 137 |
+
"src/llm_memory_editability/hebbian_model.py",
|
| 138 |
+
"src/llm_memory_editability/hebbian_learning.py",
|
| 139 |
+
"tests/test_qwen_path_learning.py",
|
| 140 |
+
]
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def freeze():
|
| 144 |
+
if (ART / "execution-lock.json").exists():
|
| 145 |
+
raise RuntimeError("Execution lock exists")
|
| 146 |
+
assert read(ART / "preflight.json")["passed"]
|
| 147 |
+
assert read(ART / "selection-lock.json")["selection_sha256"] == digest(DATA / "selection.json")
|
| 148 |
+
frozen = {}
|
| 149 |
+
for relative in sources() + [
|
| 150 |
+
"docs/hebbian-learning-plan-v1.md",
|
| 151 |
+
"docs/experimental-protocol.md",
|
| 152 |
+
]:
|
| 153 |
+
path = ROOT / relative
|
| 154 |
+
target = ART / "execution-source" / relative
|
| 155 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 156 |
+
shutil.copyfile(path, target)
|
| 157 |
+
frozen[relative] = digest(path)
|
| 158 |
+
cfg = read(CONFIG)
|
| 159 |
+
model = ROOT / cfg["model_source"] / "model.safetensors"
|
| 160 |
+
write(
|
| 161 |
+
ART / "execution-lock.json",
|
| 162 |
+
{
|
| 163 |
+
"time": now(),
|
| 164 |
+
"status": "locked_before_development_updates",
|
| 165 |
+
"sources": frozen,
|
| 166 |
+
"inputs": {
|
| 167 |
+
str(p.relative_to(ROOT)): digest(p)
|
| 168 |
+
for p in [DATA / "selection.json", DATA / "text.json", model]
|
| 169 |
+
},
|
| 170 |
+
"matrix": jobs(),
|
| 171 |
+
"environment": {
|
| 172 |
+
"python": platform.python_version(),
|
| 173 |
+
"torch": torch.__version__,
|
| 174 |
+
"transformers": transformers.__version__,
|
| 175 |
+
"numpy": np.__version__,
|
| 176 |
+
},
|
| 177 |
+
"config": cfg,
|
| 178 |
+
},
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def check_lock():
|
| 183 |
+
lock = read(ART / "execution-lock.json")
|
| 184 |
+
for relative in sources():
|
| 185 |
+
assert digest(ROOT / relative) == lock["sources"][relative], relative
|
| 186 |
+
for relative in (
|
| 187 |
+
"data/qwen-path-learning-v1/selection.json",
|
| 188 |
+
"data/qwen-path-learning-v1/text.json",
|
| 189 |
+
):
|
| 190 |
+
assert digest(ROOT / relative) == lock["inputs"][relative]
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def optimizer(engine, lr):
|
| 194 |
+
cfg = engine.cfg["optimizer"]
|
| 195 |
+
return torch.optim.AdamW(
|
| 196 |
+
[engine.delta],
|
| 197 |
+
lr=lr,
|
| 198 |
+
betas=tuple(cfg["betas"]),
|
| 199 |
+
eps=cfg["eps"],
|
| 200 |
+
weight_decay=cfg["weight_decay"],
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def schedule(cfg, episode, seed, n_r=64, n_text=64):
|
| 205 |
+
rng = np.random.default_rng(cfg["seed"] + 1000 * episode + seed)
|
| 206 |
+
# Fixed cyclic shuffled decks give exactly equal aggregate exposure across jobs.
|
| 207 |
+
replay, text = rng.permutation(n_r), rng.permutation(n_text)
|
| 208 |
+
return [
|
| 209 |
+
{
|
| 210 |
+
"R": [int(replay[(step * 8 + i) % n_r]) for i in range(8)],
|
| 211 |
+
"text": [int(text[(step * 2 + i) % n_text]) for i in range(2)],
|
| 212 |
+
}
|
| 213 |
+
for step in range(cfg["steps"])
|
| 214 |
+
]
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def save_checkpoint(path, engine, opt, job, step, history, ledger):
|
| 218 |
+
temporary = path.with_suffix(f".{os.getpid()}.tmp")
|
| 219 |
+
torch.save(
|
| 220 |
+
{
|
| 221 |
+
"delta": engine.delta.detach().cpu(),
|
| 222 |
+
"optimizer": opt.state_dict(),
|
| 223 |
+
"job": job,
|
| 224 |
+
"step": step,
|
| 225 |
+
"history": history,
|
| 226 |
+
"ledger": ledger,
|
| 227 |
+
"execution_lock": digest(ART / "execution-lock.json"),
|
| 228 |
+
},
|
| 229 |
+
temporary,
|
| 230 |
+
)
|
| 231 |
+
temporary.replace(path)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def evaluate_node(engine, episode, selection, texts, step, output, full_test=False):
|
| 235 |
+
result = {
|
| 236 |
+
"step": step,
|
| 237 |
+
"time": now(),
|
| 238 |
+
"E": engine.evaluate(episode, views=(0, 1, 2, 3), with_kl=False),
|
| 239 |
+
"R": engine.evaluate(selection["R"]),
|
| 240 |
+
"V": engine.evaluate(selection["V"]),
|
| 241 |
+
"text_dev": engine.evaluate_text(texts["dev"]),
|
| 242 |
+
"delta_norm": float(engine.delta.norm()),
|
| 243 |
+
"relative_delta_norm": float(engine.delta.norm() / engine.down.weight.norm()),
|
| 244 |
+
}
|
| 245 |
+
if full_test:
|
| 246 |
+
result["U"] = engine.evaluate(selection["U"], views=(0, 1, 2, 3))
|
| 247 |
+
result["text_test"] = engine.evaluate_text(texts["test"])
|
| 248 |
+
write(output / f"node-{step:03d}.json", result)
|
| 249 |
+
return result
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def train_job(engine, job):
|
| 253 |
+
check_lock()
|
| 254 |
+
cfg = engine.cfg
|
| 255 |
+
out = RESULTS / job["id"]
|
| 256 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 257 |
+
if (out / "complete.json").exists():
|
| 258 |
+
return
|
| 259 |
+
engine.restore()
|
| 260 |
+
selection, texts = read(DATA / "selection.json"), read(DATA / "text.json")
|
| 261 |
+
phase = job["phase"]
|
| 262 |
+
records = selection["E_dev" if phase == "dev" else "E_confirm"]
|
| 263 |
+
episode = records[job["episode"] * 4 : (job["episode"] + 1) * 4]
|
| 264 |
+
training_enc = [r["encoded"][0] for r in episode]
|
| 265 |
+
reference_enc = (
|
| 266 |
+
[r["encoded"][0] for role in ("R", "V") for r in selection[role]]
|
| 267 |
+
+ texts["train"]
|
| 268 |
+
+ texts["dev"]
|
| 269 |
+
)
|
| 270 |
+
if phase == "confirm":
|
| 271 |
+
reference_enc += [enc for r in selection["U"] for enc in r["encoded"]] + texts["test"]
|
| 272 |
+
missing = [e for e in reference_enc if e["key"] not in engine.reference]
|
| 273 |
+
engine.cache_reference(missing)
|
| 274 |
+
if job["condition"] != "ordinary":
|
| 275 |
+
engine.route = "group" if job["condition"] == "candidate" else "random"
|
| 276 |
+
engine.route_group = job["group"]
|
| 277 |
+
engine.route_seed = job["seed"]
|
| 278 |
+
opt = optimizer(engine, job["lr"])
|
| 279 |
+
batches = schedule(cfg, job["episode"], job["seed"])
|
| 280 |
+
write(out / "schedule.json", batches)
|
| 281 |
+
history, ledger, start = (
|
| 282 |
+
[],
|
| 283 |
+
{
|
| 284 |
+
"E_sequences": 0,
|
| 285 |
+
"R_sequences": 0,
|
| 286 |
+
"text_sequences": 0,
|
| 287 |
+
"supervised_E_tokens": 0,
|
| 288 |
+
"R_prediction_tokens": 0,
|
| 289 |
+
"text_prediction_tokens": 0,
|
| 290 |
+
"padded_training_tokens": 0,
|
| 291 |
+
},
|
| 292 |
+
0,
|
| 293 |
+
)
|
| 294 |
+
checkpoint = out / "latest.pt"
|
| 295 |
+
if checkpoint.exists():
|
| 296 |
+
ck = torch.load(checkpoint, map_location=engine.device, weights_only=False)
|
| 297 |
+
assert ck["job"] == job and ck["execution_lock"] == digest(ART / "execution-lock.json")
|
| 298 |
+
with torch.no_grad():
|
| 299 |
+
engine.delta.copy_(ck["delta"])
|
| 300 |
+
opt.load_state_dict(ck["optimizer"])
|
| 301 |
+
history, ledger, start = ck["history"], ck["ledger"], ck["step"]
|
| 302 |
+
else:
|
| 303 |
+
evaluate_node(engine, episode, selection, texts, 0, out, phase == "confirm")
|
| 304 |
+
save_checkpoint(out / "step-000.pt", engine, opt, job, 0, history, ledger)
|
| 305 |
+
begun = time.time()
|
| 306 |
+
torch.cuda.reset_peak_memory_stats(engine.device)
|
| 307 |
+
for index in range(start, cfg["steps"]):
|
| 308 |
+
plan = batches[index]
|
| 309 |
+
replay = [selection["R"][i]["encoded"][0] for i in plan["R"]]
|
| 310 |
+
text = [texts["train"][i] for i in plan["text"]]
|
| 311 |
+
opt.zero_grad(set_to_none=True)
|
| 312 |
+
ce, _ = engine.objectives(training_enc, include_kl=False)
|
| 313 |
+
ce.mean().backward()
|
| 314 |
+
_, rkl = engine.objectives(replay)
|
| 315 |
+
(job["beta"] * rkl.mean() / 2).backward()
|
| 316 |
+
_, tkl = engine.objectives(text)
|
| 317 |
+
(job["beta"] * tkl.mean() / 2).backward()
|
| 318 |
+
gradient_norm = torch.nn.utils.clip_grad_norm_([engine.delta], cfg["optimizer"]["clip"])
|
| 319 |
+
if not torch.isfinite(gradient_norm):
|
| 320 |
+
raise RuntimeError(f"Non-finite gradient in {job['id']} step {index + 1}")
|
| 321 |
+
opt.step()
|
| 322 |
+
history.append(
|
| 323 |
+
{
|
| 324 |
+
"step": index + 1,
|
| 325 |
+
"ce": float(ce.detach().mean()),
|
| 326 |
+
"r_kl": float(rkl.detach().mean()),
|
| 327 |
+
"text_kl": float(tkl.detach().mean()),
|
| 328 |
+
"gradient_norm_before_clip": float(gradient_norm),
|
| 329 |
+
}
|
| 330 |
+
)
|
| 331 |
+
ledger["E_sequences"] += len(training_enc)
|
| 332 |
+
ledger["R_sequences"] += len(replay)
|
| 333 |
+
ledger["text_sequences"] += len(text)
|
| 334 |
+
ledger["supervised_E_tokens"] += sum(sum(e["loss_mask"]) for e in training_enc)
|
| 335 |
+
ledger["R_prediction_tokens"] += sum(sum(e["loss_mask"]) for e in replay)
|
| 336 |
+
ledger["text_prediction_tokens"] += sum(sum(e["loss_mask"]) for e in text)
|
| 337 |
+
ledger["padded_training_tokens"] += sum(
|
| 338 |
+
len(es) * max(len(e["input_ids"]) for e in es) for es in (training_enc, replay, text)
|
| 339 |
+
)
|
| 340 |
+
step = index + 1
|
| 341 |
+
if step in cfg["nodes"]:
|
| 342 |
+
evaluate_node(engine, episode, selection, texts, step, out, phase == "confirm")
|
| 343 |
+
save_checkpoint(out / f"step-{step:03d}.pt", engine, opt, job, step, history, ledger)
|
| 344 |
+
if step % 16 == 0 or step in cfg["nodes"]:
|
| 345 |
+
save_checkpoint(checkpoint, engine, opt, job, step, history, ledger)
|
| 346 |
+
write(
|
| 347 |
+
out / "status.json",
|
| 348 |
+
{
|
| 349 |
+
"time": now(),
|
| 350 |
+
"state": "training",
|
| 351 |
+
"step": step,
|
| 352 |
+
"job": job,
|
| 353 |
+
"device": str(engine.device),
|
| 354 |
+
"seconds_this_attempt": time.time() - begun,
|
| 355 |
+
},
|
| 356 |
+
)
|
| 357 |
+
print(json.dumps({"job": job["id"], "step": step, "ce": history[-1]["ce"]}), flush=True)
|
| 358 |
+
write(out / "history.json", history)
|
| 359 |
+
write(
|
| 360 |
+
out / "complete.json",
|
| 361 |
+
{
|
| 362 |
+
"time": now(),
|
| 363 |
+
"job": job,
|
| 364 |
+
"steps": cfg["steps"],
|
| 365 |
+
"ledger": ledger,
|
| 366 |
+
"schedule_sha256": digest(out / "schedule.json"),
|
| 367 |
+
"seconds_this_attempt": time.time() - begun,
|
| 368 |
+
"peak_gpu_bytes": torch.cuda.max_memory_allocated(engine.device),
|
| 369 |
+
"device": str(engine.device),
|
| 370 |
+
"trainable_parameters": engine.delta.numel(),
|
| 371 |
+
"parent_down_hash": engine.base_hash,
|
| 372 |
+
"forward_tokens_engine_cumulative": engine.forward_tokens,
|
| 373 |
+
"flops_estimate": {
|
| 374 |
+
"convention": "Approximate dense 2*N per forward token plus backward through "
|
| 375 |
+
"downstream half and head; padding included, attention term omitted; "
|
| 376 |
+
"reference/evaluation costs recorded separately",
|
| 377 |
+
"value": 4
|
| 378 |
+
* sum(p.numel() for p in engine.model.parameters())
|
| 379 |
+
* ledger["padded_training_tokens"],
|
| 380 |
+
"not_hardware_counter": True,
|
| 381 |
+
},
|
| 382 |
+
},
|
| 383 |
+
)
|
| 384 |
+
engine.restore()
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def train_shard(device, shard, shards):
|
| 388 |
+
engine = PathEngine(device)
|
| 389 |
+
for index, job in enumerate(jobs()):
|
| 390 |
+
if index % shards == shard:
|
| 391 |
+
train_job(engine, job)
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def select_learning_rates():
|
| 395 |
+
cfg = read(CONFIG)
|
| 396 |
+
summaries, chosen = [], {}
|
| 397 |
+
for beta in cfg["betas_replay"]:
|
| 398 |
+
options = []
|
| 399 |
+
for lr in cfg["learning_rates"]:
|
| 400 |
+
records = []
|
| 401 |
+
for job in jobs():
|
| 402 |
+
if job["beta"] == beta and job["lr"] == lr:
|
| 403 |
+
assert (RESULTS / job["id"] / "complete.json").exists()
|
| 404 |
+
node = read(RESULTS / job["id"] / "node-128.json")
|
| 405 |
+
base = read(RESULTS / job["id"] / "node-000.json")
|
| 406 |
+
records.append(
|
| 407 |
+
{
|
| 408 |
+
"E": mean([r for r in node["E"] if r["view"] == 0], "correct"),
|
| 409 |
+
"V_loss": mean(base["V"], "correct") - mean(node["V"], "correct"),
|
| 410 |
+
"text_kl": mean(node["text_dev"], "kl"),
|
| 411 |
+
}
|
| 412 |
+
)
|
| 413 |
+
option = {
|
| 414 |
+
"beta": beta,
|
| 415 |
+
"lr": lr,
|
| 416 |
+
**{k: mean(records, k) for k in ("E", "V_loss", "text_kl")},
|
| 417 |
+
}
|
| 418 |
+
options.append(option)
|
| 419 |
+
eligible = [r for r in options if r["V_loss"] <= 0.05]
|
| 420 |
+
if eligible:
|
| 421 |
+
choice = min(eligible, key=lambda r: (-r["E"], r["text_kl"], r["lr"]))
|
| 422 |
+
else:
|
| 423 |
+
choice = min(options, key=lambda r: (r["V_loss"], r["text_kl"], r["lr"]))
|
| 424 |
+
chosen[str(beta)] = {**choice, "retention_condition_passed": bool(eligible)}
|
| 425 |
+
summaries.extend(options)
|
| 426 |
+
write(
|
| 427 |
+
ART / "learning-rate-selection.json",
|
| 428 |
+
{"time": now(), "node": 128, "rows": summaries, "chosen": chosen, "used_U": False},
|
| 429 |
+
)
|
| 430 |
+
return chosen
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
@torch.no_grad()
|
| 434 |
+
def diagnose(device, episode_index):
|
| 435 |
+
check_lock()
|
| 436 |
+
cfg = read(CONFIG)
|
| 437 |
+
chosen = read(ART / "learning-rate-selection.json")["chosen"]["1"]
|
| 438 |
+
job = next(
|
| 439 |
+
j
|
| 440 |
+
for j in jobs()
|
| 441 |
+
if j["episode"] == episode_index and j["beta"] == 1 and j["lr"] == chosen["lr"]
|
| 442 |
+
)
|
| 443 |
+
engine = PathEngine(device)
|
| 444 |
+
selection = read(DATA / "selection.json")
|
| 445 |
+
episode = selection["E_dev"][episode_index * 4 : (episode_index + 1) * 4]
|
| 446 |
+
records = episode + selection["R"]
|
| 447 |
+
encs = [r["encoded"][0] for r in records]
|
| 448 |
+
engine.cache_reference(encs)
|
| 449 |
+
output = RESULTS / job["id"] / "diagnostics"
|
| 450 |
+
output.mkdir(exist_ok=True)
|
| 451 |
+
base_E = engine.evaluate(episode)
|
| 452 |
+
zero_R = engine.evaluate(selection["R"], generate=False)
|
| 453 |
+
for step in cfg["nodes"][1:]:
|
| 454 |
+
if (output / f"step-{step:03d}.json").exists():
|
| 455 |
+
continue
|
| 456 |
+
ck = torch.load(
|
| 457 |
+
RESULTS / job["id"] / f"step-{step:03d}.pt",
|
| 458 |
+
map_location=engine.device,
|
| 459 |
+
weights_only=False,
|
| 460 |
+
)
|
| 461 |
+
engine.delta.copy_(ck["delta"])
|
| 462 |
+
engine.route = "all"
|
| 463 |
+
full_E = engine.evaluate(episode)
|
| 464 |
+
full_R = engine.evaluate(selection["R"], generate=False)
|
| 465 |
+
energies = {}
|
| 466 |
+
for start in range(0, len(encs), 8):
|
| 467 |
+
chunk = encs[start : start + 8]
|
| 468 |
+
engine.capture = []
|
| 469 |
+
engine.objectives(chunk, include_kl=False)
|
| 470 |
+
captured = engine.capture[0]
|
| 471 |
+
for i, enc in enumerate(chunk):
|
| 472 |
+
energies[enc["key"]] = captured[i, : len(enc["roles"])].tolist()
|
| 473 |
+
engine.capture = None
|
| 474 |
+
result = {
|
| 475 |
+
"step": step,
|
| 476 |
+
"episode": episode_index,
|
| 477 |
+
"job": job,
|
| 478 |
+
"base_E": base_E,
|
| 479 |
+
"zero_R": zero_R,
|
| 480 |
+
"all_E": full_E,
|
| 481 |
+
"all_R": full_R,
|
| 482 |
+
"groups": {},
|
| 483 |
+
}
|
| 484 |
+
for group in cfg["groups"] + ["L", "A"]:
|
| 485 |
+
engine.route, engine.route_group = "group", group
|
| 486 |
+
group_E = engine.evaluate(episode)
|
| 487 |
+
group_R = engine.evaluate(selection["R"], generate=False)
|
| 488 |
+
group_result = {"E": group_E, "R": group_R, "random": []}
|
| 489 |
+
if group in cfg["groups"]:
|
| 490 |
+
for seed in cfg["matching"]["diagnostic_seeds"]:
|
| 491 |
+
positions, matches = {}, {}
|
| 492 |
+
for enc in encs:
|
| 493 |
+
selected, info = random_positions(
|
| 494 |
+
enc["roles"],
|
| 495 |
+
group,
|
| 496 |
+
enc["key"],
|
| 497 |
+
seed,
|
| 498 |
+
cfg["matching"]["position_bins"],
|
| 499 |
+
cfg["matching"]["draws"],
|
| 500 |
+
energies[enc["key"]],
|
| 501 |
+
)
|
| 502 |
+
info["energy_matched"] = (
|
| 503 |
+
info["valid"]
|
| 504 |
+
and info["relative_energy_error"]
|
| 505 |
+
<= cfg["matching"]["norm_relative_tolerance"]
|
| 506 |
+
)
|
| 507 |
+
matches[enc["key"]] = info
|
| 508 |
+
positions[enc["key"]] = selected
|
| 509 |
+
engine.route, engine.route_positions = "positions", positions
|
| 510 |
+
group_result["random"].append(
|
| 511 |
+
{
|
| 512 |
+
"seed": seed,
|
| 513 |
+
"matches": matches,
|
| 514 |
+
"positions": positions,
|
| 515 |
+
"E": engine.evaluate(episode),
|
| 516 |
+
"R": engine.evaluate(selection["R"], generate=False),
|
| 517 |
+
}
|
| 518 |
+
)
|
| 519 |
+
result["groups"][group] = group_result
|
| 520 |
+
engine.route = "all"
|
| 521 |
+
recovered = engine.evaluate(episode, generate=False)
|
| 522 |
+
result["restore_max_ce_error"] = max(
|
| 523 |
+
abs(a["ce"] - b["ce"]) for a, b in zip(full_E, recovered, strict=True)
|
| 524 |
+
)
|
| 525 |
+
result["position_energy"] = energies
|
| 526 |
+
write(output / f"step-{step:03d}.json", result)
|
| 527 |
+
print(json.dumps({"diagnostic_episode": episode_index, "step": step}), flush=True)
|
| 528 |
+
engine.restore()
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def candidate_decision():
|
| 532 |
+
cfg = read(CONFIG)
|
| 533 |
+
chosen = read(ART / "learning-rate-selection.json")["chosen"]["1"]
|
| 534 |
+
rows = []
|
| 535 |
+
for job in jobs():
|
| 536 |
+
if job["beta"] != 1 or job["lr"] != chosen["lr"]:
|
| 537 |
+
continue
|
| 538 |
+
d = read(RESULTS / job["id"] / "diagnostics/step-128.json")
|
| 539 |
+
gain = mean(d["base_E"], "ce") - mean(d["all_E"], "ce")
|
| 540 |
+
risk = mean(d["all_R"], "kl")
|
| 541 |
+
noise = max(abs(r["kl"]) for r in d["zero_R"])
|
| 542 |
+
for group in cfg["groups"]:
|
| 543 |
+
g = d["groups"][group]
|
| 544 |
+
retained = None if gain <= 0 else (mean(d["base_E"], "ce") - mean(g["E"], "ce")) / gain
|
| 545 |
+
reduction = None if risk <= 0 else 1 - mean(g["R"], "kl") / risk
|
| 546 |
+
matching = []
|
| 547 |
+
for control in g["random"]:
|
| 548 |
+
matched_ids = {
|
| 549 |
+
int(key.split("-")[1])
|
| 550 |
+
for key, m in control["matches"].items()
|
| 551 |
+
if m["energy_matched"]
|
| 552 |
+
}
|
| 553 |
+
e_fraction = sum(r["case_id"] in matched_ids for r in d["all_E"]) / len(d["all_E"])
|
| 554 |
+
r_fraction = sum(r["case_id"] in matched_ids for r in d["all_R"]) / len(d["all_R"])
|
| 555 |
+
all_r = [r for r in d["all_R"] if r["case_id"] in matched_ids]
|
| 556 |
+
cand_r = [r for r in g["R"] if r["case_id"] in matched_ids]
|
| 557 |
+
random_r = [r for r in control["R"] if r["case_id"] in matched_ids]
|
| 558 |
+
difference = None if not all_r else mean(random_r, "kl") - mean(cand_r, "kl")
|
| 559 |
+
matching.append(
|
| 560 |
+
{
|
| 561 |
+
"seed": control["seed"],
|
| 562 |
+
"E_coverage": e_fraction,
|
| 563 |
+
"R_coverage": r_fraction,
|
| 564 |
+
"candidate_minus_random_improvement": difference,
|
| 565 |
+
"valid": e_fraction >= cfg["matching"]["minimum_coverage"]
|
| 566 |
+
and r_fraction >= cfg["matching"]["minimum_coverage"],
|
| 567 |
+
}
|
| 568 |
+
)
|
| 569 |
+
valid = [m for m in matching if m["valid"]]
|
| 570 |
+
beats_random = (
|
| 571 |
+
bool(valid)
|
| 572 |
+
and float(np.median([m["candidate_minus_random_improvement"] for m in valid]))
|
| 573 |
+
> cfg["gate"]["noise_multiplier"] * noise
|
| 574 |
+
)
|
| 575 |
+
passes = bool(
|
| 576 |
+
gain > 0
|
| 577 |
+
and mean(d["all_E"], "correct") > mean(d["base_E"], "correct")
|
| 578 |
+
and retained >= cfg["gate"]["learning_retained"]
|
| 579 |
+
and mean(g["E"], "correct") >= mean(d["all_E"], "correct")
|
| 580 |
+
and risk >= max(cfg["gate"]["kl_floor"], cfg["gate"]["noise_multiplier"] * noise)
|
| 581 |
+
and reduction >= cfg["gate"]["kl_reduction"]
|
| 582 |
+
and beats_random
|
| 583 |
+
)
|
| 584 |
+
rows.append(
|
| 585 |
+
{
|
| 586 |
+
"episode": job["episode"],
|
| 587 |
+
"group": group,
|
| 588 |
+
"E_gain": gain,
|
| 589 |
+
"learning_retained": retained,
|
| 590 |
+
"R_kl": risk,
|
| 591 |
+
"R_kl_reduction": reduction,
|
| 592 |
+
"E_correct_all": mean(d["all_E"], "correct"),
|
| 593 |
+
"E_correct_candidate": mean(g["E"], "correct"),
|
| 594 |
+
"noise": noise,
|
| 595 |
+
"matching": matching,
|
| 596 |
+
"beats_random": beats_random,
|
| 597 |
+
"passes": passes,
|
| 598 |
+
}
|
| 599 |
+
)
|
| 600 |
+
eligible = [
|
| 601 |
+
g
|
| 602 |
+
for g in cfg["groups"]
|
| 603 |
+
if sum(r["passes"] for r in rows if r["group"] == g) >= cfg["gate"]["units_required"]
|
| 604 |
+
]
|
| 605 |
+
winner = (
|
| 606 |
+
min(
|
| 607 |
+
eligible,
|
| 608 |
+
key=lambda g: (
|
| 609 |
+
-float(np.mean([r["R_kl_reduction"] for r in rows if r["group"] == g])),
|
| 610 |
+
cfg["groups"].index(g),
|
| 611 |
+
),
|
| 612 |
+
)
|
| 613 |
+
if eligible
|
| 614 |
+
else None
|
| 615 |
+
)
|
| 616 |
+
result = {
|
| 617 |
+
"time": now(),
|
| 618 |
+
"rows": rows,
|
| 619 |
+
"candidate": winner,
|
| 620 |
+
"status": "eligible_for_confirmation" if winner else "stop_after_development",
|
| 621 |
+
"confirmation_started": False,
|
| 622 |
+
"selection_uses_U": False,
|
| 623 |
+
"coverage_rule": "At least 80% of E and R must have disjoint count/bin/energy matches "
|
| 624 |
+
"in a fixed random seed; compare candidate/random on identical matched records",
|
| 625 |
+
}
|
| 626 |
+
write(ART / "candidate-decision.json", result)
|
| 627 |
+
return result
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/realworld_composition.py
ADDED
|
@@ -0,0 +1,629 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Complete GPT/Loop training on original 2Wiki questions and atomic facts."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import copy
|
| 6 |
+
import hashlib
|
| 7 |
+
import json
|
| 8 |
+
import math
|
| 9 |
+
import os
|
| 10 |
+
import time
|
| 11 |
+
from contextlib import nullcontext
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import torch
|
| 16 |
+
import torch.nn.functional as F
|
| 17 |
+
from transformers import GPT2Config, GPT2TokenizerFast
|
| 18 |
+
|
| 19 |
+
from .grok_depth import utc
|
| 20 |
+
from .grokking_reproduction import ReproductionGPT, model_digest
|
| 21 |
+
from .realworld_composition_data import (
|
| 22 |
+
answer_scores,
|
| 23 |
+
atomic_question,
|
| 24 |
+
encode_example,
|
| 25 |
+
sha256,
|
| 26 |
+
write_json,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def construct(config, spec, device):
|
| 31 |
+
"""Build the same eight-block reference before taking a shared prefix."""
|
| 32 |
+
torch.manual_seed(spec["initialization"])
|
| 33 |
+
options = {
|
| 34 |
+
"vocab_size": config["vocab_size"],
|
| 35 |
+
"n_positions": config.get("positions", 1024),
|
| 36 |
+
"n_embd": config["hidden_size"],
|
| 37 |
+
"n_head": config["attention_heads"],
|
| 38 |
+
"n_layer": 8,
|
| 39 |
+
"resid_pdrop": config["dropout"],
|
| 40 |
+
"embd_pdrop": config["dropout"],
|
| 41 |
+
"attn_pdrop": config["dropout"],
|
| 42 |
+
"activation_function": "gelu_new",
|
| 43 |
+
"use_cache": False,
|
| 44 |
+
}
|
| 45 |
+
model = ReproductionGPT(GPT2Config(**options), repeats=spec["repeats"])
|
| 46 |
+
model.transformer.h = torch.nn.ModuleList(list(model.transformer.h)[: spec["unique_layers"]])
|
| 47 |
+
model.config.n_layer = spec["unique_layers"]
|
| 48 |
+
return model.to(device)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def shared_prefix_digest(model):
|
| 52 |
+
digest = hashlib.sha256()
|
| 53 |
+
for name, tensor in model.state_dict().items():
|
| 54 |
+
if name.startswith("transformer.h.") and int(name.split(".")[2]) >= 4:
|
| 55 |
+
continue
|
| 56 |
+
digest.update(name.encode())
|
| 57 |
+
digest.update(tensor.detach().cpu().contiguous().numpy().tobytes())
|
| 58 |
+
return digest.hexdigest()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def tensor_digests(model):
|
| 62 |
+
return {
|
| 63 |
+
name: hashlib.sha256(tensor.detach().cpu().contiguous().numpy().tobytes()).hexdigest()
|
| 64 |
+
for name, tensor in model.state_dict().items()
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class BatchStream:
|
| 69 |
+
"""Keep actual incomplete epoch batches, with a complete restore state."""
|
| 70 |
+
|
| 71 |
+
def __init__(self, size, seed):
|
| 72 |
+
self.size = size
|
| 73 |
+
self.rng = np.random.default_rng(seed)
|
| 74 |
+
self.remaining = np.empty(0, dtype=np.int64)
|
| 75 |
+
|
| 76 |
+
def batch(self, size):
|
| 77 |
+
if not len(self.remaining):
|
| 78 |
+
self.remaining = self.rng.permutation(self.size)
|
| 79 |
+
chosen, self.remaining = self.remaining[:size], self.remaining[size:]
|
| 80 |
+
return chosen
|
| 81 |
+
|
| 82 |
+
def state_dict(self):
|
| 83 |
+
return {
|
| 84 |
+
"remaining": self.remaining.copy(),
|
| 85 |
+
"rng": copy.deepcopy(self.rng.bit_generator.state),
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
def load_state_dict(self, state):
|
| 89 |
+
self.remaining = state["remaining"].copy()
|
| 90 |
+
self.rng.bit_generator.state = copy.deepcopy(state["rng"])
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def pack(records, pad, device):
|
| 94 |
+
length = math.ceil(max(len(r["encoded"]["input"]) for r in records) / 8) * 8
|
| 95 |
+
targets = max(len(r["encoded"]["target"]) for r in records)
|
| 96 |
+
tokens = np.full((len(records), length), pad, dtype=np.int64)
|
| 97 |
+
positions = np.zeros((len(records), targets), dtype=np.int64)
|
| 98 |
+
labels = np.full((len(records), targets), -100, dtype=np.int64)
|
| 99 |
+
for i, record in enumerate(records):
|
| 100 |
+
encoded = record["encoded"]
|
| 101 |
+
tokens[i, : len(encoded["input"])] = encoded["input"]
|
| 102 |
+
n = len(encoded["target"])
|
| 103 |
+
positions[i, :n] = np.arange(len(encoded["prefix"]) - 1, len(encoded["prefix"]) - 1 + n)
|
| 104 |
+
labels[i, :n] = encoded["target"]
|
| 105 |
+
return tuple(torch.as_tensor(a, device=device) for a in (tokens, positions, labels))
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def example_losses(logits, labels):
|
| 109 |
+
valid = labels != -100
|
| 110 |
+
if not bool(valid.any(dim=1).all()):
|
| 111 |
+
raise ValueError("Every example must supervise its answer and EOS")
|
| 112 |
+
losses = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none").view_as(
|
| 113 |
+
labels
|
| 114 |
+
)
|
| 115 |
+
return losses.sum(dim=1) / valid.sum(dim=1)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def optimizer_for(model, lr, decay):
|
| 119 |
+
params = list(model.named_parameters())
|
| 120 |
+
groups = [
|
| 121 |
+
{
|
| 122 |
+
"params": [p for n, p in params if not any(s in n for s in ["bias", "ln"])],
|
| 123 |
+
"weight_decay": decay,
|
| 124 |
+
},
|
| 125 |
+
{
|
| 126 |
+
"params": [p for n, p in params if any(s in n for s in ["bias", "ln"])],
|
| 127 |
+
"weight_decay": 0.0,
|
| 128 |
+
},
|
| 129 |
+
]
|
| 130 |
+
return torch.optim.AdamW(
|
| 131 |
+
groups, lr=lr, betas=(0.9, 0.999), eps=1e-8, fused=next(model.parameters()).is_cuda
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def autocast(device):
|
| 136 |
+
return (
|
| 137 |
+
torch.autocast("cuda", dtype=torch.bfloat16)
|
| 138 |
+
if torch.device(device).type == "cuda"
|
| 139 |
+
else nullcontext()
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def update(model, optimizer, records, spec, device, pad):
|
| 144 |
+
model.train()
|
| 145 |
+
optimizer.zero_grad(set_to_none=True)
|
| 146 |
+
loss_total, executed, readout, attention = 0.0, 0, 0, 0
|
| 147 |
+
for start in range(0, len(records), spec["microbatch_size"]):
|
| 148 |
+
chunk = records[start : start + spec["microbatch_size"]]
|
| 149 |
+
tokens, positions, labels = pack(chunk, pad, device)
|
| 150 |
+
with autocast(device):
|
| 151 |
+
loss = example_losses(model(tokens, positions), labels).sum() / len(records)
|
| 152 |
+
loss.backward()
|
| 153 |
+
loss_total += float(loss.detach())
|
| 154 |
+
executed += tokens.numel()
|
| 155 |
+
readout += positions.numel()
|
| 156 |
+
attention += len(chunk) * tokens.shape[1] ** 2
|
| 157 |
+
norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 158 |
+
if not math.isfinite(loss_total) or not math.isfinite(float(norm)):
|
| 159 |
+
raise FloatingPointError("Nonfinite loss or gradient; preserve this failure")
|
| 160 |
+
optimizer.step()
|
| 161 |
+
d, blocks = model.config.n_embd, len(model.transformer.h) * model.repeats
|
| 162 |
+
flops = (
|
| 163 |
+
6 * 12 * d * d * blocks * executed
|
| 164 |
+
+ 6 * d * model.config.vocab_size * readout
|
| 165 |
+
+ 12 * blocks * d * attention
|
| 166 |
+
)
|
| 167 |
+
return {
|
| 168 |
+
"loss": loss_total,
|
| 169 |
+
"gradient_norm": float(norm),
|
| 170 |
+
"executed_input_tokens": executed,
|
| 171 |
+
"effective_input_tokens": sum(len(r["encoded"]["input"]) for r in records),
|
| 172 |
+
"estimated_matmul_training_flops": flops,
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
@torch.no_grad()
|
| 177 |
+
def generate(model, prefixes, tokenizer, device, limit=64, sequence_limit=256):
|
| 178 |
+
"""Right-padded greedy generation; only the question prefix enters the model."""
|
| 179 |
+
model.eval()
|
| 180 |
+
sizes = np.array([len(p) for p in prefixes], dtype=np.int64)
|
| 181 |
+
if not len(sizes) or not (sizes > 0).all() or not (sizes <= sequence_limit).all():
|
| 182 |
+
raise ValueError("Generation requires nonempty prefixes within the sequence limit")
|
| 183 |
+
budgets = np.minimum(limit, sequence_limit - sizes)
|
| 184 |
+
tokens = torch.full(
|
| 185 |
+
(len(prefixes), min(sequence_limit, int(sizes.max()) + limit)),
|
| 186 |
+
tokenizer.eos_token_id,
|
| 187 |
+
device=device,
|
| 188 |
+
dtype=torch.long,
|
| 189 |
+
)
|
| 190 |
+
for i, prefix in enumerate(prefixes):
|
| 191 |
+
tokens[i, : len(prefix)] = torch.as_tensor(prefix, device=device)
|
| 192 |
+
output, ended = [[] for _ in prefixes], np.zeros(len(prefixes), dtype=bool)
|
| 193 |
+
for offset in range(limit):
|
| 194 |
+
active = ~ended & (offset < budgets)
|
| 195 |
+
if not active.any():
|
| 196 |
+
break
|
| 197 |
+
length = min(sequence_limit, int(sizes.max()) + offset)
|
| 198 |
+
positions = torch.as_tensor(np.minimum(sizes + offset - 1, length - 1), device=device)[
|
| 199 |
+
:, None
|
| 200 |
+
]
|
| 201 |
+
with autocast(device):
|
| 202 |
+
selected = model(tokens[:, :length], positions)[:, 0].argmax(-1)
|
| 203 |
+
chosen = selected.cpu().tolist()
|
| 204 |
+
for i, token in enumerate(chosen):
|
| 205 |
+
if active[i]:
|
| 206 |
+
output[i].append(token)
|
| 207 |
+
ended[i] = token == tokenizer.eos_token_id
|
| 208 |
+
indices = torch.as_tensor(np.flatnonzero(active), device=device)
|
| 209 |
+
tokens[indices, torch.as_tensor(sizes[active] + offset, device=device)] = selected[indices]
|
| 210 |
+
model.train()
|
| 211 |
+
return [
|
| 212 |
+
{
|
| 213 |
+
"prediction": tokenizer.decode(
|
| 214 |
+
ids[:-1] if stop else ids, skip_special_tokens=True
|
| 215 |
+
).strip(),
|
| 216 |
+
"generated_tokens": ids,
|
| 217 |
+
"eos": bool(stop),
|
| 218 |
+
"truncated": not bool(stop),
|
| 219 |
+
"context_limit_reached": not bool(stop) and bool(len(ids) >= sequence_limit - size),
|
| 220 |
+
"generation_limit_reached": not bool(stop) and len(ids) >= limit,
|
| 221 |
+
}
|
| 222 |
+
for ids, stop, size in zip(output, ended, sizes, strict=True)
|
| 223 |
+
]
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def aggregate(predictions):
|
| 227 |
+
fields = ["canonical_em", "alias_em", "unambiguous_alias_em", "f1", "nll", "eos", "truncated"]
|
| 228 |
+
result = {"n": len(predictions)}
|
| 229 |
+
for key in fields:
|
| 230 |
+
values = [float(p[key]) for p in predictions if p[key] is not None]
|
| 231 |
+
result[key] = sum(values) / len(values) if values else None
|
| 232 |
+
if key == "nll":
|
| 233 |
+
result["nll_n"] = len(values)
|
| 234 |
+
eligible = [p for p in predictions if p.get("has_unambiguous_answer", True)]
|
| 235 |
+
result["unambiguous_answer_coverage"] = (
|
| 236 |
+
len(eligible) / len(predictions) if predictions else None
|
| 237 |
+
)
|
| 238 |
+
result["unambiguous_alias_em_eligible"] = (
|
| 239 |
+
sum(float(p["unambiguous_alias_em"]) for p in eligible) / len(eligible)
|
| 240 |
+
if eligible
|
| 241 |
+
else None
|
| 242 |
+
)
|
| 243 |
+
result["answer_accuracy"] = result["alias_em"]
|
| 244 |
+
return result
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
@torch.no_grad()
|
| 248 |
+
def evaluate(model, records, tokenizer, device, batch_size=32):
|
| 249 |
+
predictions = []
|
| 250 |
+
for start in range(0, len(records), batch_size):
|
| 251 |
+
chunk = records[start : start + batch_size]
|
| 252 |
+
generated = generate(model, [r["encoded"]["prefix"] for r in chunk], tokenizer, device)
|
| 253 |
+
model.eval()
|
| 254 |
+
tokens, positions, labels = pack(chunk, tokenizer.eos_token_id, device)
|
| 255 |
+
with autocast(device):
|
| 256 |
+
losses = example_losses(model(tokens, positions), labels).float().cpu().tolist()
|
| 257 |
+
for row, result, loss in zip(chunk, generated, losses, strict=True):
|
| 258 |
+
em, f1 = answer_scores(result["prediction"], [row["answer"], *row.get("aliases", [])])
|
| 259 |
+
unique_answers = row.get(
|
| 260 |
+
"unambiguous_answers", [row["answer"], *row.get("unambiguous_aliases", [])]
|
| 261 |
+
)
|
| 262 |
+
result.update(
|
| 263 |
+
id=row["id"],
|
| 264 |
+
canonical_em=answer_scores(result["prediction"], [row["answer"]])[0],
|
| 265 |
+
alias_em=em,
|
| 266 |
+
f1=f1,
|
| 267 |
+
nll=loss,
|
| 268 |
+
unambiguous_alias_em=answer_scores(result["prediction"], unique_answers)[0],
|
| 269 |
+
has_unambiguous_answer=bool(unique_answers),
|
| 270 |
+
canonical_answer_globally_unambiguous=row.get(
|
| 271 |
+
"canonical_answer_globally_unambiguous", True
|
| 272 |
+
),
|
| 273 |
+
gold=row["answer"],
|
| 274 |
+
role=row.get("role"),
|
| 275 |
+
required_role=row.get("required_role"),
|
| 276 |
+
)
|
| 277 |
+
predictions.append(result)
|
| 278 |
+
model.train()
|
| 279 |
+
return aggregate(predictions), predictions
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def evaluate_dataset(model, data, tokenizer, device, full=False, autonomous=False):
|
| 283 |
+
atoms = {r["id"]: r for r in data["atoms"]}
|
| 284 |
+
chains = {r["id"]: r for r in data["train_compositions"] + data["evaluation_compositions"]}
|
| 285 |
+
panels = data["panels"]
|
| 286 |
+
groups = {
|
| 287 |
+
"atomic": list(atoms.values()) if full else [atoms[i] for i in panels["atomic"]],
|
| 288 |
+
"train_composition": data["train_compositions"]
|
| 289 |
+
if full
|
| 290 |
+
else [chains[i] for i in panels["train_composition"]],
|
| 291 |
+
}
|
| 292 |
+
selected = (
|
| 293 |
+
data["evaluation_compositions"]
|
| 294 |
+
if full
|
| 295 |
+
else [chains[i] for name, ids in panels.items() if name.startswith("test_") for i in ids]
|
| 296 |
+
)
|
| 297 |
+
groups["test_all"] = selected
|
| 298 |
+
metrics, raw = {}, {}
|
| 299 |
+
for name, records in groups.items():
|
| 300 |
+
metrics[name], raw[name] = (
|
| 301 |
+
evaluate(model, records, tokenizer, device) if records else (aggregate([]), [])
|
| 302 |
+
)
|
| 303 |
+
lookup = {p["id"]: p for p in raw["atomic"]}
|
| 304 |
+
for role in ["II", "IO", "OI", "OO"]:
|
| 305 |
+
metrics["test_" + role.lower()] = aggregate(
|
| 306 |
+
[p for p in raw["test_all"] if p["role"] == role]
|
| 307 |
+
)
|
| 308 |
+
metrics["test_required_role_" + role.lower()] = aggregate(
|
| 309 |
+
[p for p in raw["test_all"] if p["required_role"] == role]
|
| 310 |
+
)
|
| 311 |
+
filters = {
|
| 312 |
+
"test_unambiguous_canonical_answers": lambda r: r.get(
|
| 313 |
+
"canonical_answer_globally_unambiguous", True
|
| 314 |
+
),
|
| 315 |
+
"test_no_known_shortcut": lambda r: not r.get("known_direct_shortcut", False),
|
| 316 |
+
"test_head_tail_unseen": lambda r: not r.get(
|
| 317 |
+
"head_tail_seen_in_combination_training", False
|
| 318 |
+
),
|
| 319 |
+
"test_seen_operation": lambda r: r.get("operation_seen", False),
|
| 320 |
+
"test_no_shortcut_seen_operation": lambda r: not r.get("known_direct_shortcut", False)
|
| 321 |
+
and r.get("operation_seen", False),
|
| 322 |
+
}
|
| 323 |
+
for name, include in filters.items():
|
| 324 |
+
ids = {r["id"] for r in selected if include(r)}
|
| 325 |
+
metrics[name] = aggregate([p for p in raw["test_all"] if p["id"] in ids])
|
| 326 |
+
metrics[name]["coverage"] = len(ids) / len(selected) if selected else None
|
| 327 |
+
for index, name in enumerate(["test_first_atom", "test_second_atom"]):
|
| 328 |
+
metrics[name] = aggregate([lookup[r["atom_ids"][index]] for r in selected])
|
| 329 |
+
metrics["gold_bridge_second"] = metrics["test_second_atom"].copy()
|
| 330 |
+
prerequisite = {r["id"] for r in selected if all(lookup[a]["alias_em"] for a in r["atom_ids"])}
|
| 331 |
+
metrics["test_prerequisites_correct"] = aggregate(
|
| 332 |
+
[p for p in raw["test_all"] if p["id"] in prerequisite]
|
| 333 |
+
)
|
| 334 |
+
metrics["test_prerequisites_correct"]["coverage"] = (
|
| 335 |
+
len(prerequisite) / len(selected) if selected else None
|
| 336 |
+
)
|
| 337 |
+
if autonomous:
|
| 338 |
+
second_calls = []
|
| 339 |
+
invalid = []
|
| 340 |
+
for row in selected:
|
| 341 |
+
bridge_prediction = lookup[row["atom_ids"][0]]["prediction"]
|
| 342 |
+
q = atomic_question(bridge_prediction, row["edges"][1][1])
|
| 343 |
+
try:
|
| 344 |
+
encoded = encode_example(tokenizer, q, row["answer"])
|
| 345 |
+
except ValueError:
|
| 346 |
+
invalid.append(row)
|
| 347 |
+
continue
|
| 348 |
+
second_calls.append(
|
| 349 |
+
{**row, "question": q, "encoded": encoded, "autonomous_bridge": bridge_prediction}
|
| 350 |
+
)
|
| 351 |
+
_, predictions = (
|
| 352 |
+
evaluate(model, second_calls, tokenizer, device) if second_calls else (None, [])
|
| 353 |
+
)
|
| 354 |
+
for row, result in zip(second_calls, predictions, strict=True):
|
| 355 |
+
result["bridge_prediction"] = row["autonomous_bridge"]
|
| 356 |
+
result["second_question"] = row["question"]
|
| 357 |
+
predictions.extend(
|
| 358 |
+
{
|
| 359 |
+
"id": row["id"],
|
| 360 |
+
"canonical_em": 0.0,
|
| 361 |
+
"alias_em": 0.0,
|
| 362 |
+
"unambiguous_alias_em": 0.0,
|
| 363 |
+
"f1": 0.0,
|
| 364 |
+
"nll": None,
|
| 365 |
+
"eos": False,
|
| 366 |
+
"truncated": True,
|
| 367 |
+
"has_unambiguous_answer": bool(row.get("unambiguous_answers", [])),
|
| 368 |
+
"canonical_answer_globally_unambiguous": row.get(
|
| 369 |
+
"canonical_answer_globally_unambiguous", True
|
| 370 |
+
),
|
| 371 |
+
"invalid_generated_bridge_length": True,
|
| 372 |
+
}
|
| 373 |
+
for row in invalid
|
| 374 |
+
)
|
| 375 |
+
raw["autonomous"] = predictions
|
| 376 |
+
metrics["autonomous"] = aggregate(predictions)
|
| 377 |
+
metrics["autonomous"]["invalid_bridge_prompts"] = len(invalid)
|
| 378 |
+
return metrics, raw
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def save_checkpoint(path, model, optimizer, stream, counts, step, counters, wall_seconds=None):
|
| 382 |
+
temporary = Path(path).with_suffix(".tmp")
|
| 383 |
+
torch.save(
|
| 384 |
+
{
|
| 385 |
+
"model": model.state_dict(),
|
| 386 |
+
"optimizer": optimizer.state_dict(),
|
| 387 |
+
"stream": stream.state_dict(),
|
| 388 |
+
"counts": counts,
|
| 389 |
+
"step": step,
|
| 390 |
+
"counters": counters,
|
| 391 |
+
"wall_seconds": wall_seconds,
|
| 392 |
+
"cpu_rng": torch.get_rng_state(),
|
| 393 |
+
"cuda_rng": torch.cuda.get_rng_state(),
|
| 394 |
+
},
|
| 395 |
+
temporary,
|
| 396 |
+
)
|
| 397 |
+
temporary.replace(path)
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def worker(config, spec, gpu):
|
| 401 |
+
torch.set_num_threads(4)
|
| 402 |
+
torch.set_num_interop_threads(1)
|
| 403 |
+
torch.cuda.set_device(gpu)
|
| 404 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 405 |
+
device = f"cuda:{gpu}"
|
| 406 |
+
data = json.loads(Path(config["data_file"]).read_text())
|
| 407 |
+
assert sha256(config["data_file"]) == config["data_sha256"]
|
| 408 |
+
tokenizer = GPT2TokenizerFast.from_pretrained(config["tokenizer"], local_files_only=True)
|
| 409 |
+
phase = config.get("phase", "development")
|
| 410 |
+
out = Path(config["results_root"]) / phase / spec["name"]
|
| 411 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 412 |
+
model = construct(config["model"], spec, device)
|
| 413 |
+
optimizer = optimizer_for(model, spec["learning_rate"], spec["weight_decay"])
|
| 414 |
+
records = data["atoms"] + data["train_compositions"]
|
| 415 |
+
stream = BatchStream(len(records), spec["sampling_seed"])
|
| 416 |
+
counts = np.zeros(len(records), dtype=np.int64)
|
| 417 |
+
counters = dict(
|
| 418 |
+
training_seconds=0.0,
|
| 419 |
+
examples=0,
|
| 420 |
+
supervised_tokens=0,
|
| 421 |
+
executed_input_tokens=0,
|
| 422 |
+
effective_input_tokens=0,
|
| 423 |
+
estimated_matmul_training_flops=0,
|
| 424 |
+
)
|
| 425 |
+
history, initial_step, wall_offset = [], 0, 0.0
|
| 426 |
+
started = time.perf_counter()
|
| 427 |
+
if (out / "latest.pt").exists():
|
| 428 |
+
checkpoint = torch.load(out / "latest.pt", map_location=device, weights_only=False)
|
| 429 |
+
model.load_state_dict(checkpoint["model"])
|
| 430 |
+
optimizer.load_state_dict(checkpoint["optimizer"])
|
| 431 |
+
stream.load_state_dict(checkpoint["stream"])
|
| 432 |
+
counts, initial_step, counters = (
|
| 433 |
+
checkpoint["counts"],
|
| 434 |
+
checkpoint["step"],
|
| 435 |
+
checkpoint["counters"],
|
| 436 |
+
)
|
| 437 |
+
torch.set_rng_state(checkpoint["cpu_rng"].cpu())
|
| 438 |
+
torch.cuda.set_rng_state(checkpoint["cuda_rng"].cpu())
|
| 439 |
+
history = [
|
| 440 |
+
r for r in json.loads((out / "learning.json").read_text()) if r["step"] <= initial_step
|
| 441 |
+
]
|
| 442 |
+
wall_offset = checkpoint.get("wall_seconds")
|
| 443 |
+
if wall_offset is None:
|
| 444 |
+
wall_offset = history[-1]["wall_seconds"] if history else 0.0
|
| 445 |
+
metadata = json.loads((out / "run.json").read_text())
|
| 446 |
+
metadata.update(pid=os.getpid(), gpu=gpu, resumed_from_step=initial_step)
|
| 447 |
+
write_json(out / "run.json", metadata)
|
| 448 |
+
del checkpoint
|
| 449 |
+
else:
|
| 450 |
+
torch.manual_seed(spec["dropout_seed"])
|
| 451 |
+
metadata = {
|
| 452 |
+
"spec": spec,
|
| 453 |
+
"model": config["model"],
|
| 454 |
+
"phase": phase,
|
| 455 |
+
"evaluation_nodes": config["evaluation_nodes"],
|
| 456 |
+
"execution_lock_sha256": sha256(config["execution_lock"]),
|
| 457 |
+
"world_sha256": config["data_sha256"],
|
| 458 |
+
"initial_model_sha256": model_digest(model),
|
| 459 |
+
"initial_tensor_sha256": tensor_digests(model),
|
| 460 |
+
"common_four_block_initial_sha256": shared_prefix_digest(model),
|
| 461 |
+
"parameters": sum(p.numel() for p in model.parameters()),
|
| 462 |
+
"atomic_examples": len(data["atoms"]),
|
| 463 |
+
"composition_examples": len(data["train_compositions"]),
|
| 464 |
+
"vocab_size": len(tokenizer),
|
| 465 |
+
"dtype": "BF16 AMP; FP32 parameters and Adam states",
|
| 466 |
+
"gpu": gpu,
|
| 467 |
+
"gpu_name": torch.cuda.get_device_name(gpu),
|
| 468 |
+
"pid": os.getpid(),
|
| 469 |
+
"job_type": phase + "-training",
|
| 470 |
+
"tracking_group": config["tracking"]["group"],
|
| 471 |
+
}
|
| 472 |
+
write_json(out / "run.json", metadata)
|
| 473 |
+
write_json(out / "learning.json", [])
|
| 474 |
+
nodes = set(config["evaluation_nodes"])
|
| 475 |
+
last_loss = None
|
| 476 |
+
for step in range(initial_step, spec["steps"] + 1):
|
| 477 |
+
if step > initial_step:
|
| 478 |
+
for group in optimizer.param_groups:
|
| 479 |
+
group["lr"] = spec["learning_rate"] * min((step - 1) / spec["warmup_steps"], 1.0)
|
| 480 |
+
ids = stream.batch(spec["batch_size"])
|
| 481 |
+
selected = [records[i] for i in ids]
|
| 482 |
+
torch.cuda.synchronize()
|
| 483 |
+
began = time.perf_counter()
|
| 484 |
+
values = update(model, optimizer, selected, spec, device, tokenizer.eos_token_id)
|
| 485 |
+
torch.cuda.synchronize()
|
| 486 |
+
counters["training_seconds"] += time.perf_counter() - began
|
| 487 |
+
last_loss = values["loss"]
|
| 488 |
+
counts[ids] += 1
|
| 489 |
+
counters["examples"] += len(ids)
|
| 490 |
+
counters["supervised_tokens"] += sum(len(r["encoded"]["target"]) for r in selected)
|
| 491 |
+
for key in [
|
| 492 |
+
"executed_input_tokens",
|
| 493 |
+
"effective_input_tokens",
|
| 494 |
+
"estimated_matmul_training_flops",
|
| 495 |
+
]:
|
| 496 |
+
counters[key] += values[key]
|
| 497 |
+
if step % 50 == 0:
|
| 498 |
+
write_json(
|
| 499 |
+
out / "status.json",
|
| 500 |
+
{
|
| 501 |
+
"state": "training",
|
| 502 |
+
"step": step,
|
| 503 |
+
"target_step": spec["steps"],
|
| 504 |
+
"loss": last_loss,
|
| 505 |
+
"training_seconds": counters["training_seconds"],
|
| 506 |
+
"examples": counters["examples"],
|
| 507 |
+
"wall_seconds": wall_offset + time.perf_counter() - started,
|
| 508 |
+
"pid": os.getpid(),
|
| 509 |
+
"updated_utc": utc(),
|
| 510 |
+
},
|
| 511 |
+
)
|
| 512 |
+
if step in nodes and not any(r["step"] == step for r in history):
|
| 513 |
+
metrics, predictions = evaluate_dataset(model, data, tokenizer, device)
|
| 514 |
+
write_json(out / f"predictions-{step:07d}.json", predictions)
|
| 515 |
+
history.append(
|
| 516 |
+
{
|
| 517 |
+
"step": step,
|
| 518 |
+
"metrics": metrics,
|
| 519 |
+
**counters,
|
| 520 |
+
"wall_seconds": wall_offset + time.perf_counter() - started,
|
| 521 |
+
"loss": last_loss,
|
| 522 |
+
"atomic_epochs": float(counts[: len(data["atoms"])].mean()),
|
| 523 |
+
"composition_epochs": float(counts[len(data["atoms"]) :].mean()),
|
| 524 |
+
"peak_gpu_memory_bytes": torch.cuda.max_memory_allocated(),
|
| 525 |
+
"created_utc": utc(),
|
| 526 |
+
}
|
| 527 |
+
)
|
| 528 |
+
write_json(out / "learning.json", history)
|
| 529 |
+
save_checkpoint(
|
| 530 |
+
out / "latest.pt",
|
| 531 |
+
model,
|
| 532 |
+
optimizer,
|
| 533 |
+
stream,
|
| 534 |
+
counts,
|
| 535 |
+
step,
|
| 536 |
+
counters,
|
| 537 |
+
wall_offset + time.perf_counter() - started,
|
| 538 |
+
)
|
| 539 |
+
torch.save(
|
| 540 |
+
{"model": model.state_dict(), "step": step}, out / f"checkpoint-{step:07d}.pt"
|
| 541 |
+
)
|
| 542 |
+
np.savez_compressed(out / f"exposure-{step:07d}.npz", counts=counts)
|
| 543 |
+
print(
|
| 544 |
+
json.dumps(
|
| 545 |
+
{
|
| 546 |
+
"step": step,
|
| 547 |
+
"loss": last_loss,
|
| 548 |
+
"metrics": metrics,
|
| 549 |
+
"training_seconds": counters["training_seconds"],
|
| 550 |
+
}
|
| 551 |
+
),
|
| 552 |
+
flush=True,
|
| 553 |
+
)
|
| 554 |
+
elif (
|
| 555 |
+
step > initial_step and step % config.get("resume_checkpoint_interval", 1000000000) == 0
|
| 556 |
+
):
|
| 557 |
+
save_checkpoint(
|
| 558 |
+
out / "latest.pt",
|
| 559 |
+
model,
|
| 560 |
+
optimizer,
|
| 561 |
+
stream,
|
| 562 |
+
counts,
|
| 563 |
+
step,
|
| 564 |
+
counters,
|
| 565 |
+
wall_offset + time.perf_counter() - started,
|
| 566 |
+
)
|
| 567 |
+
metrics, predictions = evaluate_dataset(
|
| 568 |
+
model, data, tokenizer, device, full=True, autonomous=True
|
| 569 |
+
)
|
| 570 |
+
write_json(out / "endpoint-predictions.json", predictions)
|
| 571 |
+
write_json(out / "endpoint.json", metrics)
|
| 572 |
+
result = {
|
| 573 |
+
"state": "trained_pending_independent_reload",
|
| 574 |
+
"step": spec["steps"],
|
| 575 |
+
"pid": os.getpid(),
|
| 576 |
+
"model_sha256": model_digest(model),
|
| 577 |
+
"checkpoint_sha256": sha256(out / "latest.pt"),
|
| 578 |
+
**counters,
|
| 579 |
+
"wall_seconds": wall_offset + time.perf_counter() - started,
|
| 580 |
+
"completed_utc": utc(),
|
| 581 |
+
}
|
| 582 |
+
write_json(out / "trained.json", result)
|
| 583 |
+
write_json(out / "status.json", result)
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
def audit(config, spec, gpu):
|
| 587 |
+
torch.set_num_threads(4)
|
| 588 |
+
torch.set_num_interop_threads(1)
|
| 589 |
+
torch.cuda.set_device(gpu)
|
| 590 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 591 |
+
device = f"cuda:{gpu}"
|
| 592 |
+
out = Path(config["results_root"]) / config.get("phase", "development") / spec["name"]
|
| 593 |
+
trained = json.loads((out / "trained.json").read_text())
|
| 594 |
+
assert trained["pid"] != os.getpid()
|
| 595 |
+
assert sha256(out / "latest.pt") == trained["checkpoint_sha256"]
|
| 596 |
+
assert sha256(config["data_file"]) == config["data_sha256"]
|
| 597 |
+
data = json.loads(Path(config["data_file"]).read_text())
|
| 598 |
+
tokenizer = GPT2TokenizerFast.from_pretrained(config["tokenizer"], local_files_only=True)
|
| 599 |
+
model = construct(config["model"], spec, device)
|
| 600 |
+
state = torch.load(out / "latest.pt", map_location="cpu", weights_only=False)
|
| 601 |
+
model.load_state_dict(state["model"])
|
| 602 |
+
assert state["step"] == spec["steps"]
|
| 603 |
+
del state
|
| 604 |
+
assert model_digest(model) == trained["model_sha256"]
|
| 605 |
+
metrics, predictions = evaluate_dataset(
|
| 606 |
+
model, data, tokenizer, device, full=True, autonomous=True
|
| 607 |
+
)
|
| 608 |
+
expected = json.loads((out / "endpoint-predictions.json").read_text())
|
| 609 |
+
assert predictions == expected, (
|
| 610 |
+
"Endpoint generation or teacher-forced scores do not independently reproduce"
|
| 611 |
+
)
|
| 612 |
+
assert metrics == json.loads((out / "endpoint.json").read_text())
|
| 613 |
+
result = {
|
| 614 |
+
"passed": True,
|
| 615 |
+
"pid": os.getpid(),
|
| 616 |
+
"source_training_pid": trained["pid"],
|
| 617 |
+
"checkpoint_sha256": trained["checkpoint_sha256"],
|
| 618 |
+
"model_sha256": trained["model_sha256"],
|
| 619 |
+
"predictions_recomputed": sum(len(p) for p in predictions.values()),
|
| 620 |
+
"completed_utc": utc(),
|
| 621 |
+
}
|
| 622 |
+
write_json(out / "audit.json", result)
|
| 623 |
+
write_json(
|
| 624 |
+
out / "complete.json", {**trained, "state": "complete", "independently_reloaded": True}
|
| 625 |
+
)
|
| 626 |
+
write_json(
|
| 627 |
+
out / "status.json",
|
| 628 |
+
{"state": "complete", "step": spec["steps"], "independently_reloaded": True},
|
| 629 |
+
)
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/realworld_composition_data.py
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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author's v1.1 scorer.
|
| 4 |
+
The original questions and facts are retained; this is an adapted task in which
|
| 5 |
+
evaluation facts may be learned separately, never with evaluation chain labels.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
import re
|
| 13 |
+
import string
|
| 14 |
+
import zipfile
|
| 15 |
+
from collections import Counter, defaultdict
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
ARCHIVE_SHA = "95df2bf56fdabe034e27aebc580e02264232203cf52552f9efe8a919e5529eef"
|
| 19 |
+
SPLIT_SALT = "2wiki-realworld-v1:"
|
| 20 |
+
QUESTION_TEMPLATES = {
|
| 21 |
+
"father": "Who is the father of {subject}?",
|
| 22 |
+
"mother": "Who is the mother of {subject}?",
|
| 23 |
+
"child": "Who is the child of {subject}?",
|
| 24 |
+
"spouse": "Who is the spouse of {subject}?",
|
| 25 |
+
"director": "Who directed {subject}?",
|
| 26 |
+
"performer": "Who performed {subject}?",
|
| 27 |
+
"composer": "Who composed {subject}?",
|
| 28 |
+
"creator": "Who created {subject}?",
|
| 29 |
+
"editor": "Who edited {subject}?",
|
| 30 |
+
"presenter": "Who presented {subject}?",
|
| 31 |
+
"manufacturer": "Who manufactured {subject}?",
|
| 32 |
+
"publisher": "Who published {subject}?",
|
| 33 |
+
"founded by": "Who founded {subject}?",
|
| 34 |
+
"student of": "Who was the teacher of {subject}?",
|
| 35 |
+
"educated at": "Where was {subject} educated?",
|
| 36 |
+
"employer": "Who employed {subject}?",
|
| 37 |
+
"date of birth": "On what date was {subject} born?",
|
| 38 |
+
"date of death": "On what date did {subject} die?",
|
| 39 |
+
"place of birth": "Where was {subject} born?",
|
| 40 |
+
"place of death": "Where did {subject} die?",
|
| 41 |
+
"place of burial": "Where was {subject} buried?",
|
| 42 |
+
"place of detention": "Where was {subject} detained?",
|
| 43 |
+
"cause of death": "What was the cause of death of {subject}?",
|
| 44 |
+
"country of citizenship": "What is the country of citizenship of {subject}?",
|
| 45 |
+
"country": "In which country is {subject}?",
|
| 46 |
+
"inception": "On what date was {subject} established?",
|
| 47 |
+
"award received": "What award did {subject} receive?",
|
| 48 |
+
"has part": "What is a part of {subject}?",
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def sha256(path):
|
| 53 |
+
result = hashlib.sha256()
|
| 54 |
+
with Path(path).open("rb") as handle:
|
| 55 |
+
for block in iter(lambda: handle.read(8 * 1024 * 1024), b""):
|
| 56 |
+
result.update(block)
|
| 57 |
+
return result.hexdigest()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def write_json(path, value):
|
| 61 |
+
path = Path(path)
|
| 62 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 63 |
+
temporary = path.with_suffix(path.suffix + ".tmp")
|
| 64 |
+
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n")
|
| 65 |
+
temporary.replace(path)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def order(value, salt=SPLIT_SALT):
|
| 69 |
+
return hashlib.sha256((salt + str(value)).encode()).hexdigest()
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def normalize_answer(value):
|
| 73 |
+
value = "".join(c for c in value.lower() if c not in string.punctuation)
|
| 74 |
+
return " ".join(re.sub(r"\b(a|an|the)\b", " ", value).split())
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def answer_scores(prediction, answers):
|
| 78 |
+
"""Max EM/F1 across the author's canonical answer and entity aliases."""
|
| 79 |
+
p = normalize_answer(prediction)
|
| 80 |
+
scores = []
|
| 81 |
+
for answer in answers:
|
| 82 |
+
a = normalize_answer(answer)
|
| 83 |
+
if (p in {"yes", "no", "noanswer"} or a in {"yes", "no", "noanswer"}) and p != a:
|
| 84 |
+
f1 = 0.0
|
| 85 |
+
else:
|
| 86 |
+
common = sum((Counter(p.split()) & Counter(a.split())).values())
|
| 87 |
+
f1 = 2 * common / (len(p.split()) + len(a.split())) if common else 0.0
|
| 88 |
+
scores.append((float(p == a), f1))
|
| 89 |
+
return max((s[0] for s in scores), default=0.0), max((s[1] for s in scores), default=0.0)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def entity_id(identifier, surface):
|
| 93 |
+
if re.fullmatch(r"Q\d+", str(identifier)):
|
| 94 |
+
return identifier
|
| 95 |
+
return "literal:" + " ".join(str(surface).casefold().split())
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def extract_chain(row):
|
| 99 |
+
edges, surfaces = row.get("evidences_id", []), row.get("evidences", [])
|
| 100 |
+
if row.get("type") != "compositional" or len(edges) != 2 or len(surfaces) != 2:
|
| 101 |
+
return None
|
| 102 |
+
if any(len(e) != 3 for e in edges + surfaces):
|
| 103 |
+
return None
|
| 104 |
+
converted = [
|
| 105 |
+
(entity_id(e[0], s[0]), str(e[1]), entity_id(e[2], s[2]))
|
| 106 |
+
for e, s in zip(edges, surfaces, strict=True)
|
| 107 |
+
]
|
| 108 |
+
for indices in [(0, 1), (1, 0)]:
|
| 109 |
+
first, second = [converted[i] for i in indices]
|
| 110 |
+
if first[2] == second[0] and first[0] != second[2]:
|
| 111 |
+
return (first, second), [surfaces[i] for i in indices]
|
| 112 |
+
return None
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class Components:
|
| 116 |
+
def __init__(self):
|
| 117 |
+
self.parent = {}
|
| 118 |
+
|
| 119 |
+
def find(self, node):
|
| 120 |
+
self.parent.setdefault(node, node)
|
| 121 |
+
while self.parent[node] != node:
|
| 122 |
+
self.parent[node] = self.parent[self.parent[node]]
|
| 123 |
+
node = self.parent[node]
|
| 124 |
+
return node
|
| 125 |
+
|
| 126 |
+
def union(self, first, second):
|
| 127 |
+
first, second = self.find(first), self.find(second)
|
| 128 |
+
if first != second:
|
| 129 |
+
self.parent[max(first, second)] = min(first, second)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def support_sentences(row):
|
| 133 |
+
context = {title: sentences for title, sentences in row["context"]}
|
| 134 |
+
result = []
|
| 135 |
+
for title, index in row["supporting_facts"]:
|
| 136 |
+
if title not in context or not 0 <= index < len(context[title]):
|
| 137 |
+
result.append(
|
| 138 |
+
{"title": title, "index": index, "sentence": "", "invalid_support_reference": True}
|
| 139 |
+
)
|
| 140 |
+
continue
|
| 141 |
+
result.append({"title": title, "index": index, "sentence": context[title][index]})
|
| 142 |
+
return result
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def prior_cases(project):
|
| 146 |
+
path = Path(project) / "docs/development-artifacts/twohop-frozen-v1/case-manifest.json"
|
| 147 |
+
if not path.exists():
|
| 148 |
+
return set()
|
| 149 |
+
return {r["id"] for r in json.loads(path.read_text()) if r["dataset"] == "2wiki"}
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def extract_archive(archive, project):
|
| 153 |
+
if sha256(archive) != ARCHIVE_SHA:
|
| 154 |
+
raise ValueError("2Wiki archive differs from the pinned author data")
|
| 155 |
+
records, aliases, labels = [], {}, defaultdict(Counter)
|
| 156 |
+
groups = Components()
|
| 157 |
+
with zipfile.ZipFile(archive) as source:
|
| 158 |
+
for line in source.read("id_aliases.json").decode().splitlines():
|
| 159 |
+
entry = json.loads(line)
|
| 160 |
+
aliases[entry["Q_id"]] = entry["aliases"] + entry.get("demonyms", [])
|
| 161 |
+
for split in ("train", "dev"):
|
| 162 |
+
for row in json.loads(source.read(split + ".json")):
|
| 163 |
+
parsed = extract_chain(row)
|
| 164 |
+
if parsed is None:
|
| 165 |
+
continue
|
| 166 |
+
edges, surfaces = parsed
|
| 167 |
+
groups.union(edges[0][0], edges[0][2])
|
| 168 |
+
for edge, surface in zip(edges, surfaces, strict=True):
|
| 169 |
+
labels[edge[0]][surface[0]] += 1
|
| 170 |
+
labels[edge[2]][surface[2]] += 1
|
| 171 |
+
records.append(
|
| 172 |
+
{
|
| 173 |
+
"id": row["_id"],
|
| 174 |
+
"source_split": split,
|
| 175 |
+
"question": row["question"],
|
| 176 |
+
"answer": row["answer"],
|
| 177 |
+
"answer_id": row.get("answer_id"),
|
| 178 |
+
"edges": edges,
|
| 179 |
+
"surfaces": surfaces,
|
| 180 |
+
"support": support_sentences(row),
|
| 181 |
+
}
|
| 182 |
+
)
|
| 183 |
+
canonical = {
|
| 184 |
+
key: sorted(counts, key=lambda s: (-counts[s], s))[0] for key, counts in labels.items()
|
| 185 |
+
}
|
| 186 |
+
alias_owners = defaultdict(set)
|
| 187 |
+
for identifier, names in aliases.items():
|
| 188 |
+
for name in names:
|
| 189 |
+
alias_owners[normalize_answer(name)].add(identifier)
|
| 190 |
+
old = prior_cases(project)
|
| 191 |
+
subject_relation = defaultdict(set)
|
| 192 |
+
for row in records:
|
| 193 |
+
for edge in row["edges"]:
|
| 194 |
+
subject_relation[edge[:2]].add(edge[2])
|
| 195 |
+
ambiguous = {key for key, values in subject_relation.items() if len(values) > 1}
|
| 196 |
+
for row in records:
|
| 197 |
+
row["group"] = groups.find(row["edges"][0][0])
|
| 198 |
+
row["development_group"] = int(order(row["group"])[:8], 16) % 5 == 0
|
| 199 |
+
row["known_prior_case"] = row["id"] in old
|
| 200 |
+
row["aliases"] = aliases.get(row["answer_id"], [])
|
| 201 |
+
row["unambiguous_aliases"] = [
|
| 202 |
+
a for a in row["aliases"] if len(alias_owners[normalize_answer(a)]) == 1
|
| 203 |
+
]
|
| 204 |
+
row["structural_errors"] = []
|
| 205 |
+
if any(s.get("invalid_support_reference") for s in row["support"]):
|
| 206 |
+
row["structural_errors"].append("invalid_support_sentence_reference")
|
| 207 |
+
if any(edge[:2] in ambiguous for edge in row["edges"]):
|
| 208 |
+
row["structural_errors"].append("multiple_objects_for_subject_relation")
|
| 209 |
+
if row["answer_id"] and row["answer_id"] != row["edges"][1][2]:
|
| 210 |
+
row["structural_errors"].append("answer_id_does_not_match_chain")
|
| 211 |
+
if not row["answer_id"] and normalize_answer(row["answer"]) != normalize_answer(
|
| 212 |
+
row["surfaces"][1][2]
|
| 213 |
+
):
|
| 214 |
+
row["structural_errors"].append("literal_answer_does_not_match_chain")
|
| 215 |
+
if any(edge[1] not in QUESTION_TEMPLATES for edge in row["edges"]):
|
| 216 |
+
row["structural_errors"].append("unreviewed_relation_template")
|
| 217 |
+
row["support_surface_flags"] = []
|
| 218 |
+
text = normalize_answer(" ".join(s["title"] + " " + s["sentence"] for s in row["support"]))
|
| 219 |
+
for i, (edge, surface) in enumerate(zip(row["edges"], row["surfaces"], strict=True)):
|
| 220 |
+
for j in [0, 2]:
|
| 221 |
+
choices = [surface[j], *aliases.get(edge[j], [])]
|
| 222 |
+
if not any(normalize_answer(c) in text for c in choices if normalize_answer(c)):
|
| 223 |
+
row["support_surface_flags"].append(
|
| 224 |
+
f"edge{i}_position{j}_not_literal_in_support"
|
| 225 |
+
)
|
| 226 |
+
return records, aliases, canonical
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def review_sample(records, size=200):
|
| 230 |
+
"""Round-robin relation pairs, then fixed hashes; independent of model scores."""
|
| 231 |
+
result = []
|
| 232 |
+
for split in ("train", "dev"):
|
| 233 |
+
by_pair = defaultdict(list)
|
| 234 |
+
for row in records:
|
| 235 |
+
if row["source_split"] == split:
|
| 236 |
+
by_pair[tuple(e[1] for e in row["edges"])].append(row)
|
| 237 |
+
for rows in by_pair.values():
|
| 238 |
+
rows.sort(key=lambda r: order(r["id"], "2wiki-semantic-review-v1:"))
|
| 239 |
+
chosen = []
|
| 240 |
+
while len(chosen) < size:
|
| 241 |
+
added = False
|
| 242 |
+
for pair in sorted(by_pair, key=lambda p: order(p, "relation-review:")):
|
| 243 |
+
if by_pair[pair]:
|
| 244 |
+
chosen.append(by_pair[pair].pop(0))
|
| 245 |
+
added = True
|
| 246 |
+
if len(chosen) == size:
|
| 247 |
+
break
|
| 248 |
+
if not added:
|
| 249 |
+
break
|
| 250 |
+
result.extend(chosen)
|
| 251 |
+
return result
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def atomic_question(subject, relation):
|
| 255 |
+
return QUESTION_TEMPLATES[relation].format(subject=subject)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def prompt(question):
|
| 259 |
+
return "Question: " + question + "\nAnswer:"
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def encode_example(tokenizer, question, answer, limit=256, generation_limit=64):
|
| 263 |
+
prefix = tokenizer.encode(prompt(question), add_special_tokens=False)
|
| 264 |
+
target = tokenizer.encode(" " + answer, add_special_tokens=False) + [tokenizer.eos_token_id]
|
| 265 |
+
joint = tokenizer.encode(prompt(question) + " " + answer, add_special_tokens=False)
|
| 266 |
+
if joint != prefix + target[:-1]:
|
| 267 |
+
raise ValueError("Answer boundary changes joint tokenization")
|
| 268 |
+
if len(prefix) + len(target) > limit or len(target) > generation_limit:
|
| 269 |
+
raise ValueError("Example exceeds the frozen length limits; never truncate an answer")
|
| 270 |
+
return {"prefix": prefix, "target": target, "input": (prefix + target)[:-1]}
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/realworld_confirmation.py
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Data-only confirmation isolation and independent endpoint recounting."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import ast
|
| 6 |
+
import copy
|
| 7 |
+
import json
|
| 8 |
+
import re
|
| 9 |
+
import statistics
|
| 10 |
+
import string
|
| 11 |
+
from collections import Counter, defaultdict
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
from .realworld_composition_data import normalize_answer, order, sha256, write_json
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def head_bridge_names(data, canonical, aliases):
|
| 20 |
+
names = defaultdict(set)
|
| 21 |
+
for row in data["train_compositions"] + data["evaluation_compositions"]:
|
| 22 |
+
for index in (0, 2):
|
| 23 |
+
identifier = row["edges"][0][index]
|
| 24 |
+
labels = [canonical[identifier], row["surfaces"][0][index]]
|
| 25 |
+
for label in labels + aliases.get(identifier, []):
|
| 26 |
+
normalized = normalize_answer(label)
|
| 27 |
+
if normalized:
|
| 28 |
+
names[identifier].add(normalized)
|
| 29 |
+
return names
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def answer_owners(canonical, aliases):
|
| 33 |
+
owners = defaultdict(set)
|
| 34 |
+
for identifier in set(canonical) | set(aliases):
|
| 35 |
+
for name in [canonical.get(identifier, ""), *aliases.get(identifier, [])]:
|
| 36 |
+
normalized = normalize_answer(name)
|
| 37 |
+
if normalized:
|
| 38 |
+
owners[normalized].add(identifier)
|
| 39 |
+
return owners
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def isolate_confirmation(candidate, development, canonical, aliases):
|
| 43 |
+
"""Exclude every chain touching a development head/bridge name, then rebuild."""
|
| 44 |
+
dev_names = set().union(*head_bridge_names(development, canonical, aliases).values())
|
| 45 |
+
formal_names = head_bridge_names(candidate, canonical, aliases)
|
| 46 |
+
excluded_entities = {e for e, names in formal_names.items() if names & dev_names}
|
| 47 |
+
excluded = {}
|
| 48 |
+
parts = {}
|
| 49 |
+
for key in ("train_compositions", "evaluation_compositions"):
|
| 50 |
+
excluded[key] = [
|
| 51 |
+
r["id"]
|
| 52 |
+
for r in candidate[key]
|
| 53 |
+
if {r["edges"][0][0], r["edges"][0][2]} & excluded_entities
|
| 54 |
+
]
|
| 55 |
+
excluded_ids = set(excluded[key])
|
| 56 |
+
parts[key] = [copy.deepcopy(r) for r in candidate[key] if r["id"] not in excluded_ids]
|
| 57 |
+
all_chains = parts["train_compositions"] + parts["evaluation_compositions"]
|
| 58 |
+
used = {a for r in all_chains for a in r["atom_ids"]}
|
| 59 |
+
atoms = [copy.deepcopy(r) for r in candidate["atoms"] if r["id"] in used]
|
| 60 |
+
first, second = ({r["atom_ids"][i] for r in parts["train_compositions"]} for i in (0, 1))
|
| 61 |
+
seen = first | second
|
| 62 |
+
direct = {(r["edge"][0], r["edge"][2]) for r in atoms}
|
| 63 |
+
pairs = {(r["edges"][0][0], r["edges"][1][2]) for r in parts["train_compositions"]}
|
| 64 |
+
operations = {tuple(e[1] for e in r["edges"]) for r in parts["train_compositions"]}
|
| 65 |
+
owners = answer_owners(canonical, aliases)
|
| 66 |
+
for row in atoms + all_chains:
|
| 67 |
+
identifier = row["edge"][2] if "edge" in row else row["edges"][1][2]
|
| 68 |
+
row["canonical_answer_globally_unambiguous"] = owners[normalize_answer(row["answer"])] == {
|
| 69 |
+
identifier
|
| 70 |
+
}
|
| 71 |
+
for row in all_chains:
|
| 72 |
+
a, b = row["atom_ids"]
|
| 73 |
+
row["role"] = ("I" if a in seen else "O") + ("I" if b in seen else "O")
|
| 74 |
+
row["required_role"] = ("I" if a in first else "O") + ("I" if b in second else "O")
|
| 75 |
+
pair = row["edges"][0][0], row["edges"][1][2]
|
| 76 |
+
row["known_direct_shortcut"] = pair in direct
|
| 77 |
+
row["head_tail_seen_in_combination_training"] = pair in pairs
|
| 78 |
+
row["operation_seen"] = tuple(e[1] for e in row["edges"]) in operations
|
| 79 |
+
panels = {
|
| 80 |
+
"test_" + role.lower(): [
|
| 81 |
+
r["id"]
|
| 82 |
+
for r in sorted(
|
| 83 |
+
[r for r in parts["evaluation_compositions"] if r["role"] == role],
|
| 84 |
+
key=lambda r: order(r["id"], "panel:"),
|
| 85 |
+
)[:64]
|
| 86 |
+
]
|
| 87 |
+
for role in ("II", "IO", "OI", "OO")
|
| 88 |
+
}
|
| 89 |
+
panels["train_composition"] = [
|
| 90 |
+
r["id"]
|
| 91 |
+
for r in sorted(parts["train_compositions"], key=lambda r: order(r["id"], "panel:"))[:128]
|
| 92 |
+
]
|
| 93 |
+
selected = {i for ids in panels.values() for i in ids}
|
| 94 |
+
required = {a for r in all_chains if r["id"] in selected for a in r["atom_ids"]}
|
| 95 |
+
panels["atomic"] = sorted(
|
| 96 |
+
required
|
| 97 |
+
| {r["id"] for r in sorted(atoms, key=lambda r: order(r["id"], "atom-panel:"))[:128]}
|
| 98 |
+
)
|
| 99 |
+
data = {"atoms": atoms, **parts, "panels": panels}
|
| 100 |
+
report = {
|
| 101 |
+
"rule": (
|
| 102 |
+
"Exclude chains whose head/bridge canonical, annotated surface or official alias "
|
| 103 |
+
"name overlaps development head/bridge names after author normalization; "
|
| 104 |
+
"retain shared tails."
|
| 105 |
+
),
|
| 106 |
+
"excluded_entities": sorted(excluded_entities),
|
| 107 |
+
"excluded_case_ids": excluded,
|
| 108 |
+
"excluded_counts": {key: len(ids) for key, ids in excluded.items()},
|
| 109 |
+
"colliding_names": sorted(dev_names & set().union(*formal_names.values())),
|
| 110 |
+
"model_results_used": False,
|
| 111 |
+
}
|
| 112 |
+
return data, report
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def audit_confirmation(data, development, canonical, aliases):
|
| 116 |
+
"""Recount from the selected records rather than selection bookkeeping."""
|
| 117 |
+
atoms = {r["id"]: r for r in data["atoms"]}
|
| 118 |
+
train, held = data["train_compositions"], data["evaluation_compositions"]
|
| 119 |
+
rows = train + held
|
| 120 |
+
dev_names = head_bridge_names(development, canonical, aliases)
|
| 121 |
+
formal_names = head_bridge_names(data, canonical, aliases)
|
| 122 |
+
assert not set(dev_names) & set(formal_names)
|
| 123 |
+
assert not set().union(*dev_names.values()) & set().union(*formal_names.values())
|
| 124 |
+
assert len(atoms) == len(data["atoms"])
|
| 125 |
+
assert len({r["id"] for r in rows}) == len(rows)
|
| 126 |
+
|
| 127 |
+
def chain(row):
|
| 128 |
+
return tuple(tuple(e) for e in row["edges"])
|
| 129 |
+
|
| 130 |
+
assert not {chain(r) for r in train} & {chain(r) for r in held}
|
| 131 |
+
held_questions = {normalize_answer(r["question"]) for r in held}
|
| 132 |
+
assert not {normalize_answer(r["question"]) for r in train} & held_questions
|
| 133 |
+
assert not {normalize_answer(r["question"]) for r in atoms.values()} & held_questions
|
| 134 |
+
assert not {normalize_answer(r["question"]) for r in atoms.values()} & {
|
| 135 |
+
normalize_answer(r["question"]) for r in development["atoms"]
|
| 136 |
+
}
|
| 137 |
+
seen = {a for r in train for a in r["atom_ids"]}
|
| 138 |
+
first, second = ({r["atom_ids"][i] for r in train} for i in (0, 1))
|
| 139 |
+
owners = answer_owners(canonical, aliases)
|
| 140 |
+
for row in rows:
|
| 141 |
+
a, b = row["atom_ids"]
|
| 142 |
+
assert [atoms[a]["edge"], atoms[b]["edge"]] == row["edges"]
|
| 143 |
+
assert row["edges"][0][2] == row["edges"][1][0]
|
| 144 |
+
assert row["role"] == ("I" if a in seen else "O") + ("I" if b in seen else "O")
|
| 145 |
+
assert row["required_role"] == ("I" if a in first else "O") + ("I" if b in second else "O")
|
| 146 |
+
assert not row["structural_errors"]
|
| 147 |
+
assert not any(r["known_prior_case"] for r in held)
|
| 148 |
+
for pool in (list(atoms.values()), train, held):
|
| 149 |
+
prompt_answers = defaultdict(set)
|
| 150 |
+
for row in pool:
|
| 151 |
+
prompt_answers[normalize_answer(row["question"])].add(normalize_answer(row["answer"]))
|
| 152 |
+
identifier = row["edge"][2] if "edge" in row else row["edges"][1][2]
|
| 153 |
+
assert row["canonical_answer_globally_unambiguous"] == (
|
| 154 |
+
owners[normalize_answer(row["answer"])] == {identifier}
|
| 155 |
+
)
|
| 156 |
+
e = row["encoded"]
|
| 157 |
+
assert e["target"][-1] == 50256 and len(e["target"]) <= 64
|
| 158 |
+
assert e["input"] == (e["prefix"] + e["target"])[:-1]
|
| 159 |
+
assert len(e["prefix"]) + len(e["target"]) <= 256
|
| 160 |
+
assert all(len(answers) == 1 for answers in prompt_answers.values())
|
| 161 |
+
panel_ids = {i for name, ids in data["panels"].items() if name != "atomic" for i in ids}
|
| 162 |
+
assert {a for r in rows if r["id"] in panel_ids for a in r["atom_ids"]} <= set(
|
| 163 |
+
data["panels"]["atomic"]
|
| 164 |
+
)
|
| 165 |
+
return {
|
| 166 |
+
"passed": True,
|
| 167 |
+
"atoms": len(atoms),
|
| 168 |
+
"train_compositions": len(train),
|
| 169 |
+
"evaluation_compositions": len(held),
|
| 170 |
+
"evaluation_roles": dict(Counter(r["role"] for r in held)),
|
| 171 |
+
"required_role_counts": dict(Counter(r["required_role"] for r in held)),
|
| 172 |
+
"canonical_unambiguous_evaluation_count": sum(
|
| 173 |
+
r["canonical_answer_globally_unambiguous"] for r in held
|
| 174 |
+
),
|
| 175 |
+
"panels": {name: len(ids) for name, ids in data["panels"].items()},
|
| 176 |
+
"head_bridge_id_overlap": 0,
|
| 177 |
+
"head_bridge_normalized_name_overlap": 0,
|
| 178 |
+
"necessary_atomic_coverage": 1.0,
|
| 179 |
+
"known_direct_shortcuts": sum(r["known_direct_shortcut"] for r in held),
|
| 180 |
+
"unseen_operations": sum(not r["operation_seen"] for r in held),
|
| 181 |
+
"max_input_tokens": max(len(r["encoded"]["input"]) for r in list(atoms.values()) + rows),
|
| 182 |
+
"atomic_relations": dict(Counter(r["edge"][1] for r in atoms.values())),
|
| 183 |
+
"train_relation_pairs": dict(Counter(" -> ".join(e[1] for e in r["edges"]) for r in train)),
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def finalize_confirmation(config):
|
| 188 |
+
"""Independently score raw outputs using the pinned author's scorer functions."""
|
| 189 |
+
root, art = Path(config["results_root"]), Path(config["artifact_root"])
|
| 190 |
+
data = json.loads(Path(config["data_file"]).read_text())
|
| 191 |
+
scorer = Path(config["official_scorer"])
|
| 192 |
+
scope = dict(re=re, string=string, Counter=Counter)
|
| 193 |
+
tree = ast.parse(scorer.read_text())
|
| 194 |
+
functions = [
|
| 195 |
+
n
|
| 196 |
+
for n in tree.body
|
| 197 |
+
if isinstance(n, ast.FunctionDef) and n.name in {"normalize_answer", "exact_match_score"}
|
| 198 |
+
]
|
| 199 |
+
exec(compile(ast.Module(body=functions, type_ignores=[]), str(scorer), "exec"), scope)
|
| 200 |
+
|
| 201 |
+
def score(prediction, row):
|
| 202 |
+
return float(
|
| 203 |
+
any(
|
| 204 |
+
scope["exact_match_score"](prediction, g)
|
| 205 |
+
for g in [row["answer"], *row.get("aliases", [])]
|
| 206 |
+
)
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
held = data["evaluation_compositions"]
|
| 210 |
+
summary, scores, atom_scores, exposures, metadata = {}, {}, {}, {}, {}
|
| 211 |
+
for spec in config["runs"]:
|
| 212 |
+
name = spec["name"]
|
| 213 |
+
out = root / config["phase"] / name
|
| 214 |
+
complete = json.loads((out / "complete.json").read_text())
|
| 215 |
+
assert complete["step"] == spec["steps"] and complete["independently_reloaded"]
|
| 216 |
+
raw = json.loads((out / "endpoint-predictions.json").read_text())
|
| 217 |
+
metrics = json.loads((out / "endpoint.json").read_text())
|
| 218 |
+
for group, records in [
|
| 219 |
+
("atomic", data["atoms"]),
|
| 220 |
+
("train_composition", data["train_compositions"]),
|
| 221 |
+
("test_all", held),
|
| 222 |
+
]:
|
| 223 |
+
by_id = {p["id"]: p for p in raw[group]}
|
| 224 |
+
assert len(by_id) == len(records) == len(raw[group])
|
| 225 |
+
assert set(by_id) == {r["id"] for r in records}
|
| 226 |
+
recomputed = {r["id"]: score(by_id[r["id"]]["prediction"], r) for r in records}
|
| 227 |
+
assert all(recomputed[i] == by_id[i]["alias_em"] for i in recomputed)
|
| 228 |
+
assert abs(sum(recomputed.values()) / len(records) - metrics[group]["alias_em"]) < 1e-12
|
| 229 |
+
if group == "test_all":
|
| 230 |
+
scores[name] = recomputed
|
| 231 |
+
for role in ("II", "IO", "OI", "OO"):
|
| 232 |
+
selected = [r for r in held if r["role"] == role]
|
| 233 |
+
assert (
|
| 234 |
+
abs(
|
| 235 |
+
sum(recomputed[r["id"]] for r in selected) / len(selected)
|
| 236 |
+
- metrics["test_" + role.lower()]["alias_em"]
|
| 237 |
+
)
|
| 238 |
+
< 1e-12
|
| 239 |
+
)
|
| 240 |
+
if group == "atomic":
|
| 241 |
+
atom_scores[name] = recomputed
|
| 242 |
+
summary[name] = metrics
|
| 243 |
+
exposures[name] = {
|
| 244 |
+
step: np.load(out / f"exposure-{step:07d}.npz")["counts"]
|
| 245 |
+
for step in config["evaluation_nodes"]
|
| 246 |
+
}
|
| 247 |
+
metadata[name] = json.loads((out / "run.json").read_text())
|
| 248 |
+
assert complete["checkpoint_sha256"] == sha256(out / "latest.pt")
|
| 249 |
+
comparisons = []
|
| 250 |
+
for seed in sorted({s["initialization"] for s in config["runs"]}):
|
| 251 |
+
specs = {s["architecture"]: s for s in config["runs"] if s["initialization"] == seed}
|
| 252 |
+
assert set(specs) == {"standard8", "loop4x2", "standard4"}
|
| 253 |
+
names = [s["name"] for s in specs.values()]
|
| 254 |
+
assert len({metadata[n]["common_four_block_initial_sha256"] for n in names}) == 1
|
| 255 |
+
for step in config["evaluation_nodes"]:
|
| 256 |
+
assert all(
|
| 257 |
+
np.array_equal(exposures[names[0]][step], exposures[n][step]) for n in names[1:]
|
| 258 |
+
)
|
| 259 |
+
for baseline in ("standard8", "standard4"):
|
| 260 |
+
loop, base = specs["loop4x2"]["name"], specs[baseline]["name"]
|
| 261 |
+
for role in ("all", "OO"):
|
| 262 |
+
selected = held if role == "all" else [r for r in held if r["role"] == role]
|
| 263 |
+
common = [
|
| 264 |
+
r
|
| 265 |
+
for r in selected
|
| 266 |
+
if all(atom_scores[n][a] for n in (loop, base) for a in r["atom_ids"])
|
| 267 |
+
]
|
| 268 |
+
comparisons.append(
|
| 269 |
+
{
|
| 270 |
+
"initialization": seed,
|
| 271 |
+
"baseline": baseline,
|
| 272 |
+
"pool": role,
|
| 273 |
+
"n": len(selected),
|
| 274 |
+
"paired_difference": sum(
|
| 275 |
+
scores[loop][r["id"]] - scores[base][r["id"]] for r in selected
|
| 276 |
+
)
|
| 277 |
+
/ len(selected),
|
| 278 |
+
"both_models_necessary_atoms_correct_n": len(common),
|
| 279 |
+
"both_models_necessary_atoms_correct_coverage": len(common) / len(selected),
|
| 280 |
+
"conditional_paired_difference": sum(
|
| 281 |
+
scores[loop][r["id"]] - scores[base][r["id"]] for r in common
|
| 282 |
+
)
|
| 283 |
+
/ len(common)
|
| 284 |
+
if common
|
| 285 |
+
else None,
|
| 286 |
+
}
|
| 287 |
+
)
|
| 288 |
+
means = {}
|
| 289 |
+
for architecture in ("standard8", "loop4x2", "standard4"):
|
| 290 |
+
names = [s["name"] for s in config["runs"] if s["architecture"] == architecture]
|
| 291 |
+
means[architecture] = {}
|
| 292 |
+
for group in (
|
| 293 |
+
"atomic",
|
| 294 |
+
"train_composition",
|
| 295 |
+
"test_all",
|
| 296 |
+
"test_ii",
|
| 297 |
+
"test_io",
|
| 298 |
+
"test_oi",
|
| 299 |
+
"test_oo",
|
| 300 |
+
"autonomous",
|
| 301 |
+
):
|
| 302 |
+
values = [summary[n][group]["alias_em"] for n in names]
|
| 303 |
+
means[architecture][group] = {
|
| 304 |
+
"mean": statistics.mean(values),
|
| 305 |
+
"sample_sd": statistics.stdev(values),
|
| 306 |
+
"per_initialization": values,
|
| 307 |
+
}
|
| 308 |
+
result = {
|
| 309 |
+
"passed": True,
|
| 310 |
+
"runs": len(config["runs"]),
|
| 311 |
+
"scientific_updates": sum(s["steps"] for s in config["runs"]),
|
| 312 |
+
"independent_dataset_splits": 1,
|
| 313 |
+
"paired_initializations": 3,
|
| 314 |
+
"paired_exposures_equal_at_all_nodes": True,
|
| 315 |
+
"architecture_scores": means,
|
| 316 |
+
"paired_comparisons": comparisons,
|
| 317 |
+
"source_data_sha256": sha256(config["data_file"]),
|
| 318 |
+
"official_scorer_sha256": sha256(scorer),
|
| 319 |
+
}
|
| 320 |
+
write_json(art / "confirmation-summary.json", summary)
|
| 321 |
+
write_json(art / "confirmation-recount-audit.json", result)
|
| 322 |
+
return result
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/realworld_confirmation_analysis.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Registered relation/component and paired-knowledge trajectory descriptions."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
from collections import defaultdict
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
from .realworld_composition_data import write_json
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def threshold_intervals(history, group, threshold):
|
| 13 |
+
passed = [r["metrics"][group]["alias_em"] >= threshold for r in history]
|
| 14 |
+
|
| 15 |
+
def interval(index):
|
| 16 |
+
if index is None:
|
| 17 |
+
return None
|
| 18 |
+
return [history[index - 1]["step"] if index else None, history[index]["step"]]
|
| 19 |
+
|
| 20 |
+
first = next((i for i, value in enumerate(passed) if value), None)
|
| 21 |
+
sustained = next((i for i, value in enumerate(passed) if value and all(passed[i:])), None)
|
| 22 |
+
return {
|
| 23 |
+
"first_observed_interval": interval(first),
|
| 24 |
+
"sustained_observed_interval": interval(sustained),
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def analyze_confirmation(config):
|
| 29 |
+
root = Path(config["results_root"]) / config["phase"]
|
| 30 |
+
data = json.loads(Path(config["data_file"]).read_text())
|
| 31 |
+
held = {r["id"]: r for r in data["evaluation_compositions"]}
|
| 32 |
+
endpoint_groups, thresholds, nodes = {}, {}, {}
|
| 33 |
+
for spec in config["runs"]:
|
| 34 |
+
name = spec["name"]
|
| 35 |
+
out = root / name
|
| 36 |
+
raw = json.loads((out / "endpoint-predictions.json").read_text())["test_all"]
|
| 37 |
+
by_relation, by_component = defaultdict(list), defaultdict(list)
|
| 38 |
+
for prediction in raw:
|
| 39 |
+
row = held[prediction["id"]]
|
| 40 |
+
by_relation[" -> ".join(e[1] for e in row["edges"])].append(prediction["alias_em"])
|
| 41 |
+
by_component[row["group"]].append(prediction["alias_em"])
|
| 42 |
+
endpoint_groups[name] = {
|
| 43 |
+
key: {k: {"n": len(v), "alias_em": sum(v) / len(v)} for k, v in groups.items()}
|
| 44 |
+
for key, groups in [
|
| 45 |
+
("relation_pair", by_relation),
|
| 46 |
+
("source_head_bridge_component", by_component),
|
| 47 |
+
]
|
| 48 |
+
}
|
| 49 |
+
history = json.loads((out / "learning.json").read_text())
|
| 50 |
+
thresholds[name] = {
|
| 51 |
+
f"{group}_{value}": threshold_intervals(history, group, value)
|
| 52 |
+
for group, value in [("train_composition", 0.99), ("test_all", 0.5), ("test_all", 0.9)]
|
| 53 |
+
}
|
| 54 |
+
nodes[name] = {}
|
| 55 |
+
for step in config["evaluation_nodes"]:
|
| 56 |
+
node = json.loads((out / f"predictions-{step:07d}.json").read_text())
|
| 57 |
+
nodes[name][step] = {
|
| 58 |
+
group: {r["id"]: r["alias_em"] for r in node[group]}
|
| 59 |
+
for group in ("atomic", "test_all")
|
| 60 |
+
}
|
| 61 |
+
trajectories = []
|
| 62 |
+
for seed in sorted({s["initialization"] for s in config["runs"]}):
|
| 63 |
+
specs = {s["architecture"]: s for s in config["runs"] if s["initialization"] == seed}
|
| 64 |
+
loop = specs["loop4x2"]["name"]
|
| 65 |
+
for baseline in ("standard8", "standard4"):
|
| 66 |
+
base = specs[baseline]["name"]
|
| 67 |
+
for step in config["evaluation_nodes"]:
|
| 68 |
+
left, right = nodes[loop][step], nodes[base][step]
|
| 69 |
+
assert set(left["test_all"]) == set(right["test_all"])
|
| 70 |
+
for pool in ("all", "OO"):
|
| 71 |
+
selected = [
|
| 72 |
+
held[i]
|
| 73 |
+
for i in left["test_all"]
|
| 74 |
+
if pool == "all" or held[i]["role"] == pool
|
| 75 |
+
]
|
| 76 |
+
common = [
|
| 77 |
+
r
|
| 78 |
+
for r in selected
|
| 79 |
+
if all(n["atomic"][a] for n in (left, right) for a in r["atom_ids"])
|
| 80 |
+
]
|
| 81 |
+
trajectories.append(
|
| 82 |
+
{
|
| 83 |
+
"initialization": seed,
|
| 84 |
+
"baseline": baseline,
|
| 85 |
+
"step": step,
|
| 86 |
+
"pool": pool,
|
| 87 |
+
"panel_n": len(selected),
|
| 88 |
+
"both_models_necessary_atoms_correct_n": len(common),
|
| 89 |
+
"both_models_necessary_atoms_correct_coverage": len(common)
|
| 90 |
+
/ len(selected),
|
| 91 |
+
"full_panel_paired_difference": sum(
|
| 92 |
+
left["test_all"][r["id"]] - right["test_all"][r["id"]]
|
| 93 |
+
for r in selected
|
| 94 |
+
)
|
| 95 |
+
/ len(selected),
|
| 96 |
+
"conditional_paired_difference": sum(
|
| 97 |
+
left["test_all"][r["id"]] - right["test_all"][r["id"]]
|
| 98 |
+
for r in common
|
| 99 |
+
)
|
| 100 |
+
/ len(common)
|
| 101 |
+
if common
|
| 102 |
+
else None,
|
| 103 |
+
}
|
| 104 |
+
)
|
| 105 |
+
result = {
|
| 106 |
+
"endpoint_groups": endpoint_groups,
|
| 107 |
+
"threshold_intervals": thresholds,
|
| 108 |
+
"paired_knowledge_trajectories": trajectories,
|
| 109 |
+
"trajectory_scope": (
|
| 110 |
+
"Fixed panels at registered nodes; threshold brackets are descriptive and do not "
|
| 111 |
+
"identify exact crossing times or establish grokking."
|
| 112 |
+
),
|
| 113 |
+
"endpoint_scope": (
|
| 114 |
+
"Full registered evaluation pool; source components are shared by questions, "
|
| 115 |
+
"not independent worlds."
|
| 116 |
+
),
|
| 117 |
+
}
|
| 118 |
+
write_json(Path(config["artifact_root"]) / "confirmation-analysis.json", result)
|
| 119 |
+
return result
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/recurrence_use.py
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Frozen-weight update deletion and semantic first-hop interventions.
|
| 2 |
+
|
| 3 |
+
Responses are measurements of computational dependence, not learned predictors.
|
| 4 |
+
Truth graphs select donors before inference; query means prevent donor frequency
|
| 5 |
+
from creating additional scientific observations.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import time
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
import torch
|
| 14 |
+
from torch.nn import functional as F
|
| 15 |
+
|
| 16 |
+
from .depth_step import EOS, prompt_rows, truth_path_details
|
| 17 |
+
from .latent_scaling import model_digest
|
| 18 |
+
|
| 19 |
+
COMPONENTS = ("full", "attention", "mlp")
|
| 20 |
+
TASKS = ("atomic",) + tuple(f"{s}_{h}" for h in (2, 3, 4) for s in ("familiar", "strict"))
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@torch.no_grad()
|
| 24 |
+
def trace(model, tokens, repeats, *, skip=None, patch=None):
|
| 25 |
+
"""Apply one occurrence deletion or one r1 replacement, with native SDPA."""
|
| 26 |
+
if model.training or repeats < 1:
|
| 27 |
+
raise ValueError("Evaluation mode and positive recurrence are required")
|
| 28 |
+
blocks = list(model.iter_blocks(repeats))
|
| 29 |
+
if skip is not None:
|
| 30 |
+
scope, source = skip
|
| 31 |
+
if scope not in ("all", "r1") or source not in range(len(blocks)):
|
| 32 |
+
raise ValueError("Unknown skip scope/occurrence")
|
| 33 |
+
if patch is not None and patch[0] not in ("full", "mlp"):
|
| 34 |
+
raise ValueError("Unknown patch component")
|
| 35 |
+
x = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=tokens.device))
|
| 36 |
+
cache = {name: [] for name in ("input", "full", "attention", "mlp", "output")}
|
| 37 |
+
for index, block in enumerate(blocks):
|
| 38 |
+
incoming = x
|
| 39 |
+
z = block.ln1(x)
|
| 40 |
+
batch, length, width = z.shape
|
| 41 |
+
a = block.attention
|
| 42 |
+
q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2)
|
| 43 |
+
attention = a.proj(
|
| 44 |
+
F.scaled_dot_product_attention(
|
| 45 |
+
q.transpose(1, 2),
|
| 46 |
+
k.transpose(1, 2),
|
| 47 |
+
v.transpose(1, 2),
|
| 48 |
+
is_causal=True,
|
| 49 |
+
dropout_p=0.0,
|
| 50 |
+
)
|
| 51 |
+
.transpose(1, 2)
|
| 52 |
+
.reshape(batch, length, width)
|
| 53 |
+
)
|
| 54 |
+
x = x + attention
|
| 55 |
+
mlp = block.mlp(block.ln2(x))
|
| 56 |
+
if index == 0 and patch is not None and patch[0] == "mlp":
|
| 57 |
+
mlp = mlp.clone()
|
| 58 |
+
if patch[1].shape != mlp[:, 2].shape:
|
| 59 |
+
raise ValueError("Replacement shape differs")
|
| 60 |
+
mlp[:, 2] = patch[1]
|
| 61 |
+
x = x + mlp
|
| 62 |
+
if index == 0 and patch is not None and patch[0] == "full":
|
| 63 |
+
x = x.clone()
|
| 64 |
+
if patch[1].shape != x[:, 2].shape:
|
| 65 |
+
raise ValueError("Replacement shape differs")
|
| 66 |
+
x[:, 2] = patch[1]
|
| 67 |
+
if skip is not None and index == skip[1]:
|
| 68 |
+
if skip[0] == "all":
|
| 69 |
+
x, attention, mlp = incoming, torch.zeros_like(attention), torch.zeros_like(mlp)
|
| 70 |
+
else:
|
| 71 |
+
x, attention, mlp = x.clone(), attention.clone(), mlp.clone()
|
| 72 |
+
x[:, 2], attention[:, 2], mlp[:, 2] = incoming[:, 2], 0, 0
|
| 73 |
+
for name, value in zip(cache, (incoming, x - incoming, attention, mlp, x), strict=True):
|
| 74 |
+
cache[name].append(value)
|
| 75 |
+
logits = F.linear(model.ln_final(x), model.token.weight)
|
| 76 |
+
return logits, {name: torch.stack(values) for name, values in cache.items()}
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def interaction(numerator, denominator):
|
| 80 |
+
"""Ratio of query-averaged norms; an absent denominator is not zero influence."""
|
| 81 |
+
numerator, denominator = np.asarray(numerator), np.asarray(denominator)
|
| 82 |
+
if numerator.shape != denominator.shape or not len(numerator):
|
| 83 |
+
raise ValueError("Require nonempty aligned response arrays")
|
| 84 |
+
n, b = float(numerator.mean()), float(denominator.mean())
|
| 85 |
+
return {"N": n, "B": b, "C": n / b if b > 1e-8 else None}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def prediction_metrics(prediction, targets):
|
| 89 |
+
generated = prediction["generated"]
|
| 90 |
+
logits = prediction["logits"].astype(np.float64)
|
| 91 |
+
targets = np.asarray(targets, dtype=np.int64)
|
| 92 |
+
maximum = logits.max(1)
|
| 93 |
+
partition = maximum + np.log(np.exp(logits - maximum[:, None]).sum(1))
|
| 94 |
+
target_logits = logits[np.arange(len(targets)), targets]
|
| 95 |
+
competitors = logits.copy()
|
| 96 |
+
competitors[np.arange(len(targets)), targets] = -np.inf
|
| 97 |
+
return {
|
| 98 |
+
"answer": (generated[:, 0] == targets).astype(float),
|
| 99 |
+
"complete": ((generated[:, 0] == targets) & (generated[:, 1] == EOS)).astype(float),
|
| 100 |
+
"eos": (generated[:, 1] == EOS).astype(float),
|
| 101 |
+
"nll": partition - target_logits,
|
| 102 |
+
"margin": target_logits - competitors.max(1),
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def mean_metrics(metrics, mask=None):
|
| 107 |
+
length = len(next(iter(metrics.values())))
|
| 108 |
+
mask = np.ones(length, bool) if mask is None else np.asarray(mask, dtype=bool)
|
| 109 |
+
if mask.shape != (length,):
|
| 110 |
+
raise ValueError("Mask must align with observations")
|
| 111 |
+
return {
|
| 112 |
+
"n": int(mask.sum()),
|
| 113 |
+
"coverage": float(mask.mean()) if length else 0.0,
|
| 114 |
+
**{k: float(v[mask].mean()) if mask.any() else None for k, v in metrics.items()},
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def query_means(values, indices, n):
|
| 119 |
+
counts = np.bincount(indices, minlength=n)
|
| 120 |
+
sums = np.bincount(indices, weights=values, minlength=n)
|
| 121 |
+
out = np.full(n, np.nan)
|
| 122 |
+
np.divide(sums, counts, out=out, where=counts > 0)
|
| 123 |
+
return out
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def role_counts(world):
|
| 127 |
+
counts = np.zeros((len(world["atomic"]), 4), dtype=np.int64)
|
| 128 |
+
for hop in (2, 3, 4):
|
| 129 |
+
_, edges = truth_path_details(world, world[f"train_{hop}"])
|
| 130 |
+
for position in range(hop):
|
| 131 |
+
np.add.at(counts[:, position], edges[:, position], 1)
|
| 132 |
+
return counts
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def select_donors(low, high):
|
| 136 |
+
"""Enumerate shared bridge donors and select answer-blind changed paths."""
|
| 137 |
+
atoms = low["atomic"]
|
| 138 |
+
for name in TASKS:
|
| 139 |
+
np.testing.assert_array_equal(low[name], high[name])
|
| 140 |
+
id_mask = np.asarray(low["metadata"]["id_mask"], bool)
|
| 141 |
+
np.testing.assert_array_equal(id_mask, high["metadata"]["id_mask"])
|
| 142 |
+
low_roles, high_roles = role_counts(low), role_counts(high)
|
| 143 |
+
if low_roles[~id_mask].any() or high_roles[~id_mask].any():
|
| 144 |
+
raise ValueError("Strict fact has composition training exposure")
|
| 145 |
+
used_first = (low_roles[:, 0] > 0) & (high_roles[:, 0] > 0)
|
| 146 |
+
strict = ~id_mask & (low_roles.sum(1) == 0) & (high_roles.sum(1) == 0)
|
| 147 |
+
result = {"low_roles": low_roles, "high_roles": high_roles}
|
| 148 |
+
rows = low["strict_2"]
|
| 149 |
+
nodes, _ = truth_path_details(low, rows)
|
| 150 |
+
for label, eligible in (("experienced", used_first), ("strict", strict)):
|
| 151 |
+
recipients, indices = [], []
|
| 152 |
+
for i, (row, path) in enumerate(zip(rows, nodes, strict=True)):
|
| 153 |
+
mask = eligible & (atoms[:, 1] == row[1]) & (atoms[:, 2] == path[1])
|
| 154 |
+
mask &= (atoms[:, 0] != row[0]) & (atoms[:, 0] != row[-1])
|
| 155 |
+
choices = sorted(np.flatnonzero(mask), key=lambda k: tuple(atoms[k]))
|
| 156 |
+
recipients.extend([i] * len(choices))
|
| 157 |
+
indices.extend(choices)
|
| 158 |
+
result[label + "_recipients"] = np.asarray(recipients, dtype=np.int64)
|
| 159 |
+
result[label + "_atoms"] = np.asarray(indices, dtype=np.int64)
|
| 160 |
+
result["common"] = (np.bincount(result["experienced_recipients"], minlength=len(rows)) > 0) & (
|
| 161 |
+
np.bincount(result["strict_recipients"], minlength=len(rows)) > 0
|
| 162 |
+
)
|
| 163 |
+
lookup = {(int(h), int(r)): (i, int(t)) for i, (h, r, t) in enumerate(atoms)}
|
| 164 |
+
trained = {tuple(row[:-1]) for w in (low, high) for row in w["train_2"]}
|
| 165 |
+
order = sorted(range(len(atoms)), key=lambda i: tuple(atoms[i]))
|
| 166 |
+
for label in ("familiar", "strict"):
|
| 167 |
+
rows = low[label + "_2"]
|
| 168 |
+
nodes, edges = truth_path_details(low, rows)
|
| 169 |
+
recipients, donors, targets, successors = [], [], [], []
|
| 170 |
+
for i, (row, path) in enumerate(zip(rows, nodes, strict=True)):
|
| 171 |
+
for fact in order:
|
| 172 |
+
h, r1, bridge = map(int, atoms[fact])
|
| 173 |
+
successor = lookup.get((bridge, int(row[2])))
|
| 174 |
+
if successor is None:
|
| 175 |
+
continue
|
| 176 |
+
next_index, target = successor
|
| 177 |
+
if (
|
| 178 |
+
r1 != row[1]
|
| 179 |
+
or h in (row[0], row[-1], target)
|
| 180 |
+
or bridge == path[1]
|
| 181 |
+
or target == row[-1]
|
| 182 |
+
or (h, r1, int(row[2])) in trained
|
| 183 |
+
or id_mask[fact] != id_mask[edges[i, 0]]
|
| 184 |
+
or id_mask[next_index] != id_mask[edges[i, 1]]
|
| 185 |
+
):
|
| 186 |
+
continue
|
| 187 |
+
recipients.append(i)
|
| 188 |
+
donors.append(fact)
|
| 189 |
+
targets.append(target)
|
| 190 |
+
successors.append(next_index)
|
| 191 |
+
break
|
| 192 |
+
result[label + "_changed_recipients"] = np.asarray(recipients, dtype=np.int64)
|
| 193 |
+
result[label + "_changed_atoms"] = np.asarray(donors, dtype=np.int64)
|
| 194 |
+
result[label + "_changed_targets"] = np.asarray(targets, dtype=np.int64)
|
| 195 |
+
result[label + "_changed_successors"] = np.asarray(successors, dtype=np.int64)
|
| 196 |
+
return result
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
@torch.no_grad()
|
| 200 |
+
def generate(model, rows, separator, repeats, *, skip=None, donor_atoms=None, component="full"):
|
| 201 |
+
"""Free answer and free EOS; a donor sees only the atomic question prefix."""
|
| 202 |
+
rows = np.asarray(rows, np.int64)
|
| 203 |
+
if not len(rows):
|
| 204 |
+
return {
|
| 205 |
+
"generated": np.empty((0, 2), np.int64),
|
| 206 |
+
"logits": np.empty((0, model.config.vocab_size), np.float32),
|
| 207 |
+
}, None
|
| 208 |
+
device = next(model.parameters()).device
|
| 209 |
+
tokens = torch.as_tensor(prompt_rows(rows, separator), device=device)
|
| 210 |
+
|
| 211 |
+
def forward(inputs):
|
| 212 |
+
patch = None
|
| 213 |
+
if donor_atoms is not None:
|
| 214 |
+
donor = torch.zeros_like(inputs)
|
| 215 |
+
donor[:, :3] = torch.as_tensor(
|
| 216 |
+
prompt_rows(donor_atoms, separator)[:, :3], device=device
|
| 217 |
+
)
|
| 218 |
+
_, donor_cache = trace(model, donor, 1)
|
| 219 |
+
field = "output" if component == "full" else "mlp"
|
| 220 |
+
patch = (component, donor_cache[field][0, :, 2])
|
| 221 |
+
return trace(model, inputs, repeats, skip=skip, patch=patch)
|
| 222 |
+
|
| 223 |
+
logits, cache = forward(tokens)
|
| 224 |
+
answer_logits = logits[:, -1]
|
| 225 |
+
answer = answer_logits.argmax(-1)
|
| 226 |
+
eos_logits, _ = forward(torch.cat((tokens, answer[:, None]), dim=1))
|
| 227 |
+
prediction = {
|
| 228 |
+
"generated": torch.stack((answer, eos_logits[:, -1].argmax(-1)), 1).cpu().numpy(),
|
| 229 |
+
"logits": answer_logits.cpu().numpy(),
|
| 230 |
+
}
|
| 231 |
+
return prediction, cache
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def response_arrays(baseline, changed, source):
|
| 235 |
+
arrays, rows = {}, []
|
| 236 |
+
for component in COMPONENTS:
|
| 237 |
+
for site, position in (("all", None), ("r1", 2), ("answer", -1)):
|
| 238 |
+
a, b = baseline[component], changed[component]
|
| 239 |
+
n, d = (b - a).norm(dim=-1), a.norm(dim=-1)
|
| 240 |
+
n, d = (
|
| 241 |
+
(n.mean(-1), d.mean(-1))
|
| 242 |
+
if position is None
|
| 243 |
+
else (n[..., position], d[..., position])
|
| 244 |
+
)
|
| 245 |
+
for target in range(source + 1, len(a)):
|
| 246 |
+
numerator, denominator = n[target].cpu().numpy(), d[target].cpu().numpy()
|
| 247 |
+
key = f"{component}_{site}_i{source}_j{target}"
|
| 248 |
+
arrays[key + "_N"], arrays[key + "_B"] = numerator, denominator
|
| 249 |
+
rows.append(
|
| 250 |
+
{
|
| 251 |
+
"component": component,
|
| 252 |
+
"site": site,
|
| 253 |
+
"source": source,
|
| 254 |
+
"target": target,
|
| 255 |
+
**interaction(numerator, denominator),
|
| 256 |
+
}
|
| 257 |
+
)
|
| 258 |
+
return arrays, rows
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
@torch.no_grad()
|
| 262 |
+
def evaluate(model, world, selection, repeats):
|
| 263 |
+
started = time.perf_counter()
|
| 264 |
+
if any(p.requires_grad for p in model.parameters()) or model.training:
|
| 265 |
+
raise ValueError("All weights must be frozen in evaluation mode")
|
| 266 |
+
before = model_digest(model)
|
| 267 |
+
model.repeats = repeats
|
| 268 |
+
separator = world["metadata"]["separator_token"]
|
| 269 |
+
arrays, summaries, engineering = {}, {}, {}
|
| 270 |
+
predictions, caches, metrics = {}, {}, {}
|
| 271 |
+
conditions = [("baseline", None)] + [
|
| 272 |
+
(f"skip_{scope}_{i}", (scope, i)) for scope in ("all", "r1") for i in range(repeats)
|
| 273 |
+
]
|
| 274 |
+
for task in TASKS:
|
| 275 |
+
rows = world[task]
|
| 276 |
+
arrays[task + "_rows"] = rows
|
| 277 |
+
predictions[task], metrics[task] = {}, {}
|
| 278 |
+
for name, skip in conditions:
|
| 279 |
+
pred, cache = generate(model, rows, separator, repeats, skip=skip)
|
| 280 |
+
m = prediction_metrics(pred, rows[:, -1])
|
| 281 |
+
predictions[task][name], metrics[task][name] = pred, m
|
| 282 |
+
for field, values in {**pred, **m}.items():
|
| 283 |
+
arrays[f"{task}_{name}_{field}"] = values
|
| 284 |
+
summaries[f"{task}/{name}"] = {"full_pool": mean_metrics(m)}
|
| 285 |
+
if name == "baseline":
|
| 286 |
+
caches[task] = cache
|
| 287 |
+
inputs = torch.as_tensor(
|
| 288 |
+
prompt_rows(rows, separator), device=next(model.parameters()).device
|
| 289 |
+
)
|
| 290 |
+
native = model(inputs)[:, -1].cpu().numpy()
|
| 291 |
+
if not np.array_equal(native, pred["logits"]):
|
| 292 |
+
raise AssertionError("Traced logits differ from native forward")
|
| 293 |
+
engineering[task + "_native_logits_exact"] = True
|
| 294 |
+
elif task != "atomic":
|
| 295 |
+
response, cells = response_arrays(caches[task], cache, skip[1])
|
| 296 |
+
arrays.update({f"{task}_{name}_{k}": v for k, v in response.items()})
|
| 297 |
+
summaries[f"{task}/{name}"]["responses"] = cells
|
| 298 |
+
if name == f"skip_r1_{repeats - 1}":
|
| 299 |
+
for field in ("generated", "logits"):
|
| 300 |
+
np.testing.assert_array_equal(pred[field], predictions[task]["baseline"][field])
|
| 301 |
+
engineering[task + "_last_r1_no_downstream_effect"] = True
|
| 302 |
+
del cache
|
| 303 |
+
for task in TASKS[1:]:
|
| 304 |
+
_, edges = truth_path_details(world, world[task])
|
| 305 |
+
arrays[task + "_atomic_indices"] = edges
|
| 306 |
+
common = np.ones(len(world[task]), bool)
|
| 307 |
+
for name, _ in conditions:
|
| 308 |
+
common &= metrics["atomic"][name]["complete"][edges].all(1)
|
| 309 |
+
arrays[task + "_common_atomic_mask"] = common
|
| 310 |
+
for name, _ in conditions:
|
| 311 |
+
cell = summaries[f"{task}/{name}"]
|
| 312 |
+
cell["necessary_atomic_coverage"] = float(
|
| 313 |
+
metrics["atomic"][name]["complete"][edges].all(1).mean()
|
| 314 |
+
)
|
| 315 |
+
cell["common_atomic_pool"] = mean_metrics(metrics[task][name], common)
|
| 316 |
+
# Self-prefix patches at equal physical length verify absence of later-relation information.
|
| 317 |
+
for task in ("familiar_2", "strict_2"):
|
| 318 |
+
rows = world[task]
|
| 319 |
+
atoms = np.c_[rows[:, :2], np.zeros(len(rows), np.int64)]
|
| 320 |
+
for component in ("full", "mlp"):
|
| 321 |
+
pred, _ = generate(
|
| 322 |
+
model, rows, separator, repeats, donor_atoms=atoms, component=component
|
| 323 |
+
)
|
| 324 |
+
for field in ("generated", "logits"):
|
| 325 |
+
np.testing.assert_array_equal(pred[field], predictions[task]["baseline"][field])
|
| 326 |
+
engineering[f"{task}_self_prefix_{component}_exact"] = True
|
| 327 |
+
rows = world["strict_2"]
|
| 328 |
+
_, edges = truth_path_details(world, rows)
|
| 329 |
+
common = selection["common"]
|
| 330 |
+
donor_atom_ok = np.ones(len(world["atomic"]), bool)
|
| 331 |
+
for label in ("experienced", "strict"):
|
| 332 |
+
recipients, facts = selection[label + "_recipients"], selection[label + "_atoms"]
|
| 333 |
+
donor_atom_ok[facts] = metrics["atomic"]["baseline"]["complete"][facts].astype(bool)
|
| 334 |
+
for component in ("full", "mlp"):
|
| 335 |
+
if not len(recipients):
|
| 336 |
+
continue
|
| 337 |
+
pred, _ = generate(
|
| 338 |
+
model,
|
| 339 |
+
rows[recipients],
|
| 340 |
+
separator,
|
| 341 |
+
repeats,
|
| 342 |
+
donor_atoms=world["atomic"][facts],
|
| 343 |
+
component=component,
|
| 344 |
+
)
|
| 345 |
+
m = prediction_metrics(pred, rows[recipients, -1])
|
| 346 |
+
key = f"same_{label}_{component}"
|
| 347 |
+
for field, value in {**pred, **m}.items():
|
| 348 |
+
arrays[key + "_" + field] = value
|
| 349 |
+
balanced = {k: query_means(v, recipients, len(rows)) for k, v in m.items()}
|
| 350 |
+
summaries[key] = {
|
| 351 |
+
"common_graph_pool": mean_metrics(balanced, common),
|
| 352 |
+
"all_available": mean_metrics(balanced, np.isfinite(balanced["complete"])),
|
| 353 |
+
}
|
| 354 |
+
known = metrics["atomic"]["baseline"]["complete"][edges].all(1)
|
| 355 |
+
for label in ("experienced", "strict"):
|
| 356 |
+
recipients, facts = selection[label + "_recipients"], selection[label + "_atoms"]
|
| 357 |
+
for recipient, fact in zip(recipients, facts, strict=True):
|
| 358 |
+
known[recipient] &= donor_atom_ok[fact]
|
| 359 |
+
arrays["same_common_known_mask"] = known & common
|
| 360 |
+
summaries["same_baseline"] = {
|
| 361 |
+
"common_graph_pool": mean_metrics(metrics["strict_2"]["baseline"], common),
|
| 362 |
+
"common_known_pool": mean_metrics(metrics["strict_2"]["baseline"], known & common),
|
| 363 |
+
}
|
| 364 |
+
for label in ("experienced", "strict"):
|
| 365 |
+
recipients = selection[label + "_recipients"]
|
| 366 |
+
for component in ("full", "mlp"):
|
| 367 |
+
key = f"same_{label}_{component}"
|
| 368 |
+
if key in summaries:
|
| 369 |
+
m = {
|
| 370 |
+
k: arrays[key + "_" + k] for k in ("answer", "complete", "eos", "nll", "margin")
|
| 371 |
+
}
|
| 372 |
+
balanced = {k: query_means(v, recipients, len(rows)) for k, v in m.items()}
|
| 373 |
+
summaries[key]["common_known_pool"] = mean_metrics(balanced, known & common)
|
| 374 |
+
for label in ("familiar", "strict"):
|
| 375 |
+
task = label + "_2"
|
| 376 |
+
recipients = selection[label + "_changed_recipients"]
|
| 377 |
+
facts = selection[label + "_changed_atoms"]
|
| 378 |
+
targets = selection[label + "_changed_targets"]
|
| 379 |
+
if not len(recipients):
|
| 380 |
+
continue
|
| 381 |
+
original = world[task][recipients]
|
| 382 |
+
counterfactual = original.copy()
|
| 383 |
+
counterfactual[:, 0] = world["atomic"][facts, 0]
|
| 384 |
+
counterfactual[:, -1] = targets
|
| 385 |
+
truth_path_details(world, counterfactual)
|
| 386 |
+
native_cf, _ = generate(model, counterfactual, separator, repeats)
|
| 387 |
+
values = {
|
| 388 |
+
"baseline": {k: v[recipients] for k, v in predictions[task]["baseline"].items()},
|
| 389 |
+
"counterfactual": native_cf,
|
| 390 |
+
}
|
| 391 |
+
for component in ("full", "mlp"):
|
| 392 |
+
values[component], _ = generate(
|
| 393 |
+
model,
|
| 394 |
+
original,
|
| 395 |
+
separator,
|
| 396 |
+
repeats,
|
| 397 |
+
donor_atoms=world["atomic"][facts],
|
| 398 |
+
component=component,
|
| 399 |
+
)
|
| 400 |
+
for name, pred in values.items():
|
| 401 |
+
key = f"changed_{label}_{name}"
|
| 402 |
+
m = prediction_metrics(pred, targets)
|
| 403 |
+
for field, vector in {**pred, **m}.items():
|
| 404 |
+
arrays[key + "_" + field] = vector
|
| 405 |
+
summaries[key] = mean_metrics(m)
|
| 406 |
+
arrays.update({"selection_" + k: v for k, v in selection.items()})
|
| 407 |
+
if model_digest(model) != before:
|
| 408 |
+
raise AssertionError("Intervention changed model parameters")
|
| 409 |
+
return arrays, {
|
| 410 |
+
"repeats": repeats,
|
| 411 |
+
"seconds": time.perf_counter() - started,
|
| 412 |
+
"weights_unchanged": True,
|
| 413 |
+
"model_sha256": before,
|
| 414 |
+
"engineering": engineering,
|
| 415 |
+
"conditions": summaries,
|
| 416 |
+
}
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/representation_alignment.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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Intermediate supervision and input-compatible states in complete causal GPTs.
|
| 2 |
+
|
| 3 |
+
The intervention observes the first executed block at the first relation token.
|
| 4 |
+
Every arm executes the same forward/backward graph. Ordinary full-token CE,
|
| 5 |
+
auxiliary entity CE, and state geometry are recorded separately.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import time
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
+
from torch.nn import functional as F
|
| 19 |
+
|
| 20 |
+
from .grok_depth import EpochStream, GraphStep, make_optimizer, utc, write_json
|
| 21 |
+
from .grok_loop_model import LoopGPT, flops
|
| 22 |
+
from .latent_scaling import build_world, construct, model_digest
|
| 23 |
+
from .storage_composition import data_digest, evaluate, file_hash, pack_sentences
|
| 24 |
+
from .storage_frontier import learning_rate
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class RepresentationGPT(LoopGPT):
|
| 28 |
+
"""Unchanged GPT/Loop computation, optionally exposing a causal early state."""
|
| 29 |
+
|
| 30 |
+
def forward(self, tokens, positions=None, repeats=None, return_bridge=False):
|
| 31 |
+
p = self.dropout if self.training else 0.0
|
| 32 |
+
x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device))
|
| 33 |
+
x = F.dropout(x, p=p, training=self.training)
|
| 34 |
+
bridge = None
|
| 35 |
+
for index, block in enumerate(self.iter_blocks(repeats)):
|
| 36 |
+
z = block.ln1(x)
|
| 37 |
+
batch, length, width = z.shape
|
| 38 |
+
a = block.attention
|
| 39 |
+
q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2)
|
| 40 |
+
y = F.scaled_dot_product_attention(
|
| 41 |
+
q.transpose(1, 2),
|
| 42 |
+
k.transpose(1, 2),
|
| 43 |
+
v.transpose(1, 2),
|
| 44 |
+
is_causal=True,
|
| 45 |
+
dropout_p=p,
|
| 46 |
+
)
|
| 47 |
+
y = a.proj(y.transpose(1, 2).reshape(batch, length, width))
|
| 48 |
+
x = x + F.dropout(y, p=p, training=self.training)
|
| 49 |
+
x = x + F.dropout(block.mlp(block.ln2(x)), p=p, training=self.training)
|
| 50 |
+
if index == 0 and return_bridge:
|
| 51 |
+
bridge = x[:, 3]
|
| 52 |
+
x = self.ln_final(x)
|
| 53 |
+
if positions is not None:
|
| 54 |
+
x = x[torch.arange(len(tokens), device=tokens.device)[:, None], positions]
|
| 55 |
+
logits = F.linear(x, self.token.weight)
|
| 56 |
+
return (logits, bridge) if return_bridge else logits
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def new_model(spec, device):
|
| 60 |
+
# Construct through the established initializer, then replace only the type.
|
| 61 |
+
model = construct(spec, device)
|
| 62 |
+
model.__class__ = RepresentationGPT
|
| 63 |
+
return model
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def pack_training(world):
|
| 67 |
+
strata = [world[k] for k in ("common_atomic", "train_composite", "anchor_atomic")]
|
| 68 |
+
tokens, labels = (
|
| 69 |
+
np.concatenate(parts)
|
| 70 |
+
for parts in zip(*(pack_sentences(rows) for rows in strata), strict=True)
|
| 71 |
+
)
|
| 72 |
+
# Column 2 is the atomic answer or the composition's first-hop answer.
|
| 73 |
+
# It never enters the composed input; it is an explicit auxiliary target.
|
| 74 |
+
targets = np.concatenate([rows[:, 2] for rows in strata])
|
| 75 |
+
return (tokens, labels, targets), [len(rows) for rows in strata]
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def objective(model, tokens, labels, targets, bridge_weight, alignment_weight):
|
| 79 |
+
logits, bridge = model(tokens, return_bridge=True)
|
| 80 |
+
text_ce = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100)
|
| 81 |
+
bridge_logits = F.linear(model.ln_final(bridge), model.token.weight)
|
| 82 |
+
bridge_ce = F.cross_entropy(bridge_logits, targets)
|
| 83 |
+
canonical = model.token(targets).detach()
|
| 84 |
+
alignment = (
|
| 85 |
+
(F.normalize(bridge, dim=-1) - F.normalize(canonical, dim=-1)).square().sum(-1).mean()
|
| 86 |
+
)
|
| 87 |
+
parts = torch.stack((text_ce, bridge_ce, alignment))
|
| 88 |
+
return text_ce + bridge_weight * bridge_ce + alignment_weight * alignment, parts
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class RepresentationStep(GraphStep):
|
| 92 |
+
def __init__(self, model, optimizer, table, batch_size, spec):
|
| 93 |
+
self.spec = spec
|
| 94 |
+
super().__init__(model, optimizer, table, batch_size)
|
| 95 |
+
|
| 96 |
+
def eager(self):
|
| 97 |
+
self.optimizer.zero_grad(set_to_none=False)
|
| 98 |
+
tokens, labels, targets = (part[self.index] for part in self.table)
|
| 99 |
+
loss, self.components = objective(
|
| 100 |
+
self.model,
|
| 101 |
+
tokens,
|
| 102 |
+
labels,
|
| 103 |
+
targets,
|
| 104 |
+
self.spec["bridge_weight"],
|
| 105 |
+
self.spec["alignment_weight"],
|
| 106 |
+
)
|
| 107 |
+
loss.backward()
|
| 108 |
+
norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True)
|
| 109 |
+
self.optimizer.step()
|
| 110 |
+
return loss, norm
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def run_name(spec):
|
| 114 |
+
return f"{spec['phase']}-w{spec['world']}-i{spec['initialization']}-{spec['arm']}"
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def train(spec, out, source, device):
|
| 118 |
+
out = Path(out)
|
| 119 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 120 |
+
if (out / "run.json").exists():
|
| 121 |
+
raise FileExistsError(f"Do not overwrite an attempt: {out}")
|
| 122 |
+
torch.set_num_threads(1)
|
| 123 |
+
torch.set_num_interop_threads(1)
|
| 124 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 125 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 126 |
+
torch.cuda.set_device(device)
|
| 127 |
+
started = time.perf_counter()
|
| 128 |
+
world = build_world(spec)
|
| 129 |
+
np.savez_compressed(out / "world.npz", **world)
|
| 130 |
+
arrays, sizes = pack_training(world)
|
| 131 |
+
model = new_model(spec, device)
|
| 132 |
+
initial_hash = model_digest(model)
|
| 133 |
+
write_json(
|
| 134 |
+
out / "run.json",
|
| 135 |
+
{
|
| 136 |
+
"spec": spec,
|
| 137 |
+
"source": source,
|
| 138 |
+
"world_sha256": data_digest(world),
|
| 139 |
+
"initial_model_sha256": initial_hash,
|
| 140 |
+
"pid": os.getpid(),
|
| 141 |
+
"gpu": device.index,
|
| 142 |
+
"gpu_name": torch.cuda.get_device_name(device),
|
| 143 |
+
"dtype": "float32",
|
| 144 |
+
"parameters": sum(p.numel() for p in model.parameters()),
|
| 145 |
+
"atomic_examples": sizes[0] + sizes[2],
|
| 146 |
+
"composition_examples": sizes[1],
|
| 147 |
+
"vocab_size": model.config.vocab_size,
|
| 148 |
+
},
|
| 149 |
+
)
|
| 150 |
+
table = tuple(torch.as_tensor(a, device=device) for a in arrays)
|
| 151 |
+
lr = torch.tensor(spec["lr"], device=device)
|
| 152 |
+
optimizer = make_optimizer(model, lr, spec["weight_decay"])
|
| 153 |
+
model.train()
|
| 154 |
+
graph = RepresentationStep(model, optimizer, table, spec["batch_size"], spec)
|
| 155 |
+
assert model_digest(model) == initial_hash, "CUDA capture changed initialization"
|
| 156 |
+
streams = [EpochStream(n, spec["stream_seed"] + j) for j, n in enumerate(sizes)]
|
| 157 |
+
offsets = np.cumsum([0, *sizes[:-1]])
|
| 158 |
+
counts = [np.zeros(n, dtype=np.int64) for n in sizes]
|
| 159 |
+
input_hash = hashlib.sha256()
|
| 160 |
+
history, step, training_seconds = [], 0, 0.0
|
| 161 |
+
flop_step = flops(model.config, spec["repeats"], spec["batch_size"], 9, output_positions=9)
|
| 162 |
+
# All arms also execute the auxiliary readout and normalization.
|
| 163 |
+
flop_step += 6 * spec["batch_size"] * model.config.width * model.config.vocab_size
|
| 164 |
+
|
| 165 |
+
def measure():
|
| 166 |
+
metrics, predictions = evaluate(model, world, "low", device)
|
| 167 |
+
parts = graph.components.detach().cpu().tolist() if step else [None] * 3
|
| 168 |
+
row = {
|
| 169 |
+
"step": step,
|
| 170 |
+
"metrics": metrics,
|
| 171 |
+
"text_ce": parts[0],
|
| 172 |
+
"bridge_ce": parts[1],
|
| 173 |
+
"alignment_loss": parts[2],
|
| 174 |
+
"training_seconds": training_seconds,
|
| 175 |
+
"wall_seconds": time.perf_counter() - started,
|
| 176 |
+
"examples": step * spec["batch_size"],
|
| 177 |
+
"supervised_tokens": step * spec["batch_size"] // 3 * (7 + 9 + 7),
|
| 178 |
+
"auxiliary_target_presentations": step * spec["batch_size"],
|
| 179 |
+
"estimated_matmul_training_flops": step * flop_step,
|
| 180 |
+
"composition_epochs": step * spec["batch_size"] / 3 / sizes[1],
|
| 181 |
+
}
|
| 182 |
+
history.append(row)
|
| 183 |
+
write_json(out / "learning.json", history)
|
| 184 |
+
np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions)
|
| 185 |
+
write_json(out / "status.json", {"state": "running", "step": step, "budget": spec["steps"]})
|
| 186 |
+
print(
|
| 187 |
+
json.dumps(
|
| 188 |
+
{
|
| 189 |
+
"run": run_name(spec),
|
| 190 |
+
"step": step,
|
| 191 |
+
"atomic": metrics["common_atomic"]["accuracy"],
|
| 192 |
+
"train": metrics["train_composite"]["accuracy"],
|
| 193 |
+
"familiar": metrics["familiar_test"]["accuracy"],
|
| 194 |
+
"strict": metrics["strict_test"]["accuracy"],
|
| 195 |
+
}
|
| 196 |
+
),
|
| 197 |
+
flush=True,
|
| 198 |
+
)
|
| 199 |
+
model.train()
|
| 200 |
+
|
| 201 |
+
measure()
|
| 202 |
+
for end in spec["nodes"][1:]:
|
| 203 |
+
torch.cuda.synchronize(device)
|
| 204 |
+
began = time.perf_counter()
|
| 205 |
+
while step < end:
|
| 206 |
+
n = min(128, end - step)
|
| 207 |
+
indices = []
|
| 208 |
+
for j, stream in enumerate(streams):
|
| 209 |
+
drawn = stream.take(n * spec["batch_size"] // 3).reshape(n, -1)
|
| 210 |
+
counts[j] += np.bincount(drawn.ravel(), minlength=sizes[j])
|
| 211 |
+
indices.append(drawn + offsets[j])
|
| 212 |
+
indices = np.concatenate(indices, axis=1)
|
| 213 |
+
input_hash.update(indices.tobytes())
|
| 214 |
+
indices = torch.as_tensor(indices, device=device)
|
| 215 |
+
for j in range(n):
|
| 216 |
+
lr.fill_(learning_rate(spec, step + j + 1))
|
| 217 |
+
loss = graph(indices[j])
|
| 218 |
+
step += n
|
| 219 |
+
torch.cuda.synchronize(device)
|
| 220 |
+
training_seconds += time.perf_counter() - began
|
| 221 |
+
if not np.isfinite(float(loss)):
|
| 222 |
+
raise FloatingPointError(f"Nonfinite objective at {step}")
|
| 223 |
+
measure()
|
| 224 |
+
model.eval()
|
| 225 |
+
torch.save(
|
| 226 |
+
{"spec": spec, "model": model.state_dict(), "optimizer": optimizer.state_dict()},
|
| 227 |
+
out / "model.pt",
|
| 228 |
+
)
|
| 229 |
+
np.savez_compressed(out / "exposures.npz", **{f"stratum{j}": c for j, c in enumerate(counts)})
|
| 230 |
+
write_json(
|
| 231 |
+
out / "complete.json",
|
| 232 |
+
{
|
| 233 |
+
"spec": spec,
|
| 234 |
+
"source": source,
|
| 235 |
+
"finished_utc": utc(),
|
| 236 |
+
"metrics": history[-1]["metrics"],
|
| 237 |
+
"training_seconds": training_seconds,
|
| 238 |
+
"world_sha256": data_digest(world),
|
| 239 |
+
"initial_model_sha256": initial_hash,
|
| 240 |
+
"sample_stream_sha256": input_hash.hexdigest(),
|
| 241 |
+
"model_sha256": file_hash(out / "model.pt"),
|
| 242 |
+
},
|
| 243 |
+
)
|
| 244 |
+
write_json(out / "status.json", {"state": "complete", "step": step})
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def audit(out, device):
|
| 248 |
+
out = Path(out)
|
| 249 |
+
# Match trainer arithmetic before comparing generated tokens and NLL.
|
| 250 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 251 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 252 |
+
payload = torch.load(out / "model.pt", map_location="cpu", weights_only=False)
|
| 253 |
+
spec = payload["spec"]
|
| 254 |
+
model = new_model(spec, device)
|
| 255 |
+
model.load_state_dict(payload["model"])
|
| 256 |
+
world = build_world(spec)
|
| 257 |
+
metrics, predictions = evaluate(model, world, "low", device)
|
| 258 |
+
saved = np.load(out / f"predictions-{spec['steps']:06d}.npz")
|
| 259 |
+
max_nll_error = 0.0
|
| 260 |
+
for key, actual in predictions.items():
|
| 261 |
+
if key.endswith("nll"):
|
| 262 |
+
max_nll_error = max(max_nll_error, float(np.max(np.abs(actual - saved[key]))))
|
| 263 |
+
np.testing.assert_allclose(actual, saved[key], rtol=1e-5, atol=1e-5)
|
| 264 |
+
else:
|
| 265 |
+
np.testing.assert_array_equal(actual, saved[key])
|
| 266 |
+
write_json(
|
| 267 |
+
out / "audit.json",
|
| 268 |
+
{"passed": True, "metrics": metrics, "max_nll_error": max_nll_error, "allow_tf32": True},
|
| 269 |
+
)
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/small_lm_composition.py
ADDED
|
@@ -0,0 +1,543 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Development comparison in an unchanged, fully trained pretrained Qwen LM.
|
| 2 |
+
|
| 3 |
+
Only training document grouping differs. All weights, native embeddings,
|
| 4 |
+
residuals, attention, norms and distinct MLP layers are retained.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import hashlib
|
| 10 |
+
import json
|
| 11 |
+
import math
|
| 12 |
+
import re
|
| 13 |
+
import shutil
|
| 14 |
+
import time
|
| 15 |
+
from collections import Counter
|
| 16 |
+
from datetime import datetime, timezone
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
import transformers
|
| 22 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 23 |
+
|
| 24 |
+
QUESTIONS = (
|
| 25 |
+
(
|
| 26 |
+
"Who is {head}'s mentor?",
|
| 27 |
+
"Who mentors {head}?",
|
| 28 |
+
"Name the mentor of {head}.",
|
| 29 |
+
"Who is the mentor of {head}?",
|
| 30 |
+
),
|
| 31 |
+
(
|
| 32 |
+
"Which city does {bridge} live in?",
|
| 33 |
+
"What city is {bridge}'s home?",
|
| 34 |
+
"Where does {bridge} live?",
|
| 35 |
+
"Name the city where {bridge} lives.",
|
| 36 |
+
),
|
| 37 |
+
(
|
| 38 |
+
"Which city does {head}'s mentor live in?",
|
| 39 |
+
"What city is home to {head}'s mentor?",
|
| 40 |
+
"Where does the mentor of {head} live?",
|
| 41 |
+
"Name the city where {head}'s mentor lives.",
|
| 42 |
+
),
|
| 43 |
+
)
|
| 44 |
+
CITIES = (
|
| 45 |
+
"Paris Rome London Berlin Tokyo Oslo Lima Cairo Delhi Seoul Dublin Madrid "
|
| 46 |
+
"Vienna Boston Sydney Lisbon"
|
| 47 |
+
).split()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def read(path):
|
| 51 |
+
return json.loads(Path(path).read_text())
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def write(path, value):
|
| 55 |
+
path = Path(path)
|
| 56 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 57 |
+
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def sha(path):
|
| 61 |
+
with Path(path).open("rb") as handle:
|
| 62 |
+
return hashlib.file_digest(handle, "sha256").hexdigest()
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def now():
|
| 66 |
+
return datetime.now(timezone.utc).isoformat()
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def build_world(config):
|
| 70 |
+
first = (
|
| 71 |
+
"Rhea Mara Evan Luca Nora Iris Owen Hugo Cora Theo Nina Leon Vera Finn Dana Arlo"
|
| 72 |
+
).split()
|
| 73 |
+
last = "Hale Vale Mercer Rowan Keane Flint Arden Voss North Lark".split()
|
| 74 |
+
names = [f"{a} {b}" for a in first for b in last]
|
| 75 |
+
n = config["target_triples"] + config["background_triples"]
|
| 76 |
+
assert 2 * n <= len(names)
|
| 77 |
+
rng = np.random.default_rng(config["world_seed"])
|
| 78 |
+
names = rng.permutation(names).tolist()
|
| 79 |
+
rows = []
|
| 80 |
+
for split, count in (
|
| 81 |
+
("target", config["target_triples"]),
|
| 82 |
+
("background", config["background_triples"]),
|
| 83 |
+
):
|
| 84 |
+
cities = rng.permutation([CITIES[i % len(CITIES)] for i in range(count)])
|
| 85 |
+
for city in cities:
|
| 86 |
+
i = len(rows)
|
| 87 |
+
rows.append(
|
| 88 |
+
dict(id=i, split=split, head=names[2 * i], bridge=names[2 * i + 1], city=str(city))
|
| 89 |
+
)
|
| 90 |
+
return rows
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def prompt(row, hop, variant=0):
|
| 94 |
+
return "Fictional registry.\nQuestion: " + QUESTIONS[hop][variant].format(**row) + "\nAnswer:"
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def answer(row, hop):
|
| 98 |
+
return row["bridge"] if hop == 0 else row["city"]
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def encode_document(tokenizer, row, hop, variant):
|
| 102 |
+
ids = tokenizer.encode(
|
| 103 |
+
prompt(row, hop, variant) + " " + answer(row, hop) + ".", add_special_tokens=False
|
| 104 |
+
) + [tokenizer.eos_token_id]
|
| 105 |
+
# The initial token of each atomic document has no within-document predecessor.
|
| 106 |
+
# It remains unscored when documents are joined, preserving every target token.
|
| 107 |
+
return dict(ids=ids, labels=[-100, *ids[1:]], triple=row["id"], hop=hop, variant=variant)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def corpus(tokenizer, world):
|
| 111 |
+
records = {}
|
| 112 |
+
for row in world:
|
| 113 |
+
hops = range(3) if row["split"] == "background" else range(2)
|
| 114 |
+
for hop in hops:
|
| 115 |
+
for variant in range(4):
|
| 116 |
+
records[row["id"], hop, variant] = encode_document(tokenizer, row, hop, variant)
|
| 117 |
+
return records
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def stream(config, world):
|
| 121 |
+
rng = np.random.default_rng(config["training_seed"])
|
| 122 |
+
background = [r["id"] for r in world if r["split"] == "background"]
|
| 123 |
+
result = []
|
| 124 |
+
for _ in range(config["steps"]):
|
| 125 |
+
pairs = [
|
| 126 |
+
[int(i), int(v)]
|
| 127 |
+
for i, v in zip(
|
| 128 |
+
rng.choice(len(world), config["atomic_pairs_per_step"], replace=False),
|
| 129 |
+
rng.integers(4, size=config["atomic_pairs_per_step"]),
|
| 130 |
+
strict=True,
|
| 131 |
+
)
|
| 132 |
+
]
|
| 133 |
+
compositions = [
|
| 134 |
+
[int(i), int(v)]
|
| 135 |
+
for i, v in zip(
|
| 136 |
+
rng.choice(background, config["background_compositions_per_step"], replace=False),
|
| 137 |
+
rng.integers(4, size=config["background_compositions_per_step"]),
|
| 138 |
+
strict=True,
|
| 139 |
+
)
|
| 140 |
+
]
|
| 141 |
+
result.append(dict(pairs=pairs, compositions=compositions))
|
| 142 |
+
return result
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def documents(records, batch, arm):
|
| 146 |
+
docs = []
|
| 147 |
+
for i, v in batch["pairs"]:
|
| 148 |
+
first, second = records[i, 0, v], records[i, 1, v]
|
| 149 |
+
if arm == "separate":
|
| 150 |
+
docs.extend([first, second])
|
| 151 |
+
elif arm == "linked":
|
| 152 |
+
docs.append(
|
| 153 |
+
dict(ids=first["ids"] + second["ids"], labels=first["labels"] + second["labels"])
|
| 154 |
+
)
|
| 155 |
+
else:
|
| 156 |
+
raise ValueError(arm)
|
| 157 |
+
docs.extend(records[i, 2, v] for i, v in batch["compositions"])
|
| 158 |
+
return docs
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def batch_tensors(docs, pad_id, device):
|
| 162 |
+
width = max(len(d["ids"]) for d in docs)
|
| 163 |
+
ids = torch.full((len(docs), width), pad_id, device=device, dtype=torch.long)
|
| 164 |
+
labels = torch.full_like(ids, -100)
|
| 165 |
+
mask = torch.zeros_like(ids)
|
| 166 |
+
for i, doc in enumerate(docs):
|
| 167 |
+
n = len(doc["ids"])
|
| 168 |
+
ids[i, :n] = torch.tensor(doc["ids"], device=device)
|
| 169 |
+
labels[i, :n] = torch.tensor(doc["labels"], device=device)
|
| 170 |
+
mask[i, :n] = 1
|
| 171 |
+
return dict(input_ids=ids, attention_mask=mask, labels=labels)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def normalize(text):
|
| 175 |
+
return re.sub(r"\s+", " ", text.strip().rstrip(".").strip()).casefold()
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def grade(text, gold):
|
| 179 |
+
first_line = text.strip().split("\n")[0]
|
| 180 |
+
return normalize(first_line) == normalize(gold)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def evaluation_rows(world):
|
| 184 |
+
return [
|
| 185 |
+
dict(**row, hop=hop, prompt=prompt(row, hop), answer=answer(row, hop))
|
| 186 |
+
for row in world
|
| 187 |
+
for hop in (range(3) if row["split"] == "target" else [2])
|
| 188 |
+
]
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
@torch.inference_mode()
|
| 192 |
+
def evaluate(model, tokenizer, world, config):
|
| 193 |
+
model.eval()
|
| 194 |
+
tokenizer.padding_side = "left"
|
| 195 |
+
rows = evaluation_rows(world)
|
| 196 |
+
results = []
|
| 197 |
+
for start in range(0, len(rows), config["eval_batch"]):
|
| 198 |
+
chunk = rows[start : start + config["eval_batch"]]
|
| 199 |
+
enc = tokenizer(
|
| 200 |
+
[r["prompt"] for r in chunk],
|
| 201 |
+
padding=True,
|
| 202 |
+
return_tensors="pt",
|
| 203 |
+
add_special_tokens=False,
|
| 204 |
+
).to(config["device"])
|
| 205 |
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 206 |
+
generated = model.generate(
|
| 207 |
+
**enc,
|
| 208 |
+
do_sample=False,
|
| 209 |
+
max_new_tokens=config["max_new_tokens"],
|
| 210 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 211 |
+
eos_token_id=tokenizer.eos_token_id,
|
| 212 |
+
use_cache=True,
|
| 213 |
+
)[:, enc.input_ids.shape[1] :]
|
| 214 |
+
for row, tokens in zip(chunk, generated.cpu().tolist(), strict=True):
|
| 215 |
+
# Drop batching padding after the first EOS; retain the actual generated EOS.
|
| 216 |
+
if tokenizer.eos_token_id in tokens:
|
| 217 |
+
tokens = tokens[: tokens.index(tokenizer.eos_token_id) + 1]
|
| 218 |
+
text = tokenizer.decode(tokens, skip_special_tokens=True)
|
| 219 |
+
results.append(
|
| 220 |
+
dict(**row, tokens=tokens, text=text, correct=grade(text, row["answer"]))
|
| 221 |
+
)
|
| 222 |
+
return results
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def score(rows):
|
| 226 |
+
result = {}
|
| 227 |
+
for split, hop, key in (
|
| 228 |
+
("target", 0, "first_hop"),
|
| 229 |
+
("target", 1, "second_hop"),
|
| 230 |
+
("target", 2, "two_hop"),
|
| 231 |
+
("background", 2, "background_two_hop"),
|
| 232 |
+
):
|
| 233 |
+
selected = [r for r in rows if r["split"] == split and r["hop"] == hop]
|
| 234 |
+
result[key] = sum(r["correct"] for r in selected) / len(selected)
|
| 235 |
+
indexed = {(r["id"], r["hop"]): r for r in rows if r["split"] == "target"}
|
| 236 |
+
mastered = [
|
| 237 |
+
i for i, h in indexed if h == 0 and indexed[i, 0]["correct"] and indexed[i, 1]["correct"]
|
| 238 |
+
]
|
| 239 |
+
result["both_atomic_coverage"] = len(mastered) / sum(h == 0 for _, h in indexed)
|
| 240 |
+
result["two_hop_if_both_atomic"] = (
|
| 241 |
+
sum(indexed[i, 2]["correct"] for i in mastered) / len(mastered) if mastered else None
|
| 242 |
+
)
|
| 243 |
+
return result
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def prepare(config_path):
|
| 247 |
+
config = read(config_path)
|
| 248 |
+
art = Path(config["artifact_root"])
|
| 249 |
+
if (art / "lock.json").exists():
|
| 250 |
+
raise RuntimeError("Development lock already exists; do not overwrite it.")
|
| 251 |
+
tokenizer = AutoTokenizer.from_pretrained(config["model_path"], local_files_only=True)
|
| 252 |
+
world = build_world(config)
|
| 253 |
+
batches = stream(config, world)
|
| 254 |
+
records = corpus(tokenizer, world)
|
| 255 |
+
assert all(h != 2 or world[i]["split"] == "background" for i, h, _ in records)
|
| 256 |
+
stats = {}
|
| 257 |
+
for arm in config["arms"]:
|
| 258 |
+
counts = Counter()
|
| 259 |
+
token_counts = Counter()
|
| 260 |
+
input_tokens = supervised_tokens = padded_tokens = attention_cells = 0
|
| 261 |
+
for batch in batches:
|
| 262 |
+
docs = documents(records, batch, arm)
|
| 263 |
+
for d in docs:
|
| 264 |
+
input_tokens += len(d["ids"])
|
| 265 |
+
supervised_tokens += sum(t != -100 for t in d["labels"])
|
| 266 |
+
counts.update(t for t in d["labels"] if t != -100)
|
| 267 |
+
token_counts.update(d["ids"])
|
| 268 |
+
width = max(len(d["ids"]) for d in docs)
|
| 269 |
+
padded_tokens += len(docs) * width
|
| 270 |
+
attention_cells += len(docs) * width**2
|
| 271 |
+
stats[arm] = dict(
|
| 272 |
+
input_tokens=input_tokens,
|
| 273 |
+
supervised_tokens=supervised_tokens,
|
| 274 |
+
padded_tokens=padded_tokens,
|
| 275 |
+
attention_cells=attention_cells,
|
| 276 |
+
target_token_counts=sorted(counts.items()),
|
| 277 |
+
input_token_counts=sorted(token_counts.items()),
|
| 278 |
+
)
|
| 279 |
+
for key in ("input_tokens", "supervised_tokens", "target_token_counts", "input_token_counts"):
|
| 280 |
+
assert stats["separate"][key] == stats["linked"][key], key
|
| 281 |
+
write(art / "world.json", world)
|
| 282 |
+
write(art / "stream.json", batches)
|
| 283 |
+
write(art / "data-audit.json", dict(status="passed", stats=stats, target_composition_labels=0))
|
| 284 |
+
sources = [
|
| 285 |
+
str(config_path),
|
| 286 |
+
__file__,
|
| 287 |
+
"scripts/run_small_lm_composition.py",
|
| 288 |
+
"tests/test_small_lm_composition.py",
|
| 289 |
+
str(art / "development-plan.md"),
|
| 290 |
+
]
|
| 291 |
+
frozen = {}
|
| 292 |
+
for source in sources:
|
| 293 |
+
path = Path(source).resolve()
|
| 294 |
+
relative = path.relative_to(Path.cwd())
|
| 295 |
+
dest = art / "source" / relative
|
| 296 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 297 |
+
shutil.copyfile(path, dest)
|
| 298 |
+
frozen[str(relative)] = sha(path)
|
| 299 |
+
model_files = {
|
| 300 |
+
str(p): sha(p)
|
| 301 |
+
for p in Path(config["model_path"]).iterdir()
|
| 302 |
+
if p.suffix in (".safetensors", ".json")
|
| 303 |
+
}
|
| 304 |
+
write(
|
| 305 |
+
art / "lock.json",
|
| 306 |
+
dict(
|
| 307 |
+
status="locked_before_training",
|
| 308 |
+
utc=now(),
|
| 309 |
+
sources=frozen,
|
| 310 |
+
model_files=model_files,
|
| 311 |
+
world_sha256=sha(art / "world.json"),
|
| 312 |
+
stream_sha256=sha(art / "stream.json"),
|
| 313 |
+
),
|
| 314 |
+
)
|
| 315 |
+
print(
|
| 316 |
+
json.dumps(
|
| 317 |
+
{
|
| 318 |
+
"status": "prepared",
|
| 319 |
+
"stats": {
|
| 320 |
+
a: {k: v for k, v in s.items() if not k.endswith("counts")}
|
| 321 |
+
for a, s in stats.items()
|
| 322 |
+
},
|
| 323 |
+
}
|
| 324 |
+
),
|
| 325 |
+
flush=True,
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def parameter_samples(model):
|
| 330 |
+
names = [
|
| 331 |
+
"model.embed_tokens.weight",
|
| 332 |
+
"model.layers.0.self_attn.q_proj.weight",
|
| 333 |
+
"model.layers.0.mlp.down_proj.weight",
|
| 334 |
+
"model.layers.0.input_layernorm.weight",
|
| 335 |
+
"model.layers.27.self_attn.o_proj.weight",
|
| 336 |
+
"model.layers.27.mlp.down_proj.weight",
|
| 337 |
+
]
|
| 338 |
+
params = dict(model.named_parameters())
|
| 339 |
+
return {n: params[n].detach().flatten()[:4096].clone() for n in names}
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def train(config_path, arm):
|
| 343 |
+
config = read(config_path)
|
| 344 |
+
assert arm in config["arms"]
|
| 345 |
+
art = Path(config["artifact_root"])
|
| 346 |
+
lock = read(art / "lock.json")
|
| 347 |
+
for path, expected in lock["sources"].items():
|
| 348 |
+
assert sha(path) == expected, path
|
| 349 |
+
for path, expected in lock["model_files"].items():
|
| 350 |
+
assert sha(path) == expected, path
|
| 351 |
+
assert sha(art / "world.json") == lock["world_sha256"]
|
| 352 |
+
assert sha(art / "stream.json") == lock["stream_sha256"]
|
| 353 |
+
out = Path(config["output_root"]) / arm
|
| 354 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 355 |
+
if (out / "status.json").exists():
|
| 356 |
+
raise RuntimeError("A run record already exists; preserve it and use a new output root.")
|
| 357 |
+
write(out / "status.json", dict(status="running", arm=arm, utc=now()))
|
| 358 |
+
begun = time.perf_counter()
|
| 359 |
+
torch.set_num_threads(config["cpu_threads"])
|
| 360 |
+
torch.manual_seed(config["training_seed"])
|
| 361 |
+
torch.backends.cuda.matmul.allow_tf32 = False
|
| 362 |
+
torch.backends.cudnn.allow_tf32 = False
|
| 363 |
+
torch.cuda.set_device(config["device"])
|
| 364 |
+
torch.cuda.reset_peak_memory_stats()
|
| 365 |
+
tokenizer = AutoTokenizer.from_pretrained(config["model_path"], local_files_only=True)
|
| 366 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 367 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 368 |
+
config["model_path"],
|
| 369 |
+
torch_dtype=torch.float32,
|
| 370 |
+
attn_implementation="sdpa",
|
| 371 |
+
local_files_only=True,
|
| 372 |
+
).to(config["device"])
|
| 373 |
+
model.requires_grad_(True)
|
| 374 |
+
assert all(p.requires_grad for p in model.parameters())
|
| 375 |
+
assert model.config.num_hidden_layers == 28 and model.config.hidden_size == 1024
|
| 376 |
+
assert len({id(layer.mlp) for layer in model.model.layers}) == 28
|
| 377 |
+
samples = parameter_samples(model)
|
| 378 |
+
world, batches = read(art / "world.json"), read(art / "stream.json")
|
| 379 |
+
records = corpus(tokenizer, world)
|
| 380 |
+
optimizer = torch.optim.AdamW(
|
| 381 |
+
model.parameters(),
|
| 382 |
+
lr=config["learning_rate"],
|
| 383 |
+
weight_decay=config["weight_decay"],
|
| 384 |
+
fused=True,
|
| 385 |
+
)
|
| 386 |
+
curve = []
|
| 387 |
+
token_count = 0
|
| 388 |
+
train_seconds = 0.0
|
| 389 |
+
initial_gradients = {}
|
| 390 |
+
for step in range(config["steps"] + 1):
|
| 391 |
+
if step in config["nodes"]:
|
| 392 |
+
rows = evaluate(model, tokenizer, world, config)
|
| 393 |
+
write(out / f"predictions-{step:05d}.json", rows)
|
| 394 |
+
record = dict(step=step, **score(rows))
|
| 395 |
+
curve.append(record)
|
| 396 |
+
write(out / "curve.json", curve)
|
| 397 |
+
print(json.dumps(dict(arm=arm, **record)), flush=True)
|
| 398 |
+
if step == config["steps"]:
|
| 399 |
+
break
|
| 400 |
+
rate = config["minimum_learning_rate"] + 0.5 * (
|
| 401 |
+
config["learning_rate"] - config["minimum_learning_rate"]
|
| 402 |
+
) * (
|
| 403 |
+
1
|
| 404 |
+
+ math.cos(
|
| 405 |
+
math.pi
|
| 406 |
+
* max(0, step - config["warmup_steps"])
|
| 407 |
+
/ (config["steps"] - config["warmup_steps"])
|
| 408 |
+
)
|
| 409 |
+
)
|
| 410 |
+
rate *= min(1.0, (step + 1) / config["warmup_steps"])
|
| 411 |
+
for group in optimizer.param_groups:
|
| 412 |
+
group["lr"] = rate
|
| 413 |
+
model.train()
|
| 414 |
+
docs = documents(records, batches[step], arm)
|
| 415 |
+
inputs = batch_tensors(docs, tokenizer.pad_token_id, config["device"])
|
| 416 |
+
token_count += int(inputs["labels"].ne(-100).sum())
|
| 417 |
+
torch.cuda.synchronize()
|
| 418 |
+
tick = time.perf_counter()
|
| 419 |
+
optimizer.zero_grad(set_to_none=True)
|
| 420 |
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 421 |
+
loss = model(**inputs, use_cache=False).loss
|
| 422 |
+
assert torch.isfinite(loss), float(loss)
|
| 423 |
+
loss.backward()
|
| 424 |
+
if step == 0:
|
| 425 |
+
for name, p in model.named_parameters():
|
| 426 |
+
assert p.grad is not None and torch.isfinite(p.grad).all(), name
|
| 427 |
+
if name in samples:
|
| 428 |
+
initial_gradients[name] = float(p.grad.norm())
|
| 429 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), config["gradient_clip"])
|
| 430 |
+
optimizer.step()
|
| 431 |
+
torch.cuda.synchronize()
|
| 432 |
+
train_seconds += time.perf_counter() - tick
|
| 433 |
+
if (step + 1) % 32 == 0:
|
| 434 |
+
print(
|
| 435 |
+
json.dumps(
|
| 436 |
+
dict(
|
| 437 |
+
arm=arm,
|
| 438 |
+
step=step + 1,
|
| 439 |
+
loss=float(loss),
|
| 440 |
+
learning_rate=rate,
|
| 441 |
+
train_seconds=train_seconds,
|
| 442 |
+
)
|
| 443 |
+
),
|
| 444 |
+
flush=True,
|
| 445 |
+
)
|
| 446 |
+
changed = {
|
| 447 |
+
n: bool(not torch.equal(old, parameter_samples(model)[n])) for n, old in samples.items()
|
| 448 |
+
}
|
| 449 |
+
assert all(changed.values()), changed
|
| 450 |
+
parameter_count = sum(p.numel() for p in model.parameters())
|
| 451 |
+
model.save_pretrained(out / "model", safe_serialization=True)
|
| 452 |
+
tokenizer.save_pretrained(out / "model")
|
| 453 |
+
final_rows = rows
|
| 454 |
+
del optimizer, model, samples, inputs, loss
|
| 455 |
+
torch.cuda.empty_cache()
|
| 456 |
+
reloaded = AutoModelForCausalLM.from_pretrained(
|
| 457 |
+
out / "model",
|
| 458 |
+
torch_dtype=torch.float32,
|
| 459 |
+
attn_implementation="sdpa",
|
| 460 |
+
local_files_only=True,
|
| 461 |
+
).to(config["device"])
|
| 462 |
+
reloaded_rows = evaluate(reloaded, tokenizer, world, config)
|
| 463 |
+
assert [r["tokens"] for r in final_rows] == [r["tokens"] for r in reloaded_rows]
|
| 464 |
+
write(
|
| 465 |
+
out / "reload-audit.json",
|
| 466 |
+
dict(status="passed", predictions=len(final_rows), exact_generated_tokens=True),
|
| 467 |
+
)
|
| 468 |
+
budget = read(art / "data-audit.json")["stats"][arm]
|
| 469 |
+
assert token_count == budget["supervised_tokens"]
|
| 470 |
+
summary = dict(
|
| 471 |
+
status="complete",
|
| 472 |
+
phase="development",
|
| 473 |
+
arm=arm,
|
| 474 |
+
utc=now(),
|
| 475 |
+
metrics=score(final_rows),
|
| 476 |
+
model_repo=config["model_repo"],
|
| 477 |
+
model_revision=config["model_revision"],
|
| 478 |
+
lock_sha256=sha(art / "lock.json"),
|
| 479 |
+
parameter_count=parameter_count,
|
| 480 |
+
trainable_parameters=parameter_count,
|
| 481 |
+
sampled_parameters_changed=changed,
|
| 482 |
+
initial_sampled_gradient_norms=initial_gradients,
|
| 483 |
+
budget={k: v for k, v in budget.items() if not k.endswith("counts")},
|
| 484 |
+
updates=config["steps"],
|
| 485 |
+
train_seconds=train_seconds,
|
| 486 |
+
process_seconds=time.perf_counter() - begun,
|
| 487 |
+
peak_gpu_bytes=torch.cuda.max_memory_allocated(),
|
| 488 |
+
torch_version=torch.__version__,
|
| 489 |
+
transformers_version=transformers.__version__,
|
| 490 |
+
gpu=torch.cuda.get_device_name(),
|
| 491 |
+
train_weight_dtype="float32",
|
| 492 |
+
forward_dtype="bfloat16 autocast",
|
| 493 |
+
tf32=False,
|
| 494 |
+
checkpoint_files={str(p): sha(p) for p in (out / "model").glob("*.safetensors")},
|
| 495 |
+
)
|
| 496 |
+
write(out / "summary.json", summary)
|
| 497 |
+
write(out / "status.json", dict(status="complete", utc=now()))
|
| 498 |
+
print(json.dumps(summary), flush=True)
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
def report(config_path):
|
| 502 |
+
config = read(config_path)
|
| 503 |
+
art = Path(config["artifact_root"])
|
| 504 |
+
runs, predictions = {}, {}
|
| 505 |
+
for arm in config["arms"]:
|
| 506 |
+
out = Path(config["output_root"]) / arm
|
| 507 |
+
runs[arm] = read(out / "summary.json")
|
| 508 |
+
assert runs[arm]["status"] == "complete"
|
| 509 |
+
assert read(out / "reload-audit.json")["status"] == "passed"
|
| 510 |
+
rows = read(out / f"predictions-{config['steps']:05d}.json")
|
| 511 |
+
assert score(rows) == runs[arm]["metrics"]
|
| 512 |
+
predictions[arm] = {(r["id"], r["hop"]): r for r in rows if r["split"] == "target"}
|
| 513 |
+
common = [
|
| 514 |
+
i
|
| 515 |
+
for i, h in predictions["separate"]
|
| 516 |
+
if h == 0
|
| 517 |
+
and all(predictions[a][i, hop]["correct"] for a in config["arms"] for hop in (0, 1))
|
| 518 |
+
]
|
| 519 |
+
conditional = {
|
| 520 |
+
a: sum(predictions[a][i, 2]["correct"] for i in common) / len(common) if common else None
|
| 521 |
+
for a in config["arms"]
|
| 522 |
+
}
|
| 523 |
+
result = dict(
|
| 524 |
+
status="complete",
|
| 525 |
+
phase="development_only",
|
| 526 |
+
utc=now(),
|
| 527 |
+
runs=runs,
|
| 528 |
+
common_atomic_n=len(common),
|
| 529 |
+
common_atomic_coverage=len(common) / config["target_triples"],
|
| 530 |
+
common_atomic_two_hop=conditional,
|
| 531 |
+
two_hop_difference=runs["linked"]["metrics"]["two_hop"]
|
| 532 |
+
- runs["separate"]["metrics"]["two_hop"],
|
| 533 |
+
notes=[
|
| 534 |
+
"One synthetic world and one training seed; no independent confirmation.",
|
| 535 |
+
"Natural-language fictional facts; original pretrained Qwen architecture.",
|
| 536 |
+
"Exact fact, input-token and supervised-token exposure match.",
|
| 537 |
+
"Document grouping changes context, positions and attention work.",
|
| 538 |
+
"Linked training co-presents the head and final city; not zero cooccurrence.",
|
| 539 |
+
"This behavior comparison does not uniquely identify an MLP mechanism.",
|
| 540 |
+
],
|
| 541 |
+
)
|
| 542 |
+
write(art / "summary.json", result)
|
| 543 |
+
print(json.dumps({k: v for k, v in result.items() if k != "runs"}), flush=True)
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/small_lm_followup.py
ADDED
|
@@ -0,0 +1,558 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small full-Qwen development: matched rehearsal, pairing, and factual updates."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import copy
|
| 6 |
+
import itertools
|
| 7 |
+
import json
|
| 8 |
+
import math
|
| 9 |
+
import shutil
|
| 10 |
+
import time
|
| 11 |
+
from collections import Counter
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import torch
|
| 16 |
+
import transformers
|
| 17 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 18 |
+
|
| 19 |
+
from . import small_lm_composition as base
|
| 20 |
+
|
| 21 |
+
HELDOUT = (
|
| 22 |
+
"Give the name of the person mentoring {head}.",
|
| 23 |
+
"In which city is {bridge} living?",
|
| 24 |
+
"In which city is the person mentoring {head} living?",
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def pairing_stream(config, world):
|
| 29 |
+
batches = base.stream(config, world)
|
| 30 |
+
rng = np.random.default_rng(config["pairing_seed"])
|
| 31 |
+
for batch in batches:
|
| 32 |
+
pairs = batch["pairs"]
|
| 33 |
+
|
| 34 |
+
def valid(order, pairs=pairs):
|
| 35 |
+
return all(
|
| 36 |
+
world[i]["city"] != world[pairs[k][0]]["city"]
|
| 37 |
+
for (i, _), k in zip(pairs, order, strict=True)
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
candidates = (rng.permutation(len(pairs)).tolist() for _ in range(1000))
|
| 41 |
+
order = next((p for p in candidates if valid(p)), None)
|
| 42 |
+
if order is None:
|
| 43 |
+
order = next(
|
| 44 |
+
(list(p) for p in itertools.permutations(range(len(pairs))) if valid(p)), None
|
| 45 |
+
)
|
| 46 |
+
if order is None:
|
| 47 |
+
raise ValueError("Batch cannot match distinct cities; revise before training.")
|
| 48 |
+
batch["second_order"] = order
|
| 49 |
+
return batches
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def training_documents(records, batch, arm, copies=1):
|
| 53 |
+
pairs = batch["pairs"]
|
| 54 |
+
singles = [records[i, h, v] for i, v in pairs for h in (0, 1)]
|
| 55 |
+
docs = []
|
| 56 |
+
if arm == "separate":
|
| 57 |
+
docs.extend(singles)
|
| 58 |
+
else:
|
| 59 |
+
order = range(len(pairs)) if arm == "linked" else batch["second_order"]
|
| 60 |
+
if arm not in ("linked", "shuffled"):
|
| 61 |
+
raise ValueError(arm)
|
| 62 |
+
for (i, v), j in zip(pairs, order, strict=True):
|
| 63 |
+
k, w = pairs[j]
|
| 64 |
+
first, second = records[i, 0, v], records[k, 1, w]
|
| 65 |
+
docs.append(
|
| 66 |
+
dict(ids=first["ids"] + second["ids"], labels=first["labels"] + second["labels"])
|
| 67 |
+
)
|
| 68 |
+
docs.extend(singles * copies)
|
| 69 |
+
docs.extend(records[i, 2, v] for i, v in batch["compositions"])
|
| 70 |
+
return docs
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def edit_design(config, world):
|
| 74 |
+
rng = np.random.default_rng(config["edit_seed"])
|
| 75 |
+
ids = []
|
| 76 |
+
for city in base.CITIES:
|
| 77 |
+
options = [r["id"] for r in world if r["split"] == "target" and r["city"] == city]
|
| 78 |
+
ids.extend(int(i) for i in rng.choice(options, len(options) // 2, replace=False))
|
| 79 |
+
cities = rng.permutation(base.CITIES).tolist()
|
| 80 |
+
shift = int(rng.integers(1, len(cities)))
|
| 81 |
+
mapping = dict(zip(cities, cities[shift:] + cities[:shift], strict=True))
|
| 82 |
+
changed = copy.deepcopy(world)
|
| 83 |
+
for row in changed:
|
| 84 |
+
if row["id"] in ids:
|
| 85 |
+
row["city"] = mapping[row["city"]]
|
| 86 |
+
rng = np.random.default_rng(config["edit_training_seed"])
|
| 87 |
+
background = [r["id"] for r in world if r["split"] == "background"]
|
| 88 |
+
batches = []
|
| 89 |
+
for _ in range(config["edit_steps"]):
|
| 90 |
+
specs = []
|
| 91 |
+
for pool, count, hop in (
|
| 92 |
+
(ids, config["edited_second_per_step"], 1),
|
| 93 |
+
(ids, config["replayed_first_per_step"], 0),
|
| 94 |
+
(background, config["background_atomic_per_step"], None),
|
| 95 |
+
(background, config["background_compositions_edit_per_step"], 2),
|
| 96 |
+
):
|
| 97 |
+
for i in rng.choice(pool, count, replace=False):
|
| 98 |
+
h = int(rng.integers(2)) if hop is None else hop
|
| 99 |
+
specs.append([int(i), h, int(rng.integers(4))])
|
| 100 |
+
batches.append(specs)
|
| 101 |
+
return dict(edited_ids=sorted(ids), city_mapping=mapping, world=changed, stream=batches)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def view_prompt(row, hop, view):
|
| 105 |
+
if view == 0:
|
| 106 |
+
return base.prompt(row, hop)
|
| 107 |
+
return "Fictional registry.\nQuestion: " + HELDOUT[hop].format(**row) + "\nAnswer:"
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def evaluation_rows(world, extras=False):
|
| 111 |
+
return [
|
| 112 |
+
dict(
|
| 113 |
+
**row,
|
| 114 |
+
hop=hop,
|
| 115 |
+
view=view,
|
| 116 |
+
mode="direct",
|
| 117 |
+
prompt=view_prompt(row, hop, view),
|
| 118 |
+
answer=base.answer(row, hop),
|
| 119 |
+
)
|
| 120 |
+
for view in ((0, 1) if extras else (0,))
|
| 121 |
+
for row in world
|
| 122 |
+
if view == 0 or row["split"] == "target"
|
| 123 |
+
for hop in range(3)
|
| 124 |
+
]
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def autonomous_rows(world, direct):
|
| 128 |
+
lookup = {r["id"]: r for r in world}
|
| 129 |
+
result = []
|
| 130 |
+
for first in direct:
|
| 131 |
+
if first["split"] != "target" or first["hop"] != 0:
|
| 132 |
+
continue
|
| 133 |
+
bridge = first["text"].strip().split("\n")[0].strip().rstrip(".").strip()
|
| 134 |
+
row = lookup[first["id"]]
|
| 135 |
+
substituted = dict(row, bridge=bridge)
|
| 136 |
+
result.append(
|
| 137 |
+
dict(
|
| 138 |
+
**row,
|
| 139 |
+
hop=2,
|
| 140 |
+
view=first["view"],
|
| 141 |
+
mode="autonomous",
|
| 142 |
+
prompt=view_prompt(substituted, 1, first["view"]),
|
| 143 |
+
answer=row["city"],
|
| 144 |
+
generated_bridge=bridge,
|
| 145 |
+
first_tokens=first["tokens"],
|
| 146 |
+
first_text=first["text"],
|
| 147 |
+
first_correct=first["correct"],
|
| 148 |
+
)
|
| 149 |
+
)
|
| 150 |
+
return result
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@torch.inference_mode()
|
| 154 |
+
def generate(model, tokenizer, rows, config):
|
| 155 |
+
model.eval()
|
| 156 |
+
tokenizer.padding_side = "left"
|
| 157 |
+
result = []
|
| 158 |
+
for start in range(0, len(rows), config["eval_batch"]):
|
| 159 |
+
chunk = rows[start : start + config["eval_batch"]]
|
| 160 |
+
x = tokenizer(
|
| 161 |
+
[r["prompt"] for r in chunk],
|
| 162 |
+
padding=True,
|
| 163 |
+
return_tensors="pt",
|
| 164 |
+
add_special_tokens=False,
|
| 165 |
+
).to(config["device"])
|
| 166 |
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 167 |
+
tokens = model.generate(
|
| 168 |
+
**x,
|
| 169 |
+
do_sample=False,
|
| 170 |
+
max_new_tokens=config["max_new_tokens"],
|
| 171 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 172 |
+
eos_token_id=tokenizer.eos_token_id,
|
| 173 |
+
use_cache=True,
|
| 174 |
+
)[:, x.input_ids.shape[1] :]
|
| 175 |
+
for row, tok in zip(chunk, tokens.cpu().tolist(), strict=True):
|
| 176 |
+
if tokenizer.eos_token_id in tok:
|
| 177 |
+
tok = tok[: tok.index(tokenizer.eos_token_id) + 1]
|
| 178 |
+
text = tokenizer.decode(tok, skip_special_tokens=True)
|
| 179 |
+
result.append(dict(row, tokens=tok, text=text, correct=base.grade(text, row["answer"])))
|
| 180 |
+
return result
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def evaluate(model, tokenizer, world, config, extras=False):
|
| 184 |
+
direct = generate(model, tokenizer, evaluation_rows(world, extras), config)
|
| 185 |
+
if not extras:
|
| 186 |
+
return direct
|
| 187 |
+
return direct + generate(model, tokenizer, autonomous_rows(world, direct), config)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def mean_correct(rows):
|
| 191 |
+
return sum(r["correct"] for r in rows) / len(rows) if rows else None
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def metrics(rows, old_world, edit):
|
| 195 |
+
primary = [r for r in rows if r["view"] == 0 and r["mode"] == "direct"]
|
| 196 |
+
result = base.score(primary)
|
| 197 |
+
result["background_atomic"] = mean_correct(
|
| 198 |
+
[r for r in primary if r["split"] == "background" and r["hop"] < 2]
|
| 199 |
+
)
|
| 200 |
+
edited = set(edit["edited_ids"])
|
| 201 |
+
old = {r["id"]: r for r in old_world}
|
| 202 |
+
for view in (0, 1):
|
| 203 |
+
subset = [r for r in rows if r["view"] == view]
|
| 204 |
+
if not subset:
|
| 205 |
+
continue
|
| 206 |
+
for pool, keep in (("E", True), ("U", False)):
|
| 207 |
+
target = [r for r in subset if r["split"] == "target" and (r["id"] in edited) == keep]
|
| 208 |
+
for hop, name in ((0, "first"), (1, "second"), (2, "two")):
|
| 209 |
+
cell = [r for r in target if r["hop"] == hop and r["mode"] == "direct"]
|
| 210 |
+
result[f"v{view}_{pool}_{name}"] = mean_correct(cell)
|
| 211 |
+
if hop == 2 and cell:
|
| 212 |
+
result[f"v{view}_{pool}_old_two"] = sum(
|
| 213 |
+
base.grade(r["text"], old[r["id"]]["city"]) for r in cell
|
| 214 |
+
) / len(cell)
|
| 215 |
+
result[f"v{view}_{pool}_autonomous"] = mean_correct(
|
| 216 |
+
[r for r in target if r["mode"] == "autonomous"]
|
| 217 |
+
)
|
| 218 |
+
if view == 1:
|
| 219 |
+
for hop, name in ((0, "first"), (1, "second"), (2, "two")):
|
| 220 |
+
result[f"heldout_{name}"] = mean_correct(
|
| 221 |
+
[r for r in subset if r["mode"] == "direct" and r["hop"] == hop]
|
| 222 |
+
)
|
| 223 |
+
return result
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def document_budget(docs):
|
| 227 |
+
width = max(len(d["ids"]) for d in docs)
|
| 228 |
+
return dict(
|
| 229 |
+
input_tokens=sum(len(d["ids"]) for d in docs),
|
| 230 |
+
supervised_tokens=sum(sum(t != -100 for t in d["labels"]) for d in docs),
|
| 231 |
+
padded_tokens=len(docs) * width,
|
| 232 |
+
attention_cells=len(docs) * width**2,
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def prepare(config_path):
|
| 237 |
+
config = base.read(config_path)
|
| 238 |
+
art = Path(config["artifact_root"])
|
| 239 |
+
if (art / "lock.json").exists():
|
| 240 |
+
raise RuntimeError("Preserve existing lock.")
|
| 241 |
+
tokenizer = AutoTokenizer.from_pretrained(config["model_path"], local_files_only=True)
|
| 242 |
+
world = base.build_world(config)
|
| 243 |
+
batches = pairing_stream(config, world)
|
| 244 |
+
edit = edit_design(config, world)
|
| 245 |
+
records = base.corpus(tokenizer, world)
|
| 246 |
+
stats = {arm: Counter() for arm in config["arms"]}
|
| 247 |
+
for batch in batches:
|
| 248 |
+
signatures = []
|
| 249 |
+
for arm in config["arms"]:
|
| 250 |
+
docs = training_documents(records, batch, arm, config["standalone_rehearsal_copies"])
|
| 251 |
+
stats[arm].update(document_budget(docs))
|
| 252 |
+
signatures.append(
|
| 253 |
+
(
|
| 254 |
+
Counter(t for d in docs for t in d["ids"]),
|
| 255 |
+
Counter(t for d in docs for t in d["labels"] if t != -100),
|
| 256 |
+
)
|
| 257 |
+
)
|
| 258 |
+
assert all(s == signatures[0] for s in signatures)
|
| 259 |
+
changed = base.corpus(tokenizer, edit["world"])
|
| 260 |
+
edit_stats = {branch: Counter() for branch in ("update", "replay")}
|
| 261 |
+
for specs in edit["stream"]:
|
| 262 |
+
for branch, rec in (("update", changed), ("replay", records)):
|
| 263 |
+
docs = [rec[tuple(s)] for s in specs]
|
| 264 |
+
edit_stats[branch].update(document_budget(docs))
|
| 265 |
+
assert [len(changed[tuple(s)]["ids"]) for s in specs] == [
|
| 266 |
+
len(records[tuple(s)]["ids"]) for s in specs
|
| 267 |
+
]
|
| 268 |
+
assert edit_stats["update"] == edit_stats["replay"]
|
| 269 |
+
base.write(art / "world.json", world)
|
| 270 |
+
base.write(art / "stream.json", batches)
|
| 271 |
+
base.write(art / "edit-design.json", edit)
|
| 272 |
+
base.write(
|
| 273 |
+
art / "data-audit.json",
|
| 274 |
+
dict(
|
| 275 |
+
status="passed",
|
| 276 |
+
training=stats,
|
| 277 |
+
editing=edit_stats,
|
| 278 |
+
paired_batch_checks=len(batches),
|
| 279 |
+
equal_edit_length_checks=len(edit["stream"]),
|
| 280 |
+
target_composition_labels=0,
|
| 281 |
+
edit_target_composition_labels=0,
|
| 282 |
+
),
|
| 283 |
+
)
|
| 284 |
+
sources = [
|
| 285 |
+
str(config_path),
|
| 286 |
+
str(Path(__file__).relative_to(Path.cwd())) if Path(__file__).is_absolute() else __file__,
|
| 287 |
+
"src/llm_memory_editability/small_lm_composition.py",
|
| 288 |
+
"scripts/run_small_lm_followup.py",
|
| 289 |
+
"tests/test_small_lm_followup.py",
|
| 290 |
+
str(art / "development-plan.md"),
|
| 291 |
+
]
|
| 292 |
+
hashes = {}
|
| 293 |
+
for source in sources:
|
| 294 |
+
relative = Path(source).resolve().relative_to(Path.cwd())
|
| 295 |
+
dest = art / "source" / relative
|
| 296 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 297 |
+
shutil.copyfile(relative, dest)
|
| 298 |
+
hashes[str(relative)] = base.sha(relative)
|
| 299 |
+
model_files = {
|
| 300 |
+
str(p): base.sha(p)
|
| 301 |
+
for p in Path(config["model_path"]).iterdir()
|
| 302 |
+
if p.suffix in (".safetensors", ".json")
|
| 303 |
+
}
|
| 304 |
+
base.write(
|
| 305 |
+
art / "lock.json",
|
| 306 |
+
dict(
|
| 307 |
+
status="locked_before_training",
|
| 308 |
+
utc=base.now(),
|
| 309 |
+
sources=hashes,
|
| 310 |
+
model_files=model_files,
|
| 311 |
+
data_files={
|
| 312 |
+
str(art / f): base.sha(art / f)
|
| 313 |
+
for f in ("world.json", "stream.json", "edit-design.json", "data-audit.json")
|
| 314 |
+
},
|
| 315 |
+
),
|
| 316 |
+
)
|
| 317 |
+
print(json.dumps(dict(status="prepared", training=stats, editing=edit_stats)), flush=True)
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def check_lock(config):
|
| 321 |
+
art = Path(config["artifact_root"])
|
| 322 |
+
lock = base.read(art / "lock.json")
|
| 323 |
+
for group in ("sources", "model_files", "data_files"):
|
| 324 |
+
for path, digest in lock[group].items():
|
| 325 |
+
assert base.sha(path) == digest, path
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def learning_rate(step, steps, lr, minimum, warmup):
|
| 329 |
+
decay = 0.5 * (1 + math.cos(math.pi * max(0, step - warmup) / (steps - warmup)))
|
| 330 |
+
return (minimum + (lr - minimum) * decay) * min(1.0, (step + 1) / warmup)
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def run(config_path, arm, branch=None):
|
| 334 |
+
config = base.read(config_path)
|
| 335 |
+
check_lock(config)
|
| 336 |
+
assert arm in config["arms"] and branch in (None, "update", "replay")
|
| 337 |
+
art = Path(config["artifact_root"])
|
| 338 |
+
root = Path(config["output_root"])
|
| 339 |
+
out = root / ("training" if branch is None else "editing") / arm
|
| 340 |
+
if branch:
|
| 341 |
+
out = out / branch
|
| 342 |
+
if (out / "status.json").exists():
|
| 343 |
+
raise RuntimeError(f"Preserve existing run: {out}")
|
| 344 |
+
old_world = base.read(art / "world.json")
|
| 345 |
+
edit = base.read(art / "edit-design.json")
|
| 346 |
+
# Both update and replay are scored against the SAME edited world.
|
| 347 |
+
world = edit["world"] if branch else old_world
|
| 348 |
+
source = Path(config["model_path"]) if branch is None else root / "training" / arm / "model"
|
| 349 |
+
if branch:
|
| 350 |
+
parent = base.read(root / "training" / arm / "summary.json")
|
| 351 |
+
for path, digest in parent["checkpoint_files"].items():
|
| 352 |
+
assert base.sha(path) == digest
|
| 353 |
+
steps = config["edit_steps"] if branch else config["steps"]
|
| 354 |
+
nodes = config["edit_nodes"] if branch else config["nodes"]
|
| 355 |
+
seed = config["edit_training_seed"] if branch else config["training_seed"]
|
| 356 |
+
prefix = "edit_" if branch else ""
|
| 357 |
+
batches = edit["stream"] if branch else base.read(art / "stream.json")
|
| 358 |
+
base.write(out / "status.json", dict(status="running", utc=base.now(), arm=arm, branch=branch))
|
| 359 |
+
started = time.perf_counter()
|
| 360 |
+
torch.set_num_threads(config["cpu_threads"])
|
| 361 |
+
torch.manual_seed(seed)
|
| 362 |
+
torch.backends.cuda.matmul.allow_tf32 = False
|
| 363 |
+
torch.backends.cudnn.allow_tf32 = False
|
| 364 |
+
torch.cuda.set_device(config["device"])
|
| 365 |
+
torch.cuda.reset_peak_memory_stats()
|
| 366 |
+
tokenizer = AutoTokenizer.from_pretrained(config["model_path"], local_files_only=True)
|
| 367 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 368 |
+
|
| 369 |
+
def load_model(path):
|
| 370 |
+
return AutoModelForCausalLM.from_pretrained(
|
| 371 |
+
path, torch_dtype=torch.float32, attn_implementation="sdpa", local_files_only=True
|
| 372 |
+
).to(config["device"])
|
| 373 |
+
|
| 374 |
+
model = load_model(source)
|
| 375 |
+
model.requires_grad_(True)
|
| 376 |
+
assert model.config.num_hidden_layers == 28 and model.config.hidden_size == 1024
|
| 377 |
+
assert len({id(layer.mlp) for layer in model.model.layers}) == 28
|
| 378 |
+
samples = base.parameter_samples(model)
|
| 379 |
+
parameter_count = sum(p.numel() for p in model.parameters())
|
| 380 |
+
records = base.corpus(tokenizer, edit["world"] if branch == "update" else old_world)
|
| 381 |
+
optimizer = torch.optim.AdamW(
|
| 382 |
+
model.parameters(),
|
| 383 |
+
lr=config[prefix + "learning_rate"],
|
| 384 |
+
weight_decay=config["weight_decay"],
|
| 385 |
+
fused=True,
|
| 386 |
+
)
|
| 387 |
+
curve, budget = [], Counter()
|
| 388 |
+
train_seconds = 0.0
|
| 389 |
+
for step in range(steps + 1):
|
| 390 |
+
if step in nodes:
|
| 391 |
+
rows = evaluate(model, tokenizer, world, config, extras=step == steps)
|
| 392 |
+
base.write(out / f"predictions-{step:05d}.json", rows)
|
| 393 |
+
record = dict(step=step, **metrics(rows, old_world, edit))
|
| 394 |
+
curve.append(record)
|
| 395 |
+
base.write(out / "curve.json", curve)
|
| 396 |
+
print(json.dumps(dict(arm=arm, branch=branch, **record)), flush=True)
|
| 397 |
+
if step == steps:
|
| 398 |
+
break
|
| 399 |
+
rate = learning_rate(
|
| 400 |
+
step,
|
| 401 |
+
steps,
|
| 402 |
+
config[prefix + "learning_rate"],
|
| 403 |
+
config[prefix + "minimum_learning_rate"],
|
| 404 |
+
config[prefix + "warmup_steps"],
|
| 405 |
+
)
|
| 406 |
+
for group in optimizer.param_groups:
|
| 407 |
+
group["lr"] = rate
|
| 408 |
+
docs = (
|
| 409 |
+
[records[tuple(s)] for s in batches[step]]
|
| 410 |
+
if branch
|
| 411 |
+
else training_documents(
|
| 412 |
+
records, batches[step], arm, config["standalone_rehearsal_copies"]
|
| 413 |
+
)
|
| 414 |
+
)
|
| 415 |
+
budget.update(document_budget(docs))
|
| 416 |
+
inputs = base.batch_tensors(docs, tokenizer.pad_token_id, config["device"])
|
| 417 |
+
model.train()
|
| 418 |
+
torch.cuda.synchronize()
|
| 419 |
+
tick = time.perf_counter()
|
| 420 |
+
optimizer.zero_grad(set_to_none=True)
|
| 421 |
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 422 |
+
loss = model(**inputs, use_cache=False).loss
|
| 423 |
+
assert torch.isfinite(loss)
|
| 424 |
+
loss.backward()
|
| 425 |
+
if step == 0:
|
| 426 |
+
assert all(
|
| 427 |
+
p.requires_grad and p.grad is not None and torch.isfinite(p.grad).all()
|
| 428 |
+
for p in model.parameters()
|
| 429 |
+
)
|
| 430 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), config["gradient_clip"])
|
| 431 |
+
optimizer.step()
|
| 432 |
+
torch.cuda.synchronize()
|
| 433 |
+
train_seconds += time.perf_counter() - tick
|
| 434 |
+
if (step + 1) % 64 == 0:
|
| 435 |
+
print(
|
| 436 |
+
json.dumps(
|
| 437 |
+
dict(
|
| 438 |
+
arm=arm,
|
| 439 |
+
branch=branch,
|
| 440 |
+
step=step + 1,
|
| 441 |
+
loss=float(loss.detach()),
|
| 442 |
+
train_seconds=train_seconds,
|
| 443 |
+
)
|
| 444 |
+
),
|
| 445 |
+
flush=True,
|
| 446 |
+
)
|
| 447 |
+
changed = {
|
| 448 |
+
n: not torch.equal(before, base.parameter_samples(model)[n])
|
| 449 |
+
for n, before in samples.items()
|
| 450 |
+
}
|
| 451 |
+
assert all(changed.values())
|
| 452 |
+
architecture = model.config.to_dict()
|
| 453 |
+
model.save_pretrained(out / "model", safe_serialization=True)
|
| 454 |
+
tokenizer.save_pretrained(out / "model")
|
| 455 |
+
final_rows = rows
|
| 456 |
+
del optimizer, model, samples, inputs, loss
|
| 457 |
+
torch.cuda.empty_cache()
|
| 458 |
+
reloaded = load_model(out / "model")
|
| 459 |
+
again = evaluate(reloaded, tokenizer, world, config, extras=True)
|
| 460 |
+
assert [r["tokens"] for r in final_rows] == [r["tokens"] for r in again]
|
| 461 |
+
assert [r["prompt"] for r in final_rows] == [r["prompt"] for r in again]
|
| 462 |
+
base.write(
|
| 463 |
+
out / "reload-audit.json",
|
| 464 |
+
dict(
|
| 465 |
+
status="passed",
|
| 466 |
+
predictions=len(again),
|
| 467 |
+
exact_generated_tokens=True,
|
| 468 |
+
exact_autonomous_prompts=True,
|
| 469 |
+
),
|
| 470 |
+
)
|
| 471 |
+
expected = base.read(art / "data-audit.json")
|
| 472 |
+
assert budget == expected["editing" if branch else "training"][branch or arm]
|
| 473 |
+
# Dense matrix estimate: 3x forward for training; all vocab logits are evaluated.
|
| 474 |
+
d, layers, intermediate = 1024, 28, architecture["intermediate_size"]
|
| 475 |
+
kv = architecture["num_key_value_heads"] * architecture["head_dim"]
|
| 476 |
+
query_width = architecture["num_attention_heads"] * architecture["head_dim"]
|
| 477 |
+
attention_projections = 2 * d * query_width + 2 * d * kv
|
| 478 |
+
per_token = layers * (attention_projections + 3 * d * intermediate)
|
| 479 |
+
per_token += d * architecture["vocab_size"]
|
| 480 |
+
flops = (
|
| 481 |
+
6 * per_token * budget["padded_tokens"]
|
| 482 |
+
+ 12
|
| 483 |
+
* layers
|
| 484 |
+
* (architecture["num_attention_heads"] * architecture["head_dim"])
|
| 485 |
+
* budget["attention_cells"]
|
| 486 |
+
)
|
| 487 |
+
summary = dict(
|
| 488 |
+
status="complete",
|
| 489 |
+
phase="development_only",
|
| 490 |
+
arm=arm,
|
| 491 |
+
branch=branch,
|
| 492 |
+
utc=base.now(),
|
| 493 |
+
metrics=metrics(final_rows, old_world, edit),
|
| 494 |
+
updates=steps,
|
| 495 |
+
parameter_count=parameter_count,
|
| 496 |
+
trainable_parameters=parameter_count,
|
| 497 |
+
initial_all_gradients_finite=True,
|
| 498 |
+
sampled_parameters_changed=changed,
|
| 499 |
+
source_checkpoint=str(source),
|
| 500 |
+
fresh_optimizer=True,
|
| 501 |
+
budget=dict(budget),
|
| 502 |
+
estimated_training_matrix_flops=flops,
|
| 503 |
+
train_seconds=train_seconds,
|
| 504 |
+
process_seconds=time.perf_counter() - started,
|
| 505 |
+
peak_gpu_bytes=torch.cuda.max_memory_allocated(),
|
| 506 |
+
torch_version=torch.__version__,
|
| 507 |
+
transformers_version=transformers.__version__,
|
| 508 |
+
gpu=torch.cuda.get_device_name(),
|
| 509 |
+
tf32=False,
|
| 510 |
+
lock_sha256=base.sha(art / "lock.json"),
|
| 511 |
+
checkpoint_files={str(p): base.sha(p) for p in (out / "model").glob("*.safetensors")},
|
| 512 |
+
)
|
| 513 |
+
base.write(out / "summary.json", summary)
|
| 514 |
+
base.write(out / "status.json", dict(status="complete", utc=base.now()))
|
| 515 |
+
print(json.dumps(summary), flush=True)
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
def report(config_path):
|
| 519 |
+
config = base.read(config_path)
|
| 520 |
+
check_lock(config)
|
| 521 |
+
art, root = Path(config["artifact_root"]), Path(config["output_root"])
|
| 522 |
+
world, edit = base.read(art / "world.json"), base.read(art / "edit-design.json")
|
| 523 |
+
runs = {}
|
| 524 |
+
checks = 0
|
| 525 |
+
for arm in config["arms"]:
|
| 526 |
+
for branch in (None, "update", "replay"):
|
| 527 |
+
out = root / ("editing" if branch else "training") / arm
|
| 528 |
+
if branch:
|
| 529 |
+
out /= branch
|
| 530 |
+
key = f"{arm}/{branch or 'training'}"
|
| 531 |
+
summary = base.read(out / "summary.json")
|
| 532 |
+
assert summary["status"] == "complete"
|
| 533 |
+
assert base.read(out / "reload-audit.json")["status"] == "passed"
|
| 534 |
+
for node in base.read(out / "curve.json"):
|
| 535 |
+
rows = base.read(out / f"predictions-{node['step']:05d}.json")
|
| 536 |
+
assert all(base.grade(r["text"], r["answer"]) == r["correct"] for r in rows)
|
| 537 |
+
assert dict(step=node["step"], **metrics(rows, world, edit)) == node
|
| 538 |
+
checks += len(rows)
|
| 539 |
+
assert metrics(rows, world, edit) == summary["metrics"]
|
| 540 |
+
runs[key] = summary
|
| 541 |
+
result = dict(
|
| 542 |
+
status="complete",
|
| 543 |
+
phase="single_world_development",
|
| 544 |
+
utc=base.now(),
|
| 545 |
+
runs=runs,
|
| 546 |
+
node_prediction_checks=checks,
|
| 547 |
+
total_train_seconds=sum(r["train_seconds"] for r in runs.values()),
|
| 548 |
+
total_process_seconds=sum(r["process_seconds"] for r in runs.values()),
|
| 549 |
+
total_updates=sum(r["updates"] for r in runs.values()),
|
| 550 |
+
total_input_tokens=sum(r["budget"]["input_tokens"] for r in runs.values()),
|
| 551 |
+
total_supervised_tokens=sum(r["budget"]["supervised_tokens"] for r in runs.values()),
|
| 552 |
+
estimated_training_matrix_flops=sum(
|
| 553 |
+
r["estimated_training_matrix_flops"] for r in runs.values()
|
| 554 |
+
),
|
| 555 |
+
lock_sha256=base.sha(art / "lock.json"),
|
| 556 |
+
)
|
| 557 |
+
base.write(art / "summary.json", result)
|
| 558 |
+
print(json.dumps({k: v for k, v in result.items() if k != "runs"}), flush=True)
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/storage_composition.py
ADDED
|
@@ -0,0 +1,424 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fact-load experiments in unmodified GPT-2 blocks and depth-shared GPT-2 blocks.
|
| 2 |
+
|
| 3 |
+
Template-language data are controlled; the architecture is an ordinary causal LM.
|
| 4 |
+
No embeddings/projections are frozen, no intermediate answers are supplied, and
|
| 5 |
+
all non-padding next tokens contribute to the training loss.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
import time
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
import torch
|
| 17 |
+
from torch.nn import functional as F
|
| 18 |
+
|
| 19 |
+
from .bios_model import ModelConfig
|
| 20 |
+
from .grok_depth import EpochStream, GraphStep, SmallGPT, make_optimizer, utc, write_json
|
| 21 |
+
from .grok_loop_model import LoopGPT, flops
|
| 22 |
+
from .text_pretrain import WORDS, atomic_sentence, composite_sentence
|
| 23 |
+
|
| 24 |
+
SOURCE_FILES = [
|
| 25 |
+
"src/llm_memory_editability/storage_composition.py",
|
| 26 |
+
"src/llm_memory_editability/bios_model.py",
|
| 27 |
+
"src/llm_memory_editability/grok_depth.py",
|
| 28 |
+
"src/llm_memory_editability/grok_loop_model.py",
|
| 29 |
+
"src/llm_memory_editability/text_pretrain.py",
|
| 30 |
+
"scripts/run_storage_composition.py",
|
| 31 |
+
"tests/test_storage_composition.py",
|
| 32 |
+
]
|
| 33 |
+
ARCHITECTURES = {
|
| 34 |
+
"standard1": (1, 1),
|
| 35 |
+
"standard2": (2, 1),
|
| 36 |
+
"standard3": (3, 1),
|
| 37 |
+
"loop1x2": (1, 2),
|
| 38 |
+
"loop1x3": (1, 3),
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def file_hash(path):
|
| 43 |
+
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def build_world(spec):
|
| 47 |
+
"""Keep the target subgraph, vocabulary and candidates fixed across loads.
|
| 48 |
+
|
| 49 |
+
Matched low load repeats anchor atomics outside every evaluated chain.
|
| 50 |
+
High load teaches distinct distractor atomics. The original development
|
| 51 |
+
setting repeated familiar atomics; its results are retained separately.
|
| 52 |
+
"""
|
| 53 |
+
rng = np.random.default_rng(spec["world"])
|
| 54 |
+
hn, bn, tn = (spec[k] for k in ("heads_n", "bridges_n", "tails_n"))
|
| 55 |
+
familiar, strict = spec["familiar_n"], spec["strict_n"]
|
| 56 |
+
core = familiar + strict
|
| 57 |
+
if not (0 < familiar < core <= min(hn, bn)):
|
| 58 |
+
raise ValueError("Invalid disjoint familiar/strict subgraph sizes")
|
| 59 |
+
heads = np.arange(len(WORDS), len(WORDS) + hn)
|
| 60 |
+
bridges = np.arange(heads[-1] + 1, heads[-1] + 1 + bn)
|
| 61 |
+
tails = np.arange(bridges[-1] + 1, bridges[-1] + 1 + tn)
|
| 62 |
+
first = []
|
| 63 |
+
for index, head in enumerate(heads):
|
| 64 |
+
candidates = (
|
| 65 |
+
bridges[:familiar]
|
| 66 |
+
if index < familiar
|
| 67 |
+
else bridges[familiar:core]
|
| 68 |
+
if index < core
|
| 69 |
+
else bridges
|
| 70 |
+
)
|
| 71 |
+
first.extend((head, r, rng.choice(candidates)) for r in range(13, 17))
|
| 72 |
+
first = np.asarray(first, dtype=np.int64)
|
| 73 |
+
second = np.asarray(
|
| 74 |
+
[(b, r, rng.choice(tails)) for b in bridges for r in range(17, 21)], dtype=np.int64
|
| 75 |
+
)
|
| 76 |
+
lookup = {(int(h), int(r)): int(t) for h, r, t in second}
|
| 77 |
+
paths = np.asarray(
|
| 78 |
+
[
|
| 79 |
+
(h, r1, b, r2, lookup[int(b), r2])
|
| 80 |
+
for h, r1, b in first[: core * 4]
|
| 81 |
+
for r2 in range(17, 21)
|
| 82 |
+
],
|
| 83 |
+
dtype=np.int64,
|
| 84 |
+
)
|
| 85 |
+
familiar_paths = paths[paths[:, 0] < heads[familiar]]
|
| 86 |
+
# Hold out entire (head, terminal) pairs, including alternate relation paths.
|
| 87 |
+
reserved = rng.random((familiar, tn)) < spec["holdout_fraction"]
|
| 88 |
+
held = reserved[familiar_paths[:, 0] - heads[0], familiar_paths[:, 4] - tails[0]]
|
| 89 |
+
world = {
|
| 90 |
+
"common_atomic": np.concatenate([first[: core * 4], second[: core * 4]]),
|
| 91 |
+
"background_atomic": np.concatenate([first[: familiar * 4], second[: familiar * 4]]),
|
| 92 |
+
"extra_atomic": np.concatenate([first[core * 4 :], second[core * 4 :]]),
|
| 93 |
+
"train_composite": familiar_paths[~held],
|
| 94 |
+
"familiar_test": familiar_paths[held],
|
| 95 |
+
"strict_test": paths[paths[:, 0] >= heads[familiar]],
|
| 96 |
+
}
|
| 97 |
+
if spec.get("low_extra") == "anchors":
|
| 98 |
+
anchors = spec["anchor_n"]
|
| 99 |
+
if not 0 < anchors <= min(hn, bn) - core:
|
| 100 |
+
raise ValueError("Anchor entities must be outside the common subgraph")
|
| 101 |
+
world["anchor_atomic"] = np.concatenate(
|
| 102 |
+
[first[core * 4 : (core + anchors) * 4], second[core * 4 : (core + anchors) * 4]]
|
| 103 |
+
)
|
| 104 |
+
if any(not len(rows) for rows in world.values()):
|
| 105 |
+
raise ValueError("Empty stratum: do not silently reroll a world")
|
| 106 |
+
atoms = np.concatenate([world["common_atomic"], world["extra_atomic"]])
|
| 107 |
+
audit_world(world)
|
| 108 |
+
assert len(atoms) == 4 * (hn + bn)
|
| 109 |
+
return world
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def audit_world(world):
|
| 113 |
+
atoms = np.concatenate([world["common_atomic"], world["extra_atomic"]])
|
| 114 |
+
lookup = {(int(h), int(r)): int(t) for h, r, t in atoms}
|
| 115 |
+
assert len(lookup) == len(atoms)
|
| 116 |
+
for name in ("train_composite", "familiar_test", "strict_test"):
|
| 117 |
+
for h, r1, b, r2, t in world[name]:
|
| 118 |
+
assert lookup[int(h), int(r1)] == b
|
| 119 |
+
assert lookup[int(b), int(r2)] == t
|
| 120 |
+
train_pairs = {tuple(r[[0, 4]]) for r in world["train_composite"]}
|
| 121 |
+
assert not train_pairs & {tuple(r[[0, 4]]) for r in world["familiar_test"]}
|
| 122 |
+
train_facts = {(int(h), int(r1), int(b)) for h, r1, b, _r2, _t in world["train_composite"]} | {
|
| 123 |
+
(int(b), int(r2), int(t)) for _h, _r1, b, r2, t in world["train_composite"]
|
| 124 |
+
}
|
| 125 |
+
strict_facts = {(int(h), int(r1), int(b)) for h, r1, b, _r2, _t in world["strict_test"]} | {
|
| 126 |
+
(int(b), int(r2), int(t)) for _h, _r1, b, r2, t in world["strict_test"]
|
| 127 |
+
}
|
| 128 |
+
assert not strict_facts & train_facts
|
| 129 |
+
assert not strict_facts & set(map(tuple, world["extra_atomic"]))
|
| 130 |
+
if "anchor_atomic" in world:
|
| 131 |
+
assert not set(map(tuple, world["anchor_atomic"])) & set(map(tuple, world["common_atomic"]))
|
| 132 |
+
assert set(map(tuple, world["anchor_atomic"])) <= set(map(tuple, world["extra_atomic"]))
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def pack_sentences(rows):
|
| 136 |
+
render = atomic_sentence if rows.shape[1] == 3 else composite_sentence
|
| 137 |
+
x = np.zeros((len(rows), 9), dtype=np.int64)
|
| 138 |
+
labels = np.full_like(x, -100)
|
| 139 |
+
for index, row in enumerate(rows):
|
| 140 |
+
sentence = render(row)
|
| 141 |
+
x[index, : len(sentence) - 1] = sentence[:-1]
|
| 142 |
+
labels[index, : len(sentence) - 1] = sentence[1:]
|
| 143 |
+
return x, labels
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class FullTokenStep(GraphStep):
|
| 147 |
+
def eager(self):
|
| 148 |
+
self.optimizer.zero_grad(set_to_none=True)
|
| 149 |
+
tokens, labels = (part[self.index] for part in self.table)
|
| 150 |
+
logits = self.model(tokens)
|
| 151 |
+
loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100)
|
| 152 |
+
loss.backward()
|
| 153 |
+
norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True)
|
| 154 |
+
self.optimizer.step()
|
| 155 |
+
return loss, norm
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def construct(spec, device):
|
| 159 |
+
layers, repeats = ARCHITECTURES[spec["architecture"]]
|
| 160 |
+
config = ModelConfig(
|
| 161 |
+
vocab_size=len(WORDS) + spec["heads_n"] + spec["bridges_n"] + spec["tails_n"],
|
| 162 |
+
width=spec["width"],
|
| 163 |
+
layers=layers,
|
| 164 |
+
heads=spec["heads"],
|
| 165 |
+
context=16,
|
| 166 |
+
)
|
| 167 |
+
torch.manual_seed(spec["initialization"])
|
| 168 |
+
if repeats == 1:
|
| 169 |
+
model = SmallGPT(config, dropout=spec["dropout"])
|
| 170 |
+
else:
|
| 171 |
+
# Same unique-block initialization as standard1, without zeroing residuals.
|
| 172 |
+
model = LoopGPT(config, repeats, spec["dropout"], initialization="legacy_unique")
|
| 173 |
+
return model.to(device)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
@torch.no_grad()
|
| 177 |
+
def generate_rows(model, rows, device, repeats=None, batch_size=512):
|
| 178 |
+
"""Greedy answer, then '.', then EOS; feed back every generated token."""
|
| 179 |
+
model.eval()
|
| 180 |
+
if rows.shape[1] == 3:
|
| 181 |
+
prompts = np.asarray([atomic_sentence(r)[:5] for r in rows])
|
| 182 |
+
else:
|
| 183 |
+
prompts = np.asarray([composite_sentence(r)[:7] for r in rows])
|
| 184 |
+
predictions, nlls = [], []
|
| 185 |
+
kwargs = {"repeats": repeats} if isinstance(model, LoopGPT) else {}
|
| 186 |
+
for start in range(0, len(rows), batch_size):
|
| 187 |
+
tokens = torch.as_tensor(prompts[start : start + batch_size], device=device)
|
| 188 |
+
target = torch.as_tensor(rows[start : start + batch_size, -1], device=device)
|
| 189 |
+
generated = []
|
| 190 |
+
for i in range(3):
|
| 191 |
+
logits = model(tokens, **kwargs)[:, -1]
|
| 192 |
+
if i == 0:
|
| 193 |
+
nlls.append(F.cross_entropy(logits, target, reduction="none").cpu().numpy())
|
| 194 |
+
next_token = logits.argmax(-1)
|
| 195 |
+
generated.append(next_token.cpu().numpy())
|
| 196 |
+
tokens = torch.cat([tokens, next_token[:, None]], dim=1)
|
| 197 |
+
predictions.append(np.stack(generated, axis=1))
|
| 198 |
+
pred, nll = np.concatenate(predictions), np.concatenate(nlls)
|
| 199 |
+
answer_ok = pred[:, 0] == rows[:, -1]
|
| 200 |
+
full_ok = answer_ok & (pred[:, 1] == 5) & (pred[:, 2] == 1)
|
| 201 |
+
metrics = {
|
| 202 |
+
"n": len(rows),
|
| 203 |
+
"answer_accuracy": float(answer_ok.mean()),
|
| 204 |
+
"accuracy": float(full_ok.mean()),
|
| 205 |
+
"answer_nll": float(nll.mean()),
|
| 206 |
+
}
|
| 207 |
+
return metrics, {"generated": pred, "correct": full_ok, "answer_nll": nll}
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def evaluate(model, world, load, device, repeats=None):
|
| 211 |
+
metrics, predictions = {}, {}
|
| 212 |
+
names = ["common_atomic", "train_composite", "familiar_test", "strict_test"]
|
| 213 |
+
if "anchor_atomic" in world:
|
| 214 |
+
names.append("anchor_atomic")
|
| 215 |
+
if load == "high":
|
| 216 |
+
names.append("extra_atomic")
|
| 217 |
+
for name in names:
|
| 218 |
+
metrics[name], pred = generate_rows(model, world[name], device, repeats)
|
| 219 |
+
predictions.update({name + "_" + k: v for k, v in pred.items()})
|
| 220 |
+
for name in ("familiar_test", "strict_test"):
|
| 221 |
+
rows = world[name]
|
| 222 |
+
first = rows[:, [0, 1, 2]]
|
| 223 |
+
second = rows[:, [2, 3, 4]]
|
| 224 |
+
_m, p1 = generate_rows(model, first, device, repeats)
|
| 225 |
+
_m, p2 = generate_rows(model, second, device, repeats)
|
| 226 |
+
covered = p1["correct"] & p2["correct"]
|
| 227 |
+
generated_second = second.copy()
|
| 228 |
+
generated_second[:, 0] = p1["generated"][:, 0]
|
| 229 |
+
_m, autonomous = generate_rows(model, generated_second, device, repeats)
|
| 230 |
+
calls_ok = (
|
| 231 |
+
(p1["generated"][:, 1] == 5) & (p1["generated"][:, 2] == 1) & autonomous["correct"]
|
| 232 |
+
)
|
| 233 |
+
direct = predictions[name + "_correct"]
|
| 234 |
+
metrics[name].update(
|
| 235 |
+
{
|
| 236 |
+
"atomic_correct_coverage": float(covered.mean()),
|
| 237 |
+
"conditional_accuracy": float(direct[covered].mean()) if covered.any() else None,
|
| 238 |
+
"autonomous_two_calls": float(calls_ok.mean()),
|
| 239 |
+
}
|
| 240 |
+
)
|
| 241 |
+
predictions.update({name + "_coverage": covered, name + "_two_calls": calls_ok})
|
| 242 |
+
model.train()
|
| 243 |
+
return metrics, predictions
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def data_digest(world):
|
| 247 |
+
digest = hashlib.sha256()
|
| 248 |
+
for key, value in sorted(world.items()):
|
| 249 |
+
digest.update(key.encode())
|
| 250 |
+
digest.update(str(value.shape).encode())
|
| 251 |
+
digest.update(value.tobytes())
|
| 252 |
+
return digest.hexdigest()
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def run(spec, out, device="cuda:2"):
|
| 256 |
+
out = Path(out)
|
| 257 |
+
if (out / "complete.json").exists():
|
| 258 |
+
raise FileExistsError(f"Completed run exists: {out}")
|
| 259 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 260 |
+
torch.set_num_threads(1)
|
| 261 |
+
torch.set_num_interop_threads(1)
|
| 262 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 263 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 264 |
+
device = torch.device(device)
|
| 265 |
+
torch.cuda.set_device(device)
|
| 266 |
+
world = build_world(spec)
|
| 267 |
+
np.savez_compressed(out / "world.npz", **world)
|
| 268 |
+
source = {path: file_hash(path) for path in SOURCE_FILES}
|
| 269 |
+
write_json(
|
| 270 |
+
out / "spec.json", {"spec": spec, "source": source, "data_sha256": data_digest(world)}
|
| 271 |
+
)
|
| 272 |
+
model = construct(spec, device)
|
| 273 |
+
lr = torch.tensor(spec["lr"], device=device)
|
| 274 |
+
opt = make_optimizer(model, lr, spec["weight_decay"])
|
| 275 |
+
low_extra = world["anchor_atomic"] if "anchor_atomic" in world else world["background_atomic"]
|
| 276 |
+
extra = world["extra_atomic"] if spec["load"] == "high" else low_extra
|
| 277 |
+
strata = [world["common_atomic"], world["train_composite"], extra]
|
| 278 |
+
packed = [pack_sentences(rows) for rows in strata]
|
| 279 |
+
table = tuple(
|
| 280 |
+
torch.as_tensor(np.concatenate(parts), device=device) for parts in zip(*packed, strict=True)
|
| 281 |
+
)
|
| 282 |
+
sizes = [len(rows) for rows in strata]
|
| 283 |
+
offsets = np.cumsum([0, *sizes[:-1]])
|
| 284 |
+
streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)]
|
| 285 |
+
counts = [np.zeros(size, dtype=np.int64) for size in sizes]
|
| 286 |
+
batch = spec["batch_size"]
|
| 287 |
+
if batch % 3:
|
| 288 |
+
raise ValueError("Batch must divide into three equal exposure strata")
|
| 289 |
+
graph = FullTokenStep(model, opt, table, batch)
|
| 290 |
+
history, training_seconds = [], 0.0
|
| 291 |
+
layers, repeats = ARCHITECTURES[spec["architecture"]]
|
| 292 |
+
parameters = sum(p.numel() for p in model.parameters())
|
| 293 |
+
flop_step = flops(model.config, repeats, batch, 9, output_positions=9)
|
| 294 |
+
start = 0
|
| 295 |
+
|
| 296 |
+
def measure(step, loss=None):
|
| 297 |
+
metrics, predictions = evaluate(model, world, spec["load"], device)
|
| 298 |
+
row = {
|
| 299 |
+
"step": step,
|
| 300 |
+
"metrics": metrics,
|
| 301 |
+
"loss": loss,
|
| 302 |
+
"training_seconds": training_seconds,
|
| 303 |
+
"estimated_training_flops": step * flop_step,
|
| 304 |
+
}
|
| 305 |
+
history.append(row)
|
| 306 |
+
write_json(out / "learning.json", history)
|
| 307 |
+
np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions)
|
| 308 |
+
state = {
|
| 309 |
+
"spec": spec,
|
| 310 |
+
"step": step,
|
| 311 |
+
"model": model.state_dict(),
|
| 312 |
+
"optimizer": opt.state_dict(),
|
| 313 |
+
"streams": [s.state_dict() for s in streams],
|
| 314 |
+
"cpu_rng": torch.get_rng_state(),
|
| 315 |
+
"cuda_rng": torch.cuda.get_rng_state(device),
|
| 316 |
+
"counts": counts,
|
| 317 |
+
"source": source,
|
| 318 |
+
"data_sha256": data_digest(world),
|
| 319 |
+
}
|
| 320 |
+
torch.save(state, out / "latest.tmp.pt")
|
| 321 |
+
(out / "latest.tmp.pt").replace(out / "latest.pt")
|
| 322 |
+
write_json(
|
| 323 |
+
out / "status.json",
|
| 324 |
+
{
|
| 325 |
+
"step": step,
|
| 326 |
+
"budget": spec["steps"],
|
| 327 |
+
"atomic": metrics["common_atomic"]["accuracy"],
|
| 328 |
+
"familiar": metrics["familiar_test"]["accuracy"],
|
| 329 |
+
"strict": metrics["strict_test"]["accuracy"],
|
| 330 |
+
},
|
| 331 |
+
)
|
| 332 |
+
print(json.dumps({"run": str(out), "step": step, "metrics": metrics}), flush=True)
|
| 333 |
+
return row
|
| 334 |
+
|
| 335 |
+
measure(0)
|
| 336 |
+
for end in spec["nodes"]:
|
| 337 |
+
if end == 0:
|
| 338 |
+
continue
|
| 339 |
+
torch.cuda.synchronize()
|
| 340 |
+
t0 = time.perf_counter()
|
| 341 |
+
while start < end:
|
| 342 |
+
n = min(128, end - start)
|
| 343 |
+
indices = []
|
| 344 |
+
for i, stream in enumerate(streams):
|
| 345 |
+
drawn = stream.take(n * batch // 3).reshape(n, batch // 3)
|
| 346 |
+
counts[i] += np.bincount(drawn.ravel(), minlength=sizes[i])
|
| 347 |
+
indices.append(drawn + offsets[i])
|
| 348 |
+
indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device)
|
| 349 |
+
for j in range(n):
|
| 350 |
+
lr.fill_(spec["lr"] * min(1.0, (start + j + 1) / spec["warmup"]))
|
| 351 |
+
last_loss = graph(indices[j])
|
| 352 |
+
start += n
|
| 353 |
+
torch.cuda.synchronize()
|
| 354 |
+
training_seconds += time.perf_counter() - t0
|
| 355 |
+
loss = float(last_loss)
|
| 356 |
+
if not np.isfinite(loss):
|
| 357 |
+
raise FloatingPointError(f"Nonfinite loss at {end}")
|
| 358 |
+
endpoint = measure(end, loss)
|
| 359 |
+
assert start == spec["steps"]
|
| 360 |
+
# Prespecified test-time repeat sweep; these weights never change.
|
| 361 |
+
repeat_metrics = {}
|
| 362 |
+
if isinstance(model, LoopGPT):
|
| 363 |
+
for count in spec["test_repeats"]:
|
| 364 |
+
metrics, predictions = evaluate(model, world, spec["load"], device, count)
|
| 365 |
+
repeat_metrics[str(count)] = metrics
|
| 366 |
+
np.savez_compressed(out / f"repeat-{count:02d}.npz", **predictions)
|
| 367 |
+
np.savez_compressed(out / "exposures.npz", **{f"stratum{i}": c for i, c in enumerate(counts)})
|
| 368 |
+
write_json(
|
| 369 |
+
out / "complete.json",
|
| 370 |
+
{
|
| 371 |
+
"spec": spec,
|
| 372 |
+
"finished_utc": utc(),
|
| 373 |
+
"parameters": parameters,
|
| 374 |
+
"unique_blocks": layers,
|
| 375 |
+
"executed_blocks": layers * repeats,
|
| 376 |
+
"independent_facts": len(world["common_atomic"])
|
| 377 |
+
+ (len(extra) if spec["load"] == "high" or "anchor_atomic" in world else 0),
|
| 378 |
+
"training_seconds": training_seconds,
|
| 379 |
+
"endpoint": endpoint,
|
| 380 |
+
"repeat_metrics": repeat_metrics,
|
| 381 |
+
"examples": start * batch,
|
| 382 |
+
"effective_input_tokens": start * batch * 23 // 3,
|
| 383 |
+
"supervised_tokens": start * batch * 23 // 3,
|
| 384 |
+
"padded_input_tokens": start * batch * 9,
|
| 385 |
+
"source": source,
|
| 386 |
+
"data_sha256": data_digest(world),
|
| 387 |
+
"environment": {"torch": torch.__version__, "gpu": torch.cuda.get_device_name(device)},
|
| 388 |
+
},
|
| 389 |
+
)
|
| 390 |
+
return endpoint
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def audit_run(out, device="cuda:2"):
|
| 394 |
+
"""Independently reload the final checkpoint and regenerate all endpoint tokens."""
|
| 395 |
+
torch.set_num_threads(1)
|
| 396 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 397 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 398 |
+
out = Path(out)
|
| 399 |
+
complete = json.loads((out / "complete.json").read_text())
|
| 400 |
+
saved = torch.load(out / "latest.pt", map_location=device, weights_only=False)
|
| 401 |
+
assert saved["step"] == complete["spec"]["steps"]
|
| 402 |
+
world = build_world(saved["spec"])
|
| 403 |
+
assert data_digest(world) == saved["data_sha256"] == complete["data_sha256"]
|
| 404 |
+
model = construct(saved["spec"], device)
|
| 405 |
+
model.load_state_dict(saved["model"])
|
| 406 |
+
metrics, predictions = evaluate(model, world, saved["spec"]["load"], device)
|
| 407 |
+
expected = np.load(out / f"predictions-{saved['step']:06d}.npz")
|
| 408 |
+
for key, value in predictions.items():
|
| 409 |
+
# Tiny batching/platform differences can affect NLL, never generated tokens.
|
| 410 |
+
np.testing.assert_allclose(value, expected[key], rtol=1e-5, atol=1e-5)
|
| 411 |
+
assert metrics == complete["endpoint"]["metrics"]
|
| 412 |
+
exposures = np.load(out / "exposures.npz")
|
| 413 |
+
for i in range(3):
|
| 414 |
+
np.testing.assert_array_equal(exposures[f"stratum{i}"], saved["counts"][i])
|
| 415 |
+
assert exposures[f"stratum{i}"].sum() == saved["step"] * saved["spec"]["batch_size"] // 3
|
| 416 |
+
assert np.ptp(exposures[f"stratum{i}"]) <= 1
|
| 417 |
+
result = {
|
| 418 |
+
"passed": True,
|
| 419 |
+
"step": saved["step"],
|
| 420 |
+
"prediction_arrays": len(predictions),
|
| 421 |
+
"utc": utc(),
|
| 422 |
+
}
|
| 423 |
+
write_json(out / "audit.json", result)
|
| 424 |
+
return result
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/storage_frontier.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stable training and nested fact loads in ordinary GPT/Loop architectures.
|
| 2 |
+
|
| 3 |
+
The historical storage_composition implementation is reused without changing its
|
| 4 |
+
frozen sources, truth, tokenizer, architecture or full-generation score.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import json
|
| 10 |
+
import math
|
| 11 |
+
import time
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import torch
|
| 16 |
+
|
| 17 |
+
from .grok_depth import EpochStream, make_optimizer, utc, write_json
|
| 18 |
+
from .grok_loop_model import LoopGPT, flops
|
| 19 |
+
from .storage_composition import (
|
| 20 |
+
ARCHITECTURES,
|
| 21 |
+
FullTokenStep,
|
| 22 |
+
construct,
|
| 23 |
+
data_digest,
|
| 24 |
+
evaluate,
|
| 25 |
+
file_hash,
|
| 26 |
+
pack_sentences,
|
| 27 |
+
)
|
| 28 |
+
from .storage_composition import (
|
| 29 |
+
SOURCE_FILES as HISTORICAL_SOURCE_FILES,
|
| 30 |
+
)
|
| 31 |
+
from .storage_composition import (
|
| 32 |
+
build_world as historical_world,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
SOURCE_FILES = [
|
| 36 |
+
*HISTORICAL_SOURCE_FILES,
|
| 37 |
+
"src/llm_memory_editability/storage_frontier.py",
|
| 38 |
+
"scripts/run_storage_frontier.py",
|
| 39 |
+
"tests/test_storage_frontier.py",
|
| 40 |
+
]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def learning_rate(spec, step):
|
| 44 |
+
"""One-based update; paired schedules share the exact same warmup."""
|
| 45 |
+
if not 1 <= step <= spec["steps"]:
|
| 46 |
+
raise ValueError("Step must be within the training budget")
|
| 47 |
+
warmup = spec["warmup"]
|
| 48 |
+
if warmup and step <= warmup:
|
| 49 |
+
return spec["lr"] * step / warmup
|
| 50 |
+
if spec["schedule"] == "constant":
|
| 51 |
+
return spec["lr"]
|
| 52 |
+
if spec["schedule"] != "cosine":
|
| 53 |
+
raise ValueError("Unknown learning-rate schedule")
|
| 54 |
+
fraction = (step - warmup) / (spec["steps"] - warmup)
|
| 55 |
+
floor = spec["min_lr_ratio"]
|
| 56 |
+
return spec["lr"] * (floor + (1 - floor) * (1 + math.cos(math.pi * fraction)) / 2)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def build_world(spec):
|
| 60 |
+
world = historical_world(spec)
|
| 61 |
+
if "extra_count" in spec:
|
| 62 |
+
# A world-specific, fixed permutation defines nested distractor fact sets.
|
| 63 |
+
# Common facts and every combination example remain bit-identical.
|
| 64 |
+
count = spec["extra_count"]
|
| 65 |
+
if not 0 < count <= len(world["extra_atomic"]):
|
| 66 |
+
raise ValueError("Extra fact count exceeds the fixed master graph")
|
| 67 |
+
rng = np.random.default_rng(spec["world"] + 900000)
|
| 68 |
+
order = rng.permutation(len(world["extra_atomic"]))
|
| 69 |
+
world["extra_atomic"] = world["extra_atomic"][order[:count]]
|
| 70 |
+
return world
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def strata_for(spec, world):
|
| 74 |
+
extra = world["extra_atomic"] if spec["load"] == "high" else world["anchor_atomic"]
|
| 75 |
+
return [world["common_atomic"], world["train_composite"], extra]
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def run_name(spec):
|
| 79 |
+
load = spec["load"]
|
| 80 |
+
if "extra_count" in spec:
|
| 81 |
+
load = f"f{spec['extra_count'] + 8 * (spec['familiar_n'] + spec['strict_n'])}"
|
| 82 |
+
return (
|
| 83 |
+
f"w{spec['world']}-i{spec['initialization']}-{spec['architecture']}"
|
| 84 |
+
f"-d{spec['width']}-{load}-{spec['schedule']}-s{spec['steps']}"
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def train(spec, out, source, device="cuda:0"):
|
| 89 |
+
out = Path(out)
|
| 90 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 91 |
+
if (out / "latest.pt").exists() or (out / "complete.json").exists():
|
| 92 |
+
raise FileExistsError(f"Do not overwrite an existing training attempt: {out}")
|
| 93 |
+
torch.set_num_threads(1)
|
| 94 |
+
torch.set_num_interop_threads(1)
|
| 95 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 96 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 97 |
+
device = torch.device(device)
|
| 98 |
+
torch.cuda.set_device(device)
|
| 99 |
+
world = build_world(spec)
|
| 100 |
+
np.savez_compressed(out / "world.npz", **world)
|
| 101 |
+
digest = data_digest(world)
|
| 102 |
+
write_json(out / "spec.json", {"spec": spec, "source": source, "data_sha256": digest})
|
| 103 |
+
model = construct(spec, device)
|
| 104 |
+
initial_sha = file_hash(out / "spec.json")
|
| 105 |
+
lr = torch.tensor(spec["lr"], device=device)
|
| 106 |
+
optimizer = make_optimizer(model, lr, spec["weight_decay"])
|
| 107 |
+
strata = strata_for(spec, world)
|
| 108 |
+
table = tuple(
|
| 109 |
+
torch.as_tensor(np.concatenate(parts), device=device)
|
| 110 |
+
for parts in zip(*(pack_sentences(rows) for rows in strata), strict=True)
|
| 111 |
+
)
|
| 112 |
+
sizes = [len(rows) for rows in strata]
|
| 113 |
+
offsets = np.cumsum([0, *sizes[:-1]])
|
| 114 |
+
streams = [EpochStream(size, spec["stream_seed"] + i) for i, size in enumerate(sizes)]
|
| 115 |
+
counts = [np.zeros(size, dtype=np.int64) for size in sizes]
|
| 116 |
+
batch = spec["batch_size"]
|
| 117 |
+
if batch % 3:
|
| 118 |
+
raise ValueError("Batch must divide into three equal streams")
|
| 119 |
+
graph = FullTokenStep(model, optimizer, table, batch)
|
| 120 |
+
layers, repeats = ARCHITECTURES[spec["architecture"]]
|
| 121 |
+
flop_step = flops(model.config, repeats, batch, 9, output_positions=9)
|
| 122 |
+
history, training_seconds, start = [], 0.0, 0
|
| 123 |
+
|
| 124 |
+
def measure(step, loss=None):
|
| 125 |
+
metrics, predictions = evaluate(model, world, spec["load"], device)
|
| 126 |
+
row = {
|
| 127 |
+
"step": step,
|
| 128 |
+
"lr": learning_rate(spec, step) if step else 0,
|
| 129 |
+
"metrics": metrics,
|
| 130 |
+
"loss": loss,
|
| 131 |
+
"training_seconds": training_seconds,
|
| 132 |
+
"estimated_training_flops": step * flop_step,
|
| 133 |
+
}
|
| 134 |
+
history.append(row)
|
| 135 |
+
write_json(out / "learning.json", history)
|
| 136 |
+
np.savez_compressed(out / f"predictions-{step:06d}.npz", **predictions)
|
| 137 |
+
state = {
|
| 138 |
+
"spec": spec,
|
| 139 |
+
"step": step,
|
| 140 |
+
"model": model.state_dict(),
|
| 141 |
+
"optimizer": optimizer.state_dict(),
|
| 142 |
+
"streams": [stream.state_dict() for stream in streams],
|
| 143 |
+
"counts": counts,
|
| 144 |
+
"cpu_rng": torch.get_rng_state(),
|
| 145 |
+
"cuda_rng": torch.cuda.get_rng_state(device),
|
| 146 |
+
"source": source,
|
| 147 |
+
"data_sha256": digest,
|
| 148 |
+
}
|
| 149 |
+
torch.save(state, out / "latest.tmp.pt")
|
| 150 |
+
(out / "latest.tmp.pt").replace(out / "latest.pt")
|
| 151 |
+
write_json(out / "status.json", {"step": step, "budget": spec["steps"]})
|
| 152 |
+
print(json.dumps({"run": run_name(spec), "step": step, "metrics": metrics}), flush=True)
|
| 153 |
+
return row
|
| 154 |
+
|
| 155 |
+
measure(0)
|
| 156 |
+
for end in spec["nodes"]:
|
| 157 |
+
if not end:
|
| 158 |
+
continue
|
| 159 |
+
torch.cuda.synchronize()
|
| 160 |
+
started = time.perf_counter()
|
| 161 |
+
while start < end:
|
| 162 |
+
n = min(128, end - start)
|
| 163 |
+
indices = []
|
| 164 |
+
for i, stream in enumerate(streams):
|
| 165 |
+
drawn = stream.take(n * batch // 3).reshape(n, batch // 3)
|
| 166 |
+
counts[i] += np.bincount(drawn.ravel(), minlength=sizes[i])
|
| 167 |
+
indices.append(drawn + offsets[i])
|
| 168 |
+
indices = torch.as_tensor(np.concatenate(indices, axis=1), device=device)
|
| 169 |
+
for j in range(n):
|
| 170 |
+
lr.fill_(learning_rate(spec, start + j + 1))
|
| 171 |
+
last_loss = graph(indices[j])
|
| 172 |
+
start += n
|
| 173 |
+
torch.cuda.synchronize()
|
| 174 |
+
training_seconds += time.perf_counter() - started
|
| 175 |
+
loss = float(last_loss)
|
| 176 |
+
if not np.isfinite(loss):
|
| 177 |
+
raise FloatingPointError(f"Nonfinite training loss at {end}")
|
| 178 |
+
endpoint = measure(end, loss)
|
| 179 |
+
assert start == spec["steps"]
|
| 180 |
+
repeat_metrics = {}
|
| 181 |
+
if isinstance(model, LoopGPT):
|
| 182 |
+
for repeat in spec["test_repeats"]:
|
| 183 |
+
metrics, predictions = evaluate(model, world, spec["load"], device, repeat)
|
| 184 |
+
repeat_metrics[str(repeat)] = metrics
|
| 185 |
+
np.savez_compressed(out / f"repeat-{repeat:02d}.npz", **predictions)
|
| 186 |
+
np.savez_compressed(out / "exposures.npz", **{f"stratum{i}": c for i, c in enumerate(counts)})
|
| 187 |
+
result = {
|
| 188 |
+
"spec": spec,
|
| 189 |
+
"finished_utc": utc(),
|
| 190 |
+
"parameters": sum(p.numel() for p in model.parameters()),
|
| 191 |
+
"unique_blocks": layers,
|
| 192 |
+
"executed_blocks": layers * repeats,
|
| 193 |
+
"independent_facts": len(strata[0]) + len(strata[2]),
|
| 194 |
+
"training_seconds": training_seconds,
|
| 195 |
+
"endpoint": endpoint,
|
| 196 |
+
"repeat_metrics": repeat_metrics,
|
| 197 |
+
"source": source,
|
| 198 |
+
"data_sha256": digest,
|
| 199 |
+
"spec_sha256": initial_sha,
|
| 200 |
+
"checkpoint_sha256": file_hash(out / "latest.pt"),
|
| 201 |
+
"supervised_tokens": start * batch * 23 // 3,
|
| 202 |
+
"padded_input_tokens": start * batch * 9,
|
| 203 |
+
"environment": {
|
| 204 |
+
"torch": torch.__version__,
|
| 205 |
+
"numpy": np.__version__,
|
| 206 |
+
"cuda": torch.version.cuda,
|
| 207 |
+
"gpu": torch.cuda.get_device_name(device),
|
| 208 |
+
"tf32": True,
|
| 209 |
+
},
|
| 210 |
+
}
|
| 211 |
+
write_json(out / "complete.json", result)
|
| 212 |
+
return result
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def audit(out, device="cuda:0"):
|
| 216 |
+
"""Independent-process reload: tokens exact, floating NLL tolerance recorded."""
|
| 217 |
+
out = Path(out)
|
| 218 |
+
torch.set_num_threads(1)
|
| 219 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 220 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 221 |
+
torch.cuda.set_device(torch.device(device))
|
| 222 |
+
complete = json.loads((out / "complete.json").read_text())
|
| 223 |
+
saved = torch.load(out / "latest.pt", map_location=device, weights_only=False)
|
| 224 |
+
assert saved["step"] == complete["spec"]["steps"]
|
| 225 |
+
assert file_hash(out / "latest.pt") == complete["checkpoint_sha256"]
|
| 226 |
+
world = build_world(saved["spec"])
|
| 227 |
+
assert data_digest(world) == saved["data_sha256"] == complete["data_sha256"]
|
| 228 |
+
model = construct(saved["spec"], device)
|
| 229 |
+
model.load_state_dict(saved["model"])
|
| 230 |
+
metrics, predictions = evaluate(model, world, saved["spec"]["load"], device)
|
| 231 |
+
expected = np.load(out / f"predictions-{saved['step']:06d}.npz")
|
| 232 |
+
max_nll_difference = 0.0
|
| 233 |
+
for key, value in predictions.items():
|
| 234 |
+
if key.endswith("answer_nll"):
|
| 235 |
+
max_nll_difference = max(max_nll_difference, float(np.abs(value - expected[key]).max()))
|
| 236 |
+
np.testing.assert_allclose(value, expected[key], rtol=1e-5, atol=1e-5)
|
| 237 |
+
else:
|
| 238 |
+
np.testing.assert_array_equal(value, expected[key])
|
| 239 |
+
for task, values in metrics.items():
|
| 240 |
+
for key, value in values.items():
|
| 241 |
+
reference = complete["endpoint"]["metrics"][task][key]
|
| 242 |
+
if key == "answer_nll":
|
| 243 |
+
np.testing.assert_allclose(value, reference, rtol=1e-5, atol=1e-5)
|
| 244 |
+
else:
|
| 245 |
+
assert value == reference
|
| 246 |
+
exposures = np.load(out / "exposures.npz")
|
| 247 |
+
for i in range(3):
|
| 248 |
+
np.testing.assert_array_equal(exposures[f"stratum{i}"], saved["counts"][i])
|
| 249 |
+
assert exposures[f"stratum{i}"].sum() == saved["step"] * saved["spec"]["batch_size"] // 3
|
| 250 |
+
assert np.ptp(exposures[f"stratum{i}"]) <= 1
|
| 251 |
+
result = {
|
| 252 |
+
"passed": True,
|
| 253 |
+
"step": saved["step"],
|
| 254 |
+
"prediction_arrays": len(predictions),
|
| 255 |
+
"max_nll_difference": max_nll_difference,
|
| 256 |
+
"nll_rtol": 1e-5,
|
| 257 |
+
"nll_atol": 1e-5,
|
| 258 |
+
"tokens_exact": True,
|
| 259 |
+
"utc": utc(),
|
| 260 |
+
}
|
| 261 |
+
write_json(out / "audit.json", result)
|
| 262 |
+
return result
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/text_loss_source.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Factorial loss-source interventions on an unchanged text-pretraining stream."""
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
import time
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import torch
|
| 10 |
+
from torch.nn import functional as F
|
| 11 |
+
|
| 12 |
+
from .grok_depth import EpochStream, GraphStep, make_optimizer, write_json
|
| 13 |
+
from .grok_loop_model import flops
|
| 14 |
+
from .text_pretrain import construct, evaluate, sha
|
| 15 |
+
|
| 16 |
+
ARMS = {"AB": (1, 1), "A": (1, 0), "B": (0, 1), "N": (0, 0)}
|
| 17 |
+
SPLITS = ("atomic", "background_train", "background_test", "target_train", "target_test")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def loss_sources(labels, bounds):
|
| 21 |
+
"""0=atomic text, 1=background composition, 2=neutral text, -1=ignored."""
|
| 22 |
+
result = np.full(labels.shape, -1, dtype=np.int64)
|
| 23 |
+
result[: bounds[1]] = 0
|
| 24 |
+
result[bounds[1] : bounds[2]] = 1
|
| 25 |
+
result[bounds[2] :, :15] = 0
|
| 26 |
+
result[bounds[2] :, 16:] = 2
|
| 27 |
+
result[labels == -100] = -1
|
| 28 |
+
assert np.array_equal(result >= 0, labels != -100)
|
| 29 |
+
return result
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def weights_for(source, arm):
|
| 33 |
+
a, b = ARMS[arm]
|
| 34 |
+
return ((source == 0) * a + (source == 1) * b + (source == 2)).astype(np.float32)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def weighted_loss(logits, labels, weights):
|
| 38 |
+
per_token = F.cross_entropy(
|
| 39 |
+
logits.flatten(0, 1), labels.flatten(), reduction="none", ignore_index=-100
|
| 40 |
+
).view_as(labels)
|
| 41 |
+
# Removing a source does NOT renormalize the remaining losses.
|
| 42 |
+
return (per_token * weights).sum() / (labels != -100).sum()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class SourceGraphStep(GraphStep):
|
| 46 |
+
def eager(self):
|
| 47 |
+
self.optimizer.zero_grad(set_to_none=False)
|
| 48 |
+
x, positions, mask, labels, weights = (t[self.index] for t in self.table)
|
| 49 |
+
logits = self.model(x, position_ids=positions, attention_mask=mask)
|
| 50 |
+
loss = weighted_loss(logits, labels, weights)
|
| 51 |
+
loss.backward()
|
| 52 |
+
norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True)
|
| 53 |
+
self.optimizer.step()
|
| 54 |
+
return loss, norm
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@torch.inference_mode()
|
| 58 |
+
def measure(model, world, table, source, device):
|
| 59 |
+
scores, predictions = {}, {}
|
| 60 |
+
for split in SPLITS:
|
| 61 |
+
scores[split], pred = evaluate(model, world[split], device, composite=split != "atomic")
|
| 62 |
+
predictions.update({split + "_" + k: v for k, v in pred.items()})
|
| 63 |
+
atomic = predictions["atomic_answer"] == world["atomic"][:, -1]
|
| 64 |
+
known = {(h, r): ok for (h, r, _), ok in zip(world["atomic"], atomic, strict=True)}
|
| 65 |
+
eligible = np.array([known[h, r1] and known[b, r2] for h, r1, b, r2, t in world["target_test"]])
|
| 66 |
+
full = (predictions["target_test_answer"] == world["target_test"][:, -1]) & (
|
| 67 |
+
predictions["target_test_stops"] == [5, 1]
|
| 68 |
+
).all(-1)
|
| 69 |
+
scores["both_atomics"] = dict(
|
| 70 |
+
n=int(eligible.sum()),
|
| 71 |
+
coverage=float(eligible.mean()),
|
| 72 |
+
accuracy=float(full[eligible].mean()) if eligible.any() else None,
|
| 73 |
+
)
|
| 74 |
+
sums, counts = np.zeros(3), np.zeros(3, dtype=np.int64)
|
| 75 |
+
for start in range(0, len(table[0]), 128):
|
| 76 |
+
x, pos, mask, labels = [
|
| 77 |
+
torch.as_tensor(t[start : start + 128], device=device) for t in table[:4]
|
| 78 |
+
]
|
| 79 |
+
logits = model(x, position_ids=pos, attention_mask=mask)
|
| 80 |
+
nll = (
|
| 81 |
+
F.cross_entropy(
|
| 82 |
+
logits.flatten(0, 1), labels.flatten(), reduction="none", ignore_index=-100
|
| 83 |
+
)
|
| 84 |
+
.view_as(labels)
|
| 85 |
+
.cpu()
|
| 86 |
+
.numpy()
|
| 87 |
+
)
|
| 88 |
+
for group in range(3):
|
| 89 |
+
selected = source[start : start + 128] == group
|
| 90 |
+
sums[group] += nll[selected].sum(dtype=np.float64)
|
| 91 |
+
counts[group] += selected.sum()
|
| 92 |
+
scores["training_text_nll"] = {
|
| 93 |
+
name: float(sums[i] / counts[i])
|
| 94 |
+
for i, name in enumerate(("atomic", "background", "neutral"))
|
| 95 |
+
}
|
| 96 |
+
return scores, predictions
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def run(cfg, name, device):
|
| 100 |
+
overrides = cfg["runs"][name]
|
| 101 |
+
root = Path(cfg["output_root"]) / name
|
| 102 |
+
if (root / "complete.json").exists():
|
| 103 |
+
return
|
| 104 |
+
lock = json.loads(Path(cfg["lock"]).read_text())
|
| 105 |
+
for p, digest in lock["sources"].items():
|
| 106 |
+
assert sha(p) == digest, p
|
| 107 |
+
assert sha(cfg["config_path"]) == lock["config_sha256"]
|
| 108 |
+
assert sha(cfg["plan"]) == lock["plan_sha256"]
|
| 109 |
+
for p, expected in lock["inputs"].items():
|
| 110 |
+
assert sha(p) == expected, p
|
| 111 |
+
parent = Path(overrides["parent"])
|
| 112 |
+
assert sha(parent / "latest.pt") == lock["parents"][str(parent / "latest.pt")]
|
| 113 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 114 |
+
state = torch.load(parent / "latest.pt", map_location=device, weights_only=False)
|
| 115 |
+
spec = state["spec"]
|
| 116 |
+
assert spec["arm"] == "P1" and state["step"] == 32000
|
| 117 |
+
world = dict(np.load(parent / "world.npz"))
|
| 118 |
+
stored = np.load(parent / "training-table.npz")
|
| 119 |
+
table = tuple(stored[k] for k in ("tokens", "positions", "mask", "labels"))
|
| 120 |
+
bounds = np.cumsum(
|
| 121 |
+
[0, len(world["atomic"]), len(world["background_train"]), len(world["target_train"])]
|
| 122 |
+
)
|
| 123 |
+
source = loss_sources(table[3], bounds)
|
| 124 |
+
weights = weights_for(source, overrides["arm"])
|
| 125 |
+
gpu_table = tuple(torch.as_tensor(t, device=device) for t in (*table, weights))
|
| 126 |
+
model = construct(spec, device)
|
| 127 |
+
model.load_state_dict(state["model"])
|
| 128 |
+
opt = make_optimizer(model, torch.tensor(spec["lr"], device=device), spec["weight_decay"])
|
| 129 |
+
opt.load_state_dict(state["optimizer"])
|
| 130 |
+
streams = [EpochStream(bounds[i + 1] - bounds[i], spec["world"] + 100 + i) for i in range(3)]
|
| 131 |
+
for stream, saved in zip(streams, state["streams"], strict=True):
|
| 132 |
+
stream.load_state_dict(saved)
|
| 133 |
+
torch.set_rng_state(state["cpu_rng"].cpu())
|
| 134 |
+
torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device)
|
| 135 |
+
settings = dict(
|
| 136 |
+
parent=str(parent),
|
| 137 |
+
world=spec["world"],
|
| 138 |
+
initialization=spec["initialization"],
|
| 139 |
+
arm=overrides["arm"],
|
| 140 |
+
steps=cfg["steps"],
|
| 141 |
+
parent_sha256=sha(parent / "latest.pt"),
|
| 142 |
+
config=cfg["config_path"],
|
| 143 |
+
)
|
| 144 |
+
write_json(root / "settings.json", settings)
|
| 145 |
+
start, elapsed, histories = 0, 0.0, []
|
| 146 |
+
digest = hashlib.sha256()
|
| 147 |
+
# Recovery is deliberately from this branch's saved stream, never its parent's.
|
| 148 |
+
if (root / "latest.pt").exists():
|
| 149 |
+
saved = torch.load(root / "latest.pt", map_location=device, weights_only=False)
|
| 150 |
+
assert saved["settings"] == settings
|
| 151 |
+
model.load_state_dict(saved["model"])
|
| 152 |
+
opt.load_state_dict(saved["optimizer"])
|
| 153 |
+
for stream, value in zip(streams, saved["streams"], strict=True):
|
| 154 |
+
stream.load_state_dict(value)
|
| 155 |
+
torch.set_rng_state(saved["cpu_rng"].cpu())
|
| 156 |
+
torch.cuda.set_rng_state(saved["cuda_rng"].cpu(), device)
|
| 157 |
+
start, elapsed, histories = saved["step"], saved["seconds"], saved["histories"]
|
| 158 |
+
# Rebuild the hash of previously consumed paired indices from the parent state.
|
| 159 |
+
replay = [EpochStream(bounds[i + 1] - bounds[i], 0) for i in range(3)]
|
| 160 |
+
for stream, value in zip(replay, state["streams"], strict=True):
|
| 161 |
+
stream.load_state_dict(value)
|
| 162 |
+
for _ in range(start):
|
| 163 |
+
idx = np.concatenate(
|
| 164 |
+
[
|
| 165 |
+
stream.take(n) + lo
|
| 166 |
+
for stream, n, lo in zip(replay, spec["batch_parts"], bounds[:-1], strict=True)
|
| 167 |
+
]
|
| 168 |
+
)
|
| 169 |
+
digest.update(idx.tobytes())
|
| 170 |
+
initial_vector = torch.nn.utils.parameters_to_vector(
|
| 171 |
+
[v for v in state["model"].values()]
|
| 172 |
+
).clone()
|
| 173 |
+
|
| 174 |
+
def checkpoint(step):
|
| 175 |
+
metrics, predictions = measure(model, world, table, source, device)
|
| 176 |
+
record = dict(
|
| 177 |
+
step=step,
|
| 178 |
+
seconds=elapsed,
|
| 179 |
+
metrics=metrics,
|
| 180 |
+
parameter_l2_from_source=float(
|
| 181 |
+
torch.linalg.vector_norm(
|
| 182 |
+
torch.nn.utils.parameters_to_vector(model.parameters()).detach()
|
| 183 |
+
- initial_vector
|
| 184 |
+
)
|
| 185 |
+
),
|
| 186 |
+
last_loss=None if step == 0 else float(graph.loss),
|
| 187 |
+
last_gradient_norm=None if step == 0 else float(graph.grad_norm),
|
| 188 |
+
)
|
| 189 |
+
histories.append(record)
|
| 190 |
+
np.savez_compressed(root / f"predictions-{step:06d}.npz", **predictions)
|
| 191 |
+
write_json(root / "learning.json", histories)
|
| 192 |
+
model.train()
|
| 193 |
+
current = dict(
|
| 194 |
+
model=model.state_dict(),
|
| 195 |
+
optimizer=opt.state_dict(),
|
| 196 |
+
streams=[s.state_dict() for s in streams],
|
| 197 |
+
cpu_rng=torch.get_rng_state(),
|
| 198 |
+
cuda_rng=torch.cuda.get_rng_state(device),
|
| 199 |
+
step=step,
|
| 200 |
+
seconds=elapsed,
|
| 201 |
+
histories=histories,
|
| 202 |
+
settings=settings,
|
| 203 |
+
)
|
| 204 |
+
tmp = root / "latest.tmp"
|
| 205 |
+
torch.save(current, tmp)
|
| 206 |
+
tmp.replace(root / "latest.pt")
|
| 207 |
+
if step == 0 or step == cfg["steps"]:
|
| 208 |
+
torch.save(
|
| 209 |
+
dict(model=current["model"], step=step, settings=settings),
|
| 210 |
+
root / f"weights-{step:06d}.pt",
|
| 211 |
+
)
|
| 212 |
+
print(
|
| 213 |
+
json.dumps(
|
| 214 |
+
dict(
|
| 215 |
+
run=name,
|
| 216 |
+
step=step,
|
| 217 |
+
target=metrics["target_test"]["accuracy"],
|
| 218 |
+
atomic=metrics["atomic"]["accuracy"],
|
| 219 |
+
background=metrics["background_test"]["accuracy"],
|
| 220 |
+
)
|
| 221 |
+
),
|
| 222 |
+
flush=True,
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
if start == 0:
|
| 226 |
+
checkpoint(0)
|
| 227 |
+
graph = SourceGraphStep(model, opt, gpu_table, sum(spec["batch_parts"]))
|
| 228 |
+
tick = time.monotonic()
|
| 229 |
+
for step in range(start + 1, cfg["steps"] + 1):
|
| 230 |
+
idx = np.concatenate(
|
| 231 |
+
[
|
| 232 |
+
stream.take(n) + lo
|
| 233 |
+
for stream, n, lo in zip(streams, spec["batch_parts"], bounds[:-1], strict=True)
|
| 234 |
+
]
|
| 235 |
+
)
|
| 236 |
+
digest.update(idx.tobytes())
|
| 237 |
+
graph(torch.as_tensor(idx, device=device))
|
| 238 |
+
if step in cfg["nodes"]:
|
| 239 |
+
torch.cuda.synchronize()
|
| 240 |
+
elapsed += time.monotonic() - tick
|
| 241 |
+
checkpoint(step)
|
| 242 |
+
tick = time.monotonic()
|
| 243 |
+
a, b = ARMS[overrides["arm"]]
|
| 244 |
+
write_json(
|
| 245 |
+
root / "complete.json",
|
| 246 |
+
dict(
|
| 247 |
+
settings=settings,
|
| 248 |
+
final=histories[-1],
|
| 249 |
+
sample_trace_sha256=digest.hexdigest(),
|
| 250 |
+
visible_supervised_tokens=cfg["steps"] * 1984,
|
| 251 |
+
active_supervised_tokens=cfg["steps"] * (1120 * a + 288 * b + 576),
|
| 252 |
+
estimated_flops=cfg["steps"]
|
| 253 |
+
* flops(model.config, spec["repeats"], 128, 25, output_positions=25),
|
| 254 |
+
checkpoint_sha256=sha(root / "latest.pt"),
|
| 255 |
+
),
|
| 256 |
+
)
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/text_pretrain.py
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Paired full-token text pretraining with controlled cross-document access.
|
| 2 |
+
|
| 3 |
+
P0/P1 have identical token arrays and labels; only document attention changes.
|
| 4 |
+
P2 replaces an isolated neutral record by a derived fact, an explicit change in
|
| 5 |
+
supervision. This is controlled template-language pretraining, not a pretrained
|
| 6 |
+
natural-language model or a replication of the original bioS scale.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import hashlib
|
| 12 |
+
import json
|
| 13 |
+
import time
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
+
from torch.nn import functional as F
|
| 19 |
+
|
| 20 |
+
from .bios_model import ModelConfig
|
| 21 |
+
from .grok_depth import EpochStream, GraphStep, make_optimizer, write_json
|
| 22 |
+
from .grok_loop_model import LoopGPT, flops
|
| 23 |
+
|
| 24 |
+
WORDS = [
|
| 25 |
+
"<pad>",
|
| 26 |
+
"<eos>",
|
| 27 |
+
"<bos>",
|
| 28 |
+
"'s",
|
| 29 |
+
"is",
|
| 30 |
+
".",
|
| 31 |
+
"This",
|
| 32 |
+
"record",
|
| 33 |
+
"has",
|
| 34 |
+
"no",
|
| 35 |
+
"additional",
|
| 36 |
+
"fact",
|
| 37 |
+
"here",
|
| 38 |
+
"mentor",
|
| 39 |
+
"advisor",
|
| 40 |
+
"coach",
|
| 41 |
+
"supervisor",
|
| 42 |
+
"city",
|
| 43 |
+
"district",
|
| 44 |
+
"region",
|
| 45 |
+
"campus",
|
| 46 |
+
]
|
| 47 |
+
LENGTH = 26
|
| 48 |
+
PAD, EOS, BOS = 0, 1, 2
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def sha(path):
|
| 52 |
+
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def vocabulary(spec):
|
| 56 |
+
return (
|
| 57 |
+
WORDS
|
| 58 |
+
+ [f"Person{i:03d}" for i in range(spec["heads_n"])]
|
| 59 |
+
+ [f"Expert{i:03d}" for i in range(spec["bridges_n"])]
|
| 60 |
+
+ [f"Place{i:03d}" for i in range(spec["tails_n"])]
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def atomic_sentence(row):
|
| 65 |
+
h, r, t = map(int, row)
|
| 66 |
+
return [BOS, h, 3, r, 4, t, 5, EOS]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def composite_sentence(row):
|
| 70 |
+
h, r1, _b, r2, t = map(int, row)
|
| 71 |
+
return [BOS, h, 3, r1, 3, r2, 4, t, 5, EOS]
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def pack_documents(documents, groups):
|
| 75 |
+
"""Reset positions per record in every arm; BOS is an exogenous boundary.
|
| 76 |
+
|
| 77 |
+
All remaining next-token targets, including names, relations and EOS, are
|
| 78 |
+
supervised. The next record's BOS and padding are never prediction targets.
|
| 79 |
+
"""
|
| 80 |
+
seq, positions, segments = [], [], []
|
| 81 |
+
for doc, group in zip(documents, groups, strict=True):
|
| 82 |
+
seq.extend(doc)
|
| 83 |
+
positions.extend(range(len(doc)))
|
| 84 |
+
segments.extend([group] * len(doc))
|
| 85 |
+
if len(seq) > LENGTH:
|
| 86 |
+
raise ValueError("Record exceeds fixed context")
|
| 87 |
+
n = len(seq)
|
| 88 |
+
seq += [PAD] * (LENGTH - n)
|
| 89 |
+
positions += [0] * (LENGTH - n)
|
| 90 |
+
segments += list(range(100, 100 + LENGTH - n))
|
| 91 |
+
labels = np.asarray(seq[1:], dtype=np.int64)
|
| 92 |
+
labels[(labels == BOS) | (labels == PAD)] = -100
|
| 93 |
+
seg = np.asarray(segments[:-1])
|
| 94 |
+
mask = (seg[:, None] == seg[None, :]) & np.tri(LENGTH - 1, dtype=bool)
|
| 95 |
+
return (
|
| 96 |
+
np.asarray(seq[:-1], dtype=np.int64),
|
| 97 |
+
np.asarray(positions[:-1], dtype=np.int64),
|
| 98 |
+
mask[None],
|
| 99 |
+
labels,
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def build_world(spec):
|
| 104 |
+
"""One supplied world; complete head-tail pairs held out before rendering."""
|
| 105 |
+
rng = np.random.default_rng(spec["world"])
|
| 106 |
+
hn, bn, tn = spec["heads_n"], spec["bridges_n"], spec["tails_n"]
|
| 107 |
+
hs = np.arange(len(WORDS), len(WORDS) + hn)
|
| 108 |
+
bs = np.arange(hs[-1] + 1, hs[-1] + 1 + bn)
|
| 109 |
+
ts = np.arange(bs[-1] + 1, bs[-1] + 1 + tn)
|
| 110 |
+
first = np.array([(h, r, rng.choice(bs)) for h in hs for r in range(13, 17)])
|
| 111 |
+
second = np.array([(b, r, rng.choice(ts)) for b in bs for r in range(17, 21)])
|
| 112 |
+
lookup = {(int(h), int(r)): int(t) for h, r, t in second}
|
| 113 |
+
paths = np.array(
|
| 114 |
+
[(h, r1, b, r2, lookup[int(b), r2]) for h, r1, b in first for r2 in range(17, 21)],
|
| 115 |
+
dtype=np.int64,
|
| 116 |
+
)
|
| 117 |
+
reserved = rng.random((hn, tn)) < spec["holdout_fraction"]
|
| 118 |
+
held = reserved[paths[:, 0] - hs[0], paths[:, 4] - ts[0]]
|
| 119 |
+
background = paths[:, 0] < hs[0] + hn // 2
|
| 120 |
+
groups = {
|
| 121 |
+
"atomic_first": first,
|
| 122 |
+
"atomic_second": second,
|
| 123 |
+
"background_train": paths[background & ~held],
|
| 124 |
+
"background_test": paths[background & held],
|
| 125 |
+
"target_train": paths[~background & ~held],
|
| 126 |
+
"target_test": paths[~background & held],
|
| 127 |
+
}
|
| 128 |
+
for key, rows in groups.items():
|
| 129 |
+
if not len(rows):
|
| 130 |
+
raise ValueError(f"Empty world stratum {key}; do not silently reroll")
|
| 131 |
+
train_pairs = {tuple(r[[0, 4]]) for r in paths[~held]}
|
| 132 |
+
test_pairs = {tuple(r[[0, 4]]) for r in paths[held]}
|
| 133 |
+
assert not train_pairs & test_pairs
|
| 134 |
+
# Typed atomics can never expose a head and a tail together.
|
| 135 |
+
assert not set(first[:, 0]) & set(second[:, 0])
|
| 136 |
+
assert not set(first[:, 2]) & set(second[:, 2])
|
| 137 |
+
groups["atomic"] = np.concatenate([first, second])
|
| 138 |
+
groups["all_paths"] = paths
|
| 139 |
+
return groups
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def training_table(world, arm):
|
| 143 |
+
if arm not in ("P0", "P1", "P2"):
|
| 144 |
+
raise ValueError(arm)
|
| 145 |
+
packed = [pack_documents([atomic_sentence(r)], [0]) for r in world["atomic"]]
|
| 146 |
+
base_end = len(packed)
|
| 147 |
+
packed.extend(pack_documents([composite_sentence(r)], [0]) for r in world["background_train"])
|
| 148 |
+
background_end = len(packed)
|
| 149 |
+
neutral = [BOS, 6, 7, 8, 9, 10, 11, 12, 5, EOS]
|
| 150 |
+
for row in world["target_train"]:
|
| 151 |
+
h, r1, b, r2, t = row
|
| 152 |
+
third = composite_sentence(row) if arm == "P2" else neutral
|
| 153 |
+
packed.append(
|
| 154 |
+
pack_documents(
|
| 155 |
+
[atomic_sentence([h, r1, b]), atomic_sentence([b, r2, t]), third],
|
| 156 |
+
[0, 1, 2] if arm == "P0" else [0, 0, 2],
|
| 157 |
+
)
|
| 158 |
+
)
|
| 159 |
+
table = tuple(np.stack([row[i] for row in packed]) for i in range(4))
|
| 160 |
+
return table, [0, base_end, background_end, len(packed)]
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class TextGPT(LoopGPT):
|
| 164 |
+
def forward(self, tokens, position_ids=None, attention_mask=None, patch=None, cache=None):
|
| 165 |
+
if position_ids is None:
|
| 166 |
+
position_ids = torch.arange(tokens.shape[1], device=tokens.device)[None]
|
| 167 |
+
p = self.dropout if self.training else 0.0
|
| 168 |
+
x = F.dropout(self.token(tokens) + self.position(position_ids), p=p, training=self.training)
|
| 169 |
+
for layer, block in enumerate(self.iter_blocks()):
|
| 170 |
+
z = block.ln1(x)
|
| 171 |
+
batch, length, width = z.shape
|
| 172 |
+
a = block.attention
|
| 173 |
+
q, k, v = a.qkv(z).view(batch, length, 3, a.heads, width // a.heads).unbind(2)
|
| 174 |
+
y = F.scaled_dot_product_attention(
|
| 175 |
+
q.transpose(1, 2),
|
| 176 |
+
k.transpose(1, 2),
|
| 177 |
+
v.transpose(1, 2),
|
| 178 |
+
attn_mask=attention_mask,
|
| 179 |
+
is_causal=attention_mask is None,
|
| 180 |
+
dropout_p=p,
|
| 181 |
+
)
|
| 182 |
+
attn = F.dropout(
|
| 183 |
+
a.proj(y.transpose(1, 2).reshape(batch, length, width)), p=p, training=self.training
|
| 184 |
+
)
|
| 185 |
+
mlp = F.dropout(block.mlp(block.ln2(x + attn)), p=p, training=self.training)
|
| 186 |
+
if cache is not None:
|
| 187 |
+
cache[layer] = {
|
| 188 |
+
"attention": attn.detach(),
|
| 189 |
+
"mlp": mlp.detach(),
|
| 190 |
+
"full": (x + attn + mlp).detach(),
|
| 191 |
+
}
|
| 192 |
+
if patch is not None and layer == patch["layer"]:
|
| 193 |
+
pos, value, component = patch["position"], patch["value"], patch["component"]
|
| 194 |
+
if component == "full":
|
| 195 |
+
x = x + attn + mlp
|
| 196 |
+
x = x.clone()
|
| 197 |
+
x[:, pos] = value
|
| 198 |
+
continue
|
| 199 |
+
if component == "attention":
|
| 200 |
+
attn = attn.clone()
|
| 201 |
+
attn[:, pos] = value
|
| 202 |
+
elif component == "mlp":
|
| 203 |
+
mlp = mlp.clone()
|
| 204 |
+
mlp[:, pos] = value
|
| 205 |
+
else:
|
| 206 |
+
raise ValueError(component)
|
| 207 |
+
x = x + attn + mlp
|
| 208 |
+
return F.linear(self.ln_final(x), self.token.weight)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
class TextGraphStep(GraphStep):
|
| 212 |
+
def eager(self):
|
| 213 |
+
self.optimizer.zero_grad(set_to_none=False)
|
| 214 |
+
x, positions, mask, labels = (t[self.index] for t in self.table)
|
| 215 |
+
logits = self.model(x, position_ids=positions, attention_mask=mask)
|
| 216 |
+
loss = F.cross_entropy(logits.flatten(0, 1), labels.flatten(), ignore_index=-100)
|
| 217 |
+
loss.backward()
|
| 218 |
+
norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.clip, foreach=True)
|
| 219 |
+
self.optimizer.step()
|
| 220 |
+
return loss, norm
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def construct(spec, device):
|
| 224 |
+
torch.manual_seed(spec["initialization"])
|
| 225 |
+
cfg = ModelConfig(
|
| 226 |
+
vocab_size=len(vocabulary(spec)),
|
| 227 |
+
width=spec["width"],
|
| 228 |
+
layers=spec["layers"],
|
| 229 |
+
heads=spec["heads"],
|
| 230 |
+
context=LENGTH,
|
| 231 |
+
)
|
| 232 |
+
return TextGPT(cfg, repeats=spec["repeats"], dropout=spec["dropout"]).to(device)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
@torch.inference_mode()
|
| 236 |
+
def evaluate(model, rows, device, composite=False, patch=None, batch_size=256):
|
| 237 |
+
model.eval()
|
| 238 |
+
encode = composite_sentence if composite else atomic_sentence
|
| 239 |
+
prompts = np.asarray([encode(r)[:-3] for r in rows], dtype=np.int64)
|
| 240 |
+
answers, stops, probs = [], [], []
|
| 241 |
+
for start in range(0, len(rows), batch_size):
|
| 242 |
+
x = torch.as_tensor(prompts[start : start + batch_size], device=device)
|
| 243 |
+
intervention = (
|
| 244 |
+
None if patch is None else dict(patch, value=patch["value"][start : start + batch_size])
|
| 245 |
+
)
|
| 246 |
+
logits = model(x, patch=intervention)[:, -1]
|
| 247 |
+
target = torch.as_tensor(rows[start : start + batch_size, -1], device=device)
|
| 248 |
+
probs.extend(logits.softmax(-1).gather(1, target[:, None]).squeeze(1).tolist())
|
| 249 |
+
prediction = logits.argmax(-1)
|
| 250 |
+
answers.extend(prediction.tolist())
|
| 251 |
+
x = torch.cat([x, prediction[:, None]], dim=1)
|
| 252 |
+
period = model(x, patch=intervention)[:, -1].argmax(-1)
|
| 253 |
+
x = torch.cat([x, period[:, None]], dim=1)
|
| 254 |
+
eos = model(x, patch=intervention)[:, -1].argmax(-1)
|
| 255 |
+
stops.extend(torch.stack([period, eos], dim=1).tolist())
|
| 256 |
+
ans, stop, probability = np.asarray(answers), np.asarray(stops), np.asarray(probs)
|
| 257 |
+
correct = ans == rows[:, -1]
|
| 258 |
+
full = correct & (stop[:, 0] == 5) & (stop[:, 1] == EOS)
|
| 259 |
+
return dict(
|
| 260 |
+
n=len(rows),
|
| 261 |
+
answer_accuracy=float(correct.mean()),
|
| 262 |
+
accuracy=float(full.mean()),
|
| 263 |
+
answer_probability=float(probability.mean()),
|
| 264 |
+
), dict(answer=ans, stops=stop, probability=probability, target=rows[:, -1])
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def run(spec, output, device):
|
| 268 |
+
output = Path(output)
|
| 269 |
+
if (output / "complete.json").exists():
|
| 270 |
+
return json.loads((output / "complete.json").read_text())
|
| 271 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 272 |
+
lock = json.loads(Path(spec["source_lock"]).read_text())
|
| 273 |
+
for file, expected in lock["sources"].items():
|
| 274 |
+
assert sha(file) == expected, file
|
| 275 |
+
assert lock["config_sha256"] == sha(spec["config_path"])
|
| 276 |
+
torch.set_num_threads(2)
|
| 277 |
+
torch.cuda.set_device(device)
|
| 278 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 279 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 280 |
+
torch.cuda.set_per_process_memory_fraction(0.08, device)
|
| 281 |
+
world = build_world(spec)
|
| 282 |
+
cpu_table, bounds = training_table(world, spec["arm"])
|
| 283 |
+
np.savez_compressed(output / "world.npz", **world)
|
| 284 |
+
np.savez_compressed(
|
| 285 |
+
output / "training-table.npz",
|
| 286 |
+
**{k: v for k, v in zip(("tokens", "positions", "mask", "labels"), cpu_table, strict=True)},
|
| 287 |
+
)
|
| 288 |
+
write_json(output / "spec.json", spec)
|
| 289 |
+
write_json(output / "vocabulary.json", vocabulary(spec))
|
| 290 |
+
model = construct(spec, device)
|
| 291 |
+
opt = make_optimizer(model, torch.tensor(spec["lr"], device=device), spec["weight_decay"])
|
| 292 |
+
table = tuple(torch.as_tensor(t, device=device) for t in cpu_table)
|
| 293 |
+
streams = [EpochStream(bounds[i + 1] - bounds[i], spec["world"] + 100 + i) for i in range(3)]
|
| 294 |
+
latest = output / "latest.pt"
|
| 295 |
+
start, elapsed, histories = 0, 0.0, []
|
| 296 |
+
if latest.exists():
|
| 297 |
+
state = torch.load(latest, map_location=device, weights_only=False)
|
| 298 |
+
model.load_state_dict(state["model"])
|
| 299 |
+
opt.load_state_dict(state["optimizer"])
|
| 300 |
+
for stream, saved in zip(streams, state["streams"], strict=True):
|
| 301 |
+
stream.load_state_dict(saved)
|
| 302 |
+
start, elapsed, histories = state["step"], state["seconds"], state["histories"]
|
| 303 |
+
torch.set_rng_state(state["cpu_rng"].cpu())
|
| 304 |
+
torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device)
|
| 305 |
+
counts = spec["batch_parts"]
|
| 306 |
+
supervised_per_step = sum(n * tokens for n, tokens in zip(counts, [7, 9, 23], strict=True))
|
| 307 |
+
step_flops = flops(
|
| 308 |
+
model.config, spec["repeats"], sum(counts), LENGTH - 1, output_positions=LENGTH - 1
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
def checkpoint(step, seconds):
|
| 312 |
+
metrics, predictions = {}, {}
|
| 313 |
+
for split in (
|
| 314 |
+
"atomic",
|
| 315 |
+
"background_train",
|
| 316 |
+
"background_test",
|
| 317 |
+
"target_train",
|
| 318 |
+
"target_test",
|
| 319 |
+
):
|
| 320 |
+
metrics[split], preds = evaluate(
|
| 321 |
+
model, world[split], device, composite=split != "atomic"
|
| 322 |
+
)
|
| 323 |
+
predictions.update({split + "_" + k: v for k, v in preds.items()})
|
| 324 |
+
atomic_ok = predictions["atomic_answer"] == world["atomic"][:, -1]
|
| 325 |
+
knowledge = {
|
| 326 |
+
(int(h), int(r)): bool(ok)
|
| 327 |
+
for (h, r, _t), ok in zip(world["atomic"], atomic_ok, strict=True)
|
| 328 |
+
}
|
| 329 |
+
eligible = np.array(
|
| 330 |
+
[
|
| 331 |
+
knowledge[int(h), int(r1)] and knowledge[int(b), int(r2)]
|
| 332 |
+
for h, r1, b, r2, _t in world["target_test"]
|
| 333 |
+
]
|
| 334 |
+
)
|
| 335 |
+
target_ok = predictions["target_test_answer"] == world["target_test"][:, -1]
|
| 336 |
+
metrics["target_atomic_correct"] = dict(
|
| 337 |
+
n=int(eligible.sum()),
|
| 338 |
+
coverage=float(eligible.mean()),
|
| 339 |
+
answer_accuracy=float(target_ok[eligible].mean()) if eligible.any() else None,
|
| 340 |
+
)
|
| 341 |
+
record = dict(
|
| 342 |
+
step=step,
|
| 343 |
+
seconds=seconds,
|
| 344 |
+
supervised_tokens=step * supervised_per_step,
|
| 345 |
+
estimated_flops=step * step_flops,
|
| 346 |
+
metrics=metrics,
|
| 347 |
+
)
|
| 348 |
+
histories.append(record)
|
| 349 |
+
np.savez_compressed(output / f"predictions-{step:06d}.npz", **predictions)
|
| 350 |
+
write_json(output / "learning.json", histories)
|
| 351 |
+
model.train()
|
| 352 |
+
state = dict(
|
| 353 |
+
model=model.state_dict(),
|
| 354 |
+
optimizer=opt.state_dict(),
|
| 355 |
+
step=step,
|
| 356 |
+
seconds=seconds,
|
| 357 |
+
histories=histories,
|
| 358 |
+
spec=spec,
|
| 359 |
+
streams=[s.state_dict() for s in streams],
|
| 360 |
+
cpu_rng=torch.get_rng_state(),
|
| 361 |
+
cuda_rng=torch.cuda.get_rng_state(device),
|
| 362 |
+
)
|
| 363 |
+
tmp = output / "latest.tmp"
|
| 364 |
+
torch.save(state, tmp)
|
| 365 |
+
tmp.replace(latest)
|
| 366 |
+
if step in spec["weight_nodes"]:
|
| 367 |
+
torch.save(
|
| 368 |
+
dict(model=state["model"], step=step, spec=spec), output / f"weights-{step:06d}.pt"
|
| 369 |
+
)
|
| 370 |
+
print(json.dumps(dict(run=output.name, **record)), flush=True)
|
| 371 |
+
|
| 372 |
+
if start == 0:
|
| 373 |
+
checkpoint(0, elapsed)
|
| 374 |
+
model.train()
|
| 375 |
+
graph = TextGraphStep(model, opt, table, sum(counts))
|
| 376 |
+
tick = time.monotonic()
|
| 377 |
+
for step in range(start + 1, spec["steps"] + 1):
|
| 378 |
+
idx = np.concatenate(
|
| 379 |
+
[
|
| 380 |
+
stream.take(n) + offset
|
| 381 |
+
for stream, n, offset in zip(streams, counts, bounds[:-1], strict=True)
|
| 382 |
+
]
|
| 383 |
+
)
|
| 384 |
+
for group in opt.param_groups:
|
| 385 |
+
group["lr"].fill_(spec["lr"] * min(1.0, step / spec["warmup"]))
|
| 386 |
+
graph(torch.as_tensor(idx, device=device))
|
| 387 |
+
if step in spec["nodes"]:
|
| 388 |
+
torch.cuda.synchronize()
|
| 389 |
+
elapsed += time.monotonic() - tick
|
| 390 |
+
checkpoint(step, elapsed)
|
| 391 |
+
tick = time.monotonic()
|
| 392 |
+
result = dict(
|
| 393 |
+
status="complete",
|
| 394 |
+
final=histories[-1],
|
| 395 |
+
parameters=sum(p.numel() for p in model.parameters()),
|
| 396 |
+
source_lock_sha256=sha(spec["source_lock"]),
|
| 397 |
+
world_sha256=sha(output / "world.npz"),
|
| 398 |
+
peak_memory_bytes=torch.cuda.max_memory_allocated(device),
|
| 399 |
+
)
|
| 400 |
+
write_json(output / "complete.json", result)
|
| 401 |
+
return result
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/text_structure.py
ADDED
|
@@ -0,0 +1,432 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Matched relation-pair support and transfer to atomically trained facts.
|
| 2 |
+
|
| 3 |
+
Reuse the full-token text model; change composition support, not atomics,
|
| 4 |
+
per-fact role counts, unique chain count, or token marginals. Target heads and
|
| 5 |
+
bridges are disjoint from background; answer values are deliberately shared.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
import time
|
| 13 |
+
from collections import Counter
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
+
|
| 19 |
+
from .grok_depth import EpochStream, make_optimizer, utc, write_json
|
| 20 |
+
from .grok_loop_model import flops
|
| 21 |
+
from .text_pretrain import (
|
| 22 |
+
LENGTH,
|
| 23 |
+
WORDS,
|
| 24 |
+
TextGraphStep,
|
| 25 |
+
atomic_sentence,
|
| 26 |
+
composite_sentence,
|
| 27 |
+
construct,
|
| 28 |
+
evaluate,
|
| 29 |
+
pack_documents,
|
| 30 |
+
sha,
|
| 31 |
+
vocabulary,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
ARMS = ("restricted", "broad", "positive")
|
| 35 |
+
TESTS = ("id_test", "first_only", "second_only", "background_neither", "strict_test")
|
| 36 |
+
SPLITS = ("atomic", "train_composite", "positive_train", *TESTS)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def build_world(spec):
|
| 40 |
+
"""Balanced graph; common head-tail holdout defined before any model exists.
|
| 41 |
+
|
| 42 |
+
Each background bridge receives four trained heads per first relation.
|
| 43 |
+
Two of its four second facts have composition experience. Restricted
|
| 44 |
+
support pairs r1[0:2] only with even r2 and r1[2:4] only with odd r2.
|
| 45 |
+
Broad support assigns half the incoming facts of EACH r1 to each active r2.
|
| 46 |
+
Thus the relation-pair support has two components versus one, while all
|
| 47 |
+
underlying first/second edge counts match exactly.
|
| 48 |
+
"""
|
| 49 |
+
rng = np.random.default_rng(spec["world"])
|
| 50 |
+
hn, bn, tn = spec["heads_n"], spec["bridges_n"], spec["tails_n"]
|
| 51 |
+
if hn != 128 or bn != 32 or tn != 32:
|
| 52 |
+
raise ValueError("This version fixes 128 heads, 32 bridges, 32 shared answer values")
|
| 53 |
+
hs = np.arange(len(WORDS), len(WORDS) + hn)
|
| 54 |
+
bs = np.arange(hs[-1] + 1, hs[-1] + 1 + bn)
|
| 55 |
+
ts = np.arange(bs[-1] + 1, bs[-1] + 1 + tn)
|
| 56 |
+
first = []
|
| 57 |
+
for heads, bridges in ((hs[:64], bs[:16]), (hs[64:96], bs[:16]), (hs[96:], bs[16:])):
|
| 58 |
+
mappings = [rng.permutation(np.tile(bridges, len(heads) // len(bridges))) for _ in range(4)]
|
| 59 |
+
first.extend((h, 13 + ri, mappings[ri][i]) for i, h in enumerate(heads) for ri in range(4))
|
| 60 |
+
first = np.asarray(first, dtype=np.int64)
|
| 61 |
+
active, inactive = [], []
|
| 62 |
+
for bi, b in enumerate(bs[:16]):
|
| 63 |
+
chosen = (17, 18) if bi % 2 == 0 else (19, 20)
|
| 64 |
+
active.extend((b, r) for r in chosen)
|
| 65 |
+
inactive.extend((b, r) for r in range(17, 21) if r not in chosen)
|
| 66 |
+
second = []
|
| 67 |
+
for edges in (active, inactive, [(b, r) for b in bs[16:] for r in range(17, 21)]):
|
| 68 |
+
tails = rng.permutation(np.tile(ts, len(edges) // len(ts)))
|
| 69 |
+
second.extend((*edge, t) for edge, t in zip(edges, tails, strict=True))
|
| 70 |
+
second = np.asarray(sorted(second), dtype=np.int64)
|
| 71 |
+
lookup = {(int(h), int(r)): int(t) for h, r, t in second}
|
| 72 |
+
paths = np.asarray(
|
| 73 |
+
[(h, r1, b, r2, lookup[int(b), r2]) for h, r1, b in first for r2 in range(17, 21)],
|
| 74 |
+
dtype=np.int64,
|
| 75 |
+
)
|
| 76 |
+
trained_first = first[:256]
|
| 77 |
+
active_set = set(active)
|
| 78 |
+
broad_assignment = {}
|
| 79 |
+
for b in bs[:16]:
|
| 80 |
+
choices = sorted(r for bb, r in active if bb == b)
|
| 81 |
+
for r1 in range(13, 17):
|
| 82 |
+
incoming = rng.permutation(
|
| 83 |
+
trained_first[(trained_first[:, 2] == b) & (trained_first[:, 1] == r1), 0]
|
| 84 |
+
)
|
| 85 |
+
if len(incoming) != 4:
|
| 86 |
+
raise ValueError("Unbalanced graph")
|
| 87 |
+
for i, h in enumerate(incoming):
|
| 88 |
+
broad_assignment[int(h), r1] = choices[i // 2]
|
| 89 |
+
trains = {}
|
| 90 |
+
for arm in ARMS[:2]:
|
| 91 |
+
rows = []
|
| 92 |
+
for h, r1, b in trained_first:
|
| 93 |
+
choices = sorted(r for bb, r in active if bb == b)
|
| 94 |
+
r2 = (
|
| 95 |
+
choices[int(r1 >= 15)] if arm == "restricted" else broad_assignment[int(h), int(r1)]
|
| 96 |
+
)
|
| 97 |
+
rows.append((h, r1, b, r2, lookup[int(b), r2]))
|
| 98 |
+
trains[arm] = np.asarray(rows, dtype=np.int64)
|
| 99 |
+
# Two supervised paths per target person; keep the remaining head-tail
|
| 100 |
+
# pairs for an independent positive-control generalization evaluation.
|
| 101 |
+
positive = []
|
| 102 |
+
for h in hs[96:]:
|
| 103 |
+
candidates = paths[paths[:, 0] == h]
|
| 104 |
+
positive.extend(candidates[rng.choice(len(candidates), 2, replace=False)])
|
| 105 |
+
positive = np.asarray(positive, dtype=np.int64)
|
| 106 |
+
train_union = np.concatenate([trains["restricted"], trains["broad"], positive])
|
| 107 |
+
pairs = {tuple(row[[0, 4]]) for row in train_union}
|
| 108 |
+
held = np.asarray([tuple(row[[0, 4]]) not in pairs for row in paths])
|
| 109 |
+
first_seen = paths[:, 0] < hs[64]
|
| 110 |
+
second_seen = np.asarray([(int(b), int(r2)) in active_set for b, r2 in paths[:, [2, 3]]])
|
| 111 |
+
strict = paths[:, 0] >= hs[96]
|
| 112 |
+
world = dict(
|
| 113 |
+
atomic=np.concatenate([first, second]),
|
| 114 |
+
atomic_first=first,
|
| 115 |
+
atomic_second=second,
|
| 116 |
+
restricted_train=trains["restricted"],
|
| 117 |
+
broad_train=trains["broad"],
|
| 118 |
+
positive_train=positive,
|
| 119 |
+
id_test=paths[held & first_seen & second_seen],
|
| 120 |
+
first_only=paths[held & first_seen & ~second_seen],
|
| 121 |
+
second_only=paths[held & ~first_seen & second_seen],
|
| 122 |
+
background_neither=paths[held & ~first_seen & ~second_seen & ~strict],
|
| 123 |
+
strict_test=paths[held & strict],
|
| 124 |
+
strict_all=paths[strict],
|
| 125 |
+
all_paths=paths,
|
| 126 |
+
background_heads=hs[:96],
|
| 127 |
+
background_bridges=bs[:16],
|
| 128 |
+
target_heads=hs[96:],
|
| 129 |
+
target_bridges=bs[16:],
|
| 130 |
+
active_second=np.asarray(active, dtype=np.int64),
|
| 131 |
+
)
|
| 132 |
+
if any(not len(world[key]) for key in TESTS):
|
| 133 |
+
raise ValueError("Empty evaluation stratum; do not reroll worlds")
|
| 134 |
+
return world
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def role_counts(rows):
|
| 138 |
+
return (
|
| 139 |
+
Counter(map(tuple, rows[:, :3])),
|
| 140 |
+
Counter(map(tuple, rows[:, 2:])),
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def support_components(rows):
|
| 145 |
+
adjacency = {}
|
| 146 |
+
for _h, r1, _b, r2, _t in rows:
|
| 147 |
+
a, b = (0, int(r1)), (1, int(r2))
|
| 148 |
+
adjacency.setdefault(a, set()).add(b)
|
| 149 |
+
adjacency.setdefault(b, set()).add(a)
|
| 150 |
+
remaining, components = set(adjacency), []
|
| 151 |
+
while remaining:
|
| 152 |
+
stack, found = [min(remaining)], set()
|
| 153 |
+
while stack:
|
| 154 |
+
node = stack.pop()
|
| 155 |
+
if node not in found:
|
| 156 |
+
found.add(node)
|
| 157 |
+
stack.extend(adjacency[node] - found)
|
| 158 |
+
remaining -= found
|
| 159 |
+
components.append(sorted(found))
|
| 160 |
+
return components
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def data_audit(world):
|
| 164 |
+
a, b = world["restricted_train"], world["broad_train"]
|
| 165 |
+
assert len(a) == len(b) == 256
|
| 166 |
+
assert len(set(map(tuple, a))) == len(set(map(tuple, b))) == 256
|
| 167 |
+
assert role_counts(a) == role_counts(b)
|
| 168 |
+
assert Counter(t for row in a for t in composite_sentence(row)) == Counter(
|
| 169 |
+
t for row in b for t in composite_sentence(row)
|
| 170 |
+
)
|
| 171 |
+
assert len(support_components(a)) == 2 and len(support_components(b)) == 1
|
| 172 |
+
lookup = {(int(h), int(r)): int(t) for h, r, t in world["atomic"]}
|
| 173 |
+
for h, r1, bridge, r2, t in world["all_paths"]:
|
| 174 |
+
assert lookup[int(h), int(r1)] == bridge and lookup[int(bridge), int(r2)] == t
|
| 175 |
+
train_pairs = {tuple(r[[0, 4]]) for rows in (a, b, world["positive_train"]) for r in rows}
|
| 176 |
+
assert all(not train_pairs & {tuple(r[[0, 4]]) for r in world[s]} for s in TESTS)
|
| 177 |
+
assert not set(world["target_heads"]) & set(
|
| 178 |
+
np.concatenate([a[:, 0], a[:, 2], b[:, 0], b[:, 2]])
|
| 179 |
+
)
|
| 180 |
+
assert not set(world["target_bridges"]) & set(world["background_bridges"])
|
| 181 |
+
assert set(world["strict_all"][:, 2]) <= set(world["target_bridges"])
|
| 182 |
+
first_counts, second_counts = role_counts(a)
|
| 183 |
+
return dict(
|
| 184 |
+
status="passed",
|
| 185 |
+
sizes={k: len(v) for k, v in world.items()},
|
| 186 |
+
unique_chains={arm: len(world[arm + "_train"]) for arm in ARMS[:2]},
|
| 187 |
+
relation_pair_counts={
|
| 188 |
+
arm: np.bincount(
|
| 189 |
+
(world[arm + "_train"][:, 1] - 13) * 4 + world[arm + "_train"][:, 3] - 17,
|
| 190 |
+
minlength=16,
|
| 191 |
+
)
|
| 192 |
+
.reshape(4, 4)
|
| 193 |
+
.tolist()
|
| 194 |
+
for arm in ARMS[:2]
|
| 195 |
+
},
|
| 196 |
+
role_counts_match=True,
|
| 197 |
+
token_marginals_match=True,
|
| 198 |
+
first_edge_usage=list(sorted(set(first_counts.values()))),
|
| 199 |
+
second_edge_usage=list(sorted(set(second_counts.values()))),
|
| 200 |
+
common_holdout_pairs=True,
|
| 201 |
+
isolated_target_heads_and_bridges=True,
|
| 202 |
+
shared_answer_values=True,
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def training_table(world, arm):
|
| 207 |
+
if arm not in ARMS:
|
| 208 |
+
raise ValueError(arm)
|
| 209 |
+
rows = world["restricted_train" if arm == "restricted" else "broad_train"]
|
| 210 |
+
if arm == "positive":
|
| 211 |
+
rows = np.concatenate([rows, world["positive_train"]])
|
| 212 |
+
packed = [pack_documents([atomic_sentence(r)], [0]) for r in world["atomic"]]
|
| 213 |
+
packed.extend(pack_documents([composite_sentence(r)], [0]) for r in rows)
|
| 214 |
+
return (
|
| 215 |
+
tuple(np.stack([row[i] for row in packed]) for i in range(4)),
|
| 216 |
+
[0, len(world["atomic"]), len(packed)],
|
| 217 |
+
rows,
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def score_predictions(predictions):
|
| 222 |
+
correct = predictions["answer"] == predictions["target"]
|
| 223 |
+
stops = predictions["stops"]
|
| 224 |
+
full = correct & (stops[:, 0] == 5) & (stops[:, 1] == 1)
|
| 225 |
+
return dict(
|
| 226 |
+
n=len(correct),
|
| 227 |
+
answer_accuracy=float(correct.mean()),
|
| 228 |
+
accuracy=float(full.mean()),
|
| 229 |
+
answer_probability=float(predictions["probability"].mean()),
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
@torch.inference_mode()
|
| 234 |
+
def two_calls(model, rows, device):
|
| 235 |
+
first = rows[:, :3]
|
| 236 |
+
first_scores, first_pred = evaluate(model, first, device)
|
| 237 |
+
second = np.c_[first_pred["answer"], rows[:, 3:]]
|
| 238 |
+
_scores, pred = evaluate(model, second, device)
|
| 239 |
+
first_stops = first_pred["stops"]
|
| 240 |
+
format_ok = (first_stops[:, 0] == 5) & (first_stops[:, 1] == 1)
|
| 241 |
+
second_full = (
|
| 242 |
+
(pred["answer"] == rows[:, -1]) & (pred["stops"][:, 0] == 5) & (pred["stops"][:, 1] == 1)
|
| 243 |
+
)
|
| 244 |
+
first_ok = first_pred["answer"] == rows[:, 2]
|
| 245 |
+
scores = score_predictions(pred)
|
| 246 |
+
scores.update(
|
| 247 |
+
accuracy=float((format_ok & second_full).mean()),
|
| 248 |
+
path_accuracy=float((format_ok & first_ok & second_full).mean()),
|
| 249 |
+
first_accuracy=first_scores["accuracy"],
|
| 250 |
+
)
|
| 251 |
+
pred.update(
|
| 252 |
+
first_answer=first_pred["answer"],
|
| 253 |
+
first_stops=first_stops,
|
| 254 |
+
first_target=rows[:, 2],
|
| 255 |
+
first_probability=first_pred["probability"],
|
| 256 |
+
)
|
| 257 |
+
return scores, pred
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def evaluate_all(model, world, train_rows, device):
|
| 261 |
+
metrics, predictions = {}, {}
|
| 262 |
+
groups = dict(world, train_composite=train_rows)
|
| 263 |
+
for split in SPLITS:
|
| 264 |
+
scores, pred = evaluate(model, groups[split], device, composite=split != "atomic")
|
| 265 |
+
metrics[split] = scores
|
| 266 |
+
predictions.update({split + "_" + k: v for k, v in pred.items()})
|
| 267 |
+
atomic_ok = predictions["atomic_answer"] == world["atomic"][:, -1]
|
| 268 |
+
knowledge = {
|
| 269 |
+
(int(h), int(r)): bool(ok)
|
| 270 |
+
for (h, r, _t), ok in zip(world["atomic"], atomic_ok, strict=True)
|
| 271 |
+
}
|
| 272 |
+
for split in TESTS:
|
| 273 |
+
rows = world[split]
|
| 274 |
+
eligible = np.asarray(
|
| 275 |
+
[knowledge[int(h), int(r1)] and knowledge[int(b), int(r2)] for h, r1, b, r2, _t in rows]
|
| 276 |
+
)
|
| 277 |
+
predictions[split + "_eligible"] = eligible
|
| 278 |
+
conditional = {
|
| 279 |
+
k: predictions[split + "_" + k][eligible]
|
| 280 |
+
for k in ("answer", "target", "stops", "probability")
|
| 281 |
+
}
|
| 282 |
+
metrics[split + "_conditional"] = dict(
|
| 283 |
+
n=int(eligible.sum()), coverage=float(eligible.mean())
|
| 284 |
+
)
|
| 285 |
+
if eligible.any():
|
| 286 |
+
metrics[split + "_conditional"].update(score_predictions(conditional))
|
| 287 |
+
else:
|
| 288 |
+
metrics[split + "_conditional"].update(
|
| 289 |
+
answer_accuracy=None, accuracy=None, answer_probability=None
|
| 290 |
+
)
|
| 291 |
+
scores, pred = two_calls(model, rows, device)
|
| 292 |
+
metrics[split + "_two_calls"] = scores
|
| 293 |
+
predictions.update({split + "_two_calls_" + k: v for k, v in pred.items()})
|
| 294 |
+
return metrics, predictions
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def verify_lock(config, source_lock):
|
| 298 |
+
lock = json.loads(Path(source_lock).read_text())
|
| 299 |
+
assert lock["config_sha256"] == sha(config), config
|
| 300 |
+
for file, expected in lock["sources"].items():
|
| 301 |
+
assert sha(file) == expected, file
|
| 302 |
+
return lock
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def run(spec, output, device):
|
| 306 |
+
output = Path(output)
|
| 307 |
+
verify_lock(spec["config_path"], spec["source_lock"])
|
| 308 |
+
if (output / "complete.json").exists():
|
| 309 |
+
return json.loads((output / "complete.json").read_text())
|
| 310 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 311 |
+
torch.set_num_threads(2)
|
| 312 |
+
torch.cuda.set_device(device)
|
| 313 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 314 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 315 |
+
torch.cuda.set_per_process_memory_fraction(0.06, device)
|
| 316 |
+
world = build_world(spec)
|
| 317 |
+
write_json(output / "data-audit.json", data_audit(world))
|
| 318 |
+
cpu_table, bounds, train_rows = training_table(world, spec["arm"])
|
| 319 |
+
np.savez_compressed(output / "world.npz", **world, train_composite=train_rows)
|
| 320 |
+
np.savez_compressed(
|
| 321 |
+
output / "training-table.npz",
|
| 322 |
+
**{k: v for k, v in zip(("tokens", "positions", "mask", "labels"), cpu_table, strict=True)},
|
| 323 |
+
)
|
| 324 |
+
write_json(output / "spec.json", spec)
|
| 325 |
+
write_json(output / "vocabulary.json", vocabulary(spec))
|
| 326 |
+
model = construct(spec, device)
|
| 327 |
+
initial_hash = {
|
| 328 |
+
key: hashlib.sha256(value.detach().cpu().numpy().tobytes()).hexdigest()
|
| 329 |
+
for key, value in model.state_dict().items()
|
| 330 |
+
}
|
| 331 |
+
write_json(output / "initialization-hashes.json", initial_hash)
|
| 332 |
+
opt = make_optimizer(model, torch.tensor(spec["lr"], device=device), spec["weight_decay"])
|
| 333 |
+
table = tuple(torch.as_tensor(t, device=device) for t in cpu_table)
|
| 334 |
+
streams = [EpochStream(bounds[i + 1] - bounds[i], spec["world"] + 100 + i) for i in range(2)]
|
| 335 |
+
latest = output / "latest.pt"
|
| 336 |
+
start, elapsed, histories = 0, 0.0, []
|
| 337 |
+
if latest.exists():
|
| 338 |
+
state = torch.load(latest, map_location=device, weights_only=False)
|
| 339 |
+
assert state["spec"] == spec
|
| 340 |
+
model.load_state_dict(state["model"])
|
| 341 |
+
opt.load_state_dict(state["optimizer"])
|
| 342 |
+
for stream, saved in zip(streams, state["streams"], strict=True):
|
| 343 |
+
stream.load_state_dict(saved)
|
| 344 |
+
start, elapsed, histories = state["step"], state["seconds"], state["histories"]
|
| 345 |
+
torch.set_rng_state(state["cpu_rng"].cpu())
|
| 346 |
+
torch.cuda.set_rng_state(state["cuda_rng"].cpu(), device)
|
| 347 |
+
counts = spec["batch_parts"]
|
| 348 |
+
supervised_per_step = sum(n * tokens for n, tokens in zip(counts, [7, 9], strict=True))
|
| 349 |
+
step_flops = flops(
|
| 350 |
+
model.config, spec["repeats"], sum(counts), LENGTH - 1, output_positions=LENGTH - 1
|
| 351 |
+
)
|
| 352 |
+
started = utc()
|
| 353 |
+
|
| 354 |
+
def checkpoint(step, seconds):
|
| 355 |
+
metrics, predictions = evaluate_all(model, world, train_rows, device)
|
| 356 |
+
record = dict(
|
| 357 |
+
step=step,
|
| 358 |
+
seconds=seconds,
|
| 359 |
+
supervised_tokens=step * supervised_per_step,
|
| 360 |
+
estimated_flops=step * step_flops,
|
| 361 |
+
metrics=metrics,
|
| 362 |
+
)
|
| 363 |
+
histories.append(record)
|
| 364 |
+
np.savez_compressed(output / f"predictions-{step:06d}.npz", **predictions)
|
| 365 |
+
write_json(output / "learning.json", histories)
|
| 366 |
+
model.train()
|
| 367 |
+
state = dict(
|
| 368 |
+
model=model.state_dict(),
|
| 369 |
+
optimizer=opt.state_dict(),
|
| 370 |
+
step=step,
|
| 371 |
+
seconds=seconds,
|
| 372 |
+
histories=histories,
|
| 373 |
+
spec=spec,
|
| 374 |
+
streams=[s.state_dict() for s in streams],
|
| 375 |
+
cpu_rng=torch.get_rng_state(),
|
| 376 |
+
cuda_rng=torch.cuda.get_rng_state(device),
|
| 377 |
+
)
|
| 378 |
+
tmp = output / "latest.tmp"
|
| 379 |
+
torch.save(state, tmp)
|
| 380 |
+
tmp.replace(latest)
|
| 381 |
+
if step in spec["weight_nodes"]:
|
| 382 |
+
torch.save(
|
| 383 |
+
dict(model=state["model"], step=step, spec=spec), output / f"weights-{step:06d}.pt"
|
| 384 |
+
)
|
| 385 |
+
print(
|
| 386 |
+
json.dumps(
|
| 387 |
+
dict(
|
| 388 |
+
run=output.name,
|
| 389 |
+
step=step,
|
| 390 |
+
seconds=seconds,
|
| 391 |
+
metrics={k: metrics[k] for k in ("atomic", "train_composite", *TESTS)},
|
| 392 |
+
)
|
| 393 |
+
),
|
| 394 |
+
flush=True,
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
if start == 0:
|
| 398 |
+
checkpoint(0, elapsed)
|
| 399 |
+
model.train()
|
| 400 |
+
before = {k: v.detach().clone() for k, v in model.state_dict().items()}
|
| 401 |
+
graph = TextGraphStep(model, opt, table, sum(counts))
|
| 402 |
+
assert all(torch.equal(before[k], v) for k, v in model.state_dict().items())
|
| 403 |
+
tick = time.monotonic()
|
| 404 |
+
for step in range(start + 1, spec["steps"] + 1):
|
| 405 |
+
idx = np.concatenate(
|
| 406 |
+
[
|
| 407 |
+
stream.take(n) + offset
|
| 408 |
+
for stream, n, offset in zip(streams, counts, bounds[:-1], strict=True)
|
| 409 |
+
]
|
| 410 |
+
)
|
| 411 |
+
for group in opt.param_groups:
|
| 412 |
+
group["lr"].fill_(spec["lr"] * min(1.0, step / spec["warmup"]))
|
| 413 |
+
graph(torch.as_tensor(idx, device=device))
|
| 414 |
+
if step in spec["nodes"]:
|
| 415 |
+
torch.cuda.synchronize()
|
| 416 |
+
elapsed += time.monotonic() - tick
|
| 417 |
+
checkpoint(step, elapsed)
|
| 418 |
+
tick = time.monotonic()
|
| 419 |
+
result = dict(
|
| 420 |
+
status="complete",
|
| 421 |
+
started_utc=started,
|
| 422 |
+
finished_utc=utc(),
|
| 423 |
+
final=histories[-1],
|
| 424 |
+
parameters=sum(p.numel() for p in model.parameters()),
|
| 425 |
+
source_lock_sha256=sha(spec["source_lock"]),
|
| 426 |
+
world_sha256=sha(output / "world.npz"),
|
| 427 |
+
peak_memory_bytes=torch.cuda.max_memory_allocated(device),
|
| 428 |
+
gpu=torch.cuda.get_device_name(device),
|
| 429 |
+
torch_version=torch.__version__,
|
| 430 |
+
)
|
| 431 |
+
write_json(output / "complete.json", result)
|
| 432 |
+
return result
|
docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/twohop_depth.py
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Depth, held-out composition, and bridge interventions in random fact worlds.
|
| 2 |
+
|
| 3 |
+
Entity IDs and relation IDs are disjoint. A relation is a random permutation;
|
| 4 |
+
this makes every atom and each split's answer marginal exactly balanced.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import contextlib
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
import torch
|
| 17 |
+
from torch.nn import functional as F
|
| 18 |
+
|
| 19 |
+
from llm_memory_editability.bios_model import CausalLM, ModelConfig
|
| 20 |
+
|
| 21 |
+
ROOT = Path(os.environ.get("TWOHOP_PROJECT_ROOT", Path(__file__).resolve().parents[2]))
|
| 22 |
+
CONFIG = ROOT / "configs/twohop-depth-v1.json"
|
| 23 |
+
DATA = ROOT / "data/twohop-depth-v1"
|
| 24 |
+
RESULTS = ROOT / "results/twohop-depth-v1"
|
| 25 |
+
ART = ROOT / "docs/development-artifacts/twohop-depth-v1"
|
| 26 |
+
BOS, EOS, ENTITY = 1, 2, 3
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def read(path):
|
| 30 |
+
return json.loads(Path(path).read_text())
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def write(path, value):
|
| 34 |
+
path = Path(path)
|
| 35 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 36 |
+
temp = path.with_suffix(path.suffix + ".tmp")
|
| 37 |
+
temp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n")
|
| 38 |
+
temp.replace(path)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def digest(path):
|
| 42 |
+
h = hashlib.sha256()
|
| 43 |
+
with Path(path).open("rb") as f:
|
| 44 |
+
for block in iter(lambda: f.read(1024 * 1024), b""):
|
| 45 |
+
h.update(block)
|
| 46 |
+
return h.hexdigest()
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def world_arrays(seed, cfg):
|
| 50 |
+
n, r = cfg["entities"], cfg["relations"]
|
| 51 |
+
if r % 2 or r < 2:
|
| 52 |
+
raise ValueError("An even relation count is required for balanced coverage")
|
| 53 |
+
rng = np.random.default_rng(seed)
|
| 54 |
+
maps = np.stack([rng.permutation(n) for _ in range(r)])
|
| 55 |
+
# For each bridge, a regular bipartite graph over first/second relations.
|
| 56 |
+
# Each atom occurs in r/2 training compositions in EACH hop role.
|
| 57 |
+
orders = np.stack([rng.permutation(r) for _ in range(n)])
|
| 58 |
+
mask = np.zeros((n, r, r), dtype=bool)
|
| 59 |
+
for a in range(n):
|
| 60 |
+
for r1 in range(r):
|
| 61 |
+
b = maps[r1, a]
|
| 62 |
+
mask[a, r1, orders[b, (r1 + np.arange(r // 2)) % r]] = True
|
| 63 |
+
atoms = np.array([(a, rel) for a in range(n) for rel in range(r)], dtype=np.int64)
|
| 64 |
+
comps = np.array(
|
| 65 |
+
[(a, r1, r2) for a in range(n) for r1 in range(r) for r2 in range(r)],
|
| 66 |
+
dtype=np.int64,
|
| 67 |
+
)
|
| 68 |
+
a, r1, r2 = comps.T
|
| 69 |
+
bridge = maps[r1, a]
|
| 70 |
+
answer = maps[r2, bridge]
|
| 71 |
+
selected = rng.choice(np.flatnonzero(~mask.ravel()), cfg["diagnostic_cases"], replace=False)
|
| 72 |
+
cases = []
|
| 73 |
+
inverse = np.argsort(maps, axis=1)
|
| 74 |
+
for index in selected:
|
| 75 |
+
a0, r10, r20 = comps[index]
|
| 76 |
+
b0, c0 = bridge[index], answer[index]
|
| 77 |
+
# Donor contains only a first-hop prefix; neither its explicit entity nor
|
| 78 |
+
# its first-hop answer is the counterfactual final answer.
|
| 79 |
+
candidates = []
|
| 80 |
+
for b1 in range(n):
|
| 81 |
+
a1, c1 = inverse[r10, b1], maps[r20, b1]
|
| 82 |
+
if b1 != b0 and c1 not in {a1, b1, a0, b0, c0}:
|
| 83 |
+
candidates.append((int(a1), int(b1), int(c1)))
|
| 84 |
+
if not candidates:
|
| 85 |
+
raise ValueError("No answer-free bridge donor; increase world size")
|
| 86 |
+
a1, b1, c1 = candidates[int(rng.integers(len(candidates)))]
|
| 87 |
+
same_r = (r10 + 1) % r
|
| 88 |
+
same_a = inverse[same_r, b0]
|
| 89 |
+
wrong_candidates = [
|
| 90 |
+
(rr, int(maps[rr, b1])) for rr in range(r) if rr != r20 and maps[rr, b1] not in {c0, c1}
|
| 91 |
+
]
|
| 92 |
+
if not wrong_candidates:
|
| 93 |
+
raise ValueError("No distinct wrong-relation answer")
|
| 94 |
+
wrong_r, wrong_y = wrong_candidates[int(rng.integers(len(wrong_candidates)))]
|
| 95 |
+
cases.append([index, a0, r10, r20, b0, c0, a1, b1, c1, same_a, same_r, wrong_r, wrong_y])
|
| 96 |
+
ax = np.c_[np.full(len(atoms), BOS), ENTITY + atoms[:, 0], ENTITY + n + atoms[:, 1]]
|
| 97 |
+
cx = np.c_[np.full(len(comps), BOS), ENTITY + a, ENTITY + n + r1, ENTITY + n + r2]
|
| 98 |
+
return {
|
| 99 |
+
"maps": maps,
|
| 100 |
+
"atoms": atoms,
|
| 101 |
+
"comps": comps,
|
| 102 |
+
"train_mask": mask.ravel(),
|
| 103 |
+
"atomic_x": ax,
|
| 104 |
+
"atomic_y": ENTITY + maps[atoms[:, 1], atoms[:, 0]],
|
| 105 |
+
"composite_x": cx,
|
| 106 |
+
"composite_y": ENTITY + answer,
|
| 107 |
+
"bridge": ENTITY + bridge,
|
| 108 |
+
"cases": np.asarray(cases, dtype=np.int64),
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def audit_world(w, cfg):
|
| 113 |
+
n, r = cfg["entities"], cfg["relations"]
|
| 114 |
+
maps, comps = w["maps"], w["comps"]
|
| 115 |
+
assert all(np.array_equal(np.sort(row), np.arange(n)) for row in maps)
|
| 116 |
+
assert len(set(map(tuple, w["atomic_x"]))) == n * r
|
| 117 |
+
assert len(set(map(tuple, w["composite_x"]))) == n * r * r
|
| 118 |
+
for mask in (w["train_mask"], ~w["train_mask"]):
|
| 119 |
+
a, r1, r2 = comps[mask].T
|
| 120 |
+
b = maps[r1, a]
|
| 121 |
+
assert np.all(np.bincount(a * r + r1, minlength=n * r) == r // 2)
|
| 122 |
+
assert np.all(np.bincount(b * r + r2, minlength=n * r) == r // 2)
|
| 123 |
+
assert np.all(np.bincount(w["composite_y"][mask] - ENTITY, minlength=n) == r * r // 2)
|
| 124 |
+
assert np.all(~w["train_mask"][w["cases"][:, 0]])
|
| 125 |
+
for _, a, r1, r2, b, c, da, db, dc, sa, sr, wr, wy in w["cases"]:
|
| 126 |
+
assert maps[r1, a] == b and maps[r2, b] == c
|
| 127 |
+
assert maps[r1, da] == db and maps[r2, db] == dc
|
| 128 |
+
assert maps[sr, sa] == b and sr != r1
|
| 129 |
+
assert dc not in {da, db, a, b, c}
|
| 130 |
+
assert maps[wr, db] == wy and wr != r2 and wy not in {c, dc}
|
| 131 |
+
return {
|
| 132 |
+
"atoms": n * r,
|
| 133 |
+
"train_compositions": int(w["train_mask"].sum()),
|
| 134 |
+
"test_compositions": int((~w["train_mask"]).sum()),
|
| 135 |
+
"diagnostic_cases": len(w["cases"]),
|
| 136 |
+
"every_atom_train_composition_occurrences_per_hop": r // 2,
|
| 137 |
+
"balanced_answers": True,
|
| 138 |
+
"answer_free_donors": True,
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def stream_indices(length, count, rng):
|
| 143 |
+
return np.concatenate([rng.permutation(length) for _ in range((count + length - 1) // length)])[
|
| 144 |
+
:count
|
| 145 |
+
]
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def make_stream(w, seed, cfg):
|
| 149 |
+
rng = np.random.default_rng(seed)
|
| 150 |
+
count = cfg["steps"] * cfg["batch_per_kind"]
|
| 151 |
+
return {
|
| 152 |
+
"atomic": stream_indices(len(w["atomic_x"]), count, rng),
|
| 153 |
+
"composite": stream_indices(int(w["train_mask"].sum()), count, rng),
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def build_model(arch, cfg):
|
| 158 |
+
return CausalLM(
|
| 159 |
+
ModelConfig(
|
| 160 |
+
vocab_size=ENTITY + cfg["entities"] + cfg["relations"],
|
| 161 |
+
layers=arch["layers"],
|
| 162 |
+
width=arch["width"],
|
| 163 |
+
heads=arch["heads"],
|
| 164 |
+
context=8,
|
| 165 |
+
)
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def amp(device):
|
| 170 |
+
return (
|
| 171 |
+
torch.autocast("cuda", dtype=torch.bfloat16)
|
| 172 |
+
if str(device).startswith("cuda")
|
| 173 |
+
else contextlib.nullcontext()
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def training_tensors(w, device):
|
| 178 |
+
result = {}
|
| 179 |
+
for name, mask in (("atomic", slice(None)), ("composite", w["train_mask"])):
|
| 180 |
+
x, y = w[name + "_x"][mask], w[name + "_y"][mask]
|
| 181 |
+
full = np.zeros((len(x), 6), dtype=np.int64)
|
| 182 |
+
full[:, : x.shape[1]] = x
|
| 183 |
+
full[:, x.shape[1]] = y
|
| 184 |
+
full[:, x.shape[1] + 1] = EOS
|
| 185 |
+
pos = np.tile([x.shape[1] - 1, x.shape[1]], (len(x), 1))
|
| 186 |
+
labels = np.c_[y, np.full(len(x), EOS)]
|
| 187 |
+
result[name] = tuple(torch.as_tensor(v, device=device) for v in (full, pos, labels))
|
| 188 |
+
return result
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def optimizer_for(model, cfg, device):
|
| 192 |
+
decay, no_decay = [], []
|
| 193 |
+
for p in model.parameters():
|
| 194 |
+
(decay if p.ndim >= 2 else no_decay).append(p)
|
| 195 |
+
return torch.optim.AdamW(
|
| 196 |
+
[
|
| 197 |
+
{"params": decay, "weight_decay": cfg["weight_decay"]},
|
| 198 |
+
{"params": no_decay, "weight_decay": 0},
|
| 199 |
+
],
|
| 200 |
+
lr=cfg["lr"],
|
| 201 |
+
betas=(0.9, 0.999),
|
| 202 |
+
eps=1e-8,
|
| 203 |
+
fused=str(device).startswith("cuda"),
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def train_step(model, optimizer, tensors, indices, step, cfg, device):
|
| 208 |
+
parts = [tuple(v[indices[k]] for v in tensors[k]) for k in ("atomic", "composite")]
|
| 209 |
+
x, pos, labels = (torch.cat([p[j] for p in parts]) for j in range(3))
|
| 210 |
+
lr = cfg["lr"] * min(1.0, (step + 1) / cfg["warmup"])
|
| 211 |
+
for group in optimizer.param_groups:
|
| 212 |
+
group["lr"] = lr
|
| 213 |
+
optimizer.zero_grad(set_to_none=True)
|
| 214 |
+
with amp(device):
|
| 215 |
+
logits = model(x, positions=pos)
|
| 216 |
+
losses = F.cross_entropy(logits.float().flatten(0, 1), labels.flatten(), reduction="none")
|
| 217 |
+
loss = losses.mean()
|
| 218 |
+
loss.backward()
|
| 219 |
+
norm = torch.nn.utils.clip_grad_norm_(model.parameters(), cfg["gradient_clip"])
|
| 220 |
+
optimizer.step()
|
| 221 |
+
return loss.detach(), norm.detach()
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
@torch.no_grad()
|
| 225 |
+
def predict(model, x, y, device, batch=512):
|
| 226 |
+
pred, eos, prob = [], [], []
|
| 227 |
+
for start in range(0, len(x), batch):
|
| 228 |
+
q = torch.as_tensor(x[start : start + batch], device=device)
|
| 229 |
+
target = torch.as_tensor(y[start : start + batch], device=device)
|
| 230 |
+
with amp(device):
|
| 231 |
+
logits = model(q)[:, -1].float()
|
| 232 |
+
answer = logits.argmax(-1)
|
| 233 |
+
stop = model(torch.cat([q, answer[:, None]], dim=1))[:, -1].argmax(-1)
|
| 234 |
+
pred.extend(answer.cpu().tolist())
|
| 235 |
+
eos.extend(stop.cpu().tolist())
|
| 236 |
+
prob.extend(logits.log_softmax(-1).gather(1, target[:, None]).squeeze(1).cpu().tolist())
|
| 237 |
+
return np.asarray(pred), np.asarray(eos), np.asarray(prob)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
@torch.no_grad()
|
| 241 |
+
def evaluate(model, w, cfg, device):
|
| 242 |
+
arrays, metrics = {}, {}
|
| 243 |
+
for name, key, mask in (
|
| 244 |
+
("atomic", "atomic", slice(None)),
|
| 245 |
+
("train", "composite", w["train_mask"]),
|
| 246 |
+
("test", "composite", ~w["train_mask"]),
|
| 247 |
+
):
|
| 248 |
+
x, y = w[key + "_x"][mask], w[key + "_y"][mask]
|
| 249 |
+
pred, eos, logp = predict(model, x, y, device, cfg["eval_batch"])
|
| 250 |
+
arrays.update({name + "_pred": pred, name + "_eos": eos, name + "_logp": logp})
|
| 251 |
+
metrics.update(
|
| 252 |
+
{
|
| 253 |
+
name + "_answer": float(np.mean(pred == y)),
|
| 254 |
+
name + "_exact": float(np.mean((pred == y) & (eos == EOS))),
|
| 255 |
+
name + "_nll": float(-logp.mean()),
|
| 256 |
+
}
|
| 257 |
+
)
|
| 258 |
+
# Autonomous two-call baseline uses its own generated bridge, never the oracle.
|
| 259 |
+
test_ids = np.flatnonzero(~w["train_mask"])
|
| 260 |
+
a, r1, r2 = w["comps"][test_ids].T
|
| 261 |
+
bridge_pred = arrays["atomic_pred"][a * cfg["relations"] + r1]
|
| 262 |
+
bridge_eos = arrays["atomic_eos"][a * cfg["relations"] + r1]
|
| 263 |
+
second_x = np.c_[np.full(len(a), BOS), bridge_pred, ENTITY + cfg["entities"] + r2]
|
| 264 |
+
y = w["composite_y"][test_ids]
|
| 265 |
+
pred, eos, logp = predict(model, second_x, y, device, cfg["eval_batch"])
|
| 266 |
+
arrays.update(
|
| 267 |
+
two_call_pred=pred, two_call_eos=eos, two_call_logp=logp, two_call_bridge=bridge_pred
|
| 268 |
+
)
|
| 269 |
+
two_exact = (pred == y) & (eos == EOS) & (bridge_eos == EOS)
|
| 270 |
+
metrics["two_call_exact"] = float(two_exact.mean())
|
| 271 |
+
atom_ok = (arrays["atomic_pred"] == w["atomic_y"]) & (arrays["atomic_eos"] == EOS)
|
| 272 |
+
b = w["maps"][r1, a]
|
| 273 |
+
both = atom_ok[a * cfg["relations"] + r1] & atom_ok[b * cfg["relations"] + r2]
|
| 274 |
+
arrays["test_both_atoms_correct"] = both
|
| 275 |
+
exact = (arrays["test_pred"] == y) & (arrays["test_eos"] == EOS)
|
| 276 |
+
metrics["test_both_atoms_n"] = int(both.sum())
|
| 277 |
+
metrics["test_given_both_atoms"] = float(exact[both].mean()) if both.any() else None
|
| 278 |
+
return metrics, arrays
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
@torch.no_grad()
|
| 282 |
+
def states_and_logits(model, tokens, device):
|
| 283 |
+
# Mirrors bios_model.CausalLM.forward; contract-tested against ordinary forward.
|
| 284 |
+
with amp(device):
|
| 285 |
+
h = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=device))
|
| 286 |
+
states = [h.clone()]
|
| 287 |
+
for block in model.blocks:
|
| 288 |
+
h = block(h)
|
| 289 |
+
states.append(h.clone())
|
| 290 |
+
logits = F.linear(model.ln_final(h), model.token.weight)
|
| 291 |
+
return states, logits.float()
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
@torch.no_grad()
|
| 295 |
+
def patched_logits(model, tokens, layer, positions, replacement, device):
|
| 296 |
+
with amp(device):
|
| 297 |
+
h = model.token(tokens) + model.position(torch.arange(tokens.shape[1], device=device))
|
| 298 |
+
if layer == 0:
|
| 299 |
+
h[:, positions] = replacement.to(h.dtype)
|
| 300 |
+
for number, block in enumerate(model.blocks, 1):
|
| 301 |
+
h = block(h)
|
| 302 |
+
if number == layer:
|
| 303 |
+
h[:, positions] = replacement.to(h.dtype)
|
| 304 |
+
return F.linear(model.ln_final(h), model.token.weight)[:, -1].float()
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
@torch.no_grad()
|
| 308 |
+
def diagnostics(model, w, cfg, device):
|
| 309 |
+
cases = w["cases"]
|
| 310 |
+
q = torch.as_tensor(w["composite_x"][cases[:, 0]], device=device)
|
| 311 |
+
dx = np.c_[
|
| 312 |
+
np.full(len(cases), BOS), ENTITY + cases[:, 6], ENTITY + cfg["entities"] + cases[:, 2]
|
| 313 |
+
]
|
| 314 |
+
sx = np.c_[
|
| 315 |
+
np.full(len(cases), BOS), ENTITY + cases[:, 9], ENTITY + cfg["entities"] + cases[:, 10]
|
| 316 |
+
]
|
| 317 |
+
clean, logits = states_and_logits(model, q, device)
|
| 318 |
+
donor, _ = states_and_logits(model, torch.as_tensor(dx, device=device), device)
|
| 319 |
+
same, _ = states_and_logits(model, torch.as_tensor(sx, device=device), device)
|
| 320 |
+
old = torch.as_tensor(ENTITY + cases[:, 5], device=device)
|
| 321 |
+
new = torch.as_tensor(ENTITY + cases[:, 8], device=device)
|
| 322 |
+
wrong = torch.as_tensor(ENTITY + cases[:, 12], device=device)
|
| 323 |
+
row = torch.arange(len(q), device=device)
|
| 324 |
+
baseline = logits[:, -1]
|
| 325 |
+
out = {
|
| 326 |
+
"case_ids": cases[:, 0],
|
| 327 |
+
"clean_pred": baseline.argmax(-1).cpu().numpy(),
|
| 328 |
+
"clean_margin": (baseline[row, new] - baseline[row, old]).cpu().numpy(),
|
| 329 |
+
"old_y": old.cpu().numpy(),
|
| 330 |
+
"new_y": new.cpu().numpy(),
|
| 331 |
+
"wrong_y": wrong.cpu().numpy(),
|
| 332 |
+
}
|
| 333 |
+
# Fixed random orthogonal coordinate permutation preserves perturbation norm.
|
| 334 |
+
rng = np.random.default_rng(142899)
|
| 335 |
+
perm = torch.as_tensor(rng.permutation(model.config.width), device=device)
|
| 336 |
+
signs = torch.as_tensor(rng.choice([-1, 1], model.config.width), device=device)
|
| 337 |
+
for layer in range(len(clean)):
|
| 338 |
+
with amp(device):
|
| 339 |
+
lens = F.linear(model.ln_final(clean[layer]), model.token.weight).float()
|
| 340 |
+
out[f"lens_bridge_pos2_{layer}"] = lens[:, 2].argmax(-1).cpu().numpy()
|
| 341 |
+
out[f"lens_query_pos3_{layer}"] = lens[:, 3].argmax(-1).cpu().numpy()
|
| 342 |
+
delta = donor[layer][:, 2] - clean[layer][:, 2]
|
| 343 |
+
random_state = clean[layer][:, 2] + delta[:, perm] * signs
|
| 344 |
+
conditions = {
|
| 345 |
+
"bridge": ([2], donor[layer][:, [2]]),
|
| 346 |
+
"same_bridge": ([2], same[layer][:, [2]]),
|
| 347 |
+
"random": ([2], random_state[:, None]),
|
| 348 |
+
"source": ([1], donor[layer][:, [1]]),
|
| 349 |
+
"prefix": ([1, 2], donor[layer][:, [1, 2]]),
|
| 350 |
+
"identity": ([2], clean[layer][:, [2]]),
|
| 351 |
+
}
|
| 352 |
+
for name, (positions, replacement) in conditions.items():
|
| 353 |
+
z = patched_logits(model, q, layer, positions, replacement, device)
|
| 354 |
+
prefix = f"{name}_{layer}"
|
| 355 |
+
out[prefix + "_pred"] = z.argmax(-1).cpu().numpy()
|
| 356 |
+
out[prefix + "_margin"] = (z[row, new] - z[row, old]).cpu().numpy()
|
| 357 |
+
out[prefix + "_max_delta"] = (z - baseline).abs().max(-1).values.cpu().numpy()
|
| 358 |
+
return out
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def run_name(world, seed, architecture):
|
| 362 |
+
return f"w{world}-s{seed}-{architecture}"
|
docs/development-artifacts/composition-data-curves-v1/source/tests/test_composition_curves.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Conclusion-changing contracts for the data-size and knowledge-load comparisons."""
|
| 2 |
+
|
| 3 |
+
import copy
|
| 4 |
+
import importlib.util
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pytest
|
| 11 |
+
|
| 12 |
+
from llm_memory_editability.composition_curves import (
|
| 13 |
+
anchors_pass,
|
| 14 |
+
budget_nodes,
|
| 15 |
+
calibrated_choice,
|
| 16 |
+
confirmation_specs,
|
| 17 |
+
construct,
|
| 18 |
+
load_specs,
|
| 19 |
+
prepare_world,
|
| 20 |
+
)
|
| 21 |
+
from llm_memory_editability.grok_depth import EpochStream
|
| 22 |
+
|
| 23 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def spec(phi=1, entities=16):
|
| 27 |
+
return {
|
| 28 |
+
"world_seed": 311,
|
| 29 |
+
"entities": entities,
|
| 30 |
+
"max_entities": 32,
|
| 31 |
+
"relations": 8,
|
| 32 |
+
"degree": 4,
|
| 33 |
+
"phi": phi,
|
| 34 |
+
"id_fraction": 0.75,
|
| 35 |
+
"test_fraction": 0.1,
|
| 36 |
+
"evaluation_size": 128,
|
| 37 |
+
"batch_size": 16,
|
| 38 |
+
"target_exposures": 17,
|
| 39 |
+
"compute_steps": 64,
|
| 40 |
+
"width": 16,
|
| 41 |
+
"layers": 2,
|
| 42 |
+
"heads": 2,
|
| 43 |
+
"dropout": 0.1,
|
| 44 |
+
"initialization": 981,
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def test_distinct_supports_are_nested_and_never_change_world_or_test_panels():
|
| 49 |
+
previous = set()
|
| 50 |
+
identity = None
|
| 51 |
+
reference = None
|
| 52 |
+
for phi in (0, 0.5, 1, 2):
|
| 53 |
+
arrays, panels, meta = prepare_world(spec(phi))
|
| 54 |
+
current = {tuple(row[:-1]) for row in arrays["train_composite"]}
|
| 55 |
+
assert previous <= current
|
| 56 |
+
assert len(current) == meta["composition_examples"]
|
| 57 |
+
assert not current & {tuple(row[:-1]) for row in arrays["test_composite"]}
|
| 58 |
+
if identity is None:
|
| 59 |
+
identity, reference = meta["world_sha256"], panels
|
| 60 |
+
assert meta["world_sha256"] == identity
|
| 61 |
+
for key in ("atomic", "II", "OO"):
|
| 62 |
+
np.testing.assert_array_equal(panels[key], reference[key])
|
| 63 |
+
previous = current
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def test_truth_and_ood_roles_survive_fixed_vocabulary_remapping():
|
| 67 |
+
arrays, _, meta = prepare_world(spec(2))
|
| 68 |
+
atomic = {tuple(row[:2]): int(row[2]) for row in arrays["atomic"]}
|
| 69 |
+
ood = {tuple(row[:2]) for row in arrays["ood_atomic"]}
|
| 70 |
+
for head, r1, r2, answer in arrays["train_composite"]:
|
| 71 |
+
bridge = atomic[head, r1]
|
| 72 |
+
assert atomic[bridge, r2] == answer
|
| 73 |
+
assert (head, r1) not in ood and (bridge, r2) not in ood
|
| 74 |
+
for head, r1, r2, answer in arrays["ood_composite"]:
|
| 75 |
+
bridge = atomic[head, r1]
|
| 76 |
+
assert atomic[bridge, r2] == answer
|
| 77 |
+
assert (head, r1) in ood and (bridge, r2) in ood
|
| 78 |
+
assert meta["role_coverage"]["ood_composite"]["both_facts_seen_in_required_roles"] in (0, None)
|
| 79 |
+
assert arrays["atomic"][:, 1].min() >= spec()["max_entities"] + 2
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def test_same_model_parameters_and_initial_weights_at_every_load():
|
| 83 |
+
import torch
|
| 84 |
+
|
| 85 |
+
small, cfg = construct(spec(1, 8), "cpu")
|
| 86 |
+
large, large_cfg = construct(spec(1, 32), "cpu")
|
| 87 |
+
assert cfg == large_cfg
|
| 88 |
+
for key, value in small.state_dict().items():
|
| 89 |
+
assert torch.equal(value, large.state_dict()[key])
|
| 90 |
+
for n in (8, 16, 32):
|
| 91 |
+
arrays, _, meta = prepare_world(spec(1, n))
|
| 92 |
+
assert meta["knowledge_bits"] == len(arrays["atomic"]) * math.log2(n)
|
| 93 |
+
assert meta["composition_additional_independent_bits"] == 0
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def test_requests_never_cap_or_silently_repeat_distinct_compositions():
|
| 97 |
+
with pytest.raises(ValueError, match="exceeds"):
|
| 98 |
+
prepare_world(spec(100))
|
| 99 |
+
with pytest.raises(ValueError, match="vocabulary"):
|
| 100 |
+
prepare_world(spec(1, 33))
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def test_world_creation_does_not_touch_global_numpy_rng():
|
| 104 |
+
np.random.seed(775)
|
| 105 |
+
expected = np.random.random(8)
|
| 106 |
+
np.random.seed(775)
|
| 107 |
+
prepare_world(spec())
|
| 108 |
+
np.testing.assert_array_equal(np.random.random(8), expected)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def test_matched_exposure_budget_gives_every_record_the_declared_exposure():
|
| 112 |
+
item = spec()
|
| 113 |
+
total = 39
|
| 114 |
+
nodes, budgets = budget_nodes(item, total)
|
| 115 |
+
assert budgets["exposure"] == math.ceil(17 * total / 16)
|
| 116 |
+
assert budgets["exposure"] in nodes and budgets["compute"] in nodes
|
| 117 |
+
stream = EpochStream(total, 763)
|
| 118 |
+
seen = np.bincount(stream.take(budgets["exposure"] * 16), minlength=total)
|
| 119 |
+
assert seen.min() == 17 and seen.max() == 18
|
| 120 |
+
resumed = EpochStream(total, 1)
|
| 121 |
+
resumed.load_state_dict(copy.deepcopy(stream.state_dict()))
|
| 122 |
+
np.testing.assert_array_equal(stream.take(120), resumed.take(120))
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def test_fixed_development_budget_does_not_pretend_to_reach_exposure_endpoint():
|
| 126 |
+
item = {**spec(), "fixed_steps": 64}
|
| 127 |
+
nodes, budgets = budget_nodes(item, 1000)
|
| 128 |
+
assert budgets["end"] == 64
|
| 129 |
+
assert nodes[-1] == 64
|
| 130 |
+
assert budgets["exposure"] not in nodes
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def metrics(atomic=1, train=1, test=0.9):
|
| 134 |
+
return {
|
| 135 |
+
"atomic": {"accuracy": atomic},
|
| 136 |
+
"train_composition": {"accuracy": train},
|
| 137 |
+
"II": {"accuracy": test},
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def test_development_gate_does_not_reward_best_training_fit_without_generalization():
|
| 142 |
+
thresholds = {"atomic": 0.95, "train_composition": 0.95, "II": 0.8}
|
| 143 |
+
two, four = {"layers": 2}, {"layers": 4}
|
| 144 |
+
assert calibrated_choice([(two, metrics(test=0.02)), (four, metrics())], thresholds) == four
|
| 145 |
+
assert calibrated_choice([(four, metrics()), (two, metrics())], thresholds) == two
|
| 146 |
+
assert calibrated_choice([(two, metrics(atomic=0.94))], thresholds) is None
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def test_load_gate_requires_all_distinct_registered_worlds():
|
| 150 |
+
thresholds = {"atomic": 0.95, "train_composition": 0.95, "II": 0.8}
|
| 151 |
+
rows = [({"world_seed": n}, metrics()) for n in (1, 2, 3)]
|
| 152 |
+
assert anchors_pass(rows, [1, 2, 3], thresholds)
|
| 153 |
+
assert not anchors_pass(rows[:2], [1, 2, 3], thresholds)
|
| 154 |
+
assert not anchors_pass([rows[0], rows[0], rows[2]], [1, 2, 3], thresholds)
|
| 155 |
+
rows[1] = ({"world_seed": 2}, metrics(test=0.79))
|
| 156 |
+
assert not anchors_pass(rows, [1, 2, 3], thresholds)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def test_complete_registered_matrix_reuses_low_load_without_duplicate_training():
|
| 160 |
+
config = json.loads((ROOT / "configs/composition-data-curves-v1.json").read_text())
|
| 161 |
+
selected = {**config["base_spec"], "layers": 2}
|
| 162 |
+
support = confirmation_specs(config, selected)
|
| 163 |
+
load = load_specs(config, selected)
|
| 164 |
+
assert len(support) == 21 and len(load) == 15
|
| 165 |
+
assert len({row["name"] for row in support + load}) == 36
|
| 166 |
+
for world in config["confirmation_worlds"]:
|
| 167 |
+
assert {row["phi"] for row in support if row["world_seed"] == world} == set(
|
| 168 |
+
config["support_phi"]
|
| 169 |
+
)
|
| 170 |
+
anchors = [
|
| 171 |
+
row
|
| 172 |
+
for row in support
|
| 173 |
+
if row["world_seed"] == world and row["phi"] == config["anchor_phi"]
|
| 174 |
+
]
|
| 175 |
+
assert len(anchors) == 1 and anchors[0]["entities"] == 128
|
| 176 |
+
assert all(row["entities"] != 128 for row in load)
|
| 177 |
+
assert all(row["phase"] == "confirmation" for row in support + load)
|
| 178 |
+
assert config["development_world"] not in config["confirmation_worlds"]
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def load_executor():
|
| 182 |
+
module_spec = importlib.util.spec_from_file_location(
|
| 183 |
+
"curve_executor", ROOT / "scripts/execute_composition_curves.py"
|
| 184 |
+
)
|
| 185 |
+
module = importlib.util.module_from_spec(module_spec)
|
| 186 |
+
module_spec.loader.exec_module(module)
|
| 187 |
+
return module
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def test_container_isolation_uses_real_repository_and_frozen_source(tmp_path):
|
| 191 |
+
executor = load_executor()
|
| 192 |
+
config = {
|
| 193 |
+
"batch": "example",
|
| 194 |
+
"repository": "/repo",
|
| 195 |
+
"source_root": "/repo/frozen/source",
|
| 196 |
+
"runtime": {"image": "sha256:fixed", "python": "/python", "cpus": 2, "memory": "12g"},
|
| 197 |
+
}
|
| 198 |
+
name, command = executor.container_command(
|
| 199 |
+
config, Path("/repo/frozen/support-config.json"), {"name": "phi1"}, tmp_path, 1, 1
|
| 200 |
+
)
|
| 201 |
+
assert command[:4] == ["docker", "--context", "lm-memory", "run"]
|
| 202 |
+
assert "type=bind,src=/repo,dst=/repo,readonly" in command
|
| 203 |
+
assert "PYTHONPATH=/repo/frozen/source/src" in command
|
| 204 |
+
assert "device=1" in command and "--read-only" in command and "--network=none" in command
|
| 205 |
+
other, _ = executor.container_command(
|
| 206 |
+
config, Path("/repo/frozen/support-config.json"), {"name": "phi1"}, tmp_path, 1, 2
|
| 207 |
+
)
|
| 208 |
+
assert name != other
|
docs/development-artifacts/composition-data-curves-v1/support-config.json
ADDED
|
@@ -0,0 +1,780 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"batch": "composition-data-curves-v1",
|
| 3 |
+
"results_root": "/ossfs/workspace/llm-memory-editability/results/composition-data-curves-v1",
|
| 4 |
+
"gpus": [
|
| 5 |
+
0,
|
| 6 |
+
1
|
| 7 |
+
],
|
| 8 |
+
"preflight": "/ossfs/workspace/experiment-runs/composition-data-curves-v1-preflight/cuda.json",
|
| 9 |
+
"runtime": {
|
| 10 |
+
"docker_context": "lm-memory",
|
| 11 |
+
"image": "sha256:a994f1a1886220693eb26b7ff201147fbd4b49477d335ab2707330cab771063f",
|
| 12 |
+
"python": "/opt/conda/bin/python",
|
| 13 |
+
"cpus": 2,
|
| 14 |
+
"memory": "12g"
|
| 15 |
+
},
|
| 16 |
+
"base_spec": {
|
| 17 |
+
"entities": 128,
|
| 18 |
+
"max_entities": 4096,
|
| 19 |
+
"relations": 32,
|
| 20 |
+
"degree": 16,
|
| 21 |
+
"id_fraction": 0.95,
|
| 22 |
+
"test_fraction": 0.1,
|
| 23 |
+
"width": 64,
|
| 24 |
+
"heads": 4,
|
| 25 |
+
"dropout": 0.1,
|
| 26 |
+
"lr": 0.0001,
|
| 27 |
+
"weight_decay": 0.1,
|
| 28 |
+
"warmup": 2000,
|
| 29 |
+
"batch_size": 256,
|
| 30 |
+
"evaluation_size": 2048,
|
| 31 |
+
"compute_steps": 128000,
|
| 32 |
+
"target_exposures": 4000,
|
| 33 |
+
"max_wall_seconds": 43200
|
| 34 |
+
},
|
| 35 |
+
"development_world": 961006101,
|
| 36 |
+
"confirmation_worlds": [
|
| 37 |
+
961006111,
|
| 38 |
+
961006112,
|
| 39 |
+
961006113
|
| 40 |
+
],
|
| 41 |
+
"initialization": 961006121,
|
| 42 |
+
"stream_seed": 961006131,
|
| 43 |
+
"calibration_layers": [
|
| 44 |
+
2,
|
| 45 |
+
4
|
| 46 |
+
],
|
| 47 |
+
"calibration_steps": [
|
| 48 |
+
128000,
|
| 49 |
+
512000
|
| 50 |
+
],
|
| 51 |
+
"calibration_thresholds": {
|
| 52 |
+
"atomic": 0.95,
|
| 53 |
+
"train_composition": 0.95,
|
| 54 |
+
"II": 0.8
|
| 55 |
+
},
|
| 56 |
+
"selection_rule": "development world only; prefer 2 layers if its fixed endpoint passes, otherwise 4; one predeclared common budget extension if neither passes",
|
| 57 |
+
"anchor_phi": 7.2,
|
| 58 |
+
"support_phi": [
|
| 59 |
+
0,
|
| 60 |
+
0.5,
|
| 61 |
+
1,
|
| 62 |
+
2,
|
| 63 |
+
4,
|
| 64 |
+
7.2,
|
| 65 |
+
12.6
|
| 66 |
+
],
|
| 67 |
+
"load_entities": [
|
| 68 |
+
128,
|
| 69 |
+
256,
|
| 70 |
+
512,
|
| 71 |
+
1024,
|
| 72 |
+
2048,
|
| 73 |
+
4096
|
| 74 |
+
],
|
| 75 |
+
"load_gate": {
|
| 76 |
+
"atomic": 0.95,
|
| 77 |
+
"train_composition": 0.95,
|
| 78 |
+
"II": 0.8
|
| 79 |
+
},
|
| 80 |
+
"tracking": {
|
| 81 |
+
"enabled": true,
|
| 82 |
+
"entity": "zhusq20",
|
| 83 |
+
"project": "llm-memory-editability",
|
| 84 |
+
"mode": "online"
|
| 85 |
+
},
|
| 86 |
+
"budget": {
|
| 87 |
+
"maximum_training_runs": 40,
|
| 88 |
+
"maximum_gpu_hours": 64,
|
| 89 |
+
"per_run_wall_seconds": 43200,
|
| 90 |
+
"extension_target_exposures": 8000,
|
| 91 |
+
"automatic_new_learning_rates": false,
|
| 92 |
+
"automatic_new_architectures": false
|
| 93 |
+
},
|
| 94 |
+
"interpretation": {
|
| 95 |
+
"primary_level": "controlled synthetic behavior; no universal capacity law or internal MLP attribution",
|
| 96 |
+
"knowledge_entropy": "F log2(N), conditional on relation keys; composition support adds zero independent bits",
|
| 97 |
+
"load_graphs": "closed random graphs at each N, same registered world-family seeds but different facts; not a nested-fact intervention",
|
| 98 |
+
"world_weighting": "three independent world families, one initialization each; do not pool queries as independent worlds",
|
| 99 |
+
"budgets": "128000 updates gives identical executed-shape FLOPs; matched average record exposures is a separate comparison"
|
| 100 |
+
},
|
| 101 |
+
"repository": "/ossfs/workspace/llm-memory-editability",
|
| 102 |
+
"source_root": "/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source",
|
| 103 |
+
"source_files": {
|
| 104 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/__init__.py": "84e6bb4a97b68f67f3256135c2b5fc35d9a83ceb04914a6cf3d38d926b015f7f",
|
| 105 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/__main__.py": "0af76e0612dd46d8097cd06d02bcd6220d89354be49910110a80b9942fdb71b3",
|
| 106 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/alignment_coverage.py": "152b868b836ff3ae18d8bb572ffe6ce956ea26edde1d283726b82215125736ff",
|
| 107 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/architecture_bridge.py": "777fe51d98b09275f487386660106e93c6c8b49e25b94e804510ed968c2df04c",
|
| 108 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/architecture_bridge_toy.py": "320d859c4d11b68299266d3f9bdb9a7e6867d635eb3d347827be082c60f0ffca",
|
| 109 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_analysis.py": "41d836fc201b9ae4f1988e0cdda3dc3be4ebc3ca898ab2ff69ca8445212407ff",
|
| 110 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_branch.py": "f5b0f0ae79f84d64e33862e40fffbc4bd9a8fd102414995e8a2d41560009c09d",
|
| 111 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_capacity.py": "a9c306f0e326a8b97eccc4c0b404d45a3e3d8697186092ac562f645b4b370ba4",
|
| 112 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_causal_paths.py": "10ea265743293fff64cc2201b7b49f5a22dd3bc3ff6a320f469948c233e65620",
|
| 113 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_confirmation_stats.py": "e40f0347bd44e8602c18fc2fbee9647010d509d6f6dc7bc3c5cb8e98036e9c9b",
|
| 114 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_context_control.py": "9205a7f8d25e0f1311d78c73638b97466f425886e62165166ba104f53050a40d",
|
| 115 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_context_gradient.py": "8376dec9883b1d2c3ef06e5e04ad01fec6a1b9eceaa5cd74db02a79629bc536f",
|
| 116 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_cross.py": "47b8f55adbe13d9bc6e1c5c9170cc95e382261ffb1f31980706ac95be03623bf",
|
| 117 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_cross_continue.py": "e6fd3a86157566559ab0e0571fbefcc1a28f22ec7add66da2105ea81d63cdaf8",
|
| 118 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_cross_scale.py": "a1be3c598403b72661b9b2df642b2b1236ae1df6fdf46d982d4d89d19487f658",
|
| 119 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_cross_train.py": "0106cae29be447319be2e7f6f0e1f5b60cc6224282331906f43ebc65ab795f38",
|
| 120 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_data.py": "d5568901f2042a6d89d447f47eddae9764eced0a9e71e3ea5adc0038a7e636d6",
|
| 121 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_direction.py": "1240f83f5ee558101bbf6f808522fa6c37ffe09dc2296749bd5e685eff8aa41d",
|
| 122 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_direction_cross.py": "66cf337b3a52508e82da6190ea01916662f1fe6fddef036844f9d1be2c179888",
|
| 123 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_direction_formation.py": "e2b19c17c6b7ebb7a884782f2c7750a7c65b935c17694d4424d354c62d0a24ed",
|
| 124 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_direction_refresh.py": "4f80060d4232ec3bf4fb5d99b0823d20ee759e088aeedf4bd49ab841357d0127",
|
| 125 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_edit.py": "dbbbc01ce57acef79d5cc46bcd39e301b256fa1e8c9eff7b1ce5ece693f86f2f",
|
| 126 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_followup.py": "06b4ffd3bbb65e2ff4df0f68e3fbf9f368257196bd4ef36eb1ffb0f7b15ee43b",
|
| 127 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_measure.py": "8c275b658c5c99316a19e2328eb53952f26b8a858b591784509391780ead3267",
|
| 128 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_mechanism_causal.py": "41aeed0ba09eba1b869e74dc29236aaa2abf142a596916dc06316754c7f21d8a",
|
| 129 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_mechanism_causal_v2.py": "bc37408e458014e746c061c65b4672e67e30adee2b5a85b325a0282fbec00dfe",
|
| 130 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_mechanism_edit.py": "ca9351ef08189c643a5b0a009af3e52b2578d5ae6265510f603cb78b229667dd",
|
| 131 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_mechanism_interventions.py": "190c75e0a2779fe96936bff38d13a03e17e0dfd9faba3d2909ffc4a65265d96f",
|
| 132 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_model.py": "99efb7feeeb15f33dd3f08174c1190f4aa470e3877d8ac6692b2d43fed4c5f4d",
|
| 133 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_organization.py": "42f714473695da4c8543f666fd15a7eab7cef1e571429b25f81818b5505bd9d5",
|
| 134 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_organization_train.py": "833426232b693495711e38101553e8bff370c837c722d76e7f9f5f2d2ed3cad6",
|
| 135 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_original_data.py": "092689c2a05aad564ff8a7c6e1ac669d7e0475908e525766cf70922037cd2488",
|
| 136 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_original_diagnostics.py": "6dd51ead7d16c1960740716fb73cb4409828666ac0332baae4c14730e39dd120",
|
| 137 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_original_model.py": "8a52e58d343320ccce9e2f1b43674cc6765b840bd4feebed4813f78296ab29a9",
|
| 138 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_original_report.py": "3483f72d479a861a4513f0a1a5dc7cbf53bcbace6a652d39f389b46ffb82286e",
|
| 139 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_original_train.py": "86b2ef1be03223dff26bc7997b91143be81fb46fd29ab8650a9cde8a39eb6891",
|
| 140 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_path_diagnostics.py": "7d95f31f9fa9099d6b05666b9a638f880aa83a88554d934c3ff05e86880d0f7e",
|
| 141 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_path_minimal.py": "6fe8f0f6dd0950adfbbc5ad0524c1fe7e96b5c054d04338c046728535257a12e",
|
| 142 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_path_transfer.py": "2a079c54c2778e9bcb8fb36ebea4f90c43ac7bb7135e6d61e8a91a250ae3a0e1",
|
| 143 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_readout_control.py": "545260dcaeac15766857271cbe8646ed3f096e445215064790b4ad62b6425afe",
|
| 144 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_relation_response.py": "56a21f6b7cd028aff011f99c9222518d0ef04bb803eda79a176e355cd735e0ca",
|
| 145 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_shortcut_confirmation.py": "92306cd8d88e0329916b52d9aadb992db286fae4ad7cf72cd846ab2b9a22553e",
|
| 146 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_shortcut_confirmation_sets.py": "063d867951c621f8110c5c2547458aa5039899d64e44c199b86a45b4661e142e",
|
| 147 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_shortcut_control.py": "a9369b1a042ef644b231763e2b62ac2b12451c3a526ccf121fd476a72fa27325",
|
| 148 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_shortcut_edit.py": "68c4980269249cbb1acf787fe5679bfad762460487f4a0cfc8e5e7f728ed8a68",
|
| 149 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_shortcut_edit_v2.py": "55ee452c248a44e0abb50f9806a00772dc6e72b683541db6cc17ffd1ac18e899",
|
| 150 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_shortcut_matched_edit.py": "a8bba1a538fe4b3d5739a2ec4d223daf54b3988d74a7aa86854af3971acd4123",
|
| 151 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bios_train.py": "c1d84d38aa1853815075041535ae3fa9890f5cf1f9f5d9019136c79521033046",
|
| 152 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bridge_reencoding.py": "128c02424642e2a479b8a439bd0342c89f77bf3befe3783a5fef9ebe01375ae5",
|
| 153 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/bridge_workspace.py": "fe8f98ff6348d879c0b3c6db6b24f18eaabe03692729f0b0c967fe8d3b5a124a",
|
| 154 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/capacity_controls.py": "dc0b6ea601216b0997c45271a2ce8e02121148f37c88649e68d8960c9a6f1796",
|
| 155 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/capacity_scaling.py": "5ee176e8d16e6e2a7becca7b89109712f940e21ead6b73a61a2ae974435e8678",
|
| 156 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/cli.py": "01c814b9644988be1bf2ab660b2010ad5e7beab99067116c2afb2b6957f9fd3b",
|
| 157 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/composition_curves.py": "520c4503f3d1525612432dd2c0b9fbf56d2e39ee5d6dff9f1484f19a7bfae8ec",
|
| 158 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/curve_tracking.py": "50cc8a1d652c44ef14d42b4a44cc800fb15e2ed72f4b83c4848870d76ab56fec",
|
| 159 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/depth_step.py": "bd69879d5ec6124c05ca28a62c2c2459734e5b4b17d32ae92005308de63b8279",
|
| 160 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/depth_step_edit_calibration.py": "2dd20b15ae1f92eb6f685eca1e914923ff349a6a94277cfd3a5a74ad9155b4b8",
|
| 161 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/depth_step_mechanism.py": "546ce23095e755959d8114ed2bcf3f3f0d70f4a8e38e5c9b5d98c7a28ea7c5a6",
|
| 162 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/experiment_tracking.py": "2afe9e767123bee16cf56f59c6c2953a100338ecf1f971945c4968a064551866",
|
| 163 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/experiments.py": "e575aceb2e3804956655d91710809818aec04c0b16a22edb441f5757629371d1",
|
| 164 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/grok_depth.py": "7d6d5af38a5dc4438b1e7ff44df8e833169d500f0d60d8933932bdb8822aca26",
|
| 165 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/grok_depth_bridge.py": "414a0dbf17c369ad6d15714c2c026aafc4fb12bb1813a3c056efe8035fe2773d",
|
| 166 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/grok_depth_data.py": "c1451a0647ef7c25567398efd63848dbb44fdf066d07718c02f7e556e6c8b94a",
|
| 167 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/grok_depth_extension.py": "f91923d3a7f154c7432e4763a0a90c0863eb75b7b35c8742838c9949795ab9f6",
|
| 168 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/grok_loop_data.py": "504de57da94618578cf792a3963f99e2dac587424d74ceae6b4c02c1d9680a8e",
|
| 169 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/grok_loop_mechanism.py": "aa11f58d3aa378741218eee29106b55da5601e1ff9bc3ac7e39ae55f26e613e2",
|
| 170 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/grok_loop_model.py": "07e84388997a1710e5c821e54cf6d23726e4289aab178347761e060851fea6cc",
|
| 171 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/grok_loop_same_bridge.py": "06538ab83312484367f84eefdf4944bddc8f3f45507dfcb96e005cb3017a3349",
|
| 172 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/grok_loop_same_bridge_eval.py": "dea9ebb3130a0d7816b11cd01ac6d105f09e3aa4a051857b71693da261632410",
|
| 173 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/grok_loop_supervision.py": "a24661453cb82764f81d631b9a1fb4642df0fc7181c5adf7cd6ac46960c9f9b7",
|
| 174 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/grok_loop_train.py": "4931606ee614aaadebbc3460c9ad9a86fbb12b5b6a1bbda9f3714f81424ff142",
|
| 175 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/grok_multihop.py": "67ed1f37b04fbef7031f208e5ca140aea1b6158adb64ec8b0fe12217eb53cdbc",
|
| 176 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/grok_multihop_data.py": "d417b4d39e70cfa4010a8cd737a362d8159d73c2377330b04bf471a5079da851",
|
| 177 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/grok_usage_data.py": "cfce0e5835665933ee1a1561ee681ffa6520c564be7e2292d9206399f86e7ced",
|
| 178 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/grok_usage_train.py": "5509ab6b2ad0c93e185cdfc211a7ee5afef45a5021a74aa8ce8bce520f694f70",
|
| 179 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/grokking_dynamics_mechanism.py": "713470c8432ea27c602208cf0625452859924b83f8c62927c81894070815432c",
|
| 180 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/grokking_reproduction.py": "7e3a89d96f6fef7bd4665ac46dd1acb6e7cb461c6878647ecc7c6f425ac31117",
|
| 181 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/hebbian_data.py": "f2f5458d624fc4a49781a557641de7388937e90fda846ab03f7e17a3f455dd0e",
|
| 182 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/hebbian_followup.py": "752244bd78c5b02ba1d37a276e0547a5ff5bcf7a47986d64642f0db36cc4f4aa",
|
| 183 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/hebbian_future.py": "9fa7d88102e5b79e91735f530fe98fdd2bba20fad146238cde4f6eb591cf7105",
|
| 184 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/hebbian_interface.py": "a1ead4b413aef8f3082dcd569318fd132b64ed1a1ddb0c0c3a3aae4686589198",
|
| 185 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/hebbian_learning.py": "3dd0317b90943a22aabb80dcdc24eb38199623c5fb84a67641c3acd5de6a650e",
|
| 186 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/hebbian_model.py": "e0413d8288a679800f3f7bafc8ef072a0d6d5b29fc49de417077569eec49cc3e",
|
| 187 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/hebbian_statistics.py": "8c3a37806bed9661666c55bcb7c727ab78d9f4b2a1b384323f6a33c51d0a11f8",
|
| 188 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/hebbian_train.py": "71ca785eafbe3438da45c4f5fa543a62424f1fd5176b04b317b0c78e7c96ecbf",
|
| 189 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/interface_editing.py": "f5a9aba43a4c03373bfb59510322a9be800de53af4c3f87e967c7e03f648e0a0",
|
| 190 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/interface_tracking.py": "7b7c252998c3eb764c8eaeb389cf9aab8a1da45d97200911d9e7455e59ec3c55",
|
| 191 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/latent_scaling.py": "231050e859da58c52b9ea47d09fb5de91271df0d24cbab42dead3f911adc6119",
|
| 192 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/latent_support.py": "71e2483f8b5eb7e447594bf04def731add89f4cf140954fe87f793a69cb440a3",
|
| 193 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/low_rank.py": "e1ddb5714d492311a43af2d5fd3dd5f578d8144db0b3d860ca71e3b603d018e1",
|
| 194 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/memory_reuse.py": "e95814cd98de22adc54e458f0b5933f2c3f13a0640c0c71a841780a9b1b52e57",
|
| 195 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/multihop_scaling.py": "cbb60954b2738d17a1fce125087f87ee203fe98c5d462d14ad22ccff5790c7c6",
|
| 196 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/natural_composition_confirmation.py": "e13986431617be78b05db8c1f84f522f5cf4b6af7cd1b2e9d89345423be977e2",
|
| 197 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/natural_composition_confirmation_v2.py": "9bfa6540da812d4e6e2a21d2a8942dd73908269ce46aff15915b1782382dee75",
|
| 198 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/neural.py": "f0df4d9bbb47b1febf0baf76d53b58319e598b6bbb29d31abca575e2dd13e025",
|
| 199 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/neural_data.py": "8812cb49f223dff57ac2fbbeb8055aa3017302e0450c194ecc984eaefcc3596e",
|
| 200 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/neural_models.py": "c5ecb2fd69aa205a22688c95049750a7b8a0fd58b7c888a026252273b3af9091",
|
| 201 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/parametric_architecture.py": "b19ebaa377705f582fef367163312f74c2b3d2cc0451d8df03f47eff16e37a19",
|
| 202 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/parametric_architecture_train.py": "232d2a9e1c3db2023cafd15cf107e57a6f37fc8139d8c81a45e5a3121ef31c5d",
|
| 203 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/qwen_constraints.py": "1b371c02d59becde87d61f3e8db20c9064588ff1908be66c06570ed2c5b1ab6f",
|
| 204 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/qwen_path_learning.py": "d62080bf19605df02e9a140332c8981094a6e65b4c84a14b35734248e278a231",
|
| 205 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/qwen_path_train.py": "09f03b01179a2cef8d98f803f61cea7e48ce636259222e394b0248d6744aec9d",
|
| 206 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/realworld_composition.py": "323f1cdb0f3c25a085e95b6f85fe352b1a91274aa5b3bbaca4e0686fdb4510c0",
|
| 207 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/realworld_composition_data.py": "7208e0d0789f0287963b6e36d2646171e334f40ee365af13af79944f81e221be",
|
| 208 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/realworld_confirmation.py": "e160fa1ab79580281753752b3e8f39584e5f2ba6a3b5d27abece6c99a291efe2",
|
| 209 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/realworld_confirmation_analysis.py": "c8a89a57f913e034d7fd2c805fc4567900cd1c4881d5b66e8ac0f44deee75802",
|
| 210 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/recurrence_use.py": "144fb9561ead5dbce0589ee986b6452af31405b1ff4fd30aae36a72076b62469",
|
| 211 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/representation_alignment.py": "9794218f052a19019a5cb6427b84877a5174de3c0485bad441cdaed0ec7bd6b6",
|
| 212 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/small_lm_composition.py": "93796eee05e305ad538a498f013463d6bcde4a03de720eff6f4bfedf903f21d1",
|
| 213 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/small_lm_followup.py": "90fdbbc5c1509d30e0e369c201b5caccac0c063636ad99101f9e3ea603ce7780",
|
| 214 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/storage_composition.py": "fa4d8b073ecb3ac69a3204ee446a4bc1ecf0c36f9d8dd1dcd0b6835c245e4c5a",
|
| 215 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/storage_frontier.py": "2a1adcbbb0439ed771e17090878b9f7c9861d2fef4544172a88c35bd037d4a22",
|
| 216 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/text_loss_source.py": "579471a04def8a11e9cc072fcb909d6e84c3b61c8d901d0d029e126f14a6d3fe",
|
| 217 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/text_pretrain.py": "cd777a56ba270d3c71ed3260f68501ee0685d4cc58a4f7b952719236adf874cb",
|
| 218 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/text_structure.py": "9c8e3f00b263a62d53868a6224830e702dcb4348c05d52cc438c1e37e365287d",
|
| 219 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/src/llm_memory_editability/twohop_depth.py": "870ad9f1f3a3736b77b1b0781d25961803d9d2e1df9aed1c709a669691b76def",
|
| 220 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/scripts/run_composition_curves.py": "f01b63f3e80427ffe37c730f81e3cc1ca854735807554d5a6cbd812416d00b3b",
|
| 221 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/scripts/execute_composition_curves.py": "ba220f8f570c62a9677694de9bdf9b3f4b4dda9be5579242bb093d9d783d939d",
|
| 222 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/scripts/report_composition_curves.py": "89320834c058bd57b3307e95d6024a5025cdb45931020cbeac7cf7e9d32cbf05",
|
| 223 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/tests/test_composition_curves.py": "3620a14156b8e40682da1309444be1e646ce10639b2691f6c99deb33e74b2674",
|
| 224 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/configs/experiment-tracking-defaults.json": "41d4b73b9d2f57f71fe51dd8500275f2c9fb3476ec24a9eeee3a8deadb5ecaa2",
|
| 225 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/configs/composition-data-curves-v1.json": "ea6b69279d78372490bb25f4bc46fda1325673a500ce070137b055acb7d75722",
|
| 226 |
+
"/ossfs/workspace/llm-memory-editability/docs/development-artifacts/composition-data-curves-v1/source/docs/development-artifacts/composition-data-curves-v1/protocol.md": "22d9eabc0facbcc40cf9fc2dbb4b07bac3d0351caf91e10aa9625bcbe3ef45ee"
|
| 227 |
+
},
|
| 228 |
+
"preflight_sha256": "599a85f6e3cd81a6105ae9168d3f4a387093fe68cd53c94697a88477e7d6f28f",
|
| 229 |
+
"frozen_utc": "2026-10-06T01:03:49.716017+00:00",
|
| 230 |
+
"git_commit": "b7b1741e5c840b68612c4eeb4fb2248ad5f2be61",
|
| 231 |
+
"runs": [
|
| 232 |
+
{
|
| 233 |
+
"entities": 128,
|
| 234 |
+
"max_entities": 4096,
|
| 235 |
+
"relations": 32,
|
| 236 |
+
"degree": 16,
|
| 237 |
+
"id_fraction": 0.95,
|
| 238 |
+
"test_fraction": 0.1,
|
| 239 |
+
"width": 64,
|
| 240 |
+
"heads": 4,
|
| 241 |
+
"dropout": 0.1,
|
| 242 |
+
"lr": 0.0001,
|
| 243 |
+
"weight_decay": 0.1,
|
| 244 |
+
"warmup": 2000,
|
| 245 |
+
"batch_size": 256,
|
| 246 |
+
"evaluation_size": 2048,
|
| 247 |
+
"compute_steps": 128000,
|
| 248 |
+
"target_exposures": 4000,
|
| 249 |
+
"max_wall_seconds": 43200,
|
| 250 |
+
"layers": 4,
|
| 251 |
+
"world_seed": 961006111,
|
| 252 |
+
"initialization": 961006121,
|
| 253 |
+
"stream_seed": 961006131,
|
| 254 |
+
"phi": 0,
|
| 255 |
+
"phase": "confirmation",
|
| 256 |
+
"name": "support-w1-phi0"
|
| 257 |
+
},
|
| 258 |
+
{
|
| 259 |
+
"entities": 128,
|
| 260 |
+
"max_entities": 4096,
|
| 261 |
+
"relations": 32,
|
| 262 |
+
"degree": 16,
|
| 263 |
+
"id_fraction": 0.95,
|
| 264 |
+
"test_fraction": 0.1,
|
| 265 |
+
"width": 64,
|
| 266 |
+
"heads": 4,
|
| 267 |
+
"dropout": 0.1,
|
| 268 |
+
"lr": 0.0001,
|
| 269 |
+
"weight_decay": 0.1,
|
| 270 |
+
"warmup": 2000,
|
| 271 |
+
"batch_size": 256,
|
| 272 |
+
"evaluation_size": 2048,
|
| 273 |
+
"compute_steps": 128000,
|
| 274 |
+
"target_exposures": 4000,
|
| 275 |
+
"max_wall_seconds": 43200,
|
| 276 |
+
"layers": 4,
|
| 277 |
+
"world_seed": 961006111,
|
| 278 |
+
"initialization": 961006121,
|
| 279 |
+
"stream_seed": 961006131,
|
| 280 |
+
"phi": 0.5,
|
| 281 |
+
"phase": "confirmation",
|
| 282 |
+
"name": "support-w1-phi0.5"
|
| 283 |
+
},
|
| 284 |
+
{
|
| 285 |
+
"entities": 128,
|
| 286 |
+
"max_entities": 4096,
|
| 287 |
+
"relations": 32,
|
| 288 |
+
"degree": 16,
|
| 289 |
+
"id_fraction": 0.95,
|
| 290 |
+
"test_fraction": 0.1,
|
| 291 |
+
"width": 64,
|
| 292 |
+
"heads": 4,
|
| 293 |
+
"dropout": 0.1,
|
| 294 |
+
"lr": 0.0001,
|
| 295 |
+
"weight_decay": 0.1,
|
| 296 |
+
"warmup": 2000,
|
| 297 |
+
"batch_size": 256,
|
| 298 |
+
"evaluation_size": 2048,
|
| 299 |
+
"compute_steps": 128000,
|
| 300 |
+
"target_exposures": 4000,
|
| 301 |
+
"max_wall_seconds": 43200,
|
| 302 |
+
"layers": 4,
|
| 303 |
+
"world_seed": 961006111,
|
| 304 |
+
"initialization": 961006121,
|
| 305 |
+
"stream_seed": 961006131,
|
| 306 |
+
"phi": 1,
|
| 307 |
+
"phase": "confirmation",
|
| 308 |
+
"name": "support-w1-phi1"
|
| 309 |
+
},
|
| 310 |
+
{
|
| 311 |
+
"entities": 128,
|
| 312 |
+
"max_entities": 4096,
|
| 313 |
+
"relations": 32,
|
| 314 |
+
"degree": 16,
|
| 315 |
+
"id_fraction": 0.95,
|
| 316 |
+
"test_fraction": 0.1,
|
| 317 |
+
"width": 64,
|
| 318 |
+
"heads": 4,
|
| 319 |
+
"dropout": 0.1,
|
| 320 |
+
"lr": 0.0001,
|
| 321 |
+
"weight_decay": 0.1,
|
| 322 |
+
"warmup": 2000,
|
| 323 |
+
"batch_size": 256,
|
| 324 |
+
"evaluation_size": 2048,
|
| 325 |
+
"compute_steps": 128000,
|
| 326 |
+
"target_exposures": 4000,
|
| 327 |
+
"max_wall_seconds": 43200,
|
| 328 |
+
"layers": 4,
|
| 329 |
+
"world_seed": 961006111,
|
| 330 |
+
"initialization": 961006121,
|
| 331 |
+
"stream_seed": 961006131,
|
| 332 |
+
"phi": 2,
|
| 333 |
+
"phase": "confirmation",
|
| 334 |
+
"name": "support-w1-phi2"
|
| 335 |
+
},
|
| 336 |
+
{
|
| 337 |
+
"entities": 128,
|
| 338 |
+
"max_entities": 4096,
|
| 339 |
+
"relations": 32,
|
| 340 |
+
"degree": 16,
|
| 341 |
+
"id_fraction": 0.95,
|
| 342 |
+
"test_fraction": 0.1,
|
| 343 |
+
"width": 64,
|
| 344 |
+
"heads": 4,
|
| 345 |
+
"dropout": 0.1,
|
| 346 |
+
"lr": 0.0001,
|
| 347 |
+
"weight_decay": 0.1,
|
| 348 |
+
"warmup": 2000,
|
| 349 |
+
"batch_size": 256,
|
| 350 |
+
"evaluation_size": 2048,
|
| 351 |
+
"compute_steps": 128000,
|
| 352 |
+
"target_exposures": 4000,
|
| 353 |
+
"max_wall_seconds": 43200,
|
| 354 |
+
"layers": 4,
|
| 355 |
+
"world_seed": 961006111,
|
| 356 |
+
"initialization": 961006121,
|
| 357 |
+
"stream_seed": 961006131,
|
| 358 |
+
"phi": 4,
|
| 359 |
+
"phase": "confirmation",
|
| 360 |
+
"name": "support-w1-phi4"
|
| 361 |
+
},
|
| 362 |
+
{
|
| 363 |
+
"entities": 128,
|
| 364 |
+
"max_entities": 4096,
|
| 365 |
+
"relations": 32,
|
| 366 |
+
"degree": 16,
|
| 367 |
+
"id_fraction": 0.95,
|
| 368 |
+
"test_fraction": 0.1,
|
| 369 |
+
"width": 64,
|
| 370 |
+
"heads": 4,
|
| 371 |
+
"dropout": 0.1,
|
| 372 |
+
"lr": 0.0001,
|
| 373 |
+
"weight_decay": 0.1,
|
| 374 |
+
"warmup": 2000,
|
| 375 |
+
"batch_size": 256,
|
| 376 |
+
"evaluation_size": 2048,
|
| 377 |
+
"compute_steps": 128000,
|
| 378 |
+
"target_exposures": 4000,
|
| 379 |
+
"max_wall_seconds": 43200,
|
| 380 |
+
"layers": 4,
|
| 381 |
+
"world_seed": 961006111,
|
| 382 |
+
"initialization": 961006121,
|
| 383 |
+
"stream_seed": 961006131,
|
| 384 |
+
"phi": 7.2,
|
| 385 |
+
"phase": "confirmation",
|
| 386 |
+
"name": "support-w1-phi7.2"
|
| 387 |
+
},
|
| 388 |
+
{
|
| 389 |
+
"entities": 128,
|
| 390 |
+
"max_entities": 4096,
|
| 391 |
+
"relations": 32,
|
| 392 |
+
"degree": 16,
|
| 393 |
+
"id_fraction": 0.95,
|
| 394 |
+
"test_fraction": 0.1,
|
| 395 |
+
"width": 64,
|
| 396 |
+
"heads": 4,
|
| 397 |
+
"dropout": 0.1,
|
| 398 |
+
"lr": 0.0001,
|
| 399 |
+
"weight_decay": 0.1,
|
| 400 |
+
"warmup": 2000,
|
| 401 |
+
"batch_size": 256,
|
| 402 |
+
"evaluation_size": 2048,
|
| 403 |
+
"compute_steps": 128000,
|
| 404 |
+
"target_exposures": 4000,
|
| 405 |
+
"max_wall_seconds": 43200,
|
| 406 |
+
"layers": 4,
|
| 407 |
+
"world_seed": 961006111,
|
| 408 |
+
"initialization": 961006121,
|
| 409 |
+
"stream_seed": 961006131,
|
| 410 |
+
"phi": 12.6,
|
| 411 |
+
"phase": "confirmation",
|
| 412 |
+
"name": "support-w1-phi12.6"
|
| 413 |
+
},
|
| 414 |
+
{
|
| 415 |
+
"entities": 128,
|
| 416 |
+
"max_entities": 4096,
|
| 417 |
+
"relations": 32,
|
| 418 |
+
"degree": 16,
|
| 419 |
+
"id_fraction": 0.95,
|
| 420 |
+
"test_fraction": 0.1,
|
| 421 |
+
"width": 64,
|
| 422 |
+
"heads": 4,
|
| 423 |
+
"dropout": 0.1,
|
| 424 |
+
"lr": 0.0001,
|
| 425 |
+
"weight_decay": 0.1,
|
| 426 |
+
"warmup": 2000,
|
| 427 |
+
"batch_size": 256,
|
| 428 |
+
"evaluation_size": 2048,
|
| 429 |
+
"compute_steps": 128000,
|
| 430 |
+
"target_exposures": 4000,
|
| 431 |
+
"max_wall_seconds": 43200,
|
| 432 |
+
"layers": 4,
|
| 433 |
+
"world_seed": 961006112,
|
| 434 |
+
"initialization": 961006122,
|
| 435 |
+
"stream_seed": 961006132,
|
| 436 |
+
"phi": 0,
|
| 437 |
+
"phase": "confirmation",
|
| 438 |
+
"name": "support-w2-phi0"
|
| 439 |
+
},
|
| 440 |
+
{
|
| 441 |
+
"entities": 128,
|
| 442 |
+
"max_entities": 4096,
|
| 443 |
+
"relations": 32,
|
| 444 |
+
"degree": 16,
|
| 445 |
+
"id_fraction": 0.95,
|
| 446 |
+
"test_fraction": 0.1,
|
| 447 |
+
"width": 64,
|
| 448 |
+
"heads": 4,
|
| 449 |
+
"dropout": 0.1,
|
| 450 |
+
"lr": 0.0001,
|
| 451 |
+
"weight_decay": 0.1,
|
| 452 |
+
"warmup": 2000,
|
| 453 |
+
"batch_size": 256,
|
| 454 |
+
"evaluation_size": 2048,
|
| 455 |
+
"compute_steps": 128000,
|
| 456 |
+
"target_exposures": 4000,
|
| 457 |
+
"max_wall_seconds": 43200,
|
| 458 |
+
"layers": 4,
|
| 459 |
+
"world_seed": 961006112,
|
| 460 |
+
"initialization": 961006122,
|
| 461 |
+
"stream_seed": 961006132,
|
| 462 |
+
"phi": 0.5,
|
| 463 |
+
"phase": "confirmation",
|
| 464 |
+
"name": "support-w2-phi0.5"
|
| 465 |
+
},
|
| 466 |
+
{
|
| 467 |
+
"entities": 128,
|
| 468 |
+
"max_entities": 4096,
|
| 469 |
+
"relations": 32,
|
| 470 |
+
"degree": 16,
|
| 471 |
+
"id_fraction": 0.95,
|
| 472 |
+
"test_fraction": 0.1,
|
| 473 |
+
"width": 64,
|
| 474 |
+
"heads": 4,
|
| 475 |
+
"dropout": 0.1,
|
| 476 |
+
"lr": 0.0001,
|
| 477 |
+
"weight_decay": 0.1,
|
| 478 |
+
"warmup": 2000,
|
| 479 |
+
"batch_size": 256,
|
| 480 |
+
"evaluation_size": 2048,
|
| 481 |
+
"compute_steps": 128000,
|
| 482 |
+
"target_exposures": 4000,
|
| 483 |
+
"max_wall_seconds": 43200,
|
| 484 |
+
"layers": 4,
|
| 485 |
+
"world_seed": 961006112,
|
| 486 |
+
"initialization": 961006122,
|
| 487 |
+
"stream_seed": 961006132,
|
| 488 |
+
"phi": 1,
|
| 489 |
+
"phase": "confirmation",
|
| 490 |
+
"name": "support-w2-phi1"
|
| 491 |
+
},
|
| 492 |
+
{
|
| 493 |
+
"entities": 128,
|
| 494 |
+
"max_entities": 4096,
|
| 495 |
+
"relations": 32,
|
| 496 |
+
"degree": 16,
|
| 497 |
+
"id_fraction": 0.95,
|
| 498 |
+
"test_fraction": 0.1,
|
| 499 |
+
"width": 64,
|
| 500 |
+
"heads": 4,
|
| 501 |
+
"dropout": 0.1,
|
| 502 |
+
"lr": 0.0001,
|
| 503 |
+
"weight_decay": 0.1,
|
| 504 |
+
"warmup": 2000,
|
| 505 |
+
"batch_size": 256,
|
| 506 |
+
"evaluation_size": 2048,
|
| 507 |
+
"compute_steps": 128000,
|
| 508 |
+
"target_exposures": 4000,
|
| 509 |
+
"max_wall_seconds": 43200,
|
| 510 |
+
"layers": 4,
|
| 511 |
+
"world_seed": 961006112,
|
| 512 |
+
"initialization": 961006122,
|
| 513 |
+
"stream_seed": 961006132,
|
| 514 |
+
"phi": 2,
|
| 515 |
+
"phase": "confirmation",
|
| 516 |
+
"name": "support-w2-phi2"
|
| 517 |
+
},
|
| 518 |
+
{
|
| 519 |
+
"entities": 128,
|
| 520 |
+
"max_entities": 4096,
|
| 521 |
+
"relations": 32,
|
| 522 |
+
"degree": 16,
|
| 523 |
+
"id_fraction": 0.95,
|
| 524 |
+
"test_fraction": 0.1,
|
| 525 |
+
"width": 64,
|
| 526 |
+
"heads": 4,
|
| 527 |
+
"dropout": 0.1,
|
| 528 |
+
"lr": 0.0001,
|
| 529 |
+
"weight_decay": 0.1,
|
| 530 |
+
"warmup": 2000,
|
| 531 |
+
"batch_size": 256,
|
| 532 |
+
"evaluation_size": 2048,
|
| 533 |
+
"compute_steps": 128000,
|
| 534 |
+
"target_exposures": 4000,
|
| 535 |
+
"max_wall_seconds": 43200,
|
| 536 |
+
"layers": 4,
|
| 537 |
+
"world_seed": 961006112,
|
| 538 |
+
"initialization": 961006122,
|
| 539 |
+
"stream_seed": 961006132,
|
| 540 |
+
"phi": 4,
|
| 541 |
+
"phase": "confirmation",
|
| 542 |
+
"name": "support-w2-phi4"
|
| 543 |
+
},
|
| 544 |
+
{
|
| 545 |
+
"entities": 128,
|
| 546 |
+
"max_entities": 4096,
|
| 547 |
+
"relations": 32,
|
| 548 |
+
"degree": 16,
|
| 549 |
+
"id_fraction": 0.95,
|
| 550 |
+
"test_fraction": 0.1,
|
| 551 |
+
"width": 64,
|
| 552 |
+
"heads": 4,
|
| 553 |
+
"dropout": 0.1,
|
| 554 |
+
"lr": 0.0001,
|
| 555 |
+
"weight_decay": 0.1,
|
| 556 |
+
"warmup": 2000,
|
| 557 |
+
"batch_size": 256,
|
| 558 |
+
"evaluation_size": 2048,
|
| 559 |
+
"compute_steps": 128000,
|
| 560 |
+
"target_exposures": 4000,
|
| 561 |
+
"max_wall_seconds": 43200,
|
| 562 |
+
"layers": 4,
|
| 563 |
+
"world_seed": 961006112,
|
| 564 |
+
"initialization": 961006122,
|
| 565 |
+
"stream_seed": 961006132,
|
| 566 |
+
"phi": 7.2,
|
| 567 |
+
"phase": "confirmation",
|
| 568 |
+
"name": "support-w2-phi7.2"
|
| 569 |
+
},
|
| 570 |
+
{
|
| 571 |
+
"entities": 128,
|
| 572 |
+
"max_entities": 4096,
|
| 573 |
+
"relations": 32,
|
| 574 |
+
"degree": 16,
|
| 575 |
+
"id_fraction": 0.95,
|
| 576 |
+
"test_fraction": 0.1,
|
| 577 |
+
"width": 64,
|
| 578 |
+
"heads": 4,
|
| 579 |
+
"dropout": 0.1,
|
| 580 |
+
"lr": 0.0001,
|
| 581 |
+
"weight_decay": 0.1,
|
| 582 |
+
"warmup": 2000,
|
| 583 |
+
"batch_size": 256,
|
| 584 |
+
"evaluation_size": 2048,
|
| 585 |
+
"compute_steps": 128000,
|
| 586 |
+
"target_exposures": 4000,
|
| 587 |
+
"max_wall_seconds": 43200,
|
| 588 |
+
"layers": 4,
|
| 589 |
+
"world_seed": 961006112,
|
| 590 |
+
"initialization": 961006122,
|
| 591 |
+
"stream_seed": 961006132,
|
| 592 |
+
"phi": 12.6,
|
| 593 |
+
"phase": "confirmation",
|
| 594 |
+
"name": "support-w2-phi12.6"
|
| 595 |
+
},
|
| 596 |
+
{
|
| 597 |
+
"entities": 128,
|
| 598 |
+
"max_entities": 4096,
|
| 599 |
+
"relations": 32,
|
| 600 |
+
"degree": 16,
|
| 601 |
+
"id_fraction": 0.95,
|
| 602 |
+
"test_fraction": 0.1,
|
| 603 |
+
"width": 64,
|
| 604 |
+
"heads": 4,
|
| 605 |
+
"dropout": 0.1,
|
| 606 |
+
"lr": 0.0001,
|
| 607 |
+
"weight_decay": 0.1,
|
| 608 |
+
"warmup": 2000,
|
| 609 |
+
"batch_size": 256,
|
| 610 |
+
"evaluation_size": 2048,
|
| 611 |
+
"compute_steps": 128000,
|
| 612 |
+
"target_exposures": 4000,
|
| 613 |
+
"max_wall_seconds": 43200,
|
| 614 |
+
"layers": 4,
|
| 615 |
+
"world_seed": 961006113,
|
| 616 |
+
"initialization": 961006123,
|
| 617 |
+
"stream_seed": 961006133,
|
| 618 |
+
"phi": 0,
|
| 619 |
+
"phase": "confirmation",
|
| 620 |
+
"name": "support-w3-phi0"
|
| 621 |
+
},
|
| 622 |
+
{
|
| 623 |
+
"entities": 128,
|
| 624 |
+
"max_entities": 4096,
|
| 625 |
+
"relations": 32,
|
| 626 |
+
"degree": 16,
|
| 627 |
+
"id_fraction": 0.95,
|
| 628 |
+
"test_fraction": 0.1,
|
| 629 |
+
"width": 64,
|
| 630 |
+
"heads": 4,
|
| 631 |
+
"dropout": 0.1,
|
| 632 |
+
"lr": 0.0001,
|
| 633 |
+
"weight_decay": 0.1,
|
| 634 |
+
"warmup": 2000,
|
| 635 |
+
"batch_size": 256,
|
| 636 |
+
"evaluation_size": 2048,
|
| 637 |
+
"compute_steps": 128000,
|
| 638 |
+
"target_exposures": 4000,
|
| 639 |
+
"max_wall_seconds": 43200,
|
| 640 |
+
"layers": 4,
|
| 641 |
+
"world_seed": 961006113,
|
| 642 |
+
"initialization": 961006123,
|
| 643 |
+
"stream_seed": 961006133,
|
| 644 |
+
"phi": 0.5,
|
| 645 |
+
"phase": "confirmation",
|
| 646 |
+
"name": "support-w3-phi0.5"
|
| 647 |
+
},
|
| 648 |
+
{
|
| 649 |
+
"entities": 128,
|
| 650 |
+
"max_entities": 4096,
|
| 651 |
+
"relations": 32,
|
| 652 |
+
"degree": 16,
|
| 653 |
+
"id_fraction": 0.95,
|
| 654 |
+
"test_fraction": 0.1,
|
| 655 |
+
"width": 64,
|
| 656 |
+
"heads": 4,
|
| 657 |
+
"dropout": 0.1,
|
| 658 |
+
"lr": 0.0001,
|
| 659 |
+
"weight_decay": 0.1,
|
| 660 |
+
"warmup": 2000,
|
| 661 |
+
"batch_size": 256,
|
| 662 |
+
"evaluation_size": 2048,
|
| 663 |
+
"compute_steps": 128000,
|
| 664 |
+
"target_exposures": 4000,
|
| 665 |
+
"max_wall_seconds": 43200,
|
| 666 |
+
"layers": 4,
|
| 667 |
+
"world_seed": 961006113,
|
| 668 |
+
"initialization": 961006123,
|
| 669 |
+
"stream_seed": 961006133,
|
| 670 |
+
"phi": 1,
|
| 671 |
+
"phase": "confirmation",
|
| 672 |
+
"name": "support-w3-phi1"
|
| 673 |
+
},
|
| 674 |
+
{
|
| 675 |
+
"entities": 128,
|
| 676 |
+
"max_entities": 4096,
|
| 677 |
+
"relations": 32,
|
| 678 |
+
"degree": 16,
|
| 679 |
+
"id_fraction": 0.95,
|
| 680 |
+
"test_fraction": 0.1,
|
| 681 |
+
"width": 64,
|
| 682 |
+
"heads": 4,
|
| 683 |
+
"dropout": 0.1,
|
| 684 |
+
"lr": 0.0001,
|
| 685 |
+
"weight_decay": 0.1,
|
| 686 |
+
"warmup": 2000,
|
| 687 |
+
"batch_size": 256,
|
| 688 |
+
"evaluation_size": 2048,
|
| 689 |
+
"compute_steps": 128000,
|
| 690 |
+
"target_exposures": 4000,
|
| 691 |
+
"max_wall_seconds": 43200,
|
| 692 |
+
"layers": 4,
|
| 693 |
+
"world_seed": 961006113,
|
| 694 |
+
"initialization": 961006123,
|
| 695 |
+
"stream_seed": 961006133,
|
| 696 |
+
"phi": 2,
|
| 697 |
+
"phase": "confirmation",
|
| 698 |
+
"name": "support-w3-phi2"
|
| 699 |
+
},
|
| 700 |
+
{
|
| 701 |
+
"entities": 128,
|
| 702 |
+
"max_entities": 4096,
|
| 703 |
+
"relations": 32,
|
| 704 |
+
"degree": 16,
|
| 705 |
+
"id_fraction": 0.95,
|
| 706 |
+
"test_fraction": 0.1,
|
| 707 |
+
"width": 64,
|
| 708 |
+
"heads": 4,
|
| 709 |
+
"dropout": 0.1,
|
| 710 |
+
"lr": 0.0001,
|
| 711 |
+
"weight_decay": 0.1,
|
| 712 |
+
"warmup": 2000,
|
| 713 |
+
"batch_size": 256,
|
| 714 |
+
"evaluation_size": 2048,
|
| 715 |
+
"compute_steps": 128000,
|
| 716 |
+
"target_exposures": 4000,
|
| 717 |
+
"max_wall_seconds": 43200,
|
| 718 |
+
"layers": 4,
|
| 719 |
+
"world_seed": 961006113,
|
| 720 |
+
"initialization": 961006123,
|
| 721 |
+
"stream_seed": 961006133,
|
| 722 |
+
"phi": 4,
|
| 723 |
+
"phase": "confirmation",
|
| 724 |
+
"name": "support-w3-phi4"
|
| 725 |
+
},
|
| 726 |
+
{
|
| 727 |
+
"entities": 128,
|
| 728 |
+
"max_entities": 4096,
|
| 729 |
+
"relations": 32,
|
| 730 |
+
"degree": 16,
|
| 731 |
+
"id_fraction": 0.95,
|
| 732 |
+
"test_fraction": 0.1,
|
| 733 |
+
"width": 64,
|
| 734 |
+
"heads": 4,
|
| 735 |
+
"dropout": 0.1,
|
| 736 |
+
"lr": 0.0001,
|
| 737 |
+
"weight_decay": 0.1,
|
| 738 |
+
"warmup": 2000,
|
| 739 |
+
"batch_size": 256,
|
| 740 |
+
"evaluation_size": 2048,
|
| 741 |
+
"compute_steps": 128000,
|
| 742 |
+
"target_exposures": 4000,
|
| 743 |
+
"max_wall_seconds": 43200,
|
| 744 |
+
"layers": 4,
|
| 745 |
+
"world_seed": 961006113,
|
| 746 |
+
"initialization": 961006123,
|
| 747 |
+
"stream_seed": 961006133,
|
| 748 |
+
"phi": 7.2,
|
| 749 |
+
"phase": "confirmation",
|
| 750 |
+
"name": "support-w3-phi7.2"
|
| 751 |
+
},
|
| 752 |
+
{
|
| 753 |
+
"entities": 128,
|
| 754 |
+
"max_entities": 4096,
|
| 755 |
+
"relations": 32,
|
| 756 |
+
"degree": 16,
|
| 757 |
+
"id_fraction": 0.95,
|
| 758 |
+
"test_fraction": 0.1,
|
| 759 |
+
"width": 64,
|
| 760 |
+
"heads": 4,
|
| 761 |
+
"dropout": 0.1,
|
| 762 |
+
"lr": 0.0001,
|
| 763 |
+
"weight_decay": 0.1,
|
| 764 |
+
"warmup": 2000,
|
| 765 |
+
"batch_size": 256,
|
| 766 |
+
"evaluation_size": 2048,
|
| 767 |
+
"compute_steps": 128000,
|
| 768 |
+
"target_exposures": 4000,
|
| 769 |
+
"max_wall_seconds": 43200,
|
| 770 |
+
"layers": 4,
|
| 771 |
+
"world_seed": 961006113,
|
| 772 |
+
"initialization": 961006123,
|
| 773 |
+
"stream_seed": 961006133,
|
| 774 |
+
"phi": 12.6,
|
| 775 |
+
"phase": "confirmation",
|
| 776 |
+
"name": "support-w3-phi12.6"
|
| 777 |
+
}
|
| 778 |
+
],
|
| 779 |
+
"phase": "support"
|
| 780 |
+
}
|
docs/development-artifacts/composition-data-curves-v1/support-execution-lock.json
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"config_sha256": "630012f8b6c6d1a1032b3b66fb078777c3b032dd75c9db87eb315a7c9ba484b4",
|
| 3 |
+
"utc": "2026-10-06T01:07:16.671477+00:00"
|
| 4 |
+
}
|
docs/development-artifacts/composition-data-curves-v1/verification.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"passed": true,
|
| 3 |
+
"utc": "2026-10-06T01:05:47.805911+00:00",
|
| 4 |
+
"pytest": {
|
| 5 |
+
"passed": 30,
|
| 6 |
+
"files": [
|
| 7 |
+
"tests/test_composition_curves.py",
|
| 8 |
+
"tests/test_grok_depth_data.py",
|
| 9 |
+
"tests/test_grok_depth_training.py"
|
| 10 |
+
]
|
| 11 |
+
},
|
| 12 |
+
"ruff_check": "passed",
|
| 13 |
+
"ruff_format_check": "passed",
|
| 14 |
+
"cuda_preflight": "/ossfs/workspace/experiment-runs/composition-data-curves-v1-preflight/cuda.json",
|
| 15 |
+
"gpu_pipeline_reload": "/ossfs/workspace/experiment-runs/composition-data-curves-v1-preflight/smoke/audit.json",
|
| 16 |
+
"wandb_connectivity": "/ossfs/workspace/experiment-runs/composition-data-curves-v1-preflight/wandb-connectivity.json",
|
| 17 |
+
"engineering_preflight_not_scientific_result": true
|
| 18 |
+
}
|
docs/development-artifacts/compositional-capacity-discussion-20261006/note.md
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 存储与组合容量的分离:讨论候选
|
| 2 |
+
|
| 3 |
+
2026-10-06。原论文标题保持 **Transformers as Associative Memories: Exploring the Scaling of Storage and Compositional Recall**。本文件保留限定模型的代数推导与 CPU 数值核验;结合 Physics of Language Models 的后续思考、实验逻辑与故事线已按用户要求纳入[当前研究计划](../../hebbian-learning-plan-v1.md#capacity-scaling-mainline-20261006)。这不是新的训练执行协议,不修改现有运行。
|
| 4 |
+
|
| 5 |
+
## 核心问题与证据层级
|
| 6 |
+
|
| 7 |
+
随着事实负载增加,单跳可提取的知识量与多跳可组合的知识量,是否出现不同的宽度依赖?如果存在差距,中间状态的纠错能否改变它的增长规律?
|
| 8 |
+
|
| 9 |
+
复合答案由原子事实决定,不自带一份与每条链独立的新知识熵。不能因组合链数量增长,就推出存储参数必须按链数量增长。所需解释是特定表示和计算过程的代价:被压缩存储的关联能否连续使用,以及中间串扰如何随负载传播。
|
| 10 |
+
|
| 11 |
+
下面的结果仅属于随机编码、外积叠加、直接线性串接这一构造。它不证明所有可学习矩阵、MLP 或 Transformer 都具有相同损失,更不构成任意架构的容量下界。训练可重排表示、改变读写规则或实现内部纠错,这正是后续实验必须检验的部分。
|
| 12 |
+
|
| 13 |
+
## 一个精确的二阶矩计算
|
| 14 |
+
|
| 15 |
+
每个阶段有 N 个实体的独立随机单位球编码,写成 E_l ∈ R^{d×N},不同阶段也独立。阶段间关系取任意固定双射;对编码列重编号后,可无损地写成同索引关联。
|
| 16 |
+
|
| 17 |
+
记忆矩阵为 W_l = E_l E_{l-1}^T。一次查询从 E_0 e_i 开始,连续应用 h 个记忆矩阵,最后用 E_h 的内积打分。令 G_l = E_l^T E_l,则分数向量为
|
| 18 |
+
|
| 19 |
+
s = G_h G_{h-1} ... G_0 e_i.
|
| 20 |
+
|
| 21 |
+
这里 G_l 独立,E[G_l]=I。对独立于 G_l 的固定向量 v,令 a=1+(N−1)/d、b=1−1/d,有
|
| 22 |
+
|
| 23 |
+
E ||G_l v||² = a ||v||²,
|
| 24 |
+
E [(G_l v)_j²] = b v_j² + ||v||²/d.
|
| 25 |
+
|
| 26 |
+
第一式由对角元恒为 1、非对角元均值为 0 且二阶矩为 1/d 得到;第二式展开平方后,不同非对角项的交叉期望为零。对先前随机向量条件化后同样成立。
|
| 27 |
+
|
| 28 |
+
记 t 个 Gram 因子之后的错误坐标二阶矩为 q_t,则 q_0=0,且
|
| 29 |
+
|
| 30 |
+
q_{t+1} = b q_t + a^t/d,
|
| 31 |
+
q_t = (a^t − b^t)/N.
|
| 32 |
+
|
| 33 |
+
因此 h 次检索后的任一错误候选 j≠i 满足以下精确关系,期望遍历随机编码:
|
| 34 |
+
|
| 35 |
+
E[s_j] = 0,
|
| 36 |
+
Var(s_j) = { [1+(N−1)/d]^(h+1) − [1−1/d]^(h+1) } / N.
|
| 37 |
+
|
| 38 |
+
正确候选的均值为 1,二阶矩为 a^(h+1)/N + (1−1/N)b^(h+1);正确分数本身也有随机性,不可把它当成恒定信号。
|
| 39 |
+
|
| 40 |
+
特别地:
|
| 41 |
+
|
| 42 |
+
一跳:Var(s_j) = 2/d + (N−2)/d²,
|
| 43 |
+
两跳:Var(s_j) = 3/d + 3(N−2)/d² + (N²−3N+3)/d³.
|
| 44 |
+
|
| 45 |
+
在固定 h、N/d 足够大时,错误分数方差的主项为 N^h/d^(h+1)。这说明该构造中,连续组合的串扰负担增长快于单跳,不能仅按独立单跳错误率相乘解释。
|
| 46 |
+
|
| 47 |
+
这还不是准确率阈值定理。候选分数有依赖,正确分数也波动;要得到容量尺度,还须控制尾部概率和最大错误分数。把主项直接改写为 N≈d^(1+1/h),只能得到忽略尾部及对数因子的启发式尺度,不能写成已证明的 Transformer 定律。
|
| 48 |
+
|
| 49 |
+
## 中间重编码与架构含义
|
| 50 |
+
|
| 51 |
+
在每一步后使用模型自己的 argmax,将状态替换为预测实体的固定编码,再进入下一步。在必要单跳都正确的查询上,整个链确定正确。这一性质是构造的直接结果,不是新的普遍定理;它需要编码表、额外解码计算,并可能在单跳错误时做出不可逆的错误选择。
|
| 52 |
+
|
| 53 |
+
有价值的理论目标是比较两类计算在相同随机记忆负载下的准确率尺度,并明确纠错资源。之后再问训练后的非线性网络是否出现同类分离,以及是否已经学会消除它。此推导不适用于同一矩阵重复相乘;Loop 的跨步误差依赖需另行分析。
|
| 54 |
+
|
| 55 |
+
## CPU 验算与复现
|
| 56 |
+
|
| 57 |
+
[sanity_check.py](sanity_check.py) 使用 NumPy、16 次独立编码抽样,每次抽取 48 个查询;各条件的随机流固定。结果保存于 [sanity-results.json](sanity-results.json)。未进行参数训练、未使用 GPU。查询在同一编码世界内相关,768 个查询不能当作 768 个独立世界。报告的是抽样原子准确率。
|
| 58 |
+
|
| 59 |
+
当前主机复现命令:
|
| 60 |
+
|
| 61 |
+
```bash
|
| 62 |
+
LD_LIBRARY_PATH="/lib64${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 python docs/development-artifacts/compositional-capacity-discussion-20261006/sanity_check.py
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
## 小 Transformer 需要区分的解释
|
| 66 |
+
|
| 67 |
+
- 主轴采用原子世界信息量相对于参数量的负载 B/P,N 作为其中一个控制量;[知识容量对接](physics-of-language-connection.md)区分数据熵和实测掌握量。少量宽度用于验证尺度,先固定两跳,有规律后才延伸三跳。模型从头预训练,原子事实和有限组合示范可见,测试链留出。
|
| 68 |
+
- 固���最大词表、实体编码长度、关系类型、目标查询和目标事实的曝光;避免增加 N 时顺带改变词表参数或链难度。加入无关事实是一个关键比较:目标链保持不变,改变其他关联占用的记忆。
|
| 69 |
+
- 固定每条事实曝光与固定总 FLOPs 不能同时随 N 严格保持。前者用于机制主比较,后者只作资源复核;分别报告曲线,不混成同一容量结论。对临界点检查延长训练是否移动边界,不能把有限预算的优化失败写成结构不可能性。
|
| 70 |
+
- 报告全池多跳、必要单跳正确率及共同正确子集覆盖率。高平均原子准确率不足以排除组成目标链的事实恰好更难。
|
| 71 |
+
- 优先普通 Transformer 与共享块 Transformer,再按观测选一个机制变体。中间纠错若需要首跳监督,两臂给相同监督;若加入计算,补同等计算的对照。仅有外部多次问答成功不证明内部架构改善。
|
| 72 |
+
- 若串扰随负载的效应只存在于预设线性记忆、被正常训练消除,应收窄或放弃其作为普通 Transformer 主机制的解释。现有约 17% OO 平台不能被预先归因于容量。
|
| 73 |
+
|
| 74 |
+
## 相关文献及当前阅读边界
|
| 75 |
+
|
| 76 |
+
- [Meta: Scaling Laws for Looped Mixture of Experts](https://arxiv.org/html/2609.40316v1),2026-09-30 预印本:核对联合 recurrence/sparsity scaling、有效参数映射和下游计算比较。之前的参数/循环计算效率选题与其确有明显重叠。
|
| 77 |
+
- [Understanding Factual Recall in Transformers via Associative Memories](https://arxiv.org/html/2412.06538):随机编码关联记忆、事实存储与 Transformer 构造的理论基础。其单跳容量不能直接当成连续组合容量。
|
| 78 |
+
- [Sharp Capacity Thresholds in Linear Associative Memory: From Top-1 Retrieval to Tail-Average Learning](https://arxiv.org/html/2605.05189),所读为 2026-08-19 v2:核对摘要、§1 模型及 top-1 阈值陈述。v1 与 v2 的标题和定理强度不同;本次未独立验证整篇证明。其模型表明检索标准影响容量,不能将“容量取决于读出方式”本身当作我们的新发现。
|
| 79 |
+
- [Holographic Memory for Zero-Shot Compositional Reasoning in Knowledge Graphs](https://arxiv.org/html/2606.24948),2026-06-23 预印本:核对 HRR/FHRR 记忆构造、hard cleanup 两跳及必要第二跳的原子难度诊断。该模型的结果提醒我们必须核验路径上的必要事实,不能仅比较全局单跳均值。
|
| 80 |
+
- 搜索发现 OpenReview 稿件 *How Many Parameters for Multi-Hop?*,但两个正文入口都被站点验证页阻挡。本次未核对其定理,不据摘要认可其普遍容量结论;选题新颖性审查仍须补读。
|
docs/development-artifacts/compositional-capacity-discussion-20261006/physics-of-language-connection.md
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Physics of Language Models 3.3 对组合容量研究的帮助
|
| 2 |
+
|
| 3 |
+
2026-10-06,用户提出的文献连接;随后要求将思考和后续实验逻辑落盘。统一的故事线、实验顺序、判断分支和写作范围已纳入[当前研究计划](../../hebbian-learning-plan-v1.md#capacity-scaling-mainline-20261006)及[论文定位](../../paper-framing.md)。本文件保留文献口径与信息量定义,不增加训练预算或修改正在执行的协议。
|
| 4 |
+
|
| 5 |
+
## 原文口径
|
| 6 |
+
|
| 7 |
+
[Part 3.3,ICLR 2025 会议版](https://proceedings.iclr.cc/paper_files/paper/2025/file/26d3c9a66836ded8f34a944f2bfe868e-Paper-Conference.pdf)报告的是约 **2 bits of knowledge per parameter**,不是每条事实需要 2 bits。2 是受控实验中充分训练后的经验容量比例,信息论定理提供的是知识比特数的下界,不是任意 Transformer 都不得超过 2 bits/parameter 的普遍定理。
|
| 8 |
+
|
| 9 |
+
本次也读取了 [2024 arXiv 完整版](https://arxiv.org/html/2404.05405)的 §2–5、训练曝光与架构相关陈述、附录 A 的参数口径和提取验证。原文以随机生成的事实和知识 token 的损失估计信息量;名字集合、属性值、值词典分别计数。1000 次与 100 次事实曝光有不同经验容量。其参数口径排除未使用的词表行;MoE 分母是总存储参数,不是单次激活参数。提取验证借助在部分人物上微调 QA 后测试其余人物,不能自动解释为无监督零样本知识操作。
|
| 10 |
+
|
| 11 |
+
同系列 [Part 3.2,ICLR 2025 会议版](https://proceedings.iclr.cc/paper_files/paper/2025/file/d5494c8747276d3cdb2598e5617de89d-Paper-Conference.pdf)已研究提取、分类、比较、逆向搜索,并观察到提取成功与知识操作失败可以并存。因此,“记得但不会用”本身不是我们的新增主张。
|
| 12 |
+
|
| 13 |
+
## 用知识熵取代事实条数作为主负载
|
| 14 |
+
|
| 15 |
+
在固定地址与值词表、N 个独立且均匀的 M 选一属性值的简化世界中:
|
| 16 |
+
|
| 17 |
+
H(Z) = N log₂ M.
|
| 18 |
+
|
| 19 |
+
如果原子属性值的平均负对数概率为 ℓ₁(nats),则可采用与原文思路一致的经验量:
|
| 20 |
+
|
| 21 |
+
B_hat = N (log₂ M − ℓ₁ / ln 2).
|
| 22 |
+
|
| 23 |
+
跨随机世界取期望时,可由熵与交叉熵关系给出模型保有信息量的下界;单个世界的实测估计不等于已知的真实互信息。该简式只计条件属性信息,不包含随机名字/词典的学习成本,也不能直接用于相关的真实知识图。
|
| 24 |
+
|
| 25 |
+
区分两个横轴:数据负载 ρ_data=H(Z)/P,与已掌握信息的经验密度 ρ_learned=B_hat/P。提高数据量但没有学会,并不意味着存储密度提高。
|
| 26 |
+
|
| 27 |
+
多跳答案由原子世界 Z 决定。不能把大量复合查询的 log₂ 候选数相加,当作新存入的知识 bits。组合题之间共享事实,联合熵不能按题数独立计数。
|
| 28 |
+
|
| 29 |
+
## 候选容量定义与理论目标
|
| 30 |
+
|
| 31 |
+
固定世界生成器、训练支持、训练流程、知识表示、评价分布及准确率要求,定义:
|
| 32 |
+
|
| 33 |
+
- C₁(P):达到指定原子提取准确率时,可承载的最大原子世界信息量。
|
| 34 |
+
- C_h(P):同时满足同一原子提取要求及指定 h 跳泛化准确率时,可承载的最大原子世界信息量。
|
| 35 |
+
|
| 36 |
+
组合容量的单位是“满足使用要求的知识库 bits”,不是复合答案新增 bits。由定义的集合包含关系 C_h≤C₁;这个不等式不是论文贡献。真正要研究的是两者的尺度、差距随 h 的变化,以及架构是否改变差距。
|
| 37 |
+
|
| 38 |
+
尤其不能直接设 C₁(P)=2P:原文约 2 bits/parameter 是基于损失估计的峰值容量比例,与我们指定例如 99% 原子准确率时的容量边界不是同一定义。先复用其测量方法,再独立测定我们的 C₁ 和 C_h。
|
| 39 |
+
|
| 40 |
+
经典信息论能限制需要存储的世界信息,但不会因复合查询数量大就自动产生新的 h 倍信息下界。若需证明组合额外代价,必须引入明确的计算限制、状态维数、精度或中间纠错条件。前一份随机线性记忆的串扰推导只覆盖其中一个构造,不能推出所有学习到的 Transformer 都有同一尺度。
|
| 41 |
+
|
| 42 |
+
## 对当前实验的实际影响
|
| 43 |
+
|
| 44 |
+
当前真实图 65,968 条原子事实,D8 约 96.1M 总参数,二者尚未转换到相容的信息/参数口径。没有证据说明已经接近 3.3 的存储极限。仅作为量纲示例:如果每条独立关联为 20 bits,条件关联信息量约 1.32M bits,用当前总参数分母约为 0.014 bits/parameter;这不是当前真实数据的熵估计,也尚未扣除未使用词表行。
|
| 45 |
+
|
| 46 |
+
因此,下一步应先校准小模型的单跳容量曲线,适当缩小模型或增加受控事实熵,覆盖欠载至接近饱和的区间,再观察未见组合。保持共同词表,报告全部参数与按原文口径调整的参数;共享循环参数只计一次,MoE 同时报总参数和实际计算。
|
| 47 |
+
|
| 48 |
+
可检验的中心问题是:**在相同知识 bits/parameter 和必要原子提取水平下,组合能力是否仍受状态宽度、执行结构与中间纠错显著影响?** 若负载归一化能让单跳曲线接近重合、组合曲线却依架构分离,就得到超出架构排名的机制问题。先以两跳为主,负载为主轴;不自动追加架构或跳数全矩阵。
|
docs/development-artifacts/compositional-capacity-discussion-20261006/sanity-results.json
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"kind": "exploratory CPU algebra verification; no training",
|
| 3 |
+
"seed": 601006,
|
| 4 |
+
"numpy_version": "1.23.5",
|
| 5 |
+
"rows": [
|
| 6 |
+
{
|
| 7 |
+
"d": 64,
|
| 8 |
+
"associations_per_stage": 128,
|
| 9 |
+
"independent_codebook_draws": 16,
|
| 10 |
+
"queries_per_draw": 48,
|
| 11 |
+
"atomic1": 0.9817708333333334,
|
| 12 |
+
"atomic2": 0.9817708333333334,
|
| 13 |
+
"continuous_twohop": 0.4088541666666667,
|
| 14 |
+
"both_atomic_correct_coverage": 0.9635416666666666,
|
| 15 |
+
"continuous_twohop_given_both_correct": 0.4175675675675676,
|
| 16 |
+
"reset_twohop": 0.9635416666666666,
|
| 17 |
+
"reset_twohop_given_both_correct": 1.0,
|
| 18 |
+
"off_score_second_moment_onehop_measured": 0.06191769958576853,
|
| 19 |
+
"off_score_second_moment_onehop_exact": 0.06201171875,
|
| 20 |
+
"off_score_second_moment_twohop_measured": 0.19202592507422953,
|
| 21 |
+
"off_score_second_moment_twohop_exact": 0.20020675659179688
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"d": 64,
|
| 25 |
+
"associations_per_stage": 256,
|
| 26 |
+
"independent_codebook_draws": 16,
|
| 27 |
+
"queries_per_draw": 48,
|
| 28 |
+
"atomic1": 0.73828125,
|
| 29 |
+
"atomic2": 0.7760416666666666,
|
| 30 |
+
"continuous_twohop": 0.078125,
|
| 31 |
+
"both_atomic_correct_coverage": 0.5572916666666666,
|
| 32 |
+
"continuous_twohop_given_both_correct": 0.11214953271028037,
|
| 33 |
+
"reset_twohop": 0.55859375,
|
| 34 |
+
"reset_twohop_given_both_correct": 1.0,
|
| 35 |
+
"off_score_second_moment_onehop_measured": 0.09284981942132862,
|
| 36 |
+
"off_score_second_moment_onehop_exact": 0.09326171875,
|
| 37 |
+
"off_score_second_moment_twohop_measured": 0.4692728946295357,
|
| 38 |
+
"off_score_second_moment_twohop_exact": 0.4799919128417969
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"d": 128,
|
| 42 |
+
"associations_per_stage": 256,
|
| 43 |
+
"independent_codebook_draws": 16,
|
| 44 |
+
"queries_per_draw": 48,
|
| 45 |
+
"atomic1": 1.0,
|
| 46 |
+
"atomic2": 1.0,
|
| 47 |
+
"continuous_twohop": 0.64453125,
|
| 48 |
+
"both_atomic_correct_coverage": 1.0,
|
| 49 |
+
"continuous_twohop_given_both_correct": 0.64453125,
|
| 50 |
+
"reset_twohop": 1.0,
|
| 51 |
+
"reset_twohop_given_both_correct": 1.0,
|
| 52 |
+
"off_score_second_moment_onehop_measured": 0.03121580010666049,
|
| 53 |
+
"off_score_second_moment_onehop_exact": 0.0311279296875,
|
| 54 |
+
"off_score_second_moment_twohop_measured": 0.10011350323057835,
|
| 55 |
+
"off_score_second_moment_twohop_exact": 0.10083150863647461
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
"d": 128,
|
| 59 |
+
"associations_per_stage": 512,
|
| 60 |
+
"independent_codebook_draws": 16,
|
| 61 |
+
"queries_per_draw": 48,
|
| 62 |
+
"atomic1": 0.9778645833333334,
|
| 63 |
+
"atomic2": 0.96484375,
|
| 64 |
+
"continuous_twohop": 0.15494791666666666,
|
| 65 |
+
"both_atomic_correct_coverage": 0.9466145833333334,
|
| 66 |
+
"continuous_twohop_given_both_correct": 0.1623108665749656,
|
| 67 |
+
"reset_twohop": 0.9466145833333334,
|
| 68 |
+
"reset_twohop_given_both_correct": 1.0,
|
| 69 |
+
"off_score_second_moment_onehop_measured": 0.04736494144751186,
|
| 70 |
+
"off_score_second_moment_onehop_exact": 0.0467529296875,
|
| 71 |
+
"off_score_second_moment_twohop_measured": 0.2419763221214787,
|
| 72 |
+
"off_score_second_moment_twohop_exact": 0.2410902976989746
|
| 73 |
+
},
|
| 74 |
+
{
|
| 75 |
+
"d": 128,
|
| 76 |
+
"associations_per_stage": 1024,
|
| 77 |
+
"independent_codebook_draws": 16,
|
| 78 |
+
"queries_per_draw": 48,
|
| 79 |
+
"atomic1": 0.69140625,
|
| 80 |
+
"atomic2": 0.66015625,
|
| 81 |
+
"continuous_twohop": 0.013020833333333334,
|
| 82 |
+
"both_atomic_correct_coverage": 0.4635416666666667,
|
| 83 |
+
"continuous_twohop_given_both_correct": 0.02247191011235955,
|
| 84 |
+
"reset_twohop": 0.4635416666666667,
|
| 85 |
+
"reset_twohop_given_both_correct": 1.0,
|
| 86 |
+
"off_score_second_moment_onehop_measured": 0.07904413494810934,
|
| 87 |
+
"off_score_second_moment_onehop_exact": 0.0780029296875,
|
| 88 |
+
"off_score_second_moment_twohop_measured": 0.7224368904657623,
|
| 89 |
+
"off_score_second_moment_twohop_exact": 0.7091078758239746
|
| 90 |
+
}
|
| 91 |
+
],
|
| 92 |
+
"limitations": [
|
| 93 |
+
"Query samples within a codebook draw are dependent.",
|
| 94 |
+
"Atomic percentages refer to sampled queries, not all stored facts.",
|
| 95 |
+
"Reset accesses a fixed codebook and adds decoding work.",
|
| 96 |
+
"No confidence intervals or capacity exponent fitted.",
|
| 97 |
+
"Independent codebooks do not establish behavior of tied recurrent weights."
|
| 98 |
+
]
|
| 99 |
+
}
|
docs/development-artifacts/compositional-capacity-discussion-20261006/sanity_check.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CPU-only algebra check, not a Transformer training experiment.
|
| 2 |
+
|
| 3 |
+
Run on the current host with /lib64 first in LD_LIBRARY_PATH and one BLAS thread.
|
| 4 |
+
The random codebooks are independent between stages and have unit-norm columns.
|
| 5 |
+
This does not model a repeatedly applied shared matrix or SGD learning.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def main():
|
| 15 |
+
rng = np.random.default_rng(601006)
|
| 16 |
+
rows = []
|
| 17 |
+
for d, n in [(64, 128), (64, 256), (128, 256), (128, 512), (128, 1024)]:
|
| 18 |
+
totals = np.zeros(9, dtype=float)
|
| 19 |
+
for _ in range(16):
|
| 20 |
+
codebooks = [rng.normal(size=(d, n)) for _ in range(3)]
|
| 21 |
+
codebooks = [e / np.linalg.norm(e, axis=0) for e in codebooks]
|
| 22 |
+
w1 = codebooks[1] @ codebooks[0].T
|
| 23 |
+
w2 = codebooks[2] @ codebooks[1].T
|
| 24 |
+
ids = rng.choice(n, size=48, replace=False)
|
| 25 |
+
hidden = w1 @ codebooks[0][:, ids]
|
| 26 |
+
s1 = codebooks[1].T @ hidden
|
| 27 |
+
s2_atomic = codebooks[2].T @ (w2 @ codebooks[1][:, ids])
|
| 28 |
+
s2 = codebooks[2].T @ (w2 @ hidden)
|
| 29 |
+
predicted_bridge = s1.argmax(axis=0)
|
| 30 |
+
reset_scores = codebooks[2].T @ (w2 @ codebooks[1][:, predicted_bridge])
|
| 31 |
+
correct1 = predicted_bridge == ids
|
| 32 |
+
correct2 = s2_atomic.argmax(axis=0) == ids
|
| 33 |
+
both = correct1 & correct2
|
| 34 |
+
composed = s2.argmax(axis=0) == ids
|
| 35 |
+
reset_correct = reset_scores.argmax(axis=0) == ids
|
| 36 |
+
# Exact consequence of replacing a correct prediction by its codeword.
|
| 37 |
+
assert np.all(reset_correct[both])
|
| 38 |
+
wrong = np.ones((n, len(ids)), dtype=bool)
|
| 39 |
+
wrong[ids, np.arange(len(ids))] = False
|
| 40 |
+
totals += [
|
| 41 |
+
correct1.sum(), correct2.sum(), composed.sum(), both.sum(),
|
| 42 |
+
(composed & both).sum(), (s1[wrong] ** 2).mean(),
|
| 43 |
+
(s2[wrong] ** 2).mean(), len(ids), reset_correct.sum(),
|
| 44 |
+
]
|
| 45 |
+
a, b = 1 + (n - 1) / d, 1 - 1 / d
|
| 46 |
+
rows.append(dict(
|
| 47 |
+
d=d, associations_per_stage=n, independent_codebook_draws=16,
|
| 48 |
+
queries_per_draw=48, atomic1=totals[0] / totals[7],
|
| 49 |
+
atomic2=totals[1] / totals[7], continuous_twohop=totals[2] / totals[7],
|
| 50 |
+
both_atomic_correct_coverage=totals[3] / totals[7],
|
| 51 |
+
continuous_twohop_given_both_correct=totals[4] / totals[3],
|
| 52 |
+
reset_twohop=totals[8] / totals[7],
|
| 53 |
+
reset_twohop_given_both_correct=1.0,
|
| 54 |
+
off_score_second_moment_onehop_measured=totals[5] / 16,
|
| 55 |
+
off_score_second_moment_onehop_exact=(a ** 2 - b ** 2) / n,
|
| 56 |
+
off_score_second_moment_twohop_measured=totals[6] / 16,
|
| 57 |
+
off_score_second_moment_twohop_exact=(a ** 3 - b ** 3) / n,
|
| 58 |
+
))
|
| 59 |
+
output = dict(
|
| 60 |
+
kind="exploratory CPU algebra verification; no training",
|
| 61 |
+
seed=601006, numpy_version=np.__version__, rows=rows,
|
| 62 |
+
limitations=[
|
| 63 |
+
"Query samples within a codebook draw are dependent.",
|
| 64 |
+
"Atomic percentages refer to sampled queries, not all stored facts.",
|
| 65 |
+
"Reset accesses a fixed codebook and adds decoding work.",
|
| 66 |
+
"No confidence intervals or capacity exponent fitted.",
|
| 67 |
+
"Independent codebooks do not establish behavior of tied recurrent weights.",
|
| 68 |
+
],
|
| 69 |
+
)
|
| 70 |
+
Path(__file__).with_name("sanity-results.json").write_text(
|
| 71 |
+
json.dumps(output, ensure_ascii=False, indent=2) + "\n"
|
| 72 |
+
)
|
| 73 |
+
for row in rows:
|
| 74 |
+
print(json.dumps({k: row[k] for k in (
|
| 75 |
+
"d", "associations_per_stage", "atomic1", "atomic2",
|
| 76 |
+
"continuous_twohop_given_both_correct", "reset_twohop",
|
| 77 |
+
)}))
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
if __name__ == "__main__":
|
| 81 |
+
main()
|
docs/development-artifacts/memory-interface-next-v1/container/lm-memory-daemon.log
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
docs/development-artifacts/oo-budget-attribution-20261005/analysis-execution.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"real_loop": {
|
| 3 |
+
"oo_percent": 16.73161860223435,
|
| 4 |
+
"training_hours": 6.638698058694394,
|
| 5 |
+
"estimated_matmul_training_flops": 2775305955439048704,
|
| 6 |
+
"executed_input_tokens": 6554798306.666667,
|
| 7 |
+
"examples": 153249855,
|
| 8 |
+
"atomic_epochs": 1255.2304046406339,
|
| 9 |
+
"composition_epochs": 1255.2309414776405,
|
| 10 |
+
"n_initializations": 3,
|
| 11 |
+
"oo_n_each": 1283,
|
| 12 |
+
"oo_sample_sd": 0.6536630618555017
|
| 13 |
+
},
|
| 14 |
+
"synthetic_loop_wd03": {
|
| 15 |
+
"dataset": "synthetic",
|
| 16 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 17 |
+
"architecture": "loop4x2",
|
| 18 |
+
"initialization": 791101,
|
| 19 |
+
"learning_rate": 0.0001,
|
| 20 |
+
"weight_decay": 0.3,
|
| 21 |
+
"phi": 7.2,
|
| 22 |
+
"step": 1500000,
|
| 23 |
+
"oo_n": 2004,
|
| 24 |
+
"oo_percent": 81.3373253493014,
|
| 25 |
+
"evaluation_scope": "fixed_full_OO_pool",
|
| 26 |
+
"training_hours": 6.5032488311454655,
|
| 27 |
+
"estimated_matmul_training_flops": 1415910260736000000,
|
| 28 |
+
"executed_input_tokens": 3072000000,
|
| 29 |
+
"examples": 767373824,
|
| 30 |
+
"atomic_epochs": 2446.9826,
|
| 31 |
+
"composition_epochs": 2446.982894736842
|
| 32 |
+
},
|
| 33 |
+
"ratios": {
|
| 34 |
+
"training_hours": 1.020827932478953,
|
| 35 |
+
"estimated_matmul_training_flops": 1.9600860537562779,
|
| 36 |
+
"executed_input_tokens": 2.1337234071180555,
|
| 37 |
+
"examples": 0.1997069097316512,
|
| 38 |
+
"atomic_epochs": 0.5129707112100568
|
| 39 |
+
},
|
| 40 |
+
"recounted_pools": 81
|
| 41 |
+
}
|
docs/development-artifacts/oo-budget-attribution-20261005/budget-brackets.json
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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synthetic",
|
| 8 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 9 |
+
"architecture": "loop4x2",
|
| 10 |
+
"initialization": 791101,
|
| 11 |
+
"learning_rate": 0.0001,
|
| 12 |
+
"weight_decay": 0.3,
|
| 13 |
+
"phi": 7.2,
|
| 14 |
+
"step": 1500000,
|
| 15 |
+
"oo_n": 2004,
|
| 16 |
+
"oo_percent": 81.3373253493014,
|
| 17 |
+
"evaluation_scope": "fixed_full_OO_pool",
|
| 18 |
+
"training_hours": 6.5032488311454655,
|
| 19 |
+
"estimated_matmul_training_flops": 1415910260736000000,
|
| 20 |
+
"executed_input_tokens": 3072000000,
|
| 21 |
+
"examples": 767373824,
|
| 22 |
+
"atomic_epochs": 2446.9826,
|
| 23 |
+
"composition_epochs": 2446.982894736842
|
| 24 |
+
},
|
| 25 |
+
"synthetic_above": null,
|
| 26 |
+
"extrapolated": false
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"real_run": "confirmation-loop4x2-init1",
|
| 30 |
+
"budget": "estimated_matmul_training_flops",
|
| 31 |
+
"real_value": 2775487015724686848,
|
| 32 |
+
"synthetic_below": {
|
| 33 |
+
"dataset": "synthetic",
|
| 34 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 35 |
+
"architecture": "loop4x2",
|
| 36 |
+
"initialization": 791101,
|
| 37 |
+
"learning_rate": 0.0001,
|
| 38 |
+
"weight_decay": 0.3,
|
| 39 |
+
"phi": 7.2,
|
| 40 |
+
"step": 1500000,
|
| 41 |
+
"oo_n": 2004,
|
| 42 |
+
"oo_percent": 81.3373253493014,
|
| 43 |
+
"evaluation_scope": "fixed_full_OO_pool",
|
| 44 |
+
"training_hours": 6.5032488311454655,
|
| 45 |
+
"estimated_matmul_training_flops": 1415910260736000000,
|
| 46 |
+
"executed_input_tokens": 3072000000,
|
| 47 |
+
"examples": 767373824,
|
| 48 |
+
"atomic_epochs": 2446.9826,
|
| 49 |
+
"composition_epochs": 2446.982894736842
|
| 50 |
+
},
|
| 51 |
+
"synthetic_above": null,
|
| 52 |
+
"extrapolated": false
|
| 53 |
+
},
|
| 54 |
+
{
|
| 55 |
+
"real_run": "confirmation-loop4x2-init1",
|
| 56 |
+
"budget": "examples",
|
| 57 |
+
"real_value": 153249855,
|
| 58 |
+
"synthetic_below": {
|
| 59 |
+
"dataset": "synthetic",
|
| 60 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 61 |
+
"architecture": "loop4x2",
|
| 62 |
+
"initialization": 791101,
|
| 63 |
+
"learning_rate": 0.0001,
|
| 64 |
+
"weight_decay": 0.3,
|
| 65 |
+
"phi": 7.2,
|
| 66 |
+
"step": 296000,
|
| 67 |
+
"oo_n": 2004,
|
| 68 |
+
"oo_percent": 24.10179640718563,
|
| 69 |
+
"evaluation_scope": "fixed_full_OO_pool",
|
| 70 |
+
"training_hours": 1.2962222684443825,
|
| 71 |
+
"estimated_matmul_training_flops": 279406291451904000,
|
| 72 |
+
"executed_input_tokens": 606208000,
|
| 73 |
+
"examples": 151428608,
|
| 74 |
+
"atomic_epochs": 482.872525,
|
| 75 |
+
"composition_epochs": 482.8717361111111
|
| 76 |
+
},
|
| 77 |
+
"synthetic_above": {
|
| 78 |
+
"dataset": "synthetic",
|
| 79 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 80 |
+
"architecture": "loop4x2",
|
| 81 |
+
"initialization": 791101,
|
| 82 |
+
"learning_rate": 0.0001,
|
| 83 |
+
"weight_decay": 0.3,
|
| 84 |
+
"phi": 7.2,
|
| 85 |
+
"step": 300000,
|
| 86 |
+
"oo_n": 2004,
|
| 87 |
+
"oo_percent": 24.451097804391217,
|
| 88 |
+
"evaluation_scope": "fixed_full_OO_pool",
|
| 89 |
+
"training_hours": 1.3134469647612423,
|
| 90 |
+
"estimated_matmul_training_flops": 283182052147200000,
|
| 91 |
+
"executed_input_tokens": 614400000,
|
| 92 |
+
"examples": 153474816,
|
| 93 |
+
"atomic_epochs": 489.39375,
|
| 94 |
+
"composition_epochs": 489.39717105263156
|
| 95 |
+
},
|
| 96 |
+
"extrapolated": false
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"real_run": "confirmation-loop4x2-init1",
|
| 100 |
+
"budget": "atomic_epochs",
|
| 101 |
+
"real_value": 1255.2305814940578,
|
| 102 |
+
"synthetic_below": {
|
| 103 |
+
"dataset": "synthetic",
|
| 104 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 105 |
+
"architecture": "loop4x2",
|
| 106 |
+
"initialization": 791101,
|
| 107 |
+
"learning_rate": 0.0001,
|
| 108 |
+
"weight_decay": 0.3,
|
| 109 |
+
"phi": 7.2,
|
| 110 |
+
"step": 768000,
|
| 111 |
+
"oo_n": 2004,
|
| 112 |
+
"oo_percent": 70.60878243512974,
|
| 113 |
+
"evaluation_scope": "fixed_full_OO_pool",
|
| 114 |
+
"training_hours": 3.328787970851279,
|
| 115 |
+
"estimated_matmul_training_flops": 724946053496832000,
|
| 116 |
+
"executed_input_tokens": 1572864000,
|
| 117 |
+
"examples": 392895488,
|
| 118 |
+
"atomic_epochs": 1252.856725,
|
| 119 |
+
"composition_epochs": 1252.855332602339
|
| 120 |
+
},
|
| 121 |
+
"synthetic_above": {
|
| 122 |
+
"dataset": "synthetic",
|
| 123 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 124 |
+
"architecture": "loop4x2",
|
| 125 |
+
"initialization": 791101,
|
| 126 |
+
"learning_rate": 0.0001,
|
| 127 |
+
"weight_decay": 0.3,
|
| 128 |
+
"phi": 7.2,
|
| 129 |
+
"step": 772000,
|
| 130 |
+
"oo_n": 2004,
|
| 131 |
+
"oo_percent": 70.50898203592814,
|
| 132 |
+
"evaluation_scope": "fixed_full_OO_pool",
|
| 133 |
+
"training_hours": 3.3460153445280674,
|
| 134 |
+
"estimated_matmul_training_flops": 728721814192128000,
|
| 135 |
+
"executed_input_tokens": 1581056000,
|
| 136 |
+
"examples": 394941696,
|
| 137 |
+
"atomic_epochs": 1259.380075,
|
| 138 |
+
"composition_epochs": 1259.3804568713451
|
| 139 |
+
},
|
| 140 |
+
"extrapolated": false
|
| 141 |
+
},
|
| 142 |
+
{
|
| 143 |
+
"real_run": "confirmation-loop4x2-init2",
|
| 144 |
+
"budget": "training_hours",
|
| 145 |
+
"real_value": 6.642358209469045,
|
| 146 |
+
"synthetic_below": {
|
| 147 |
+
"dataset": "synthetic",
|
| 148 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 149 |
+
"architecture": "loop4x2",
|
| 150 |
+
"initialization": 791101,
|
| 151 |
+
"learning_rate": 0.0001,
|
| 152 |
+
"weight_decay": 0.3,
|
| 153 |
+
"phi": 7.2,
|
| 154 |
+
"step": 1500000,
|
| 155 |
+
"oo_n": 2004,
|
| 156 |
+
"oo_percent": 81.3373253493014,
|
| 157 |
+
"evaluation_scope": "fixed_full_OO_pool",
|
| 158 |
+
"training_hours": 6.5032488311454655,
|
| 159 |
+
"estimated_matmul_training_flops": 1415910260736000000,
|
| 160 |
+
"executed_input_tokens": 3072000000,
|
| 161 |
+
"examples": 767373824,
|
| 162 |
+
"atomic_epochs": 2446.9826,
|
| 163 |
+
"composition_epochs": 2446.982894736842
|
| 164 |
+
},
|
| 165 |
+
"synthetic_above": null,
|
| 166 |
+
"extrapolated": false
|
| 167 |
+
},
|
| 168 |
+
{
|
| 169 |
+
"real_run": "confirmation-loop4x2-init2",
|
| 170 |
+
"budget": "estimated_matmul_training_flops",
|
| 171 |
+
"real_value": 2775118595566491648,
|
| 172 |
+
"synthetic_below": {
|
| 173 |
+
"dataset": "synthetic",
|
| 174 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 175 |
+
"architecture": "loop4x2",
|
| 176 |
+
"initialization": 791101,
|
| 177 |
+
"learning_rate": 0.0001,
|
| 178 |
+
"weight_decay": 0.3,
|
| 179 |
+
"phi": 7.2,
|
| 180 |
+
"step": 1500000,
|
| 181 |
+
"oo_n": 2004,
|
| 182 |
+
"oo_percent": 81.3373253493014,
|
| 183 |
+
"evaluation_scope": "fixed_full_OO_pool",
|
| 184 |
+
"training_hours": 6.5032488311454655,
|
| 185 |
+
"estimated_matmul_training_flops": 1415910260736000000,
|
| 186 |
+
"executed_input_tokens": 3072000000,
|
| 187 |
+
"examples": 767373824,
|
| 188 |
+
"atomic_epochs": 2446.9826,
|
| 189 |
+
"composition_epochs": 2446.982894736842
|
| 190 |
+
},
|
| 191 |
+
"synthetic_above": null,
|
| 192 |
+
"extrapolated": false
|
| 193 |
+
},
|
| 194 |
+
{
|
| 195 |
+
"real_run": "confirmation-loop4x2-init2",
|
| 196 |
+
"budget": "examples",
|
| 197 |
+
"real_value": 153249855,
|
| 198 |
+
"synthetic_below": {
|
| 199 |
+
"dataset": "synthetic",
|
| 200 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 201 |
+
"architecture": "loop4x2",
|
| 202 |
+
"initialization": 791101,
|
| 203 |
+
"learning_rate": 0.0001,
|
| 204 |
+
"weight_decay": 0.3,
|
| 205 |
+
"phi": 7.2,
|
| 206 |
+
"step": 296000,
|
| 207 |
+
"oo_n": 2004,
|
| 208 |
+
"oo_percent": 24.10179640718563,
|
| 209 |
+
"evaluation_scope": "fixed_full_OO_pool",
|
| 210 |
+
"training_hours": 1.2962222684443825,
|
| 211 |
+
"estimated_matmul_training_flops": 279406291451904000,
|
| 212 |
+
"executed_input_tokens": 606208000,
|
| 213 |
+
"examples": 151428608,
|
| 214 |
+
"atomic_epochs": 482.872525,
|
| 215 |
+
"composition_epochs": 482.8717361111111
|
| 216 |
+
},
|
| 217 |
+
"synthetic_above": {
|
| 218 |
+
"dataset": "synthetic",
|
| 219 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 220 |
+
"architecture": "loop4x2",
|
| 221 |
+
"initialization": 791101,
|
| 222 |
+
"learning_rate": 0.0001,
|
| 223 |
+
"weight_decay": 0.3,
|
| 224 |
+
"phi": 7.2,
|
| 225 |
+
"step": 300000,
|
| 226 |
+
"oo_n": 2004,
|
| 227 |
+
"oo_percent": 24.451097804391217,
|
| 228 |
+
"evaluation_scope": "fixed_full_OO_pool",
|
| 229 |
+
"training_hours": 1.3134469647612423,
|
| 230 |
+
"estimated_matmul_training_flops": 283182052147200000,
|
| 231 |
+
"executed_input_tokens": 614400000,
|
| 232 |
+
"examples": 153474816,
|
| 233 |
+
"atomic_epochs": 489.39375,
|
| 234 |
+
"composition_epochs": 489.39717105263156
|
| 235 |
+
},
|
| 236 |
+
"extrapolated": false
|
| 237 |
+
},
|
| 238 |
+
{
|
| 239 |
+
"real_run": "confirmation-loop4x2-init2",
|
| 240 |
+
"budget": "atomic_epochs",
|
| 241 |
+
"real_value": 1255.2311120543293,
|
| 242 |
+
"synthetic_below": {
|
| 243 |
+
"dataset": "synthetic",
|
| 244 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 245 |
+
"architecture": "loop4x2",
|
| 246 |
+
"initialization": 791101,
|
| 247 |
+
"learning_rate": 0.0001,
|
| 248 |
+
"weight_decay": 0.3,
|
| 249 |
+
"phi": 7.2,
|
| 250 |
+
"step": 768000,
|
| 251 |
+
"oo_n": 2004,
|
| 252 |
+
"oo_percent": 70.60878243512974,
|
| 253 |
+
"evaluation_scope": "fixed_full_OO_pool",
|
| 254 |
+
"training_hours": 3.328787970851279,
|
| 255 |
+
"estimated_matmul_training_flops": 724946053496832000,
|
| 256 |
+
"executed_input_tokens": 1572864000,
|
| 257 |
+
"examples": 392895488,
|
| 258 |
+
"atomic_epochs": 1252.856725,
|
| 259 |
+
"composition_epochs": 1252.855332602339
|
| 260 |
+
},
|
| 261 |
+
"synthetic_above": {
|
| 262 |
+
"dataset": "synthetic",
|
| 263 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 264 |
+
"architecture": "loop4x2",
|
| 265 |
+
"initialization": 791101,
|
| 266 |
+
"learning_rate": 0.0001,
|
| 267 |
+
"weight_decay": 0.3,
|
| 268 |
+
"phi": 7.2,
|
| 269 |
+
"step": 772000,
|
| 270 |
+
"oo_n": 2004,
|
| 271 |
+
"oo_percent": 70.50898203592814,
|
| 272 |
+
"evaluation_scope": "fixed_full_OO_pool",
|
| 273 |
+
"training_hours": 3.3460153445280674,
|
| 274 |
+
"estimated_matmul_training_flops": 728721814192128000,
|
| 275 |
+
"executed_input_tokens": 1581056000,
|
| 276 |
+
"examples": 394941696,
|
| 277 |
+
"atomic_epochs": 1259.380075,
|
| 278 |
+
"composition_epochs": 1259.3804568713451
|
| 279 |
+
},
|
| 280 |
+
"extrapolated": false
|
| 281 |
+
},
|
| 282 |
+
{
|
| 283 |
+
"real_run": "confirmation-loop4x2-init3",
|
| 284 |
+
"budget": "training_hours",
|
| 285 |
+
"real_value": 6.636981699868209,
|
| 286 |
+
"synthetic_below": {
|
| 287 |
+
"dataset": "synthetic",
|
| 288 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 289 |
+
"architecture": "loop4x2",
|
| 290 |
+
"initialization": 791101,
|
| 291 |
+
"learning_rate": 0.0001,
|
| 292 |
+
"weight_decay": 0.3,
|
| 293 |
+
"phi": 7.2,
|
| 294 |
+
"step": 1500000,
|
| 295 |
+
"oo_n": 2004,
|
| 296 |
+
"oo_percent": 81.3373253493014,
|
| 297 |
+
"evaluation_scope": "fixed_full_OO_pool",
|
| 298 |
+
"training_hours": 6.5032488311454655,
|
| 299 |
+
"estimated_matmul_training_flops": 1415910260736000000,
|
| 300 |
+
"executed_input_tokens": 3072000000,
|
| 301 |
+
"examples": 767373824,
|
| 302 |
+
"atomic_epochs": 2446.9826,
|
| 303 |
+
"composition_epochs": 2446.982894736842
|
| 304 |
+
},
|
| 305 |
+
"synthetic_above": null,
|
| 306 |
+
"extrapolated": false
|
| 307 |
+
},
|
| 308 |
+
{
|
| 309 |
+
"real_run": "confirmation-loop4x2-init3",
|
| 310 |
+
"budget": "estimated_matmul_training_flops",
|
| 311 |
+
"real_value": 2775312255025967616,
|
| 312 |
+
"synthetic_below": {
|
| 313 |
+
"dataset": "synthetic",
|
| 314 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 315 |
+
"architecture": "loop4x2",
|
| 316 |
+
"initialization": 791101,
|
| 317 |
+
"learning_rate": 0.0001,
|
| 318 |
+
"weight_decay": 0.3,
|
| 319 |
+
"phi": 7.2,
|
| 320 |
+
"step": 1500000,
|
| 321 |
+
"oo_n": 2004,
|
| 322 |
+
"oo_percent": 81.3373253493014,
|
| 323 |
+
"evaluation_scope": "fixed_full_OO_pool",
|
| 324 |
+
"training_hours": 6.5032488311454655,
|
| 325 |
+
"estimated_matmul_training_flops": 1415910260736000000,
|
| 326 |
+
"executed_input_tokens": 3072000000,
|
| 327 |
+
"examples": 767373824,
|
| 328 |
+
"atomic_epochs": 2446.9826,
|
| 329 |
+
"composition_epochs": 2446.982894736842
|
| 330 |
+
},
|
| 331 |
+
"synthetic_above": null,
|
| 332 |
+
"extrapolated": false
|
| 333 |
+
},
|
| 334 |
+
{
|
| 335 |
+
"real_run": "confirmation-loop4x2-init3",
|
| 336 |
+
"budget": "examples",
|
| 337 |
+
"real_value": 153249855,
|
| 338 |
+
"synthetic_below": {
|
| 339 |
+
"dataset": "synthetic",
|
| 340 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 341 |
+
"architecture": "loop4x2",
|
| 342 |
+
"initialization": 791101,
|
| 343 |
+
"learning_rate": 0.0001,
|
| 344 |
+
"weight_decay": 0.3,
|
| 345 |
+
"phi": 7.2,
|
| 346 |
+
"step": 296000,
|
| 347 |
+
"oo_n": 2004,
|
| 348 |
+
"oo_percent": 24.10179640718563,
|
| 349 |
+
"evaluation_scope": "fixed_full_OO_pool",
|
| 350 |
+
"training_hours": 1.2962222684443825,
|
| 351 |
+
"estimated_matmul_training_flops": 279406291451904000,
|
| 352 |
+
"executed_input_tokens": 606208000,
|
| 353 |
+
"examples": 151428608,
|
| 354 |
+
"atomic_epochs": 482.872525,
|
| 355 |
+
"composition_epochs": 482.8717361111111
|
| 356 |
+
},
|
| 357 |
+
"synthetic_above": {
|
| 358 |
+
"dataset": "synthetic",
|
| 359 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 360 |
+
"architecture": "loop4x2",
|
| 361 |
+
"initialization": 791101,
|
| 362 |
+
"learning_rate": 0.0001,
|
| 363 |
+
"weight_decay": 0.3,
|
| 364 |
+
"phi": 7.2,
|
| 365 |
+
"step": 300000,
|
| 366 |
+
"oo_n": 2004,
|
| 367 |
+
"oo_percent": 24.451097804391217,
|
| 368 |
+
"evaluation_scope": "fixed_full_OO_pool",
|
| 369 |
+
"training_hours": 1.3134469647612423,
|
| 370 |
+
"estimated_matmul_training_flops": 283182052147200000,
|
| 371 |
+
"executed_input_tokens": 614400000,
|
| 372 |
+
"examples": 153474816,
|
| 373 |
+
"atomic_epochs": 489.39375,
|
| 374 |
+
"composition_epochs": 489.39717105263156
|
| 375 |
+
},
|
| 376 |
+
"extrapolated": false
|
| 377 |
+
},
|
| 378 |
+
{
|
| 379 |
+
"real_run": "confirmation-loop4x2-init3",
|
| 380 |
+
"budget": "atomic_epochs",
|
| 381 |
+
"real_value": 1255.2295203735143,
|
| 382 |
+
"synthetic_below": {
|
| 383 |
+
"dataset": "synthetic",
|
| 384 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 385 |
+
"architecture": "loop4x2",
|
| 386 |
+
"initialization": 791101,
|
| 387 |
+
"learning_rate": 0.0001,
|
| 388 |
+
"weight_decay": 0.3,
|
| 389 |
+
"phi": 7.2,
|
| 390 |
+
"step": 768000,
|
| 391 |
+
"oo_n": 2004,
|
| 392 |
+
"oo_percent": 70.60878243512974,
|
| 393 |
+
"evaluation_scope": "fixed_full_OO_pool",
|
| 394 |
+
"training_hours": 3.328787970851279,
|
| 395 |
+
"estimated_matmul_training_flops": 724946053496832000,
|
| 396 |
+
"executed_input_tokens": 1572864000,
|
| 397 |
+
"examples": 392895488,
|
| 398 |
+
"atomic_epochs": 1252.856725,
|
| 399 |
+
"composition_epochs": 1252.855332602339
|
| 400 |
+
},
|
| 401 |
+
"synthetic_above": {
|
| 402 |
+
"dataset": "synthetic",
|
| 403 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 404 |
+
"architecture": "loop4x2",
|
| 405 |
+
"initialization": 791101,
|
| 406 |
+
"learning_rate": 0.0001,
|
| 407 |
+
"weight_decay": 0.3,
|
| 408 |
+
"phi": 7.2,
|
| 409 |
+
"step": 772000,
|
| 410 |
+
"oo_n": 2004,
|
| 411 |
+
"oo_percent": 70.50898203592814,
|
| 412 |
+
"evaluation_scope": "fixed_full_OO_pool",
|
| 413 |
+
"training_hours": 3.3460153445280674,
|
| 414 |
+
"estimated_matmul_training_flops": 728721814192128000,
|
| 415 |
+
"executed_input_tokens": 1581056000,
|
| 416 |
+
"examples": 394941696,
|
| 417 |
+
"atomic_epochs": 1259.380075,
|
| 418 |
+
"composition_epochs": 1259.3804568713451
|
| 419 |
+
},
|
| 420 |
+
"extrapolated": false
|
| 421 |
+
}
|
| 422 |
+
]
|
docs/development-artifacts/oo-budget-attribution-20261005/budget-comparison.pdf
ADDED
|
Binary file (38.7 kB). View file
|
|
|
docs/development-artifacts/oo-budget-attribution-20261005/budget-comparison.png
ADDED
|
Git LFS Details
|
docs/development-artifacts/oo-budget-attribution-20261005/endpoints.csv
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
dataset,run,architecture,initialization,learning_rate,weight_decay,phi,step,oo_n,oo_percent,evaluation_scope,training_hours,estimated_matmul_training_flops,executed_input_tokens,examples,atomic_epochs,composition_epochs
|
| 2 |
+
synthetic,loop4x2-phi12.6-wd0.1,loop4x2,791101,0.0001,0.1,12.6,1500000,2004,66.1676646706587,fixed_full_OO_pool,6.511084337063755,1415910260736000000,3072000000,767455728,1479.289375,1479.2902109440267
|
| 3 |
+
synthetic,loop4x2-phi3.6-wd0.1,loop4x2,791101,0.0001,0.1,3.6,1500000,2004,25.64870259481038,fixed_full_OO_pool,6.498463879016539,1415910260736000000,3072000000,766474080,4335.2594,4335.260994152047
|
| 4 |
+
synthetic,loop4x2-phi7.2-wd0.1,loop4x2,791101,0.0001,0.1,7.2,1500000,2004,53.293413173652695,fixed_full_OO_pool,6.48271472582904,1415910260736000000,3072000000,767373824,2446.9826,2446.982894736842
|
| 5 |
+
synthetic,loop4x2-phi7.2-wd0.3,loop4x2,791101,0.0001,0.3,7.2,1500000,2004,81.3373253493014,fixed_full_OO_pool,6.5032488311454655,1415910260736000000,3072000000,767373824,2446.9826,2446.982894736842
|
| 6 |
+
synthetic,standard8-phi12.6-wd0.1,standard8,791101,0.0001,0.1,12.6,1500000,2004,0.0,fixed_full_OO_pool,6.750595387809185,1415910260736000000,3072000000,767455728,1479.289375,1479.2902109440267
|
| 7 |
+
synthetic,standard8-phi3.6-wd0.1,standard8,791101,0.0001,0.1,3.6,1500000,2004,0.39920159680638717,fixed_full_OO_pool,6.9142334482353185,1415910260736000000,3072000000,766474080,4335.2594,4335.260994152047
|
| 8 |
+
synthetic,standard8-phi7.2-wd0.1,standard8,791101,0.0001,0.1,7.2,1500000,2004,0.19960079840319359,fixed_full_OO_pool,6.740193886749653,1415910260736000000,3072000000,767373824,2446.9826,2446.982894736842
|
| 9 |
+
synthetic,standard8-phi7.2-wd0.3,standard8,791101,0.0001,0.3,7.2,1500000,2004,0.0,fixed_full_OO_pool,6.771571062275519,1415910260736000000,3072000000,767373824,2446.9826,2446.982894736842
|
| 10 |
+
real_native,confirmation-loop4x2-init1,loop4x2,811201,5e-05,0.1,,300000,1283,17.069368667186282,full_endpoint,6.636754266745928,2775487015724686848,6555176928,153249855,1255.2305814940578,1255.2307335934854
|
| 11 |
+
real_native,confirmation-loop4x2-init2,loop4x2,811202,5e-05,0.1,,300000,1283,17.1473109898675,full_endpoint,6.642358209469045,2775118595566491648,6554444824,153249855,1255.2311120543293,1255.2301099410204
|
| 12 |
+
real_native,confirmation-loop4x2-init3,loop4x2,811203,5e-05,0.1,,300000,1283,15.97817614964926,full_endpoint,6.636981699868209,2775312255025967616,6554773168,153249855,1255.2295203735143,1255.231980898416
|
| 13 |
+
real_native,confirmation-standard4-init1,standard4,811201,5e-05,0.1,,300000,1283,16.91348402182385,full_endpoint,4.311865449844756,1651459843050610176,6555176928,153249855,1255.2305814940578,1255.2307335934854
|
| 14 |
+
real_native,confirmation-standard4-init2,standard4,811202,5e-05,0.1,,300000,1283,17.614964925954794,full_endpoint,4.306228105037784,1651217730075777024,6554444824,153249855,1255.2311120543293,1255.2301099410204
|
| 15 |
+
real_native,confirmation-standard4-init3,standard4,811203,5e-05,0.1,,300000,1283,16.52377240841777,full_endpoint,4.338233347138804,1651354498478928384,6554773168,153249855,1255.2295203735143,1255.231980898416
|
| 16 |
+
real_native,confirmation-standard8-init1,standard8,811201,5e-05,0.1,,300000,1283,17.692907248636008,full_endpoint,6.723028642990523,2775487015724686848,6555176928,153249855,1255.2305814940578,1255.2307335934854
|
| 17 |
+
real_native,confirmation-standard8-init2,standard8,811202,5e-05,0.1,,300000,1283,19.095869056897897,full_endpoint,6.7091564928398775,2775118595566491648,6554444824,153249855,1255.2311120543293,1255.2301099410204
|
| 18 |
+
real_native,confirmation-standard8-init3,standard8,811203,5e-05,0.1,,300000,1283,16.445830085736556,full_endpoint,6.712122530073135,2775312255025967616,6554773168,153249855,1255.2295203735143,1255.231980898416
|
docs/development-artifacts/oo-budget-attribution-20261005/learning-budgets.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
docs/development-artifacts/oo-budget-attribution-20261005/recount-audit.json
ADDED
|
@@ -0,0 +1,619 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"passed": true,
|
| 3 |
+
"raw_pools_recounted": 81,
|
| 4 |
+
"records": [
|
| 5 |
+
{
|
| 6 |
+
"run": "loop4x2-phi12.6-wd0.1",
|
| 7 |
+
"step": 32000,
|
| 8 |
+
"n": 2004,
|
| 9 |
+
"correct": 0
|
| 10 |
+
},
|
| 11 |
+
{
|
| 12 |
+
"run": "loop4x2-phi12.6-wd0.1",
|
| 13 |
+
"step": 64000,
|
| 14 |
+
"n": 2004,
|
| 15 |
+
"correct": 9
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"run": "loop4x2-phi12.6-wd0.1",
|
| 19 |
+
"step": 128000,
|
| 20 |
+
"n": 2004,
|
| 21 |
+
"correct": 31
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"run": "loop4x2-phi12.6-wd0.1",
|
| 25 |
+
"step": 200000,
|
| 26 |
+
"n": 2004,
|
| 27 |
+
"correct": 56
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"run": "loop4x2-phi12.6-wd0.1",
|
| 31 |
+
"step": 300000,
|
| 32 |
+
"n": 2004,
|
| 33 |
+
"correct": 84
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"run": "loop4x2-phi12.6-wd0.1",
|
| 37 |
+
"step": 500000,
|
| 38 |
+
"n": 2004,
|
| 39 |
+
"correct": 304
|
| 40 |
+
},
|
| 41 |
+
{
|
| 42 |
+
"run": "loop4x2-phi12.6-wd0.1",
|
| 43 |
+
"step": 700000,
|
| 44 |
+
"n": 2004,
|
| 45 |
+
"correct": 527
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"run": "loop4x2-phi12.6-wd0.1",
|
| 49 |
+
"step": 1000000,
|
| 50 |
+
"n": 2004,
|
| 51 |
+
"correct": 857
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"run": "loop4x2-phi12.6-wd0.1",
|
| 55 |
+
"step": 1500000,
|
| 56 |
+
"n": 2004,
|
| 57 |
+
"correct": 1326
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"run": "loop4x2-phi3.6-wd0.1",
|
| 61 |
+
"step": 32000,
|
| 62 |
+
"n": 2004,
|
| 63 |
+
"correct": 5
|
| 64 |
+
},
|
| 65 |
+
{
|
| 66 |
+
"run": "loop4x2-phi3.6-wd0.1",
|
| 67 |
+
"step": 64000,
|
| 68 |
+
"n": 2004,
|
| 69 |
+
"correct": 4
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"run": "loop4x2-phi3.6-wd0.1",
|
| 73 |
+
"step": 128000,
|
| 74 |
+
"n": 2004,
|
| 75 |
+
"correct": 4
|
| 76 |
+
},
|
| 77 |
+
{
|
| 78 |
+
"run": "loop4x2-phi3.6-wd0.1",
|
| 79 |
+
"step": 200000,
|
| 80 |
+
"n": 2004,
|
| 81 |
+
"correct": 11
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"run": "loop4x2-phi3.6-wd0.1",
|
| 85 |
+
"step": 300000,
|
| 86 |
+
"n": 2004,
|
| 87 |
+
"correct": 12
|
| 88 |
+
},
|
| 89 |
+
{
|
| 90 |
+
"run": "loop4x2-phi3.6-wd0.1",
|
| 91 |
+
"step": 500000,
|
| 92 |
+
"n": 2004,
|
| 93 |
+
"correct": 10
|
| 94 |
+
},
|
| 95 |
+
{
|
| 96 |
+
"run": "loop4x2-phi3.6-wd0.1",
|
| 97 |
+
"step": 700000,
|
| 98 |
+
"n": 2004,
|
| 99 |
+
"correct": 22
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"run": "loop4x2-phi3.6-wd0.1",
|
| 103 |
+
"step": 1000000,
|
| 104 |
+
"n": 2004,
|
| 105 |
+
"correct": 72
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"run": "loop4x2-phi3.6-wd0.1",
|
| 109 |
+
"step": 1500000,
|
| 110 |
+
"n": 2004,
|
| 111 |
+
"correct": 514
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
"run": "loop4x2-phi7.2-wd0.1",
|
| 115 |
+
"step": 32000,
|
| 116 |
+
"n": 2004,
|
| 117 |
+
"correct": 5
|
| 118 |
+
},
|
| 119 |
+
{
|
| 120 |
+
"run": "loop4x2-phi7.2-wd0.1",
|
| 121 |
+
"step": 64000,
|
| 122 |
+
"n": 2004,
|
| 123 |
+
"correct": 5
|
| 124 |
+
},
|
| 125 |
+
{
|
| 126 |
+
"run": "loop4x2-phi7.2-wd0.1",
|
| 127 |
+
"step": 128000,
|
| 128 |
+
"n": 2004,
|
| 129 |
+
"correct": 14
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"run": "loop4x2-phi7.2-wd0.1",
|
| 133 |
+
"step": 200000,
|
| 134 |
+
"n": 2004,
|
| 135 |
+
"correct": 47
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"run": "loop4x2-phi7.2-wd0.1",
|
| 139 |
+
"step": 300000,
|
| 140 |
+
"n": 2004,
|
| 141 |
+
"correct": 70
|
| 142 |
+
},
|
| 143 |
+
{
|
| 144 |
+
"run": "loop4x2-phi7.2-wd0.1",
|
| 145 |
+
"step": 500000,
|
| 146 |
+
"n": 2004,
|
| 147 |
+
"correct": 231
|
| 148 |
+
},
|
| 149 |
+
{
|
| 150 |
+
"run": "loop4x2-phi7.2-wd0.1",
|
| 151 |
+
"step": 700000,
|
| 152 |
+
"n": 2004,
|
| 153 |
+
"correct": 426
|
| 154 |
+
},
|
| 155 |
+
{
|
| 156 |
+
"run": "loop4x2-phi7.2-wd0.1",
|
| 157 |
+
"step": 1000000,
|
| 158 |
+
"n": 2004,
|
| 159 |
+
"correct": 689
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
"run": "loop4x2-phi7.2-wd0.1",
|
| 163 |
+
"step": 1500000,
|
| 164 |
+
"n": 2004,
|
| 165 |
+
"correct": 1068
|
| 166 |
+
},
|
| 167 |
+
{
|
| 168 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 169 |
+
"step": 32000,
|
| 170 |
+
"n": 2004,
|
| 171 |
+
"correct": 6
|
| 172 |
+
},
|
| 173 |
+
{
|
| 174 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 175 |
+
"step": 64000,
|
| 176 |
+
"n": 2004,
|
| 177 |
+
"correct": 9
|
| 178 |
+
},
|
| 179 |
+
{
|
| 180 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 181 |
+
"step": 128000,
|
| 182 |
+
"n": 2004,
|
| 183 |
+
"correct": 94
|
| 184 |
+
},
|
| 185 |
+
{
|
| 186 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 187 |
+
"step": 200000,
|
| 188 |
+
"n": 2004,
|
| 189 |
+
"correct": 216
|
| 190 |
+
},
|
| 191 |
+
{
|
| 192 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 193 |
+
"step": 300000,
|
| 194 |
+
"n": 2004,
|
| 195 |
+
"correct": 490
|
| 196 |
+
},
|
| 197 |
+
{
|
| 198 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 199 |
+
"step": 500000,
|
| 200 |
+
"n": 2004,
|
| 201 |
+
"correct": 1028
|
| 202 |
+
},
|
| 203 |
+
{
|
| 204 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 205 |
+
"step": 700000,
|
| 206 |
+
"n": 2004,
|
| 207 |
+
"correct": 1352
|
| 208 |
+
},
|
| 209 |
+
{
|
| 210 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 211 |
+
"step": 1000000,
|
| 212 |
+
"n": 2004,
|
| 213 |
+
"correct": 1522
|
| 214 |
+
},
|
| 215 |
+
{
|
| 216 |
+
"run": "loop4x2-phi7.2-wd0.3",
|
| 217 |
+
"step": 1500000,
|
| 218 |
+
"n": 2004,
|
| 219 |
+
"correct": 1630
|
| 220 |
+
},
|
| 221 |
+
{
|
| 222 |
+
"run": "standard8-phi12.6-wd0.1",
|
| 223 |
+
"step": 32000,
|
| 224 |
+
"n": 2004,
|
| 225 |
+
"correct": 0
|
| 226 |
+
},
|
| 227 |
+
{
|
| 228 |
+
"run": "standard8-phi12.6-wd0.1",
|
| 229 |
+
"step": 64000,
|
| 230 |
+
"n": 2004,
|
| 231 |
+
"correct": 0
|
| 232 |
+
},
|
| 233 |
+
{
|
| 234 |
+
"run": "standard8-phi12.6-wd0.1",
|
| 235 |
+
"step": 128000,
|
| 236 |
+
"n": 2004,
|
| 237 |
+
"correct": 3
|
| 238 |
+
},
|
| 239 |
+
{
|
| 240 |
+
"run": "standard8-phi12.6-wd0.1",
|
| 241 |
+
"step": 200000,
|
| 242 |
+
"n": 2004,
|
| 243 |
+
"correct": 3
|
| 244 |
+
},
|
| 245 |
+
{
|
| 246 |
+
"run": "standard8-phi12.6-wd0.1",
|
| 247 |
+
"step": 300000,
|
| 248 |
+
"n": 2004,
|
| 249 |
+
"correct": 2
|
| 250 |
+
},
|
| 251 |
+
{
|
| 252 |
+
"run": "standard8-phi12.6-wd0.1",
|
| 253 |
+
"step": 500000,
|
| 254 |
+
"n": 2004,
|
| 255 |
+
"correct": 6
|
| 256 |
+
},
|
| 257 |
+
{
|
| 258 |
+
"run": "standard8-phi12.6-wd0.1",
|
| 259 |
+
"step": 700000,
|
| 260 |
+
"n": 2004,
|
| 261 |
+
"correct": 3
|
| 262 |
+
},
|
| 263 |
+
{
|
| 264 |
+
"run": "standard8-phi12.6-wd0.1",
|
| 265 |
+
"step": 1000000,
|
| 266 |
+
"n": 2004,
|
| 267 |
+
"correct": 2
|
| 268 |
+
},
|
| 269 |
+
{
|
| 270 |
+
"run": "standard8-phi12.6-wd0.1",
|
| 271 |
+
"step": 1500000,
|
| 272 |
+
"n": 2004,
|
| 273 |
+
"correct": 0
|
| 274 |
+
},
|
| 275 |
+
{
|
| 276 |
+
"run": "standard8-phi3.6-wd0.1",
|
| 277 |
+
"step": 32000,
|
| 278 |
+
"n": 2004,
|
| 279 |
+
"correct": 2
|
| 280 |
+
},
|
| 281 |
+
{
|
| 282 |
+
"run": "standard8-phi3.6-wd0.1",
|
| 283 |
+
"step": 64000,
|
| 284 |
+
"n": 2004,
|
| 285 |
+
"correct": 4
|
| 286 |
+
},
|
| 287 |
+
{
|
| 288 |
+
"run": "standard8-phi3.6-wd0.1",
|
| 289 |
+
"step": 128000,
|
| 290 |
+
"n": 2004,
|
| 291 |
+
"correct": 5
|
| 292 |
+
},
|
| 293 |
+
{
|
| 294 |
+
"run": "standard8-phi3.6-wd0.1",
|
| 295 |
+
"step": 200000,
|
| 296 |
+
"n": 2004,
|
| 297 |
+
"correct": 4
|
| 298 |
+
},
|
| 299 |
+
{
|
| 300 |
+
"run": "standard8-phi3.6-wd0.1",
|
| 301 |
+
"step": 300000,
|
| 302 |
+
"n": 2004,
|
| 303 |
+
"correct": 5
|
| 304 |
+
},
|
| 305 |
+
{
|
| 306 |
+
"run": "standard8-phi3.6-wd0.1",
|
| 307 |
+
"step": 500000,
|
| 308 |
+
"n": 2004,
|
| 309 |
+
"correct": 4
|
| 310 |
+
},
|
| 311 |
+
{
|
| 312 |
+
"run": "standard8-phi3.6-wd0.1",
|
| 313 |
+
"step": 700000,
|
| 314 |
+
"n": 2004,
|
| 315 |
+
"correct": 7
|
| 316 |
+
},
|
| 317 |
+
{
|
| 318 |
+
"run": "standard8-phi3.6-wd0.1",
|
| 319 |
+
"step": 1000000,
|
| 320 |
+
"n": 2004,
|
| 321 |
+
"correct": 1
|
| 322 |
+
},
|
| 323 |
+
{
|
| 324 |
+
"run": "standard8-phi3.6-wd0.1",
|
| 325 |
+
"step": 1500000,
|
| 326 |
+
"n": 2004,
|
| 327 |
+
"correct": 8
|
| 328 |
+
},
|
| 329 |
+
{
|
| 330 |
+
"run": "standard8-phi7.2-wd0.1",
|
| 331 |
+
"step": 32000,
|
| 332 |
+
"n": 2004,
|
| 333 |
+
"correct": 7
|
| 334 |
+
},
|
| 335 |
+
{
|
| 336 |
+
"run": "standard8-phi7.2-wd0.1",
|
| 337 |
+
"step": 64000,
|
| 338 |
+
"n": 2004,
|
| 339 |
+
"correct": 1
|
| 340 |
+
},
|
| 341 |
+
{
|
| 342 |
+
"run": "standard8-phi7.2-wd0.1",
|
| 343 |
+
"step": 128000,
|
| 344 |
+
"n": 2004,
|
| 345 |
+
"correct": 4
|
| 346 |
+
},
|
| 347 |
+
{
|
| 348 |
+
"run": "standard8-phi7.2-wd0.1",
|
| 349 |
+
"step": 200000,
|
| 350 |
+
"n": 2004,
|
| 351 |
+
"correct": 2
|
| 352 |
+
},
|
| 353 |
+
{
|
| 354 |
+
"run": "standard8-phi7.2-wd0.1",
|
| 355 |
+
"step": 300000,
|
| 356 |
+
"n": 2004,
|
| 357 |
+
"correct": 2
|
| 358 |
+
},
|
| 359 |
+
{
|
| 360 |
+
"run": "standard8-phi7.2-wd0.1",
|
| 361 |
+
"step": 500000,
|
| 362 |
+
"n": 2004,
|
| 363 |
+
"correct": 5
|
| 364 |
+
},
|
| 365 |
+
{
|
| 366 |
+
"run": "standard8-phi7.2-wd0.1",
|
| 367 |
+
"step": 700000,
|
| 368 |
+
"n": 2004,
|
| 369 |
+
"correct": 6
|
| 370 |
+
},
|
| 371 |
+
{
|
| 372 |
+
"run": "standard8-phi7.2-wd0.1",
|
| 373 |
+
"step": 1000000,
|
| 374 |
+
"n": 2004,
|
| 375 |
+
"correct": 8
|
| 376 |
+
},
|
| 377 |
+
{
|
| 378 |
+
"run": "standard8-phi7.2-wd0.1",
|
| 379 |
+
"step": 1500000,
|
| 380 |
+
"n": 2004,
|
| 381 |
+
"correct": 4
|
| 382 |
+
},
|
| 383 |
+
{
|
| 384 |
+
"run": "standard8-phi7.2-wd0.3",
|
| 385 |
+
"step": 32000,
|
| 386 |
+
"n": 2004,
|
| 387 |
+
"correct": 4
|
| 388 |
+
},
|
| 389 |
+
{
|
| 390 |
+
"run": "standard8-phi7.2-wd0.3",
|
| 391 |
+
"step": 64000,
|
| 392 |
+
"n": 2004,
|
| 393 |
+
"correct": 4
|
| 394 |
+
},
|
| 395 |
+
{
|
| 396 |
+
"run": "standard8-phi7.2-wd0.3",
|
| 397 |
+
"step": 128000,
|
| 398 |
+
"n": 2004,
|
| 399 |
+
"correct": 5
|
| 400 |
+
},
|
| 401 |
+
{
|
| 402 |
+
"run": "standard8-phi7.2-wd0.3",
|
| 403 |
+
"step": 200000,
|
| 404 |
+
"n": 2004,
|
| 405 |
+
"correct": 3
|
| 406 |
+
},
|
| 407 |
+
{
|
| 408 |
+
"run": "standard8-phi7.2-wd0.3",
|
| 409 |
+
"step": 300000,
|
| 410 |
+
"n": 2004,
|
| 411 |
+
"correct": 4
|
| 412 |
+
},
|
| 413 |
+
{
|
| 414 |
+
"run": "standard8-phi7.2-wd0.3",
|
| 415 |
+
"step": 500000,
|
| 416 |
+
"n": 2004,
|
| 417 |
+
"correct": 3
|
| 418 |
+
},
|
| 419 |
+
{
|
| 420 |
+
"run": "standard8-phi7.2-wd0.3",
|
| 421 |
+
"step": 700000,
|
| 422 |
+
"n": 2004,
|
| 423 |
+
"correct": 2
|
| 424 |
+
},
|
| 425 |
+
{
|
| 426 |
+
"run": "standard8-phi7.2-wd0.3",
|
| 427 |
+
"step": 1000000,
|
| 428 |
+
"n": 2004,
|
| 429 |
+
"correct": 3
|
| 430 |
+
},
|
| 431 |
+
{
|
| 432 |
+
"run": "standard8-phi7.2-wd0.3",
|
| 433 |
+
"step": 1500000,
|
| 434 |
+
"n": 2004,
|
| 435 |
+
"correct": 0
|
| 436 |
+
},
|
| 437 |
+
{
|
| 438 |
+
"run": "confirmation-loop4x2-init1",
|
| 439 |
+
"step": 300000,
|
| 440 |
+
"n": 1283,
|
| 441 |
+
"correct": 219
|
| 442 |
+
},
|
| 443 |
+
{
|
| 444 |
+
"run": "confirmation-loop4x2-init2",
|
| 445 |
+
"step": 300000,
|
| 446 |
+
"n": 1283,
|
| 447 |
+
"correct": 220
|
| 448 |
+
},
|
| 449 |
+
{
|
| 450 |
+
"run": "confirmation-loop4x2-init3",
|
| 451 |
+
"step": 300000,
|
| 452 |
+
"n": 1283,
|
| 453 |
+
"correct": 205
|
| 454 |
+
},
|
| 455 |
+
{
|
| 456 |
+
"run": "confirmation-standard4-init1",
|
| 457 |
+
"step": 300000,
|
| 458 |
+
"n": 1283,
|
| 459 |
+
"correct": 217
|
| 460 |
+
},
|
| 461 |
+
{
|
| 462 |
+
"run": "confirmation-standard4-init2",
|
| 463 |
+
"step": 300000,
|
| 464 |
+
"n": 1283,
|
| 465 |
+
"correct": 226
|
| 466 |
+
},
|
| 467 |
+
{
|
| 468 |
+
"run": "confirmation-standard4-init3",
|
| 469 |
+
"step": 300000,
|
| 470 |
+
"n": 1283,
|
| 471 |
+
"correct": 212
|
| 472 |
+
},
|
| 473 |
+
{
|
| 474 |
+
"run": "confirmation-standard8-init1",
|
| 475 |
+
"step": 300000,
|
| 476 |
+
"n": 1283,
|
| 477 |
+
"correct": 227
|
| 478 |
+
},
|
| 479 |
+
{
|
| 480 |
+
"run": "confirmation-standard8-init2",
|
| 481 |
+
"step": 300000,
|
| 482 |
+
"n": 1283,
|
| 483 |
+
"correct": 245
|
| 484 |
+
},
|
| 485 |
+
{
|
| 486 |
+
"run": "confirmation-standard8-init3",
|
| 487 |
+
"step": 300000,
|
| 488 |
+
"n": 1283,
|
| 489 |
+
"correct": 211
|
| 490 |
+
}
|
| 491 |
+
],
|
| 492 |
+
"sources_sha256": {
|
| 493 |
+
"results/grokking-reproduction-v1/data/complete.json": "c60b3c65e6ab889d78b2b0fa6b17cf82ee8739ce14cb2ae18897fe3b10cfda83",
|
| 494 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi12.6-wd0.1/run.json": "62c593fe5dc85f6a17e5a447e1b25f6c76d0dd6a5cf612283a9185138c884f05",
|
| 495 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi12.6-wd0.1/learning.json": "5ec2979a7d81bfcf71c8d009b410f06b39b9053fb1282a1a5c65e266290edcfd",
|
| 496 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi12.6-wd0.1/predictions-0032000-test_oo.npz": "a272fe5b30e5c251f4a2f5aa6f280fa23ffc6b1e30a38b7644a7054a48b489e2",
|
| 497 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi12.6-wd0.1/predictions-0064000-test_oo.npz": "c31fd027ad2284a9dd66fe4f83dd7129820b66dcfc2f3bb7f92e8c26181d7d05",
|
| 498 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi12.6-wd0.1/predictions-0128000-test_oo.npz": "586380b3f777488a86708aedbc8ab6922ee1f67ff7dad2f0d4116d1d3062db88",
|
| 499 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi12.6-wd0.1/predictions-0200000-test_oo.npz": "df645588cbd33fae6312da6817f4a3872c9085ddf15a03b48e58464d2894dedc",
|
| 500 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi12.6-wd0.1/predictions-0300000-test_oo.npz": "b7d6608fc66a83ecf2e86c367b7f73c985ce7c6dac42055d88289acad37340b9",
|
| 501 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi12.6-wd0.1/predictions-0500000-test_oo.npz": "9c9362b6e6e41d4df6ed1ca1cb7697284802bc7e06c492e8ebc6d819d2538665",
|
| 502 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi12.6-wd0.1/predictions-0700000-test_oo.npz": "77d9e7d41d1bb9ffecc989a2319a0470c504de2c13fbd5808edaf93f46c56977",
|
| 503 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi12.6-wd0.1/predictions-1000000-test_oo.npz": "7b92d86add226d179bd0cea94740728b30d6ce9e91a3acc456de5de2d47d1845",
|
| 504 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi12.6-wd0.1/predictions-1500000-test_oo.npz": "e89a82f6ff41ebd6166de73e4d90547446ef6e141e06162e47de5ba75b169ea4",
|
| 505 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi3.6-wd0.1/run.json": "8b0d1ef4aa8a68cc65b3b20ba57147598618beacbc21c30c68f40a4eae4459ba",
|
| 506 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi3.6-wd0.1/learning.json": "95a44a719606c3d43a8323a5813b8c22f48a0ce88cf57ee2378fef7cdcdabf01",
|
| 507 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi3.6-wd0.1/predictions-0032000-test_oo.npz": "e1de7070988bffe16dd420362ae3cfc30ea8858b4a878d4b5432c16cb17d5c7e",
|
| 508 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi3.6-wd0.1/predictions-0064000-test_oo.npz": "03a91a328e2a3d5a6d4477c3e396e6c895e0e5d633f3fcaa078f8586db2b7b92",
|
| 509 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi3.6-wd0.1/predictions-0128000-test_oo.npz": "b93be84721dde34cc887e68baa2851165fe4640e4ef037b054ec7eb581509419",
|
| 510 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi3.6-wd0.1/predictions-0200000-test_oo.npz": "d1ea80aeae192e1628932d805990e416db3f0f15a0fd3f3407398c7f1a6eaba3",
|
| 511 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi3.6-wd0.1/predictions-0300000-test_oo.npz": "be1d16c2703bb5790387f289734c2ccc72c9f04105214f372e866a4323783ad4",
|
| 512 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi3.6-wd0.1/predictions-0500000-test_oo.npz": "26b9adb9f8e08ae2e7843917622b4ed390181f208279a6dea7a2033495e28b43",
|
| 513 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi3.6-wd0.1/predictions-0700000-test_oo.npz": "de2ff55207351f1c0ea8cf8f73969bcf956d0055bef18cc744fcdabb5a2aed1f",
|
| 514 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi3.6-wd0.1/predictions-1000000-test_oo.npz": "f99173107a99738b0a21644679de9ca147892d972b0b86d95c87b1e57f7e8283",
|
| 515 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi3.6-wd0.1/predictions-1500000-test_oo.npz": "7c2adacf7e90a6e5808825cf6c546d9ad386f17ecd4a20a764403ed0de8eddf9",
|
| 516 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi7.2-wd0.1/run.json": "46c6a2e5aaa17363b778072faf5f6a220a5928dbd8f2c3c4b425c939247ad369",
|
| 517 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi7.2-wd0.1/learning.json": "05a659a625d60c606dd15e45c48269ff58d5e000f6c5e30eb15d43a56eb78b35",
|
| 518 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi7.2-wd0.1/predictions-0032000-test_oo.npz": "de9d3f81439e6f23b4cc5370b6007b63cb9958d8e67eb7c2b8e8c72d9e824790",
|
| 519 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi7.2-wd0.1/predictions-0064000-test_oo.npz": "ea0ce38033b2dfe1c4b92570b2432e02857e066c0936726d668170eb8453eafe",
|
| 520 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi7.2-wd0.1/predictions-0128000-test_oo.npz": "18542eeccca5b59390c42b3ba2c20253ce69defd29f766983c0fde8ef150bb01",
|
| 521 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi7.2-wd0.1/predictions-0200000-test_oo.npz": "56c805a50d43e28f31b33dfc14ff04c92e5dcbb2d711f9e2101cd88999368271",
|
| 522 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi7.2-wd0.1/predictions-0300000-test_oo.npz": "e02bd7345478544fd00715919490c3aad3a55db3651636055069483bd3f36a99",
|
| 523 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi7.2-wd0.1/predictions-0500000-test_oo.npz": "62e86937272a395a3898c539e9f9b45859c68d20e36da4e380e97d900b2f056b",
|
| 524 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi7.2-wd0.1/predictions-0700000-test_oo.npz": "540118de2d3ca1dffbe0588e1d0748651a8b43bd63dd361cbbb8a89b36b172d4",
|
| 525 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi7.2-wd0.1/predictions-1000000-test_oo.npz": "ed60ef14b9713eeec1ec029be238eafcce14fe43224c9a9ff0cc6e807e909027",
|
| 526 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi7.2-wd0.1/predictions-1500000-test_oo.npz": "7be587982acb77c4056a4192ee9ad365606e5319ec45ead3155297af39ae0db5",
|
| 527 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi7.2-wd0.3/run.json": "83c0bfa5e5cb042734b29243c10f6d3faff005103a97b8180ae79da462b26504",
|
| 528 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi7.2-wd0.3/learning.json": "265aa27765acb98a17db0af0e304d23436be75cf88a0cbf7f71d802eebdc431b",
|
| 529 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi7.2-wd0.3/predictions-0032000-test_oo.npz": "33ecea27acc46a6d5d04ff0e9ccd358e68d8e8791f0c1c1d6fa7e90a963cbd91",
|
| 530 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi7.2-wd0.3/predictions-0064000-test_oo.npz": "7e9d52ab94f47c790c608c07c2be756013636a7c6dab7b5d5e1fea56cdee0409",
|
| 531 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi7.2-wd0.3/predictions-0128000-test_oo.npz": "7f3cfae50269936f5624fa9fc61c7f9eaf120a5d4c28724980c5ddcbd9e16975",
|
| 532 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi7.2-wd0.3/predictions-0200000-test_oo.npz": "1cd33df3479903b85133bfca39dc5bffa27c4a64ff2130eb18346cacf7cdfb2e",
|
| 533 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi7.2-wd0.3/predictions-0300000-test_oo.npz": "1d28d9ad2ff6ce42b1736f1e9a41ead08cd651c06e1a28fe8c0d954a26abb023",
|
| 534 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi7.2-wd0.3/predictions-0500000-test_oo.npz": "f82b1dc268b63e636f589126516eb5e82be25e458e9ee360a38d51f5d12a3d30",
|
| 535 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi7.2-wd0.3/predictions-0700000-test_oo.npz": "89286f3fdd871f395efc7f2cce4f67b819f7b79c7279676ae3af9354c19332d4",
|
| 536 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi7.2-wd0.3/predictions-1000000-test_oo.npz": "fbd8d490ae2a1c5f06cbb37a61a2f720f0f7f46d4e9c9d465049fd3490cc3099",
|
| 537 |
+
"results/grokking-reproduction-v1/development/loop4x2-phi7.2-wd0.3/predictions-1500000-test_oo.npz": "15d16f7c1f039530076abed4e86148bcad772f059a716b74d563964a7a5dbf3b",
|
| 538 |
+
"results/grokking-reproduction-v1/development/standard8-phi12.6-wd0.1/run.json": "c68dbd61ea91244860d35f7e852b70dcd7f9168a4fb27516c1b73e00412212b2",
|
| 539 |
+
"results/grokking-reproduction-v1/development/standard8-phi12.6-wd0.1/learning.json": "8e021c7007ecf13ff4ecbfc723ac7d6bc2ab00bfa6b1e75a27fcd80410df64f3",
|
| 540 |
+
"results/grokking-reproduction-v1/development/standard8-phi12.6-wd0.1/predictions-0032000-test_oo.npz": "40edb2432dc398b082a8e65f88dc10dcc5da7a9e7668bed94eaf9157fe068b5c",
|
| 541 |
+
"results/grokking-reproduction-v1/development/standard8-phi12.6-wd0.1/predictions-0064000-test_oo.npz": "a323ced50b1a91e4ee02b2d9d7ab7e3ea50c2e65ec615b2b6c573bdb620e21d7",
|
| 542 |
+
"results/grokking-reproduction-v1/development/standard8-phi12.6-wd0.1/predictions-0128000-test_oo.npz": "b69f4269dd704950750deabc30f874cccf0bd59d24dd9a1a3d5835f18f85fa2a",
|
| 543 |
+
"results/grokking-reproduction-v1/development/standard8-phi12.6-wd0.1/predictions-0200000-test_oo.npz": "632c7e40da95c37cc5573be5d93f072031ddec4fe7bc575a7e2b7eb38127c90b",
|
| 544 |
+
"results/grokking-reproduction-v1/development/standard8-phi12.6-wd0.1/predictions-0300000-test_oo.npz": "3a826b97e142699e634a059a61e13492c1687bbd4bfb854ce18ead25a5a65276",
|
| 545 |
+
"results/grokking-reproduction-v1/development/standard8-phi12.6-wd0.1/predictions-0500000-test_oo.npz": "f695a111d1bb4ac76e2661838e448f8ea17f0cdf9b3995c77354f0baf58206df",
|
| 546 |
+
"results/grokking-reproduction-v1/development/standard8-phi12.6-wd0.1/predictions-0700000-test_oo.npz": "55b657ae8bbf22a42ed4bb8e18e70508ae50e2b57d647e8046a077b500c48718",
|
| 547 |
+
"results/grokking-reproduction-v1/development/standard8-phi12.6-wd0.1/predictions-1000000-test_oo.npz": "59d52aca1af2b394f091d50a5425af407b39aa206ccc38a03ca20dc416e019a4",
|
| 548 |
+
"results/grokking-reproduction-v1/development/standard8-phi12.6-wd0.1/predictions-1500000-test_oo.npz": "634f391c2efb311260dfca1c0d933aad911a7d77ac1984e253932779f4ee7169",
|
| 549 |
+
"results/grokking-reproduction-v1/development/standard8-phi3.6-wd0.1/run.json": "fd03256d8f10c9bbbcf2f9b42f5c0d68743992d7a025eb7b2d159b628193f372",
|
| 550 |
+
"results/grokking-reproduction-v1/development/standard8-phi3.6-wd0.1/learning.json": "d81a7441a5dd2d877216e50e9ea9378f9b270e282caf7b08d54b71fb9f34f8ab",
|
| 551 |
+
"results/grokking-reproduction-v1/development/standard8-phi3.6-wd0.1/predictions-0032000-test_oo.npz": "fcfd417607ae26f26a7bc01f20090dd527e21693a097f6887bfc7af32c796d6f",
|
| 552 |
+
"results/grokking-reproduction-v1/development/standard8-phi3.6-wd0.1/predictions-0064000-test_oo.npz": "1bf8a51b2d1cc5e3fc47fbede357bab8e0fa21e576c34b661022861408672c12",
|
| 553 |
+
"results/grokking-reproduction-v1/development/standard8-phi3.6-wd0.1/predictions-0128000-test_oo.npz": "e0a6146778a34e97bed606a49f3059b2cfcdd5c2a59645847ce523744eb473e0",
|
| 554 |
+
"results/grokking-reproduction-v1/development/standard8-phi3.6-wd0.1/predictions-0200000-test_oo.npz": "3a16c38a0cf7ba3f8d0a1f2ea49f6f79504d0870f4ce0a61bc21666463d67636",
|
| 555 |
+
"results/grokking-reproduction-v1/development/standard8-phi3.6-wd0.1/predictions-0300000-test_oo.npz": "54ff1dceec1ab82fdd3d5097354ce193ec8941f66edd499e8761fc7bdbbdc065",
|
| 556 |
+
"results/grokking-reproduction-v1/development/standard8-phi3.6-wd0.1/predictions-0500000-test_oo.npz": "c7a2404097433f8d93c2ed6c9d7d3503ea76ba447e8090ee820eec7e76846731",
|
| 557 |
+
"results/grokking-reproduction-v1/development/standard8-phi3.6-wd0.1/predictions-0700000-test_oo.npz": "9b1135b8db8c0fd71bd5d7579a29dc0d8cf5baa77a66171f0b7eb3aeef1a14ff",
|
| 558 |
+
"results/grokking-reproduction-v1/development/standard8-phi3.6-wd0.1/predictions-1000000-test_oo.npz": "b9dc9ed7de4eb7a6c9018b92868c04e98a275bebfda4a8008902e94ea5737a8a",
|
| 559 |
+
"results/grokking-reproduction-v1/development/standard8-phi3.6-wd0.1/predictions-1500000-test_oo.npz": "f21a49a8e05bd18cf61a43960a560d73290173d5fc2da95fc5e5a012bd731121",
|
| 560 |
+
"results/grokking-reproduction-v1/development/standard8-phi7.2-wd0.1/run.json": "bd83c908ebd9b52a3988cf1edaa6a43f25684782b5ddeab46883ef7de7b56999",
|
| 561 |
+
"results/grokking-reproduction-v1/development/standard8-phi7.2-wd0.1/learning.json": "5848e79a0890de6ef91960475c86665446ffea3d651eb88c7206af6bf10a27f2",
|
| 562 |
+
"results/grokking-reproduction-v1/development/standard8-phi7.2-wd0.1/predictions-0032000-test_oo.npz": "12980e13ef40e83a0088285ae55d964ef709979f31e932da3c0f6331940f8660",
|
| 563 |
+
"results/grokking-reproduction-v1/development/standard8-phi7.2-wd0.1/predictions-0064000-test_oo.npz": "77e1afb758ca100d49e123cfbc4f585283eefedc26159a8d53450ba5b0ffa8ae",
|
| 564 |
+
"results/grokking-reproduction-v1/development/standard8-phi7.2-wd0.1/predictions-0128000-test_oo.npz": "4953d8a97ecf2cfbd94722f2bd832b356bb5f823c954f41f830baeb9aac089ef",
|
| 565 |
+
"results/grokking-reproduction-v1/development/standard8-phi7.2-wd0.1/predictions-0200000-test_oo.npz": "7d969674c5f471c58ccc1d90406f6ed05fb1fa81c6e08131d483867873970b64",
|
| 566 |
+
"results/grokking-reproduction-v1/development/standard8-phi7.2-wd0.1/predictions-0300000-test_oo.npz": "9dd384900c93b6a9c4cb31dba52ebff30455580e156a5f2ece652735af496415",
|
| 567 |
+
"results/grokking-reproduction-v1/development/standard8-phi7.2-wd0.1/predictions-0500000-test_oo.npz": "6b1382e0db5e70393c9d17d77212bb414cf081a998f0c54c5778c76da041c82b",
|
| 568 |
+
"results/grokking-reproduction-v1/development/standard8-phi7.2-wd0.1/predictions-0700000-test_oo.npz": "1a11875e664200de8f035da18fc1db4972153b62b1f19a18bb9435035aaa7066",
|
| 569 |
+
"results/grokking-reproduction-v1/development/standard8-phi7.2-wd0.1/predictions-1000000-test_oo.npz": "9600c18eeb8c1fb5caacac92fbcfc448e7d6491e41f0a2044da5fcb1139b2e11",
|
| 570 |
+
"results/grokking-reproduction-v1/development/standard8-phi7.2-wd0.1/predictions-1500000-test_oo.npz": "6ce4c1071c0576a5060a7c30b4d22263fb102e6df63e3d60fa8885552c224b04",
|
| 571 |
+
"results/grokking-reproduction-v1/development/standard8-phi7.2-wd0.3/run.json": "b5406855d2b5c80c7346f1614b45a2a301ec470b40c0a73e0bcb0aa3ac614411",
|
| 572 |
+
"results/grokking-reproduction-v1/development/standard8-phi7.2-wd0.3/learning.json": "bcc0087f153515d71d6f1ff2ce51b0c14d41d054b320c959d76f27017e9be893",
|
| 573 |
+
"results/grokking-reproduction-v1/development/standard8-phi7.2-wd0.3/predictions-0032000-test_oo.npz": "3a5eae216f217b5be7d8a91e96cc33951bc626de296b95fe8d25d24b261d9329",
|
| 574 |
+
"results/grokking-reproduction-v1/development/standard8-phi7.2-wd0.3/predictions-0064000-test_oo.npz": "64cf49e27b8195343bfc8b16fc7629a43e135477475b747b51da2c41c49ca11a",
|
| 575 |
+
"results/grokking-reproduction-v1/development/standard8-phi7.2-wd0.3/predictions-0128000-test_oo.npz": "f923c264b8f4e74671eeade976e76c09b34ab0a3cbc70c8d4c7758824430362d",
|
| 576 |
+
"results/grokking-reproduction-v1/development/standard8-phi7.2-wd0.3/predictions-0200000-test_oo.npz": "492fcc96fab6011695534d98da541c9b046d81076882e51060b6e4c934f32330",
|
| 577 |
+
"results/grokking-reproduction-v1/development/standard8-phi7.2-wd0.3/predictions-0300000-test_oo.npz": "606b09064520dc28ca0f5ad1f5de23ce0b5fd4de69ed7a63fbc4c3ab20e37376",
|
| 578 |
+
"results/grokking-reproduction-v1/development/standard8-phi7.2-wd0.3/predictions-0500000-test_oo.npz": "7205738fa226f7cd4d4c3805c1f79f49553867c73a176dd5b83e08af39294c70",
|
| 579 |
+
"results/grokking-reproduction-v1/development/standard8-phi7.2-wd0.3/predictions-0700000-test_oo.npz": "d81f167040fb988813ab68691de03cee5c9dcb26c40c9c070c0f41007bc77cbd",
|
| 580 |
+
"results/grokking-reproduction-v1/development/standard8-phi7.2-wd0.3/predictions-1000000-test_oo.npz": "af428d27a5bc0b856f49645e779a40b0636c1d0f014e8dbcba5e778d8c8e870e",
|
| 581 |
+
"results/grokking-reproduction-v1/development/standard8-phi7.2-wd0.3/predictions-1500000-test_oo.npz": "cc9f6258133f83436a639e33d292c0086c091e1673e61bc63f1892d36e831aad",
|
| 582 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-loop4x2-init1/run.json": "f8fd280022b2d40edc717a7c908da922c5f4e75b24b24ae87f8bcea4e68ffaca",
|
| 583 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-loop4x2-init1/learning.json": "8e045439cc66d0aad1cf20a3fc633117bcb095dacc929b43c514217cb36d1f98",
|
| 584 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-loop4x2-init1/endpoint-predictions.json": "b398a209a41b70eca35f49127131ee5e0204f1b06205e9c6cf5e19f9dfc92c26",
|
| 585 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-loop4x2-init1/endpoint.json": "96f329a5597797d5f70621138c7b46c0a346e38cdbd63d52875151969bb3a966",
|
| 586 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-loop4x2-init2/run.json": "c185f8a370caa84baf8a5ffff8c830d70ed18a8788dbfb0c39b3fccfb5d7a144",
|
| 587 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-loop4x2-init2/learning.json": "c07a77df26c6e4e9f8e3a6e229b5d8c8af7ea31e93ed984a9a9c4e521734a48d",
|
| 588 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-loop4x2-init2/endpoint-predictions.json": "6f19e925d39316f7cda5ae461047c48a881a57cb25afae2c660d248fb9766a58",
|
| 589 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-loop4x2-init2/endpoint.json": "93a5cee6e0f93a88ace0c6520af2e5a5a4a3542e7da91c4cbad1cc67d50b5f4c",
|
| 590 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-loop4x2-init3/run.json": "92acf8f03ed1e6bdb5699f248e6aef03c40596f9f817acff255b59fbf789f555",
|
| 591 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-loop4x2-init3/learning.json": "10af8613533149838027e0d64bda4d46364b0d0e1f5851fd58857425c7d4db01",
|
| 592 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-loop4x2-init3/endpoint-predictions.json": "e37fddfe344ceb3324ce1807b3d459eaee5d089445ab644a0d738ce11bb3cb59",
|
| 593 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-loop4x2-init3/endpoint.json": "bba44c72fc8a16ff140c92a70e9c74b599e5e5d941cd346e0979d2e472c0adf7",
|
| 594 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard4-init1/run.json": "e1d0f26e708cdb11884f3a73c9c5770f91dedb0f87590b7957f9d771f37b18f6",
|
| 595 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard4-init1/learning.json": "934bfe84758d069ed9b6140eb6b93767e4eac81e12e88baeb5ed6fa7f5709894",
|
| 596 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard4-init1/endpoint-predictions.json": "cbfabe574fa68fbef5ee1ce8636dda07f2c4dc05601262479d24dec38e868652",
|
| 597 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard4-init1/endpoint.json": "d2a2b1d4dea5f0f44975c60f659c98d120b8e16da8d101f34aab91d4f049ff52",
|
| 598 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard4-init2/run.json": "c14c6ffa44556abc2075d732f67f1a7ff64b41b47da3c794f3122ea277619c66",
|
| 599 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard4-init2/learning.json": "010486fd17963c46ac8493d1ac2a19ae437f33bf56540cadb6e18907996ba540",
|
| 600 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard4-init2/endpoint-predictions.json": "7b5c9bbc21b9c2adc1b9d1d3228354a0333ba9a3918abc9b74e2c17362b59b42",
|
| 601 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard4-init2/endpoint.json": "a439df47ed9a0f515f29795c234402cde7adf4f595e8462a40e8848aa4ae78c0",
|
| 602 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard4-init3/run.json": "d44315713c460614d377c9d66fb964eefc412d59bcfb03bdec9e8cc5fddb664f",
|
| 603 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard4-init3/learning.json": "d8193f28e73a49d319d3539cd6bc89e604c0a48f6ef796dd4a0c49dfd95039bc",
|
| 604 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard4-init3/endpoint-predictions.json": "4c43f61d01bfc684bc3b9af49bb15ec45819a93fd1e13b8f266f0e92826ccf25",
|
| 605 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard4-init3/endpoint.json": "88a07f66aae6e15ba2c30ebe5c9475193189a448b99d00a0ebaf6add09c9f17e",
|
| 606 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard8-init1/run.json": "c20f15d7ea290881e114e8f24f3d53798c79d1ee14a9c1d6fa72062c1bc74c7c",
|
| 607 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard8-init1/learning.json": "b0b2b1c401b896518324fa16227a1cc2072b894ca48b1569f0108b2304baa81a",
|
| 608 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard8-init1/endpoint-predictions.json": "827ae62858fcddf436b24eb331f308304c957b7c04cf4429dd9a30882a96695b",
|
| 609 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard8-init1/endpoint.json": "52b08c70b82458de76fcb3b5c94b3f7b1c1e8e5570d0e253a39a8cc1cd00cb84",
|
| 610 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard8-init2/run.json": "cd4df24357259f187c4212bfd21e55f16336dfc8182c94b21937b6940e6093ea",
|
| 611 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard8-init2/learning.json": "86b41da13c8fe6438b8a12b2645fd5b2f13051a74f5c7caab35ebc61c6a52627",
|
| 612 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard8-init2/endpoint-predictions.json": "dd2a4fca6ddb6f4a2b5763f194b1fbd8e7f40003ec4593e98e23feb2c8c45425",
|
| 613 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard8-init2/endpoint.json": "19ebb12cce35e9ee26ba7069cdd0eb59cbeda72cd94166c4a22f3a1498730642",
|
| 614 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard8-init3/run.json": "bf45cdb24a989a287f48d5d2dd40435f02756187095b6eccfd2a1e0dcbafcc36",
|
| 615 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard8-init3/learning.json": "28d1a7641e0323dbcfeaaa47cb0d78c62b7473d8c576d654b25b4038b7c93baa",
|
| 616 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard8-init3/endpoint-predictions.json": "f8ddfcafc4296554d803f6078de3472e3a4f7c31f702004ba28c15c6aae26493",
|
| 617 |
+
"results/realworld-composition-confirmation-v1/confirmation/confirmation-standard8-init3/endpoint.json": "b590152f4206e2c2106c369781907795d1114ef4061526d8a43c0b19c575f4cd"
|
| 618 |
+
}
|
| 619 |
+
}
|