max / apply_v41_growth_patch.py
manjunathan123's picture
Upload folder using huggingface_hub
071cd07 verified
Raw History Blame Contribute Delete
14.9 kB
#!/usr/bin/env python3
"""Safely build a v41 entrypoint from an updated SNN Baby Brain source.
Examples:
python apply_v41_growth_patch.py .\40.py --output .\41.py
python apply_v41_growth_patch.py .\41.py --output .\41_rebuilt.py
The original source is never overwritten unless --in-place is explicitly supplied.
The script aborts when core patch anchors no longer match rather than guessing.
"""
from __future__ import annotations
import argparse
import re
import shutil
import sys
import time
from pathlib import Path
from apply_lifelong_growth_patch import patch_source as apply_lifelong_persistence_patch
from v41_memory_growth_templates import VECTOR_HIPPOCAMPUS_BLOCK, BIO_MEMORY_CLASS
V41_HEADER = "SNN BABY BRAIN v41.0 - SELF-GROWING CORE + PERSISTENT MEMORY/SKILLS + AI WORKBENCH"
CHANGELOG = (
"v41.0 combines the v40.4 developer workbench, approval-gated human workflow, AI-team delegation, historical multimodal encoders, and "
"dynamic-growth persistence repairs from the v29.4 growth/memory patch, plus disk-backed append-only hippocampus memory and unlimited-by-default biological episode/replay retention. It preserves learned core weights, synchronizes optimizers after "
"neural growth, restores skill adapters from checkpoint tensors plus metadata, persists the skill registry atomically, and records a privacy-conscious "
"append-only growth/memory event ledger. Architecture growth is demand-driven with no fixed software ceilings in the core growth settings; physical "
"memory, compute, training data, and quality evaluation remain real constraints.\n\n"
)
CAPABILITY_BLOCK = ''' # v41.0: factual capability/implementation report. This reports enabled mechanisms,
# current runtime state, and known limits rather than claiming benchmark-level quality.
if cmd in {"capability_report", "capability-status"}:
try:
arch = student.get_architecture_stats()
except Exception as _arch_exc:
arch = {"error": f"{type(_arch_exc).__name__}: {_arch_exc}"}
skill_bank = getattr(student, "skill_adapters", None)
skill_names = list(skill_bank.names()) if skill_bank is not None and hasattr(skill_bank, "names") else []
modality_modules = {
"vision_encoder": vision_enc, "vision_decoder": vision_dec, "vision_classifier": vision_class,
"audio_encoder": audio_enc, "audio_decoder": audio_dec, "audio_classifier": audio_class,
"video_encoder": video_enc, "video_decoder": video_dec, "text_encoder": text_enc,
"multimodal_fusion": mm_fusion, "text_image_generator": text_image_gen,
"text_audio_generator": text_audio_gen, "text_video_generator": text_video_gen,
"state_encoder": state_enc, "action_decoder": action_dec, "colorizer": colorizer,
}
component_state = {
name: {
"instantiated": module is not None,
"weight_source": _COMPONENT_WEIGHT_SOURCES.get(name, "unknown_or_unverified"),
}
for name, module in modality_modules.items()
}
try:
_event_log_path = SCRIPT_DIR / "lifelong_learning_events.jsonl"
event_log_count = sum(1 for _ in _event_log_path.open("r", encoding="utf-8")) if _event_log_path.exists() else 0
except Exception:
event_log_count = None
bio_memory_path = SCRIPT_DIR / "bio_memory_v16.json"
try:
_bio_memory_data = json.loads(bio_memory_path.read_text(encoding="utf-8")) if bio_memory_path.exists() else {}
bio_episode_count = len(_bio_memory_data.get("episodes", []))
bio_replay_count = len(_bio_memory_data.get("replay_queue", []))
bio_semantic_count = len(_bio_memory_data.get("semantic", {}))
except Exception:
bio_episode_count = bio_replay_count = bio_semantic_count = None
capability_report = {
"version": "41.0",
"architecture_growth": {
"status": "enabled_demand_and_energy_gated",
"software_caps": {"layers": Config.MAX_LAYERS, "embed_dim": Config.MAX_EMBED_DIM,
"sequence_length": Config.MAX_SEQ_LEN,
"ff_dim_per_layer": Config.MAX_FF_DIM_PER_LAYER,
"total_ff_units": Config.MAX_TOTAL_FF_UNITS,
"multimodal_sequence_length": Config.MAX_MULTIMODAL_SEQ},
"architecture": arch,
"training_checkpoint_loaded": bool(getattr(student, "_snn_checkpoint_loaded", False)),
"physical_limits": "RAM, VRAM, compute, disk space, and training quality still constrain growth",
},
"persistent_skills": {
"adapter_count": len(skill_names), "skills": skill_names,
"registry_file": SKILL_STATE_FILE.name,
"weight_checkpoint": ACTIVE_BRAIN_FILE.name,
},
"persistent_memory": {
"working_memory_items": len(getattr(executive.memory, "items", [])),
"hippocampus_items": int(getattr(getattr(brain, "hippocampus", None), "count", 0)),
"hippocampus_archive_file": str(SCRIPT_DIR / "hippocampus_memory.jsonl"),
"semantic_memory_capacity_setting": Config.SEMANTIC_MEMORY_CAPACITY,
"biological_episode_memory_file": str(bio_memory_path),
"biological_episode_count_on_disk": bio_episode_count,
"replay_queue_count_on_disk": bio_replay_count,
"semantic_task_count_on_disk": bio_semantic_count,
"biological_episode_retention": "unlimited by default; optional explicit capacity only",
"verified_memory_file": str(SCRIPT_DIR / "agi_lab" / "human_learning_memory.json"),
"growth_memory_event_count": event_log_count,
"event_log": "lifelong_learning_events.jsonl",
},
"reasoning_and_evaluation": {
"reasoning_enabled": bool(Config.REASONING_ENABLED),
"self_reflection_enabled": bool(Config.SELF_REFLECTION_ENABLED),
"held_out_evaluation_available": True,
"quality_claim": "must be measured on representative held-out tasks; not implied by architecture alone",
},
"coding_workbench": {"available": dev_workbench is not None,
"writes_require_explicit_apply": True,
"tests_are_os_sandboxed": False},
"workflow_orchestration": {"available": company_workflow is not None,
"execution_requires_approval": True},
"external_ai_team": {"available": ai_delegation is not None,
"providers_enabled_by_default": False,
"credentials_from_environment": True},
"multimodal_components": component_state,
"teacher_api_online": bool(TEACHER_ONLINE),
"inference_cost_and_speed": "not claimed; measure on the target hardware and workload",
"safety": "approval gates and allowlists are implemented, but this is not a formal safety certification",
}
print(json.dumps(capability_report, indent=2, ensure_ascii=False, default=str))
continue
'''
def _replace_class_block(text: str, start_marker: str, end_marker: str, replacement: str, label: str) -> str:
start = text.find(start_marker)
if start < 0:
raise RuntimeError(f"Cannot locate {label} start anchor; refusing unsafe rebuild.")
end = text.find(end_marker, start + len(start_marker))
if end < 0:
raise RuntimeError(f"Cannot locate {label} end anchor; refusing unsafe rebuild.")
return text[:start] + replacement.rstrip() + "\n\n" + text[end:]
def _apply_unbounded_memory_growth(text: str) -> str:
# Replacing whole class blocks is intentionally anchor-bounded and idempotent.
text = _replace_class_block(
text, "class VectorHippocampus:", "\ndef _hippo_store(",
VECTOR_HIPPOCAMPUS_BLOCK, "VectorHippocampus")
text = _replace_class_block(
text, "class HumanInspiredMemorySystems:", "\n\nclass HumanInspiredCapabilityGraph:",
BIO_MEMORY_CLASS, "HumanInspiredMemorySystems")
text, n = re.subn(
r"(?m)^(\s*SEMANTIC_MEMORY_CAPACITY\s*=\s*)(?:None|\d+)(?:\s*#.*)?$",
r"\1None # unlimited-by-default; bounded only when explicitly configured",
text, count=1)
if n != 1:
raise RuntimeError("Cannot locate Config.SEMANTIC_MEMORY_CAPACITY; refusing to leave a stale memory ceiling.")
text, n_mm = re.subn(
r"(?m)^(\s*MAX_MULTIMODAL_SEQ\s*=\s*)(?:None|\d+)(?:\s*#.*)?$",
r"\1None # grows as required; physical resources remain the limit",
text, count=1)
if n_mm != 1:
raise RuntimeError("Cannot locate Config.MAX_MULTIMODAL_SEQ; refusing to leave a stale multimodal sequence ceiling.")
return text
def build_v41(source: str) -> str:
text = apply_lifelong_persistence_patch(source)
text = _apply_unbounded_memory_growth(text)
if "SNN BABY BRAIN v41.0" not in text:
text, n = re.subn(r"(?m)^SNN BABY BRAIN v40(?:\.\d+)? - .*?$", V41_HEADER, text, count=1)
if n != 1:
raise RuntimeError("Cannot locate the v40.x version header; refusing to create a mislabeled v41 build.")
else:
text = re.sub(r"(?m)^SNN BABY BRAIN v41\.0 - .*?$", V41_HEADER, text, count=1)
if "v41.0 combines the v40.4 developer workbench" not in text:
anchor = "v31.0 adds asynchronous approved-task execution, step-level progress telemetry, and immediate natural-language task-status responses.\n"
if anchor not in text:
raise RuntimeError("Cannot insert the v41 changelog: expected history anchor is missing.")
text = text.replace(anchor, CHANGELOG + anchor, 1)
if "if cmd in {\"capability_report\", \"capability-status\"}:" not in text:
anchor = ''' # ===== v40.3 HUMAN-STYLE COMPANY WORKFLOW =====\n if cmd == "company":\n'''
if anchor not in text:
raise RuntimeError("Cannot install capability_report: command dispatcher anchor is missing.")
text = text.replace(anchor, CAPABILITY_BLOCK + anchor, 1)
text = text.replace("40.py", "41.py")
text = text.replace("python 39.py --always-on", "python 41.py --always-on")
text = text.replace(
"SNN BABY BRAIN v40.4 - DEVELOPER WORKBENCH + HUMAN WORKFLOW + AI TEAM + HISTORICAL ENCODERS",
V41_HEADER,
)
text = text.replace("v40.4 DEVELOPER:", "v41.0 DEVELOPER WORKBENCH:")
text = text.replace("v40.4 APPROVAL-GATED SOFTWARE DEVELOPMENT WORKBENCH", "v41.0 APPROVAL-GATED SOFTWARE DEVELOPMENT WORKBENCH")
text = text.replace('print("COMMANDS: train [file/pdf/docx] | trainhard', 'print("COMMANDS: capability_report | train [file/pdf/docx] | trainhard')
text = text.replace('print(" help | save | load [snn_brain_active.safetensors] | teacher [on|off] | brain")',
'print(" help | capability_report | save | load [snn_brain_active.safetensors] | teacher [on|off] | brain")')
# Postconditions catch version drift and accidental removal of the long-term repairs.
required = [
"LIFELONG_GROWTH_PERSISTENCE_PATCH_V1",
"def log_lifelong_event(",
"def _persist_skill_registry(",
"def _notify_skill_growth(",
"load_skill_adapters(student, preloaded_state_dict)",
"optimizer=optimizer)",
"if cmd in {\"capability_report\", \"capability-status\"}:",
"MAX_TOTAL_FF_UNITS = None",
"self.path_archive = SCRIPT_DIR / \"hippocampus_memory.jsonl\"",
"episodic_capacity: Optional[int] = None",
"SEMANTIC_MEMORY_CAPACITY = None # unlimited-by-default",
"MAX_MULTIMODAL_SEQ = None # grows as required; physical resources remain the limit",
]
for marker in required:
if marker not in text:
raise RuntimeError(f"Postcondition failed; missing required feature marker: {marker}")
return text
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("source", type=Path, help="Updated SNN Baby Brain v40.x/v41 source")
parser.add_argument("--output", type=Path, help="Output path (default: 41.py or <source>_v41.py)")
parser.add_argument("--in-place", action="store_true", help="Replace source after creating a timestamped backup")
args = parser.parse_args()
source_path = args.source.expanduser().resolve()
if not source_path.is_file():
print(f"ERROR: source file not found: {source_path}", file=sys.stderr)
return 2
try:
original = source_path.read_text(encoding="utf-8", errors="replace")
built = build_v41(original)
except Exception as exc:
print(f"BUILD ABORTED (source unchanged): {type(exc).__name__}: {exc}", file=sys.stderr)
return 3
if args.in_place:
target = source_path
backup = source_path.with_suffix(source_path.suffix + f".backup_{time.strftime('%Y%m%d_%H%M%S')}")
shutil.copy2(source_path, backup)
else:
target = args.output.expanduser().resolve() if args.output else (
source_path.with_name("41.py") if source_path.name == "40.py" else source_path.with_name(source_path.stem + "_v41.py")
)
if target == source_path:
print("ERROR: output resolves to source; use --in-place for an intentional replacement.", file=sys.stderr)
return 2
backup = None
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(built, encoding="utf-8", newline="")
try:
compile(built, str(target), "exec")
except SyntaxError as exc:
if backup and backup.exists():
shutil.copy2(backup, source_path)
target.unlink(missing_ok=True)
print(f"BUILD FAILED syntax check; output removed: {exc}", file=sys.stderr)
return 4
print(f"Created: {target}")
print(f"Bytes: {len(built.encode('utf-8'))}; syntax: PASS")
if backup:
print(f"Backup: {backup}")
print("Included: v40 workbench + dynamic growth + checkpoint skill recovery + durable skill registry + verified-memory event ledger + capability_report.")
return 0
if __name__ == "__main__":
raise SystemExit(main())