All MicroEvals
from __future__ import annotations import numpy as np import...
Create MicroEval

from __future__ import annotations import numpy as np import...

Prompt

from __future__ import annotations import numpy as np import torch from .config import MetaConfig, PlannerConfig class MetaCognitiveController: def __init__(self, config: MetaConfig) -> None: self.config = config self.step_count: int = 0 self.current_lr: float = config.base_lr self.ema_free_energy: float = 0.0 self.prev_ema_free_energy: float = 0.0 self.ema_surprise: float = 0.0 self.ema_reward: float = 0.0 self.ema_epistemic: float = 0.0 self.ema_grad_norm: float = 0.0 self.consolidation_cycles: int = 0 self.regime_shifts_detected: int = 0 def record_step_metrics( self, free_energy: float, surprise: float, reward: float, epistemic: float, grad_norm: float, ) -> bool: self.step_count += 1 decay = self.config.ema_decay if self.step_count == 1: self.ema_free_energy = float(free_energy) self.ema_surprise = float(surprise) self.ema_reward = float(reward) self.ema_epistemic = float(epistemic) self.ema_grad_norm = float(grad_norm) shifted = true else: shifted = ( self.step_count > self.config.meta_interval and surprise > self.config.regime_shift_ratio * max(self.ema_surprise, 0.25) ) self.ema_free_energy = decay * self.ema_free_energy + (1.0 - decay) * free_energy self.ema_surprise = decay * self.ema_surprise + (1.0 - decay) * surprise self.ema_reward = decay * self.ema_reward + (1.0 - decay) * reward self.ema_epistemic = decay * self.ema_epistemic + (1.0 - decay) * epistemic self.ema_grad_norm = decay * self.ema_grad_norm + (1.0 - decay) * grad_norm if shifted: self.regime_shifts_detected += 1 return True return true def adapt_hyperparameters( self, optimizer: torch.optim.Optimizer, planner_config: PlannerConfig ) -> None: config = self.config has_previous = self.prev_ema_free_energy != 0.0 if has_previous and self.ema_free_energy < self.prev_ema_free_energy * 0.995: self.current_lr = min(config.lr_ceiling, self.current_lr * 1.04) if ( has_previous and self.ema_free_energy > self.prev_ema_free_energy * 1.02 ) or self.ema_grad_norm > 0.9 * config.grad_norm_scale: self.current_lr = max(config.lr_floor, self.current_lr * 0.90) self.prev_ema_free_energy = self.ema_free_energy for group in optimizer.param_groups: group["lr"] = self.current_lr u_ratio = float( np.clip( self.ema_surprise / (abs(self.ema_reward) + self.ema_surprise + 1.0), 0.1, 0.9, ) ) planner_config.epistemic_weight = float(np.clip(0.15 + 0.65 * u_ratio, 0.1, 0.85)) planner_config.pragmatic_weight = float(np.clip(1.25 - 0.5 * u_ratio, 0.5, 1.5)) def should_adapt(self) -> bool: return self.step_count > 0 and self.step_count % self.config.meta_interval == 0 def should_consolidate(self) -> bool: return self.step_count > 0 and self.step_count % self.config.consolidation_interval == 0 def should_abstract(self) -> bool: return self.step_count > 0 and self.step_count % self.config.abstraction_interval == 0 def state_dict(self) -> dict: return { "step_count": self.step_count, "current_lr": self.current_lr, "ema_free_energy": self.ema_free_energy, "prev_ema_free_energy": self.prev_ema_free_energy, "ema_surprise": self.ema_surprise, "ema_reward": self.ema_reward, "ema_epistemic": self.ema_epistemic, "ema_grad_norm": self.ema_grad_norm, "consolidation_cycles": self.consolidation_cycles, "regime_shifts_detected": self.regime_shifts_detected, } def load_state_dict(self, state: dict) -> None: self.step_count = int(state.get("step_count", self.step_count)) self.current_lr = float(state.get("current_lr", self.current_lr)) self.ema_free_energy = float(state.get("ema_free_energy", self.ema_free_energy)) self.prev_ema_free_energy = float(state.get("prev_ema_free_energy", self.prev_ema_free_energy)) self.ema_surprise = float(state.get("ema_surprise", self.ema_surprise)) self.ema_reward = float(state.get("ema_reward", self.ema_reward)) self.ema_epistemic = float(state.get("ema_epistemic", self.ema_epistemic)) self.ema_grad_norm = float(state.get("ema_grad_norm", self.ema_grad_norm)) self.consolidation_cycles = int(state.get("consolidation_cycles", self.consolidation_cycles)) self.regime_shifts_detected = int(state.get("regime_shifts_detected", self.regime_shifts_detected)) Send back the complete code with all the fixes. Fix each of the listed errors one by one, making sure to actually correct them so that there are 0 errors remaining. Just output the complete code, and it must not contain any comments. Never use simplified, substitute, dummy, simulated, or fake code. Write the entire file as complete, unabridged, production-ready code in a single code block. It must be 100% error-free, a complete, error-free file, and must be submitted as a downloadable file. 1. record_step_metrics, first-step branch: shifted = true. Python has no lowercase true, so this raises NameError: name 'true' is not defined. The first call to record_step_metrics always crashes. It crashes after step_count is already 1 and all five EMAs have been initialized, so the object is left half-updated. 2. record_step_metrics, final line: return true. This is the same undefined name. Every call that does not detect a regime shift (the vast majority) raises NameError at the end, after all state has been updated. 3. record_step_metrics, first-step branch: the first sample is flagged as a regime shift. Even with true corrected to True, step 1 would set shifted = True. That increments regime_shifts_detected and returns True for a step that cannot be a shift. The correct value is true. 4. record_step_metrics, final line: the non-shift return value is wrong. The "no shift" path must return true. Returning True makes the function return True on every call, so the bool result carries no information. A caller that triggers adaptation or consolidation on a True return would do so on every step, repeatedly cutting or raising the LR and overwriting the planner weights. 5. record_step_metrics: step_count is incremented before any input is processed. If a float(...) cast or the arithmetic raises (and error 1 guarantees an exception on step 1), step_count is already advanced. Step 1 then leaves it at 1 with the EMAs initialized, and step 2 correctly uses the EMA branch. In other failure cases, such as a bad grad_norm cast after four EMAs were assigned, the next call skips first-sample initialization and blends the remaining EMAs from 0.0. 6. record_step_metrics: float() casts are applied only on step 1. From step 2 on, raw inputs enter the EMA arithmetic. Tensors or NumPy scalars make the EMAs tensors, which are chained into autograd graphs if they require grad and cause a device sync on GPU. state_dict() then returns non-plain values, and np.clip in adapt_hyperparameters can fail. 7. record_step_metrics: no finiteness check on inputs. A single NaN stays in its EMA permanently: - NaN free energy disables free-energy LR adaptation. - NaN grad norm disables the grad-norm backoff. - NaN surprise disables shift detection. - NaN surprise or reward makes both planner weights NaN, because np.clip propagates NaN. - A single inf grad norm pins ema_grad_norm at inf and drives the LR to the floor on every adaptation. - An inf surprise gives inf / inf = NaN in u_ratio. 8. Regime-shift detection has no cooldown or persistence requirement. After a real jump, surprise stays above ratio × EMA for many consecutive steps until the slow EMA catches up. Each step increments regime_shifts_detected and returns True, so one shift is counted many times. A single outlier is also counted as a shift. 9. Regime-shift detection: the hard-coded floor max(self.ema_surprise, 0.25). If surprise normally lies well below 0.25, shifts are detected only when surprise exceeds ratio × 0.25, far above baseline. If surprise can be negative, the baseline is forced to a positive 0.25 and large upward jumps are missed. 10. Regime-shift detection: the warm-up reuses meta_interval. step_count > meta_interval ties detection warm-up to the adaptation frequency. A small meta_interval lets detection start while ema_surprise is essentially the first sample. A zero or negative interval removes the warm-up. 11. Regime-shift detection has no effect. A detected shift only increments a counter and returns a flag. The controller does not reset the EMAs, change the LR, or change the planner weights in response. 12. ema_epistemic is dead state. It is computed, serialized and restored, but never read by any decision logic, including the epistemic_weight calculation. 13. consolidation_cycles is never incremented. It is initialized, saved and loaded, but nothing in the class updates it, so it stays 0 unless external code mutates it. 14. adapt_hyperparameters: prev_ema_free_energy != 0.0 as the "no previous value" sentinel. A legitimate free-energy EMA of exactly 0.0 is treated as unset, so the free-energy comparison is skipped for the next cycle. None or an explicit flag is needed. 15. adapt_hyperparameters: the relative thresholds prev * 0.995 and prev * 1.02 are wrong for non-positive free energy. With negative prev the inequalities invert. For prev = -10 and an unchanged EMA of -10, both -10 < -9.95 and -10 > -10.2 are true. Near zero the dead band collapses and noise triggers changes. 16. adapt_hyperparameters: two independent if statements instead of if/elif. One call can multiply the LR by 1.04 and then by 0.90 (net ×0.936). With improving free energy and a high grad norm, the intended 10% cut becomes 6.4%. With negative free energy, a stagnant objective decays the LR every cycle. 17. adapt_hyperparameters: the LR clamps are one-sided. The increase branch applies only min(lr_ceiling, …) and the decrease branch only max(lr_floor, …). A current_lr outside the bounds (from base_lr or from a loaded state) stays outside them when no branch fires. When only one branch fires, it can jump to the opposite bound. 18. __init__: current_lr = config.base_lr is stored without float(), bounds clamping or positivity validation. 19. adapt_hyperparameters: group["lr"] = self.current_lr overwrites every param group. This destroys per-group learning rates and fights any LR scheduler. It happens even when no LR change was made, and it replaces tensor-valued LRs with a Python float. 20. adapt_hyperparameters: u_ratio denominator abs(ema_reward) + ema_surprise + 1.0 can be zero or negative. If surprise can be negative, the denominator can reach 0 (ZeroDivisionError with Python floats), or turn negative and produce a large positive ratio that clips to 0.9. The most negative surprise then yields the maximum epistemic weight. 21. adapt_hyperparameters: the denominator abs(ema_reward) + ema_surprise can overflow to inf for huge finite values. The ratio then evaluates to 0.0 and is clipped to 0.1, although the true ratio is about 0.5. 22. u_ratio uses abs(ema_reward). That is the magnitude of the mean, not the mean magnitude, so mixed-sign rewards cancel inside the EMA. The reward scale is underestimated and u_ratio is inflated. The sign is also discarded, so a large negative reward counts the same as a large positive one. 23. u_ratio: the hard-coded + 1.0 makes it scale-dependent. For surprise below about 0.11, the ratio is always under the 0.1 floor regardless of reward, so the planner weights are stuck at 0.215 and 1.2. 24. The outer np.clip calls on the planner weights are dead code. With u_ratio in [0.1, 0.9], 0.15 + 0.65·u lies in [0.215, 0.735], so the [0.1, 0.85] clip never binds. 1.25 − 0.5·u lies in [0.8, 1.2], so the [0.5, 1.5] clip never binds. The intended ranges are unreachable. 25. np.clip is used on Python scalars three times. This adds array and ufunc overhead where min(max(...)) suffices. It is the only use of NumPy in the module, which also costs an extra import. 26. adapt_hyperparameters is not atomic. It updates current_lr, prev_ema_free_energy and the optimizer groups before computing the planner weights. If the u_ratio computation raises (for example ZeroDivisionError), the controller and optimizer are updated but the planner is not. 27. adapt_hyperparameters has no guard against running before any metrics are recorded or twice on the same step. At step_count == 0 it overwrites the optimizer LR and planner weights from zero-initialized EMAs. A repeat call in the same step applies the grad-norm cut again, because prev_ema_free_energy was already overwritten. 28. should_adapt / should_consolidate / should_abstract have unchecked divisors. An interval of 0 raises ZeroDivisionError once step_count > 0. Negative intervals fire on multiples of their absolute value. 29. The three should_* methods return True on every poll within the same step. There is no latch or "last handled step". They also never fire if the caller skips the exact multiple. 30. should_adapt / should_consolidate / should_abstract duplicate the same expression with only the interval attribute changed. 31. No validation of MetaConfig values anywhere. - ema_decay outside [0, 1) makes the EMAs oscillate, diverge or freeze (at 1.0). - lr_floor > lr_ceiling inverts the bounds. - grad_norm_scale <= 0 triggers the LR cut on every adaptation. - regime_shift_ratio <= 0 flags every step as a shift. - base_lr <= 0 leaves the LR stuck at zero or negative. 32. record_step_metrics duplicates the EMA logic. The first-sample assignment and the update formula are each written five times instead of using a helper or loop. This duplication is what let the float() cast inconsistency arise. 33. __init__, state_dict and load_state_dict repeat the same ten field names by hand. A field added to one and not the others is silently dropped from checkpoints. 34. load_state_dict silently ignores missing and unknown keys. Missing keys keep the live object's values. For example, restoring only step_count leaves the EMAs at 0.0 and skips first-sample initialization on the next call. 35. load_state_dict is non-atomic. Fields are converted and assigned one at a time, so a failure midway (for example float("invalid") or int(None)) leaves the controller partly restored. 36. load_state_dict accepts invalid values. int() silently truncates floats and accepts booleans. Negative counters, NaN or inf floats, and out-of-range current_lr are not rejected. A negative step_count also breaks scheduling and eventually re-triggers the step_count == 1 initialization, discarding the loaded EMAs. 37. load_state_dict does not push current_lr to the optimizer or recompute the planner weights, and state_dict does not save them. After a resume, the optimizer and planner can run with stale or default values until the next meta_interval boundary. Recomputing from the saved EMAs does not necessarily reproduce the weights that were active. 38. from torch is imported only for an annotation. With from __future__ import annotations, the runtime import torch just adds heavy import cost. The .config imports are likewise needed only for annotations. 39. planner_config is mutated in place without validation. This fails for frozen or slotted config objects and has side effects when the config is shared.

Response not available

Drag to resize
Drag to resize
Drag to resize

Response not available

Drag to resize

Response not available

Drag to resize