#!/usr/bin/env python3 """Idempotently apply the SNN Baby Brain v41.1 growth/replay/capability fixes. Use after building a new v41 source from a newer v40.x base: python apply_v41_growth_patch.py .\\40.py --output .\\41_base.py python apply_v41_1_fixes.py .\\41_base.py --output .\\41.py This patcher refuses to emit an output if any critical v41.1 feature is missing. The original source file is never overwritten. """ from __future__ import annotations import argparse import hashlib import re import sys from pathlib import Path CAPABILITY_TEMPLATE = Path(__file__).with_name("SNN_Baby_Brain_41_CAPABILITY_BLOCK.txt") OPTIMIZER_HELPERS = '''def _register_growth_optimizer(optimizer: Optional[torch.optim.Optimizer], model: Optional[nn.Module]) -> None: """Track live optimizers weakly so positional-parameter growth can update them safely.""" if optimizer is None or model is None: return refs = getattr(model, "_growth_optimizer_refs", None) if refs is None: refs = [] setattr(model, "_growth_optimizer_refs", refs) live = [] found = False for ref in refs: try: obj = ref() if isinstance(ref, weakref.ReferenceType) else ref except Exception: obj = None if obj is not None: live.append(weakref.ref(obj) if not isinstance(ref, weakref.ReferenceType) else ref) if obj is optimizer: found = True if not found: live.append(weakref.ref(optimizer)) setattr(model, "_growth_optimizer_refs", live) def _sync_replaced_parameter_with_growth_optimizers(model: nn.Module, old_param: nn.Parameter, new_param: nn.Parameter) -> int: """Replace a grown parameter in known optimizers, dropping incompatible moments.""" refs = getattr(model, "_growth_optimizer_refs", []) or [] kept_refs, changed = [], 0 for ref in refs: try: optimizer = ref() if isinstance(ref, weakref.ReferenceType) else ref except Exception: optimizer = None if optimizer is None: continue kept_refs.append(ref if isinstance(ref, weakref.ReferenceType) else weakref.ref(optimizer)) replaced = False for group in getattr(optimizer, "param_groups", []): params = group.get("params", []) for idx, param in enumerate(params): if param is old_param: params[idx] = new_param replaced = True if replaced: try: optimizer.state.pop(old_param, None) except Exception: pass changed += 1 setattr(model, "_growth_optimizer_refs", kept_refs) return changed ''' REPLAY_CLASS = '''class HippocampalReplayBuffer: """Replay store with unlimited-by-default retention and an optional explicit cap. max_episodes=None means retain all episodes in the active replay archive. A positive max_episodes value opts into a bounded in-memory buffer. Disk space is still finite. Ordinary chat remains unverified unless an authorized source verifies it. """ def __init__(self, max_episodes: Optional[int] = None, consolidation_every: Optional[int] = None): configured_cap = Config.REPLAY_BUFFER_MAX if max_episodes is None else max_episodes self.max_episodes = None if configured_cap is None or int(configured_cap) <= 0 else int(configured_cap) self.consolidation_every = (Config.CONSOLIDATION_EVERY if consolidation_every is None else max(1, int(consolidation_every))) self.episodes: List[dict] = []; self.total_stored = 0 def store(self, prompt: str, response: str, da_level: float, turn: int, reward: float = 0.0, thoughts: str = "", verified: bool = False, source: str = "unverified_chat"): item = { 'prompt': str(prompt), 'response': str(response), 'da_level': round(float(da_level), 4), 'turn': int(turn), 'ts': time.time(), 'reward': float(reward), 'thoughts': str(thoughts or ""), 'verified': bool(verified), 'source': str(source or "unverified_chat"), } self.episodes.append(item) self.total_stored += 1 if self.max_episodes is not None and len(self.episodes) > self.max_episodes: del self.episodes[:len(self.episodes) - self.max_episodes] def verified_count(self) -> int: return sum(1 for ep in self.episodes if ep.get('verified') is True and str(ep.get('prompt', '')).strip() and str(ep.get('response', '')).strip()) def should_consolidate(self, turn: int) -> bool: return (turn > 0 and turn % max(1, self.consolidation_every) == 0 and self.verified_count() >= 5) def sample(self, n: int = 20, verified_only: bool = True) -> List[dict]: pool = [ep for ep in self.episodes if not verified_only or ep.get('verified') is True] pool = [ep for ep in pool if str(ep.get('prompt', '')).strip() and str(ep.get('response', '')).strip()] if not pool: return [] pool = sorted(pool, key=lambda e: (float(e.get('reward', 0.0)), float(e.get('da_level', 0.0))), reverse=True) pool = pool[:max(n, len(pool) // 2)] return random.sample(pool, min(max(1, int(n)), len(pool))) def save(self, path: Path): try: tmp = path.with_suffix(path.suffix + '.tmp') episodes_to_save = (self.episodes if self.max_episodes is None else self.episodes[-self.max_episodes:]) with open(tmp, 'w', encoding='utf-8') as f: json.dump({'episodes': episodes_to_save, 'total_stored': self.total_stored}, f, indent=2, ensure_ascii=False) tmp.replace(path) except Exception as e: logger.warning(f"Replay buffer save failed: {e}") def load(self, path: Path): try: if path.exists(): with open(path, 'r', encoding='utf-8') as f: d = json.load(f) self.episodes = d.get('episodes', []) if self.max_episodes is not None and len(self.episodes) > self.max_episodes: self.episodes = self.episodes[-self.max_episodes:] for ep in self.episodes: ep['verified'] = bool(ep.get('verified', False)) ep.setdefault('source', 'legacy_unverified') self.total_stored = d.get('total_stored', len(self.episodes)) print(f"[MEMORY] Loaded {len(self.episodes)} episodes ({self.verified_count()} verified training examples)") except Exception as e: logger.warning(f"Replay buffer load failed: {e}") ''' def patch_source(text: str) -> str: # Correct/version the header and changelog even when the source is a clean v41.0 build. text = re.sub(r'(?m)^SNN BABY BRAIN v41\.0 - (.*)$', r'SNN BABY BRAIN v41.1 - \1', text, count=1) text = text.replace('v41.0 combines the v40.4 developer workbench', 'v41.1 combines the v40.4 developer workbench') text = text.replace('"version": "41.0",', '"version": "41.1",') text = text.replace('unlimited-by-default biological episode/replay retention.', 'unlimited-by-default biological and conversational replay retention; direct forward inputs now expand positional capacity rather than being silently clipped.') if 'import weakref\n' not in text: if 'import contextlib\n' not in text: raise RuntimeError('Import anchor missing; cannot add weakref safely.') text = text.replace('import contextlib\n', 'import contextlib\nimport weakref\n', 1) text, n = re.subn(r'(?m)^\s*REPLAY_BUFFER_MAX\s*=\s*300\s*$', ' # Unlimited-by-default conversation replay retention; positive values are opt-in caps.\n REPLAY_BUFFER_MAX = None', text, count=1) if n == 0 and 'REPLAY_BUFFER_MAX = None' not in text: raise RuntimeError('Cannot find REPLAY_BUFFER_MAX setting; refusing partial patch.') if 'class HippocampalReplayBuffer:' in text and 'self.max_episodes = None if configured_cap is None' not in text: start = text.find('class HippocampalReplayBuffer:') end = text.find('\ndef train_verified_conversation_example(', start) if start < 0 or end < 0: raise RuntimeError('Replay buffer class anchors missing; refusing partial patch.') text = text[:start] + REPLAY_CLASS.rstrip() + '\n\n' + text[end+1:] if '_register_growth_optimizer(' not in text: anchor = 'def sync_optimizer_with_model(optimizer: Optional[torch.optim.Optimizer], model: nn.Module) -> int:\n' if anchor not in text: raise RuntimeError('Optimizer sync anchor missing; refusing partial patch.') text = text.replace(anchor, OPTIMIZER_HELPERS + anchor, 1) if '_register_growth_optimizer(optimizer, model)' not in text: anchor = ''' if optimizer is None or not getattr(optimizer, "param_groups", None): return 0 ''' if anchor not in text: raise RuntimeError('Optimizer body anchor missing; refusing partial patch.') text = text.replace(anchor, anchor + ' _register_growth_optimizer(optimizer, model)\n', 1) old_grow = ''' new_pos_data = torch.randn(1, new_len, self.embed_dim, device=Config.device) * 0.02 new_pos_data[:, :old_len, :] = self.pos_encoding.data self.pos_encoding = nn.Parameter(new_pos_data) self.max_seq_len = new_len ''' new_grow = ''' old_pos_parameter = self.pos_encoding new_pos_data = torch.randn(1, new_len, self.embed_dim, device=Config.device) * 0.02 new_pos_data[:, :old_len, :] = old_pos_parameter.data self.pos_encoding = nn.Parameter(new_pos_data) self.max_seq_len = new_len try: _sync_replaced_parameter_with_growth_optimizers(self, old_pos_parameter, self.pos_encoding) except Exception as _optimizer_sync_exc: logger.warning("Positional-growth optimizer synchronization failed: %s", _optimizer_sync_exc) ''' if old_grow in text: text = text.replace(old_grow, new_grow, 1) elif '_sync_replaced_parameter_with_growth_optimizers(self, old_pos_parameter, self.pos_encoding)' not in text: raise RuntimeError('Positional growth anchor changed; refusing unsafe rebuild.') old_forward = ''' def forward(self, input_ids, hidden_states=None, past_kv=None, neuromod=None, route_override=None, pos_offset=0): B, T = input_ids.shape layer_trace = [] if getattr(self, "_capture_jspace_trace", False) else None self._last_jspace_trace = None self._last_jspace_final_hidden = None if T > self.max_seq_len: input_ids = input_ids[:, -self.max_seq_len:]; T = self.max_seq_len ''' new_forward = ''' def forward(self, input_ids, hidden_states=None, past_kv=None, neuromod=None, route_override=None, pos_offset=0): B, T = input_ids.shape layer_trace = [] if getattr(self, "_capture_jspace_trace", False) else None self._last_jspace_trace = None self._last_jspace_final_hidden = None required_positions = int(pos_offset) + int(T) if required_positions > self.max_seq_len: self.ensure_max_seq_len(required_positions) if required_positions > self.max_seq_len: raise RuntimeError(f"Context growth could not satisfy {required_positions} positions; capacity is {self.max_seq_len}.") ''' if old_forward in text: text = text.replace(old_forward, new_forward, 1) elif 'required_positions = int(pos_offset) + int(T)' not in text: raise RuntimeError('Forward context anchor changed; refusing unsafe rebuild.') # Inspection helpers should also grow context; don't trim away context silently. text = text.replace(''' if input_ids.shape[1] > self.max_seq_len: input_ids = input_ids[:, -self.max_seq_len:] ''', ''' if input_ids.shape[1] > self.max_seq_len: self.ensure_max_seq_len(int(input_ids.shape[1])) ''', 2) text = text.replace(''' if ids.shape[1] > self.max_seq_len: ids = ids[:, -self.max_seq_len:] ''', ''' if ids.shape[1] > self.max_seq_len: self.ensure_max_seq_len(int(ids.shape[1])) ''', 1) # Register optimizers at creation time in the core training and replay paths. optimizer_patterns = [ (''' optimizer = torch.optim.AdamW( core_params, lr=float(learning_rate or getattr(Config, "TEACH_RL_LEARNING_RATE", 1e-5)), weight_decay=float(getattr(Config, "WEIGHT_DECAY", 0.01)), ) ''', 'student_model'), (''' optimizer = torch.optim.AdamW( core_params, lr=float(learning_rate or getattr(Config, "TEACH_CORE_LEARNING_RATE", Config.DEFAULT_LEARNING_RATE)), weight_decay=float(getattr(Config, "WEIGHT_DECAY", 0.01)), ) ''', 'student_model'), (''' opt = torch.optim.AdamW(student.parameters(), lr=Config.DEFAULT_LEARNING_RATE, weight_decay=Config.WEIGHT_DECAY) ''', 'student'), (''' opt = torch.optim.AdamW([p for p in self.student.parameters() if p.requires_grad], lr=Config.DEFAULT_LEARNING_RATE) lm_loss = sleep_consolidation(self.student, self.tokenizer, replay, opt, n_epochs=1) ''', 'self.student'), (''' optimizer = torch.optim.AdamW(params, lr=learning_rate, weight_decay=float(getattr(Config, "WEIGHT_DECAY", 0.01))) ''', 'student_indented'), ] for pattern, model_name in optimizer_patterns: if pattern in text: if model_name == 'self.student': registration = ' _register_growth_optimizer(opt, self.student)\n' replacement = pattern.replace(' lm_loss =', registration + ' lm_loss =') elif model_name == 'student': registration = ' _register_growth_optimizer(opt, student)\n' replacement = pattern + registration elif model_name == 'student_indented': registration = ' _register_growth_optimizer(optimizer, student)\n' replacement = pattern + registration else: registration = f' _register_growth_optimizer(optimizer, {model_name})\n' replacement = pattern + registration if registration not in text[text.find(pattern):text.find(pattern) + len(pattern) + len(registration) + 64]: text = text.replace(pattern, replacement, 1) # Replace the entire capability block with the maintained v41.1 report template. if not CAPABILITY_TEMPLATE.is_file(): raise RuntimeError(f'Capability template missing: {CAPABILITY_TEMPLATE}') block = CAPABILITY_TEMPLATE.read_text(encoding='utf-8') marker = ' # ===== v40.3 HUMAN-STYLE COMPANY WORKFLOW =====' end = text.find(marker) if end < 0: raise RuntimeError('Capability block end marker missing; refusing partial patch.') start_candidates = [ text.find(' # v41.0: factual capability/implementation report.'), text.find(' # v41.1: factual capability/implementation report.'), text.find(' if cmd in {"capability_report", "capability-status"}:'), text.find(' if cmd in {"capability_report", "capability-status", "capability_compare", "capability-comparison"}:') ] start_candidates = [x for x in start_candidates if x >= 0 and x < end] if not start_candidates: raise RuntimeError('Capability block start marker missing; refusing partial patch.') start = min(start_candidates) text = text[:start] + block.rstrip() + '\n\n' + text[end:] text = text.replace('COMMANDS: capability_report | train [file/pdf/docx]', 'COMMANDS: capability_report | capability_compare | train [file/pdf/docx]') text = text.replace('help | capability_report | save | load', 'help | capability_report | capability_compare | save | load') required = [ 'SNN BABY BRAIN v41.1 - SELF-GROWING CORE', 'REPLAY_BUFFER_MAX = None', 'self.max_episodes = None if configured_cap is None', 'required_positions = int(pos_offset) + int(T)', '_sync_replaced_parameter_with_growth_optimizers(self, old_pos_parameter, self.pos_encoding)', '"capability_comparison": capability_comparison', '"comparison_scenario": "fully_grown_and_thoroughly_trained_ideal_case"', 'FULLY GROWN + THOROUGHLY TRAINED IDEAL CASE', 'if cmd in {"capability_report", "capability-status", "capability_compare", "capability-comparison"}:', ] missing = [m for m in required if m not in text] if missing: raise RuntimeError('v41.1 postcondition failed: ' + ', '.join(missing)) compile(text, '', 'exec') return text def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('source', type=Path, help='v41.0 or newer Python source to patch') parser.add_argument('--output', type=Path, required=True, help='Output path; source is never overwritten') args = parser.parse_args() source = args.source.expanduser().resolve() output = args.output.expanduser().resolve() if not source.is_file(): print(f'ERROR: source file not found: {source}', file=sys.stderr) return 2 try: text = source.read_text(encoding='utf-8', errors='replace') patched = patch_source(text) output.parent.mkdir(parents=True, exist_ok=True) output.write_text(patched, encoding='utf-8') except Exception as exc: print(f'PATCH ABORTED (source unchanged): {type(exc).__name__}: {exc}', file=sys.stderr) return 3 digest = hashlib.sha256(output.read_bytes()).hexdigest() print(f'WROTE {output}\nSHA256 {digest}\nPASS v41.1 patch and syntax validation') return 0 if __name__ == '__main__': raise SystemExit(main())