perforatedai.configure_perforatedai

   1import sys
   2import shutil
   3import json
   4import os
   5import select
   6import re
   7
   8# POSIX-only. The module must still import on native Windows (perforate_model
   9# imports it unconditionally); the interactive TUI just cannot run there.
  10try:
  11    import termios
  12    import tty
  13except ImportError:  # pragma: no cover - exercised only on Windows
  14    termios = None
  15    tty = None
  16
  17from perforatedai import globals_perforatedai as GPA
  18
  19try:
  20    import torch
  21except Exception:  # pragma: no cover - torch is a hard dependency at runtime
  22    torch = None
  23
  24
  25# ---------------------------------------------------------------------------
  26# Selection list plumbing
  27# ---------------------------------------------------------------------------
  28def dedupe_list(values):
  29    """Return a list with duplicates removed while preserving order."""
  30    seen = set()
  31    unique = []
  32    for value in values:
  33        if value in seen:
  34            continue
  35        seen.add(value)
  36        unique.append(value)
  37    return unique
  38
  39
  40def python_supplied_owner(var_names, item):
  41    """The first list in ``var_names`` whose script-supplied items include ``item``."""
  42    for var_name in var_names:
  43        if item in (GPA.pc.get_python_supplied(var_name) or []):
  44            return var_name
  45    return None
  46
  47
  48def python_owned_message(label, var_name):
  49    return (
  50        f"{label} is set by a Python call ({var_name}) — change it in your script; "
  51        "the CLI can't override it."
  52    )
  53
  54
  55def id_python_owner(module_id):
  56    return python_supplied_owner(
  57        ("module_ids_to_perforate", "module_ids_to_track"), module_id
  58    )
  59
  60
  61def type_python_owner(type_name):
  62    return python_supplied_owner(
  63        ("module_names_to_perforate", "module_names_to_track"), type_name
  64    )
  65
  66
  67def normalize_selection_conflicts():
  68    """Normalize id and name selection lists and remove direct conflicts."""
  69    ids_perforate = dedupe_list(GPA.pc.get_module_ids_to_perforate())
  70    ids_track = dedupe_list(GPA.pc.get_module_ids_to_track())
  71    names_perforate = dedupe_list(GPA.pc.get_module_names_to_perforate())
  72    names_track = dedupe_list(GPA.pc.get_module_names_to_track())
  73
  74    overlap_ids = set(ids_perforate) & set(ids_track)
  75    overlap_names = set(names_perforate) & set(names_track)
  76
  77    if overlap_ids:
  78        ids_track = [value for value in ids_track if value not in overlap_ids]
  79    if overlap_names:
  80        names_track = [value for value in names_track if value not in overlap_names]
  81
  82    GPA.pc.set_module_ids_to_perforate(ids_perforate)
  83    GPA.pc.set_module_ids_to_track(ids_track)
  84    GPA.pc.set_module_names_to_perforate(names_perforate)
  85    GPA.pc.set_module_names_to_track(names_track)
  86
  87
  88def get_module_entries(model):
  89    """Collect modules for interactive navigation.
  90
  91    Each entry also carries ``is_replaced_root`` (this module's class is in
  92    ``modules_to_replace`` and will be restructured before training) and
  93    ``in_replaced`` / ``replaced_root`` (this module lives under such a module,
  94    so its id will not exist at training time).
  95    """
  96    entries = []
  97    for name, module in model.named_modules(remove_duplicate=False):
  98        if name == "":
  99            continue
 100        module_id = "." + name
 101        depth = name.count(".")
 102        entries.append(
 103            {
 104                "id": module_id,
 105                "name": name,
 106                "type_name": type(module).__name__,
 107                "module": module,
 108                "depth": depth,
 109                "direct_param_count": sum(
 110                    param.numel()
 111                    for _param_name, param in module.named_parameters(recurse=False)
 112                ),
 113                "tree_param_count": sum(
 114                    param.numel()
 115                    for _param_name, param in module.named_parameters(recurse=True)
 116                ),
 117                # Trainable: this module or any submodule has a requires_grad
 118                # parameter. Only trainable modules may be perforated.
 119                "trainable": any(
 120                    param.requires_grad
 121                    for _param_name, param in module.named_parameters(recurse=True)
 122                ),
 123            }
 124        )
 125
 126    # named_modules() is a DFS pre-order traversal, so a module's children
 127    # (if any) always immediately follow it in `entries`.
 128    for i, entry in enumerate(entries):
 129        entry["has_children"] = i + 1 < len(entries) and entries[i + 1]["id"].startswith(
 130            entry["id"] + "."
 131        )
 132
 133    replace_classes = tuple(GPA.pc.get_modules_to_replace())
 134    replaced_root_ids = []
 135    for entry in entries:
 136        entry["is_replaced_root"] = (
 137            len(replace_classes) > 0
 138            and isinstance(entry["module"], replace_classes)
 139        )
 140        if entry["is_replaced_root"]:
 141            replaced_root_ids.append(entry["id"])
 142
 143    for entry in entries:
 144        entry["replaced_root"] = None
 145        entry["in_replaced"] = False
 146        for root_id in replaced_root_ids:
 147            if entry["id"].startswith(root_id + "."):
 148                entry["replaced_root"] = root_id
 149                entry["in_replaced"] = True
 150                break
 151
 152    return entries
 153
 154
 155def get_id_mode(module_id):
 156    """Get explicit id-based mode for a module id ("perforated"/"tracked"/None)."""
 157    if module_id in GPA.pc.get_module_ids_to_perforate():
 158        return "perforated"
 159    if module_id in GPA.pc.get_module_ids_to_track():
 160        return "tracked"
 161    return None
 162
 163
 164def get_name_mode(module_type_name):
 165    """Get type-name-based mode for a module type ("perforated"/"tracked"/None)."""
 166    if module_type_name in GPA.pc.get_module_names_to_perforate():
 167        return "perforated"
 168    if module_type_name in GPA.pc.get_module_names_to_track():
 169        return "tracked"
 170    return None
 171
 172
 173def get_parent_module_id(module_id):
 174    """Return the direct parent module id for a dot-id module path."""
 175    parts = module_id.split(".")
 176    if len(parts) <= 2:
 177        return None
 178    return "." + ".".join(parts[1:-1])
 179
 180
 181def get_tied_parameters_map(entries):
 182    """Return a map from module_id to a list of other full param ids sharing memory.
 183
 184    Detects weight tying by comparing data_ptr() across the direct (non-recursive)
 185    parameters of every entry. Only cross-module ties are reported; intra-module
 186    shared params are ignored.
 187    """
 188    ptr_to_params = {}
 189    for entry in entries:
 190        module_id = entry["id"]
 191        for param_name, param in entry["module"].named_parameters(recurse=False):
 192            ptr = param.data_ptr()
 193            if ptr == 0:
 194                continue
 195            full_param_id = module_id + "." + param_name
 196            if ptr not in ptr_to_params:
 197                ptr_to_params[ptr] = []
 198            ptr_to_params[ptr].append((full_param_id, module_id))
 199
 200    tied_map = {}
 201    for param_list in ptr_to_params.values():
 202        if len(param_list) <= 1:
 203            continue
 204        for full_param_id, module_id in param_list:
 205            others = [fp for fp, mid in param_list if mid != module_id]
 206            if others:
 207                if module_id not in tied_map:
 208                    tied_map[module_id] = []
 209                for fp in others:
 210                    if fp not in tied_map[module_id]:
 211                        tied_map[module_id].append(fp)
 212    return tied_map
 213
 214
 215# ---------------------------------------------------------------------------
 216# Block rules
 217# ---------------------------------------------------------------------------
 218def get_block_types(entries):
 219    """Class names of blocks: modules with children that occur more than once."""
 220    counts = {}
 221    for entry in entries:
 222        if entry["has_children"] and not entry["in_replaced"] and not entry["is_replaced_root"]:
 223            counts[entry["type_name"]] = counts.get(entry["type_name"], 0) + 1
 224    return {name for name, count in counts.items() if count > 1}
 225
 226
 227def get_block_instances(entries, block):
 228    """Every live instance of a block, in model order."""
 229    return [
 230        entry
 231        for entry in entries
 232        if entry["type_name"] == block
 233        and entry["has_children"]
 234        and not entry["in_replaced"]
 235        and not entry["is_replaced_root"]
 236    ]
 237
 238
 239def get_block_rule_for_entry(entry, entries_by_id):
 240    """The nearest enclosing block's rule that targets this module, with that block.
 241
 242    Returns (rule, block_instance_id), or (None, None).
 243    """
 244    rules = GPA.pc.get_block_rules()
 245    if not rules:
 246        return None, None
 247    all_ids = set(entries_by_id.keys())
 248    ancestor_id = entry["id"]
 249    while True:
 250        split_at = ancestor_id.rfind(".")
 251        if split_at <= 0:
 252            return None, None
 253        ancestor_id = ancestor_id[:split_at]
 254        ancestor = entries_by_id.get(ancestor_id)
 255        if ancestor is None:
 256            continue
 257        for rule in rules:
 258            if (
 259                rule["block"] == ancestor["type_name"]
 260                and entry["id"] == ancestor_id + rule["path"]
 261            ):
 262                rule_structure = rule.get("structure")
 263                if rule_structure is not None:
 264                    if _instance_structure_from_ids(all_ids, ancestor_id) != rule_structure:
 265                        continue
 266                return rule, ancestor_id
 267
 268
 269def get_instance_structure(entries, instance_id):
 270    """Sorted list of all relative submodule paths under instance_id."""
 271    prefix = instance_id + "."
 272    return sorted(e["id"][len(instance_id):] for e in entries if e["id"].startswith(prefix))
 273
 274
 275def _instance_structure_from_ids(all_ids, instance_id):
 276    """Same as get_instance_structure but works from a set of module ids."""
 277    prefix = instance_id + "."
 278    return sorted(mid[len(instance_id):] for mid in all_ids if mid.startswith(prefix))
 279
 280
 281def get_block_rule_targets(entries, rule):
 282    """Ids of the modules a block rule hits in the CLI's view of the model.
 283
 284    Only includes instances whose full internal structure matches the structure
 285    stored in the rule. Rules without a stored structure (created before this
 286    check was added) apply to all instances that have the path.
 287    """
 288    ids = {entry["id"] for entry in entries}
 289    rule_structure = rule.get("structure")
 290
 291    def _structure_matches(inst_id):
 292        if rule_structure is None:
 293            return True
 294        return _instance_structure_from_ids(ids, inst_id) == rule_structure
 295
 296    return [
 297        entry["id"] + rule["path"]
 298        for entry in get_block_instances(entries, rule["block"])
 299        if entry["id"] + rule["path"] in ids and _structure_matches(entry["id"])
 300    ]
 301
 302
 303def find_block_rule(block, path, structure=None):
 304    """Return the block rule for (block, path), optionally filtered by structure.
 305
 306    When structure is given, return the rule that has that exact structure (or a
 307    rule with no stored structure for backward compat). When structure is None,
 308    return the first matching rule regardless of structure.
 309    """
 310    for rule in GPA.pc.get_block_rules():
 311        if rule["block"] == block and rule["path"] == path:
 312            if structure is None:
 313                return rule
 314            if rule.get("structure") == structure:
 315                return rule
 316    return None
 317
 318
 319def block_rule_python_owned(rule):
 320    return rule in (GPA.pc.get_python_supplied("block_rules") or [])
 321
 322
 323def block_rule_scope_text(entries, rule):
 324    """How many blocks a rule really applies to, and why any are excluded."""
 325    all_instances = get_block_instances(entries, rule["block"])
 326    targets = get_block_rule_targets(entries, rule)
 327    resolved = resolve_entry_modes(entries)
 328    applied = [
 329        target
 330        for target in targets
 331        if resolved[target]["source"] == "block" and resolved[target]["block_rule"] == rule
 332    ]
 333
 334    rule_structure = rule.get("structure")
 335    if rule_structure is not None:
 336        ids = {entry["id"] for entry in entries}
 337        structure_skipped = sum(
 338            1 for inst in all_instances
 339            if _instance_structure_from_ids(ids, inst["id"]) != rule_structure
 340        )
 341        matching_count = len(all_instances) - structure_skipped
 342    else:
 343        structure_skipped = 0
 344        matching_count = len(all_instances)
 345
 346    text = "%d of %d %s modules" % (len(applied), matching_count, rule["block"])
 347    if structure_skipped:
 348        text += f" ({structure_skipped} different-structure {rule['block']}s skipped)"
 349    ignored = len(targets) - len(applied)
 350    if ignored:
 351        text += f", {ignored} ignored: a mode on an enclosing module or set by id wins"
 352    return text
 353
 354
 355def set_block_rule(block, path, mode, entries, template_id=None):
 356    """Set (or toggle off) a block rule; returns a short message."""
 357    structure = get_instance_structure(entries, template_id) if template_id is not None else None
 358    existing = find_block_rule(block, path, structure=structure)
 359    if existing is not None and block_rule_python_owned(existing):
 360        return python_owned_message(f"the {block} {path} block rule", "block_rules")
 361    rules = [
 362        dict(rule)
 363        for rule in GPA.pc.get_block_rules()
 364        if not (
 365            rule["block"] == block
 366            and rule["path"] == path
 367            and rule.get("structure") == structure
 368        )
 369    ]
 370    if existing is not None and existing["mode"] == mode:
 371        GPA.pc.set_block_rules(rules)
 372        return f"removed block rule {block} {path}"
 373    rule = {"block": block, "path": path, "mode": mode}
 374    if structure is not None:
 375        rule["structure"] = structure
 376    rules.append(rule)
 377    GPA.pc.set_block_rules(rules)
 378    return f"{block} {path}: {mode_verb(mode)} ({block_rule_scope_text(entries, rule)})"
 379
 380
 381def remove_block_rule(block, path, entries, template_id=None):
 382    """Remove a block rule; returns a short message."""
 383    structure = get_instance_structure(entries, template_id) if template_id is not None else None
 384    existing = find_block_rule(block, path, structure=structure)
 385    if existing is None:
 386        return f"there is no block rule on {block} {path}"
 387    if block_rule_python_owned(existing):
 388        return python_owned_message(f"the {block} {path} block rule", "block_rules")
 389    scope = block_rule_scope_text(entries, existing)
 390    GPA.pc.set_block_rules(
 391        [dict(rule) for rule in GPA.pc.get_block_rules() if rule != existing]
 392    )
 393    return f"removed block rule {block} {path} ({scope})"
 394
 395
 396def block_mode_refusal(entry, block_types):
 397    """Why block mode can't open on this module, or None if it can."""
 398    if entry["is_replaced_root"] or entry["in_replaced"]:
 399        return (
 400            f"{entry['id']} is inside a module that will be restructured — its "
 401            "structure isn't known until training, so it can't be edited as a block."
 402        )
 403    if entry["type_name"] not in block_types:
 404        if not entry["has_children"]:
 405            return f"{entry['id']} has no submodules, so it is not a block."
 406        return (
 407            f"{entry['type_name']} occurs only once, so it is not a block. "
 408            "Use p/t on its children by id."
 409        )
 410    return None
 411
 412
 413def resolve_entry_modes(entries):
 414    """Resolve every entry's mode, source, and any overridden-by-ancestor state.
 415
 416    Returns a map of module id to a dict with:
 417      - ``eff``:    "perforated" / "tracked" / None
 418      - ``source``: "id" / "type" / "inherited" / None
 419      - ``origin_id``: the id the mode was set on (for inherited rows)
 420      - ``overridden``: {"mode", "source"} when a direct setting here is ignored
 421    """
 422    resolved = {}
 423    by_id = {entry["id"]: entry for entry in entries}
 424    for entry in entries:
 425        module_id = entry["id"]
 426        parent_id = get_parent_module_id(module_id)
 427        parent = resolved.get(parent_id) if parent_id in by_id else None
 428
 429        own_id_mode = get_id_mode(module_id)
 430        block_rule, _block_id = get_block_rule_for_entry(entry, by_id)
 431        own_block_mode = block_rule["mode"] if block_rule is not None else None
 432        own_type_mode = get_name_mode(entry["type_name"])
 433        own_mode = own_id_mode or own_block_mode or own_type_mode
 434        if own_id_mode:
 435            own_source = "id"
 436        elif own_block_mode:
 437            own_source = "block"
 438        else:
 439            own_source = "type" if own_type_mode else None
 440
 441        record = {
 442            "eff": None,
 443            "source": None,
 444            "origin_id": module_id,
 445            "overridden": None,
 446            "block_rule": None,
 447        }
 448        if parent is not None and parent["eff"] is not None:
 449            record["eff"] = parent["eff"]
 450            record["source"] = "inherited"
 451            record["origin_id"] = parent["origin_id"]
 452            if own_mode is not None:
 453                record["overridden"] = {"mode": own_mode, "source": own_source}
 454        elif own_mode is not None:
 455            record["eff"] = own_mode
 456            record["source"] = own_source
 457            record["origin_id"] = module_id
 458            if own_source == "block":
 459                record["block_rule"] = block_rule
 460        resolved[module_id] = record
 461    return resolved
 462
 463
 464# ---------------------------------------------------------------------------
 465# Formatting helpers
 466# ---------------------------------------------------------------------------
 467COLOR_PERFORATE = "00A5A5"
 468COLOR_TRACK = "8A95A0"
 469COLOR_ATTENTION = "FD4D00"
 470COLOR_ACCENT = "D9A441"
 471
 472
 473def get_color_hex_for_mode(mode):
 474    """Map a resolved mode to its color hex value."""
 475    if mode == "perforated":
 476        return COLOR_PERFORATE
 477    if mode == "tracked":
 478        return COLOR_TRACK
 479    return "000000"
 480
 481
 482def format_human_count(value):
 483    """Format integer counts into compact human-readable units (K/M/B)."""
 484    if value < 1000:
 485        return str(value)
 486    if value < 1000000:
 487        scaled = value / 1000.0
 488        text = f"{scaled:.1f}"
 489        return (text[:-2] if text.endswith(".0") else text) + "K"
 490    if value < 1000000000:
 491        scaled = value / 1000000.0
 492        text = f"{scaled:.1f}"
 493        return (text[:-2] if text.endswith(".0") else text) + "M"
 494    scaled = value / 1000000000.0
 495    text = f"{scaled:.1f}"
 496    return (text[:-2] if text.endswith(".0") else text) + "B"
 497
 498
 499def _ansi(text, code):
 500    return f"\x1b[{code}m{text}\x1b[0m"
 501
 502
 503def color_text(text, hex_color):
 504    """Render text in an ANSI truecolor foreground."""
 505    r = int(hex_color[0:2], 16)
 506    g = int(hex_color[2:4], 16)
 507    b = int(hex_color[4:6], 16)
 508    return f"\x1b[38;2;{r};{g};{b}m{text}\x1b[0m"
 509
 510
 511def color_text_on_bg(text, fg_hex, bg_hex):
 512    """Render text with an ANSI truecolor foreground and background."""
 513    fr, fg, fb = int(fg_hex[0:2], 16), int(fg_hex[2:4], 16), int(fg_hex[4:6], 16)
 514    br, bg, bb = int(bg_hex[0:2], 16), int(bg_hex[2:4], 16), int(bg_hex[4:6], 16)
 515    return f"\x1b[38;2;{fr};{fg};{fb}m\x1b[48;2;{br};{bg};{bb}m{text}\x1b[0m"
 516
 517
 518def make_color_square(hex_color):
 519    """Create one colored block character using ANSI truecolor."""
 520    return color_text("█", hex_color)
 521
 522
 523def dim(text):
 524    """Render text dimmed."""
 525    return _ansi(text, "90")
 526
 527
 528def make_inverted_text(text):
 529    """Render text with inverted foreground/background colors."""
 530    return f"\x1b[7m{text}\x1b[0m"
 531
 532
 533ANSI_ESCAPE_RE = re.compile(r"\x1b\[[0-9;]*m")
 534
 535
 536def strip_ansi(text):
 537    """Remove ANSI color/style escape codes for width calculation."""
 538    return ANSI_ESCAPE_RE.sub("", text)
 539
 540
 541def get_visual_line_count(lines, terminal_columns):
 542    """Count rendered terminal rows, including wrapped long lines."""
 543    if terminal_columns < 1:
 544        return len(lines)
 545    total = 0
 546    for line in lines:
 547        plain = strip_ansi(line)
 548        if len(plain) == 0:
 549            total += 1
 550            continue
 551        total += (len(plain) + terminal_columns - 1) // terminal_columns
 552    return total
 553
 554
 555def wrap_ansi_line_on_words(line, terminal_columns):
 556    """Wrap one ANSI-colored line on word boundaries for terminal display."""
 557    if terminal_columns < 1:
 558        return [line]
 559
 560    plain = strip_ansi(line)
 561    if len(plain) <= terminal_columns:
 562        return [line]
 563
 564    visible_to_raw = []
 565    raw_index = 0
 566    while raw_index < len(line):
 567        if line[raw_index] == "\x1b":
 568            match = ANSI_ESCAPE_RE.match(line, raw_index)
 569            if match is not None:
 570                raw_index = match.end()
 571                continue
 572        visible_to_raw.append(raw_index)
 573        raw_index += 1
 574
 575    if len(visible_to_raw) == 0:
 576        return [line]
 577
 578    wrapped = []
 579    start = 0
 580    visible_len = len(plain)
 581    while start < visible_len:
 582        while start < visible_len and plain[start] == " ":
 583            start += 1
 584        if start >= visible_len:
 585            break
 586
 587        max_end = min(visible_len, start + terminal_columns)
 588        if max_end == visible_len:
 589            end = visible_len
 590        else:
 591            split_at = plain.rfind(" ", start, max_end)
 592            end = split_at if split_at > start else max_end
 593
 594        raw_start = visible_to_raw[start]
 595        raw_end = len(line) if end >= visible_len else visible_to_raw[end]
 596        wrapped.append(line[raw_start:raw_end].rstrip())
 597
 598        if end < visible_len and plain[end] == " ":
 599            start = end + 1
 600        else:
 601            start = end
 602
 603    return wrapped if wrapped else [line]
 604
 605
 606def wrap_screen_text_for_terminal(screen_text):
 607    """Wrap full screen text to terminal width without mid-word breaks."""
 608    terminal_columns = shutil.get_terminal_size(fallback=(120, 40)).columns
 609    wrapped_lines = []
 610    for raw_line in screen_text.split("\n"):
 611        wrapped_lines.extend(wrap_ansi_line_on_words(raw_line, terminal_columns))
 612    return "\n".join(wrapped_lines)
 613
 614
 615def render_text_with_cursor(text, cursor_index):
 616    """Render text with a CLI-style inverted-character cursor."""
 617    if cursor_index < 0:
 618        cursor_index = 0
 619    if cursor_index > len(text):
 620        cursor_index = len(text)
 621    if cursor_index == len(text):
 622        return text + make_inverted_text(" ")
 623    current_char = text[cursor_index]
 624    return (
 625        text[:cursor_index]
 626        + make_inverted_text(current_char)
 627        + text[cursor_index + 1 :]
 628    )
 629
 630
 631# ---------------------------------------------------------------------------
 632# Key token predicates
 633# ---------------------------------------------------------------------------
 634def is_up_key(key):
 635    if key in ("k",):
 636        return True
 637    if not key.startswith("\x1b"):
 638        return False
 639    return key in ("\x1b[A", "\x1bOA") or (key.startswith("\x1b[") and key.endswith("A"))
 640
 641
 642def is_down_key(key):
 643    if key in ("j",):
 644        return True
 645    if not key.startswith("\x1b"):
 646        return False
 647    return key in ("\x1b[B", "\x1bOB") or (key.startswith("\x1b[") and key.endswith("B"))
 648
 649
 650def is_left_key(key):
 651    if not key.startswith("\x1b"):
 652        return False
 653    return key in ("\x1b[D", "\x1bOD") or (key.startswith("\x1b[") and key.endswith("D"))
 654
 655
 656def is_right_key(key):
 657    if not key.startswith("\x1b"):
 658        return False
 659    return key in ("\x1b[C", "\x1bOC") or (key.startswith("\x1b[") and key.endswith("C"))
 660
 661
 662def is_page_up_key(key):
 663    if key in ("K",):
 664        return True
 665    if key == "\x1b[1;2A":
 666        # Shift+Up (laptop-friendly alias; no PgUp key without Fn).
 667        return True
 668    return key == "\x1b[5~" or (key.startswith("\x1b[") and "[5" in key and key.endswith("~"))
 669
 670
 671def is_page_down_key(key):
 672    if key in ("J",):
 673        return True
 674    if key == "\x1b[1;2B":
 675        # Shift+Down (laptop-friendly alias; no PgDn key without Fn).
 676        return True
 677    return key == "\x1b[6~" or (key.startswith("\x1b[") and "[6" in key and key.endswith("~"))
 678
 679
 680def is_delete_key(key):
 681    return key == "\x1b[3~" or (key.startswith("\x1b[") and "[3" in key and key.endswith("~"))
 682
 683
 684def is_enter_key(key):
 685    return key in ("\r", "\n")
 686
 687
 688def is_tab_key(key):
 689    return key == "\t"
 690
 691
 692def is_select_key(key):
 693    """Space/Enter — used only inside the inline value editors."""
 694    return key in (" ", "\r", "\n")
 695
 696
 697def is_depth_key(key):
 698    return key in tuple("0123456789")
 699
 700
 701# ---------------------------------------------------------------------------
 702# Targets tree collapse/expand
 703# ---------------------------------------------------------------------------
 704def entry_default_expanded(entry, depth_baseline):
 705    """Whether an entry's children show when there is no explicit manual
 706    override for it.
 707
 708    ``depth_baseline`` is None before any digit key has been pressed this
 709    session (only replaced-root containers start collapsed); otherwise it's
 710    the last digit (0-9) pressed: 0 expands everything, N in 1-9 shows
 711    through depth N-1 and collapses anything deeper.
 712    """
 713    if depth_baseline is None:
 714        return not entry["is_replaced_root"]
 715    if depth_baseline == 0:
 716        return True
 717    return entry["depth"] < depth_baseline - 1
 718
 719
 720def is_entry_expanded(entry, depth_baseline, expanded_overrides):
 721    """Effective expand state: a manual ←/→ override, else the baseline."""
 722    if entry["id"] in expanded_overrides:
 723        return expanded_overrides[entry["id"]]
 724    return entry_default_expanded(entry, depth_baseline)
 725
 726
 727def is_entry_visible(entry, entries_by_id, depth_baseline, expanded_overrides):
 728    """False if any ancestor of ``entry`` is currently collapsed."""
 729    ancestor_id = entry["id"]
 730    while True:
 731        split_at = ancestor_id.rfind(".")
 732        if split_at <= 0:
 733            return True
 734        ancestor_id = ancestor_id[:split_at]
 735        ancestor = entries_by_id.get(ancestor_id)
 736        if (
 737            ancestor is not None
 738            and ancestor["has_children"]
 739            and not is_entry_expanded(ancestor, depth_baseline, expanded_overrides)
 740        ):
 741            return False
 742
 743
 744# ---------------------------------------------------------------------------
 745# Mode setters
 746# ---------------------------------------------------------------------------
 747def _clear_tracked_params_for_module_id(module_id):
 748    """Remove parameter_ids_to_track entries that belong directly to this module."""
 749    prefix = module_id + "."
 750    current = GPA.pc.get_parameter_ids_to_track()
 751    kept = GPA.pc.get_python_supplied("parameter_ids_to_track") or []
 752    updated = [p for p in current if p in kept or not p.startswith(prefix)]
 753    if len(updated) != len(current):
 754        GPA.pc.set_parameter_ids_to_track(updated)
 755
 756
 757def set_module_id_mode(module_id, mode):
 758    """Set (or toggle off) an id-based mode, enforcing id-list exclusivity."""
 759    ids_perforate = dedupe_list(GPA.pc.get_module_ids_to_perforate())
 760    ids_track = dedupe_list(GPA.pc.get_module_ids_to_track())
 761
 762    if mode == "perforated":
 763        if module_id in ids_perforate:
 764            ids_perforate = [value for value in ids_perforate if value != module_id]
 765        else:
 766            ids_perforate.append(module_id)
 767            ids_track = [value for value in ids_track if value != module_id]
 768            _clear_tracked_params_for_module_id(module_id)
 769    elif mode == "tracked":
 770        if module_id in ids_track:
 771            ids_track = [value for value in ids_track if value != module_id]
 772        else:
 773            ids_track.append(module_id)
 774            ids_perforate = [value for value in ids_perforate if value != module_id]
 775            _clear_tracked_params_for_module_id(module_id)
 776
 777    GPA.pc.set_module_ids_to_perforate(ids_perforate)
 778    GPA.pc.set_module_ids_to_track(ids_track)
 779
 780
 781def set_module_name_mode(module_type_name, mode, entries=None):
 782    """Set (or toggle off) a type-name-based mode, enforcing name-list exclusivity."""
 783    names_perforate = dedupe_list(GPA.pc.get_module_names_to_perforate())
 784    names_track = dedupe_list(GPA.pc.get_module_names_to_track())
 785
 786    if mode == "perforated":
 787        if module_type_name in names_perforate:
 788            names_perforate = [v for v in names_perforate if v != module_type_name]
 789        else:
 790            names_perforate.append(module_type_name)
 791            names_track = [v for v in names_track if v != module_type_name]
 792            if entries is not None:
 793                for entry in entries:
 794                    if entry["type_name"] == module_type_name:
 795                        _clear_tracked_params_for_module_id(entry["id"])
 796    elif mode == "tracked":
 797        if module_type_name in names_track:
 798            names_track = [v for v in names_track if v != module_type_name]
 799        else:
 800            names_track.append(module_type_name)
 801            names_perforate = [v for v in names_perforate if v != module_type_name]
 802            if entries is not None:
 803                for entry in entries:
 804                    if entry["type_name"] == module_type_name:
 805                        _clear_tracked_params_for_module_id(entry["id"])
 806
 807    GPA.pc.set_module_names_to_perforate(names_perforate)
 808    GPA.pc.set_module_names_to_track(names_track)
 809
 810
 811# ---------------------------------------------------------------------------
 812# Fused pairs
 813# ---------------------------------------------------------------------------
 814def get_fused_pair_map():
 815    """Map each fused module id to its role and partner: id -> (role, partner_id)."""
 816    fused = {}
 817    for head_id, norm_id in GPA.pc.get_modules_to_fuse():
 818        fused[head_id] = ("head", norm_id)
 819        fused[norm_id] = ("norm", head_id)
 820    return fused
 821
 822
 823def unfuse_pair(module_id, entries):
 824    """Remove the pair containing this module and track both of its modules."""
 825    pairs = [list(pair) for pair in GPA.pc.get_modules_to_fuse()]
 826    pair = next(p for p in pairs if module_id in p)
 827    if pair in (GPA.pc.get_python_supplied("modules_to_fuse") or []):
 828        return (
 829            f"{pair[0]} + {pair[1]} is fused by a Python call (modules_to_fuse) — "
 830            "change it in your script; the CLI can't override it."
 831        )
 832    GPA.pc.set_modules_to_fuse([p for p in pairs if p != pair])
 833    by_id = {entry["id"]: entry for entry in entries}
 834    for member_id in pair:
 835        entry = by_id.get(member_id)
 836        if entry is None or not entry["trainable"] or id_python_owner(member_id):
 837            continue
 838        if member_id not in GPA.pc.get_module_ids_to_track():
 839            set_module_id_mode(member_id, "tracked")
 840    return f"un-fused {pair[0]} + {pair[1]}; both are now tracked"
 841
 842
 843def stage_as_fuse_head(entry):
 844    """Validate that a module can be the head of a fused pair.
 845
 846    Returns (module_id, message) on success or (None, message) on failure.
 847    """
 848    if entry["is_replaced_root"] or entry["in_replaced"]:
 849        return None, (
 850            f"{entry['id']} is inside a module that will be restructured — its id "
 851            "won't exist at training time, so it can't be fused."
 852        )
 853    if not entry["trainable"]:
 854        return None, (
 855            f"{entry['id']} is not trainable, so it can't be the head of a fused pair."
 856        )
 857    if entry["id"] in get_fused_pair_map():
 858        return None, f"{entry['id']} is already fused."
 859    return entry["id"], (
 860        f"↓ {entry['id']} staged as head (runs first) — navigate to the norm and press f"
 861    )
 862
 863
 864def fuse_pair(head_entry, norm_entry, entries, resolved):
 865    """Fuse head_entry with norm_entry.
 866
 867    Returns a short message describing what happened or why nothing did.
 868    """
 869    head_id = head_entry["id"]
 870    norm_id = norm_entry["id"]
 871    if head_id == norm_id:
 872        return "Select two different modules to form a fused pair."
 873    if any(e["is_replaced_root"] or e["in_replaced"] for e in (head_entry, norm_entry)):
 874        return (
 875            "One of the selected modules is inside a module that will be restructured "
 876            "— its id won't exist at training time, so it can't be fused."
 877        )
 878    if not head_entry["trainable"]:
 879        return (
 880            f"{head_id} is not trainable, so it can't be the head of a fused pair. "
 881            "Stage a trainable module as the head first."
 882        )
 883    fused = get_fused_pair_map()
 884    for module_id in (head_id, norm_id):
 885        if module_id in fused:
 886            return f"{module_id} is already fused with {fused[module_id][1]}."
 887        for other_id in fused:
 888            if other_id.startswith(module_id + ".") or module_id.startswith(other_id + "."):
 889                return f"{module_id} overlaps {other_id}, which is already fused."
 890    module_counts = {}
 891    for e in entries:
 892        module_counts[id(e["module"])] = module_counts.get(id(e["module"]), 0) + 1
 893    for e in (head_entry, norm_entry):
 894        if module_counts[id(e["module"])] > 1:
 895            return f"{e['id']} is used in more than one place, so it can't be fused."
 896    if id_python_owner(head_id) == "module_ids_to_track":
 897        return python_owned_message(head_id, "module_ids_to_track")
 898    if resolved[head_id]["source"] == "inherited":
 899        return (
 900            f"{head_id} gets its mode from {resolved[head_id]['origin_id']}; "
 901            "clear that first so the head can be perforated on its own."
 902        )
 903    pairs = [list(pair) for pair in GPA.pc.get_modules_to_fuse()]
 904    pairs.append([head_id, norm_id])
 905    GPA.pc.set_modules_to_fuse(pairs)
 906    if head_id not in GPA.pc.get_module_ids_to_perforate():
 907        set_module_id_mode(head_id, "perforated")
 908    return f"fused {head_id} (head) with {norm_id} (norm); head is perforated"
 909
 910
 911def _is_norm_type(type_name):
 912    """True for BatchNorm*, LayerNorm, GroupNorm, InstanceNorm*, SyncBatchNorm, etc."""
 913    return "norm" in type_name.lower()
 914
 915
 916_NORM_DIRECT_WARNING = (
 917    "⚠ norm layers work best fused (f) with their head, "
 918    "or targeted via their parent — direct p/t may reduce effectiveness"
 919)
 920
 921
 922def set_all_types_to_tracking(entries):
 923    """Reset every module to tracked: clear id/type perforate marks, then
 924    track every type that owns parameters directly. A quick way to start from
 925    "track everything" before manually perforating the head/last layer.
 926    """
 927    GPA.pc.set_module_ids_to_perforate(
 928        GPA.pc.get_python_supplied("module_ids_to_perforate") or []
 929    )
 930    GPA.pc.set_module_names_to_perforate(
 931        GPA.pc.get_python_supplied("module_names_to_perforate") or []
 932    )
 933    # Only types that own parameters directly. Tracking a container would apply
 934    # to everything inside it and make ids and block rules there unreachable.
 935    all_type_names = dedupe_list(
 936        entry["type_name"] for entry in entries if entry["direct_param_count"] > 0
 937    )
 938    GPA.pc.set_module_names_to_track(all_type_names)
 939
 940
 941def _would_auto_track_params(entry, entries, resolved):
 942    """True if this module's direct params qualify for auto-tracking.
 943
 944    Conditions: has direct params, no module mode, and every descendant
 945    module that has direct params already has a resolved mode.
 946    """
 947    if entry["direct_param_count"] <= 0 or resolved[entry["id"]]["eff"] is not None:
 948        return False
 949    module_id = entry["id"]
 950    descendants_with_params = [
 951        e for e in entries
 952        if e["id"].startswith(module_id + ".") and e["direct_param_count"] > 0
 953    ]
 954    if not descendants_with_params:
 955        return False  # leaf modules must be explicitly assigned a mode
 956    return all(
 957        resolved[desc["id"]]["eff"] is not None or _would_auto_track_params(desc, entries, resolved)
 958        for desc in descendants_with_params
 959    )
 960
 961
 962def auto_track_unset_direct_params(entries, resolved):
 963    """Auto-track direct params for modules whose all child-module params are covered."""
 964    param_ids = list(GPA.pc.get_parameter_ids_to_track())
 965    changed = False
 966
 967    for entry in entries:
 968        if entry["in_replaced"] or entry["is_replaced_root"]:
 969            continue
 970        if not _would_auto_track_params(entry, entries, resolved):
 971            continue
 972        module_id = entry["id"]
 973        for param_name, _ in entry["module"].named_parameters(recurse=False):
 974            param_id = module_id + "." + param_name
 975            if param_id not in param_ids:
 976                param_ids.append(param_id)
 977                changed = True
 978
 979    if changed:
 980        GPA.pc.set_parameter_ids_to_track(param_ids)
 981
 982
 983def clear_module_mode(entry):
 984    """Clear a direct id rule on this module; if none, clear its type rule.
 985
 986    Returns a short human message describing what was cleared.
 987    """
 988    module_id = entry["id"]
 989    type_name = entry["type_name"]
 990
 991    ids_perforate = [v for v in GPA.pc.get_module_ids_to_perforate() if v != module_id]
 992    ids_track = [v for v in GPA.pc.get_module_ids_to_track() if v != module_id]
 993    if (
 994        module_id in GPA.pc.get_module_ids_to_perforate()
 995        or module_id in GPA.pc.get_module_ids_to_track()
 996    ):
 997        owner = id_python_owner(module_id)
 998        if owner:
 999            return python_owned_message(module_id, owner)
1000        GPA.pc.set_module_ids_to_perforate(ids_perforate)
1001        GPA.pc.set_module_ids_to_track(ids_track)
1002        return f"cleared {module_id}"
1003
1004    if (
1005        type_name in GPA.pc.get_module_names_to_perforate()
1006        or type_name in GPA.pc.get_module_names_to_track()
1007    ):
1008        owner = type_python_owner(type_name)
1009        if owner:
1010            return python_owned_message(f"the {type_name} type rule", owner)
1011        GPA.pc.set_module_names_to_perforate(
1012            [v for v in GPA.pc.get_module_names_to_perforate() if v != type_name]
1013        )
1014        GPA.pc.set_module_names_to_track(
1015            [v for v in GPA.pc.get_module_names_to_track() if v != type_name]
1016        )
1017        return f"cleared the {type_name} type rule"
1018
1019    return "nothing to clear on this module"
1020
1021
1022# ---------------------------------------------------------------------------
1023# Type rules / budget / attention
1024# ---------------------------------------------------------------------------
1025def type_rule_entries(entries):
1026    """Active type-name rules as (type_name, mode, live count) tuples."""
1027    counts = {}
1028    for entry in entries:
1029        if entry["in_replaced"]:
1030            continue
1031        counts[entry["type_name"]] = counts.get(entry["type_name"], 0) + 1
1032
1033    rules = []
1034    for type_name in sorted(GPA.pc.get_module_names_to_perforate()):
1035        rules.append((type_name, "perforated", counts.get(type_name, 0)))
1036    for type_name in sorted(GPA.pc.get_module_names_to_track()):
1037        rules.append((type_name, "tracked", counts.get(type_name, 0)))
1038    return rules
1039
1040
1041def unset_module_entries(entries, resolved):
1042    """Entries that own parameters, have no resolved mode, and are not auto-trackable."""
1043    unset = []
1044    fused = get_fused_pair_map()
1045    for entry in entries:
1046        if entry["in_replaced"] or entry["is_replaced_root"]:
1047            continue
1048        if entry["direct_param_count"] <= 0:
1049            continue
1050        if fused.get(entry["id"], (None,))[0] == "norm":
1051            continue
1052        if resolved[entry["id"]]["eff"] is None:
1053            if not _would_auto_track_params(entry, entries, resolved):
1054                unset.append(entry)
1055    return unset
1056
1057
1058def build_budget_line(entries, resolved):
1059    """The perforation-budget line: parameter cost of the current selection."""
1060    added = 0
1061    total_model_params = 0
1062    seen_added = set()
1063    seen_total = set()
1064    fused = get_fused_pair_map()
1065
1066    for entry in entries:
1067        for _name, parameter in entry["module"].named_parameters(recurse=False):
1068            pid = id(parameter)
1069            if pid not in seen_total:
1070                seen_total.add(pid)
1071                total_model_params += parameter.numel()
1072
1073        fused_role = fused.get(entry["id"])
1074        norm_of_perforated_head = (
1075            fused_role is not None
1076            and fused_role[0] == "norm"
1077            and resolved[fused_role[1]]["eff"] == "perforated"
1078        )
1079        if norm_of_perforated_head or (
1080            resolved[entry["id"]]["eff"] == "perforated" and entry["trainable"]
1081        ):
1082            for _name, parameter in entry["module"].named_parameters(recurse=False):
1083                pid = id(parameter)
1084                if pid not in seen_added:
1085                    seen_added.add(pid)
1086                    added += parameter.numel()
1087
1088    pct = (100.0 * added / total_model_params) if total_model_params else 0.0
1089    return (
1090        f"Perforation budget:  +{format_human_count(added)} params per dendrite cycle"
1091        f"  ·  model {format_human_count(total_model_params)}"
1092        f"  (+{pct:.1f}% / cycle)"
1093    )
1094
1095
1096# ---------------------------------------------------------------------------
1097# Run settings metadata
1098# ---------------------------------------------------------------------------
1099RUNTIME_ONLY_CONFIG_KEYS = {"config_file"}
1100
1101DESCRIPTION_FILE_NAME = "configuration_descriptions.json"
1102DESCRIPTION_CACHE = None
1103
1104LABEL_IMPACTFUL = "impactful"
1105LABEL_SUPPORTING = "supporting"
1106
1107
1108def _normalize_label(label_text):
1109    """Normalize a label to one of the two tiers: impactful / supporting."""
1110    if not isinstance(label_text, str):
1111        return LABEL_SUPPORTING
1112    compact = " ".join(label_text.strip().split()).lower()
1113    if compact in ("impactful", "impactful hyperparameters"):
1114        return LABEL_IMPACTFUL
1115    return LABEL_SUPPORTING
1116
1117
1118def load_description_data():
1119    """Load bucket and setting metadata from local JSON."""
1120    global DESCRIPTION_CACHE
1121    if DESCRIPTION_CACHE is not None:
1122        return DESCRIPTION_CACHE
1123
1124    description_file = os.path.join(os.path.dirname(__file__), DESCRIPTION_FILE_NAME)
1125    payload = {}
1126    try:
1127        with open(description_file, "r") as file_handle:
1128            payload = json.load(file_handle)
1129    except Exception:
1130        payload = {}
1131
1132    bucket_entries = payload.get("buckets", {})
1133    bucket_descriptions = {}
1134    setting_descriptions = {}
1135    setting_labels = {}
1136    setting_to_bucket = {}
1137    settings_by_bucket = {}
1138    bucket_order = []
1139
1140    if isinstance(bucket_entries, dict):
1141        for bucket_name, bucket_payload in bucket_entries.items():
1142            bucket_order.append(bucket_name)
1143            if isinstance(bucket_payload, dict):
1144                bucket_descriptions[bucket_name] = bucket_payload.get("description", "")
1145                bucket_settings = bucket_payload.get("settings", {})
1146                ordered_setting_names = []
1147                if isinstance(bucket_settings, dict):
1148                    for setting_name, setting_payload in bucket_settings.items():
1149                        ordered_setting_names.append(setting_name)
1150                        setting_to_bucket[setting_name] = bucket_name
1151                        if isinstance(setting_payload, dict):
1152                            setting_descriptions[setting_name] = setting_payload.get(
1153                                "description", ""
1154                            )
1155                            setting_labels[setting_name] = _normalize_label(
1156                                setting_payload.get("label")
1157                            )
1158                        elif isinstance(setting_payload, str):
1159                            setting_descriptions[setting_name] = setting_payload
1160                            setting_labels[setting_name] = LABEL_SUPPORTING
1161                settings_by_bucket[bucket_name] = ordered_setting_names
1162            elif isinstance(bucket_payload, str):
1163                bucket_descriptions[bucket_name] = bucket_payload
1164
1165    DESCRIPTION_CACHE = {
1166        "buckets": bucket_descriptions,
1167        "bucket_order": bucket_order,
1168        "settings": setting_descriptions,
1169        "setting_labels": setting_labels,
1170        "setting_to_bucket": setting_to_bucket,
1171        "settings_by_bucket": settings_by_bucket,
1172    }
1173    return DESCRIPTION_CACHE
1174
1175
1176def get_setting_label(setting_name):
1177    """Get the tier (impactful / supporting) for one setting."""
1178    setting_labels = load_description_data().get("setting_labels", {})
1179    if setting_name in setting_labels:
1180        return _normalize_label(setting_labels[setting_name])
1181    return LABEL_SUPPORTING
1182
1183
1184def format_setting_value(value):
1185    """Format setting values for compact configuration screen display."""
1186    if value is None:
1187        return "None"
1188    if callable(value):
1189        text = GPA.callable_config_repr(value)
1190    else:
1191        text = str(value)
1192    if len(text) > 140:
1193        return text[:137] + "..."
1194    return text
1195
1196
1197SWITCH_MODE_NAMES = [
1198    "DOING_SWITCH_EVERY_TIME",
1199    "DOING_HISTORY",
1200    "DOING_FIXED_SWITCH",
1201    "DOING_NO_SWITCH",
1202]
1203FORWARD_FUNCTION_NAMES = ["relu", "tanh", "sigmoid"]
1204
1205
1206def _switch_mode_values():
1207    return [
1208        GPA.pc.DOING_SWITCH_EVERY_TIME,
1209        GPA.pc.DOING_HISTORY,
1210        GPA.pc.DOING_FIXED_SWITCH,
1211        GPA.pc.DOING_NO_SWITCH,
1212    ]
1213
1214
1215def get_enum_options(setting_name):
1216    """Return the ordered set of values for an enum-like setting, else None."""
1217    if setting_name == "switch_mode":
1218        return list(_switch_mode_values())
1219    if setting_name == "pai_forward_function":
1220        return list(FORWARD_FUNCTION_NAMES)
1221    return None
1222
1223
1224def format_run_setting_value(setting_name, value):
1225    """Display string for a run setting, naming enum values."""
1226    if setting_name == "switch_mode":
1227        try:
1228            return SWITCH_MODE_NAMES[list(_switch_mode_values()).index(value)]
1229        except (ValueError, IndexError):
1230            return str(value)
1231    if setting_name == "pai_forward_function":
1232        name = getattr(value, "__name__", None)
1233        if name in FORWARD_FUNCTION_NAMES:
1234            return name
1235        return format_setting_value(value)
1236    return format_setting_value(value)
1237
1238
1239def cycle_enum_setting(setting_name, current_value):
1240    """Compute and apply the next value for an enum setting."""
1241    options = get_enum_options(setting_name)
1242    if not options:
1243        return False, f"{setting_name} is not an enum setting."
1244
1245    if setting_name == "pai_forward_function":
1246        current_name = getattr(current_value, "__name__", None)
1247        index = options.index(current_name) if current_name in options else -1
1248        next_name = options[(index + 1) % len(options)]
1249        next_value = getattr(torch, next_name) if torch is not None else next_name
1250        return apply_setting_value(setting_name, next_value)
1251
1252    index = options.index(current_value) if current_value in options else -1
1253    next_value = options[(index + 1) % len(options)]
1254    return apply_setting_value(setting_name, next_value)
1255
1256
1257def get_global_setting_value(setting_name):
1258    """Read one setting value from the global config object."""
1259    getter = getattr(GPA.pc, f"get_{setting_name}", None)
1260    if getter is not None:
1261        try:
1262            return getter()
1263        except Exception:
1264            return "<unavailable>"
1265    if hasattr(GPA.pc, setting_name) and not callable(getattr(GPA.pc, setting_name)):
1266        return getattr(GPA.pc, setting_name)
1267    return "<unavailable>"
1268
1269
1270def apply_setting_value(setting_name, value):
1271    """Apply one setting value through a setter when available."""
1272    setter = getattr(GPA.pc, f"set_{setting_name}", None)
1273    if setter is not None:
1274        setter(value)
1275        return True, ""
1276    if hasattr(GPA.pc, setting_name) and not callable(getattr(GPA.pc, setting_name)):
1277        setattr(GPA.pc, setting_name, value)
1278        return True, ""
1279    return False, f"Setting {setting_name} is not editable."
1280
1281
1282def parse_value_from_text(text, sample_value):
1283    """Parse user text into the same type as a sample value where possible."""
1284    if isinstance(sample_value, bool):
1285        lowered = text.strip().lower()
1286        if lowered in ("1", "true", "t", "yes", "y", "on"):
1287            return True
1288        if lowered in ("0", "false", "f", "no", "n", "off"):
1289            return False
1290        raise ValueError("Expected boolean value (true/false).")
1291    if isinstance(sample_value, int) and not isinstance(sample_value, bool):
1292        return int(text.strip())
1293    if isinstance(sample_value, float):
1294        return float(text.strip())
1295    return text
1296
1297
1298def get_all_global_parameters():
1299    """Collect JSON-declared run settings as name -> current value."""
1300    description_data = load_description_data()
1301    visible_names = []
1302    for bucket_name in description_data.get("bucket_order", []):
1303        visible_names.extend(
1304            description_data.get("settings_by_bucket", {}).get(bucket_name, [])
1305        )
1306    values = {}
1307    for setting_name in visible_names:
1308        if setting_name in RUNTIME_ONLY_CONFIG_KEYS:
1309            continue
1310        values[setting_name] = get_global_setting_value(setting_name)
1311    return values
1312
1313
1314def build_run_items(expanded_buckets):
1315    """Build the Run settings list: bucket rows, tier-sorted settings, dividers."""
1316    values = get_all_global_parameters()
1317    description_data = load_description_data()
1318    items = []
1319
1320    for bucket_name in description_data.get("bucket_order", []):
1321        names = [
1322            name
1323            for name in description_data.get("settings_by_bucket", {}).get(bucket_name, [])
1324            if name not in RUNTIME_ONLY_CONFIG_KEYS
1325        ]
1326        if not names:
1327            continue
1328
1329        is_expanded = expanded_buckets.get(bucket_name, False)
1330        items.append(
1331            {
1332                "type": "bucket",
1333                "bucket": bucket_name,
1334                "is_expanded": is_expanded,
1335                "count": len(names),
1336            }
1337        )
1338        if not is_expanded:
1339            continue
1340
1341        impactful = [n for n in names if get_setting_label(n) == LABEL_IMPACTFUL]
1342        supporting = [n for n in names if get_setting_label(n) != LABEL_IMPACTFUL]
1343
1344        def _setting_item(setting_name):
1345            return {
1346                "type": "setting",
1347                "bucket": bucket_name,
1348                "name": setting_name,
1349                "value": values.get(setting_name, "<unavailable>"),
1350            }
1351
1352        for setting_name in impactful:
1353            items.append(_setting_item(setting_name))
1354        if impactful and supporting:
1355            items.append({"type": "divider", "bucket": bucket_name})
1356        for setting_name in supporting:
1357            items.append(_setting_item(setting_name))
1358
1359    return items
1360
1361
1362# ---------------------------------------------------------------------------
1363# Overrides (per-target settings)
1364# ---------------------------------------------------------------------------
1365def load_existing_module_settings():
1366    """Load existing module_settings from local config sources."""
1367    merged = {}
1368    source_paths = []
1369    config_file = GPA.pc.get_config_file()
1370    run_config = GPA.pc.get_run_config_path()
1371    if config_file:
1372        source_paths.append(config_file)
1373    if run_config:
1374        source_paths.append(run_config)
1375
1376    for source_path in source_paths:
1377        if not source_path or not os.path.exists(source_path):
1378            continue
1379        try:
1380            with open(source_path, "r") as file_handle:
1381                payload = json.load(file_handle)
1382            module_settings = payload.get("module_settings", {})
1383            for scope_key, values in module_settings.items():
1384                if isinstance(values, dict):
1385                    merged[scope_key] = dict(values)
1386        except Exception:
1387            continue
1388    return merged
1389
1390
1391def get_scope_values(scope_key, module_settings_overrides, existing_module_settings):
1392    """Merged override values for one scope: saved data plus in-session edits."""
1393    values = {}
1394    if scope_key in existing_module_settings:
1395        values.update(existing_module_settings[scope_key])
1396    if scope_key in module_settings_overrides:
1397        values.update(module_settings_overrides[scope_key])
1398    return values
1399
1400
1401def set_module_scoped_value(module_settings_overrides, scope_key, setting_name, value):
1402    """Write one override value into in-session state."""
1403    module_settings_overrides.setdefault(scope_key, {})[setting_name] = value
1404
1405
1406def get_override_scope_for_entry(entry, resolved):
1407    """Determine the override scope for a target, or a reason it is blocked."""
1408    record = resolved[entry["id"]]
1409    if entry["is_replaced_root"] or entry["in_replaced"]:
1410        return None, (
1411            "Overrides are not available inside a module that will be restructured."
1412        )
1413    if record["eff"] is None:
1414        return None, (
1415            "Overrides are only for perforated modules. Perforate this one first "
1416            "(p), or track it if you just want it monitored."
1417        )
1418    if record["source"] == "inherited":
1419        origin = record["origin_id"]
1420        return None, (
1421            f"This module inherits {origin}'s mode. Open overrides on {origin} to "
1422            "change settings for the whole subtree."
1423        )
1424    if record["eff"] != "perforated":
1425        return None, "Overrides are only for perforated modules — this one is tracked."
1426
1427    if record["source"] == "type":
1428        return (
1429            {"kind": "type", "scope_key": entry["type_name"]},
1430            None,
1431        )
1432    return ({"kind": "id", "scope_key": entry["id"]}, None)
1433
1434
1435def persist_module_settings_updates(module_settings_overrides, overwrite_config_file=False):
1436    """Persist in-session module_settings updates to local config JSON files."""
1437    if not module_settings_overrides:
1438        return
1439
1440    destinations = []
1441    run_config = GPA.pc.get_run_config_path()
1442    if run_config:
1443        destinations.append(run_config)
1444    if overwrite_config_file:
1445        config_file = GPA.pc.get_config_file()
1446        if config_file and config_file not in destinations:
1447            destinations.append(config_file)
1448
1449    for destination in destinations:
1450        payload = {}
1451        if os.path.exists(destination):
1452            try:
1453                with open(destination, "r") as file_handle:
1454                    payload = json.load(file_handle)
1455            except Exception:
1456                payload = {}
1457
1458        module_settings = payload.get("module_settings", {})
1459        if not isinstance(module_settings, dict):
1460            module_settings = {}
1461        for scope_key, values in module_settings_overrides.items():
1462            existing = module_settings.get(scope_key, {})
1463            if not isinstance(existing, dict):
1464                existing = {}
1465            existing.update(values)
1466            module_settings[scope_key] = existing
1467        payload["module_settings"] = module_settings
1468
1469        directory = os.path.dirname(destination)
1470        if directory:
1471            os.makedirs(directory, exist_ok=True)
1472        with open(destination, "w") as file_handle:
1473            json.dump(payload, file_handle, indent=2)
1474
1475
1476CUSTOMIZABLE_SETTING_NAMES = list(GPA.PAIConfig._CUSTOMIZABLE.keys())
1477
1478
1479def get_setting_description(setting_name):
1480    """Help text for one setting."""
1481    descriptions = load_description_data().get("settings", {})
1482    return descriptions.get(setting_name, f"No description available for {setting_name}.")
1483
1484
1485def get_bucket_description(bucket_name):
1486    descriptions = load_description_data().get("buckets", {})
1487    return descriptions.get(bucket_name, "No description available.")
1488
1489
1490# ---------------------------------------------------------------------------
1491# Rendering
1492# ---------------------------------------------------------------------------
1493HR = "  " + "─" * 70
1494
1495
1496def terminal_size():
1497    return shutil.get_terminal_size(fallback=(120, 40))
1498
1499
1500def render_tab_bar(active_screen):
1501    """The `[ Targets | Run settings ]` tab bar with the active screen lit."""
1502    targets = "Targets"
1503    run = "Run settings"
1504    if active_screen == "targets":
1505        targets = color_text(targets, COLOR_ACCENT)
1506    else:
1507        run = color_text(run, COLOR_ACCENT)
1508    return f"[ {targets} │ {run} ]" + " " * 12 + dim("[Tab] switch panel    h legend    ? help")
1509
1510
1511MODE_VERB = {"perforated": "perforate", "tracked": "track"}
1512
1513
1514def mode_verb(mode):
1515    """Present-tense verb form of a resolved mode for user-facing display."""
1516    return MODE_VERB.get(mode, str(mode))
1517
1518
1519def make_target_marker(entry, record, entries=None, resolved=None):
1520    """(display, plain) marker for one target row."""
1521    if entry["in_replaced"]:
1522        return "     ", "     "
1523
1524    mode = record["eff"]
1525    fuse_role = get_fused_pair_map().get(entry["id"], (None,))[0]
1526    if fuse_role == "norm":
1527        return color_text("↑", COLOR_ACCENT) + "    ", "↑    "
1528    if not entry["trainable"] and record["source"] != "inherited" and (mode == "perforated" or entry["tree_param_count"] > 0):
1529        # Ineligible for perforation; takes precedence over a stale perforate mark.
1530        if mode != "tracked":
1531            return dim("∅") + "    ", "∅    "
1532    if mode is None:
1533        if entry["direct_param_count"] > 0:
1534            if entries is not None and resolved is not None and _would_auto_track_params(entry, entries, resolved):
1535                block_display = color_text("██", COLOR_TRACK)
1536                return f"~ {block_display} ", "~ ██ "
1537            glyph_display = color_text("!", COLOR_ATTENTION)
1538            block_display = color_text("██", COLOR_ATTENTION)
1539            return f"{glyph_display} {block_display} ", "! ██ "
1540        return "     ", "     "
1541
1542    block_display = make_block(mode)
1543    if fuse_role == "head":
1544        return color_text("↓", COLOR_ACCENT) + f" {block_display} ", "↓ ██ "
1545    norm_direct = _is_norm_type(entry["type_name"]) and record["source"] != "inherited"
1546    if norm_direct:
1547        block_display = color_text_on_bg("⚠⚠", "000000", get_color_hex_for_mode(mode))
1548    block_plain = "⚠█" if norm_direct else "██"
1549    if record["source"] == "inherited":
1550        return f"↳ {block_display} ", "↳ ██ "
1551    if record["source"] == "id":
1552        return f"* {block_display} ", f"* {block_plain} "
1553    if record["source"] == "block":
1554        return f"▤ {block_display} ", f"▤ {block_plain} "
1555    return f"  {block_display} ", f"  {block_plain} "
1556
1557
1558def make_block(mode):
1559    return color_text("██", get_color_hex_for_mode(mode))
1560
1561
1562def render_targets_lines(entries, visible_entries, selected_index, resolved, is_expanded_fn, pending_fuse_id=None):
1563    """Header + tree + footer for the Targets screen, as a list of lines.
1564
1565    ``is_expanded_fn(entry) -> bool`` reports the current expand state of a
1566    collapsible (``has_children``) entry.
1567    """
1568    need = len(unset_module_entries(entries, resolved))
1569    rules = type_rule_entries(entries)
1570    tied_map = get_tied_parameters_map(entries)
1571    fused_map = get_fused_pair_map()
1572
1573    lines = [render_tab_bar("targets"), ""]
1574    lines.append(
1575        dim(
1576            "  perforate = add dendrites   ·   track = not perforated"
1577            "   "
1578        )
1579    )
1580    lines.append("")
1581
1582    hint = color_text(f"[y] type rules ({len(rules)})", COLOR_ACCENT)
1583    if need > 0:
1584        noun = "module" if need == 1 else "modules"
1585        verb = "needs" if need == 1 else "need"
1586        status = color_text(f"  ⚠ {need} {noun} still {verb} a mode", COLOR_ATTENTION)
1587    else:
1588        status = color_text("  ✓ every parameter is perforated or tracked", COLOR_PERFORATE)
1589    pad = max(2, 58 - len(strip_ansi(status)))
1590    lines.append(status + " " * pad + hint)
1591    lines.append(HR)
1592
1593    def entry_lines(entry, selected):
1594        cursor = color_text("> ", "E8EEEC") if selected else "  "
1595        indent = "  " * entry["depth"]
1596        record = resolved[entry["id"]]
1597
1598        if entry["is_replaced_root"]:
1599            child_count = sum(1 for e in entries if e["replaced_root"] == entry["id"])
1600            glyph = color_text("↯", COLOR_ACCENT)
1601            is_open = is_expanded_fn(entry)
1602            toggle = "[← collapse]" if is_open else "[→ expand]"
1603            return [
1604                f"{cursor}{glyph}   {indent}{entry['id']}  "
1605                f"{dim('[' + entry['type_name'] + ']')}   "
1606                f"{dim('will be restructured for PAI before training')}",
1607                "      "
1608                + dim(
1609                    f"└ {child_count} modules below — ids won't exist at "
1610                    f"train time · target by type (P/T), not id  "
1611                )
1612                + color_text(toggle, COLOR_ACCENT),
1613            ]
1614
1615        collapse_glyph_plain = ""
1616        collapse_glyph = ""
1617        if entry["has_children"]:
1618            is_open = is_expanded_fn(entry)
1619            collapse_glyph_plain = "▾ " if is_open else "▸ "
1620            collapse_glyph = color_text(collapse_glyph_plain.strip(), COLOR_ACCENT) + " "
1621
1622        marker_display, marker_plain = make_target_marker(entry, record, entries, resolved)
1623
1624        if entry["in_replaced"]:
1625            id_part = dim(f"{entry['id']}  [{entry['type_name']}] (id stale)")
1626            return [f"{cursor}{marker_display} {indent}{collapse_glyph}{id_part}"]
1627
1628        id_part = f"{entry['id']}  {dim('[' + entry['type_name'] + ']')}"
1629
1630        tail = ""
1631        if record["eff"] is not None:
1632            mode_color = get_color_hex_for_mode(record["eff"])
1633            tail = color_text(f"mode={mode_verb(record['eff'])}", mode_color)
1634            if record["source"] == "block":
1635                rule = record["block_rule"]
1636                tail += dim(f"  (via {rule['block']} {rule['path']})")
1637            if record["source"] == "inherited":
1638                tail += dim(f"  (via {record['origin_id']})")
1639                if record["overridden"] is not None:
1640                    tail += dim(
1641                        f"  — your {mode_verb(record['overridden']['mode'])} here is ignored"
1642                    )
1643        elif entry["direct_param_count"] > 0:
1644            if _would_auto_track_params(entry, entries, resolved):
1645                tail = color_text("mode=params_tracked", COLOR_TRACK)
1646            else:
1647                tail = color_text("needs a mode", COLOR_ATTENTION)
1648
1649        fuse_role = fused_map.get(entry["id"])
1650        if fuse_role is not None and fuse_role[0] == "norm":
1651            tail = color_text(f"fused into {fuse_role[1]}", COLOR_ACCENT)
1652        elif fuse_role is not None:
1653            tail += "  " + color_text(f"fused with {fuse_role[1]}", COLOR_ACCENT)
1654        elif entry["id"] == pending_fuse_id:
1655            tail += "  " + color_text("↓ runs first", COLOR_ACCENT)
1656        elif (
1657            pending_fuse_id is not None
1658            and selected
1659            and fuse_role is None
1660            and not (entry["is_replaced_root"] or entry["in_replaced"])
1661        ):
1662            tail += "  " + color_text("↑ this module runs second", COLOR_ACCENT)
1663
1664        _direct = entry["direct_param_count"]
1665        _child = entry["tree_param_count"] - entry["direct_param_count"]
1666        if _direct > 0 and _child > 0:
1667            params = dim(f"   params={format_human_count(_direct)}   child-params={format_human_count(_child)}")
1668        elif _direct > 0:
1669            params = dim(f"   params={format_human_count(_direct)}")
1670        elif _child > 0:
1671            params = dim(f"   child-params={format_human_count(_child)}")
1672        else:
1673            params = ""
1674
1675        tied_others = tied_map.get(entry["id"], [])
1676        tie_warning = (
1677            color_text("  ⚠ tied to " + ", ".join(tied_others), COLOR_ATTENTION)
1678            if tied_others else ""
1679        )
1680
1681        lead = (
1682            2 + len(marker_plain) + 1 + len(indent) + len(collapse_glyph_plain)
1683            + len(entry["id"]) + 2 + len(entry["type_name"]) + 2
1684        )
1685        gap = max(2, 46 - lead)
1686        return [
1687            f"{cursor}{marker_display} {indent}{collapse_glyph}{id_part}"
1688            + " " * gap + tail + params + tie_warning
1689        ]
1690
1691    body_lines = []
1692    focus = (0, 1)
1693    for i, entry in enumerate(visible_entries):
1694        rendered = entry_lines(entry, i == selected_index)
1695        if i == selected_index:
1696            focus = (len(body_lines), len(body_lines) + len(rendered))
1697        body_lines.extend(rendered)
1698
1699    footer = [
1700        HR,
1701        dim(build_budget_line(entries, resolved)),
1702        "",
1703        dim(
1704            "p/t perforate·track this module   P/T whole type   x clear   "
1705            "e edit block   "
1706            "A track all   ←/→ collapse·expand   0-9 collapse depth   "
1707            "f stage head / fuse with staged head / unfuse   A track all   ←/→ collapse·expand   0-9 collapse depth   "
1708            "h legend   ↑↓/jk move   s start"
1709        ),
1710    ]
1711    return lines, body_lines, footer, focus
1712
1713
1714def render_block_mode_lines(entries, visible_entries, selected_index, block, template_id, is_expanded_fn):
1715    """Header + subtree + footer for block mode, shaped like render_targets_lines."""
1716    template_depth = next(e for e in entries if e["id"] == template_id)["depth"]
1717    all_instances = get_block_instances(entries, block)
1718    template_structure = get_instance_structure(entries, template_id)
1719    matching_instances = [
1720        inst for inst in all_instances
1721        if get_instance_structure(entries, inst["id"]) == template_structure
1722    ]
1723    other_count = len(all_instances) - len(matching_instances)
1724
1725    lines = [render_tab_bar("targets"), ""]
1726    heading = color_text(
1727        f"  Editing {len(matching_instances)} {block} module"
1728        + ("s" if len(matching_instances) != 1 else ""),
1729        COLOR_ACCENT,
1730    ) + dim(f"   (showing {template_id} as the example)")
1731    if other_count:
1732        heading += dim(
1733            f"   · {other_count} other {block}"
1734            + ("s have" if other_count != 1 else " has")
1735            + " a different structure — open one with e to edit separately"
1736        )
1737    lines.append(heading)
1738    lines.append(
1739        dim("  A block rule applies to the same path inside every instance with this structure.")
1740    )
1741    lines.append(HR)
1742
1743    body_lines = []
1744    focus = (0, 1)
1745    for i, entry in enumerate(visible_entries):
1746        selected = i == selected_index
1747        cursor = color_text("> ", "E8EEEC") if selected else "  "
1748        indent = "  " * (entry["depth"] - template_depth)
1749        glyph = ""
1750        if entry["has_children"] and entry["id"] != template_id:
1751            glyph = color_text("▾" if is_expanded_fn(entry) else "▸", COLOR_ACCENT) + " "
1752        if entry["id"] == template_id:
1753            label = f"{dim('(' + block + ')')}"
1754            row = f"{cursor}     {label}   {dim('the block itself — use P/T to set a whole type')}"
1755        else:
1756            path = entry["id"][len(template_id):]
1757            rule = find_block_rule(block, path, structure=template_structure)
1758            label = f"{path}  {dim('[' + entry['type_name'] + ']')}"
1759            if rule is not None:
1760                marker = "▤ " + make_block(rule["mode"]) + " "
1761                tail = color_text(f"mode={mode_verb(rule['mode'])}", get_color_hex_for_mode(rule["mode"]))
1762                tail += dim(f"  applies to {block_rule_scope_text(entries, rule)}")
1763                if block_rule_python_owned(rule):
1764                    tail += dim("  (set in your script)")
1765            else:
1766                marker = "     "
1767                tail = dim("no block rule")
1768            if not entry["trainable"] and entry["tree_param_count"] > 0:
1769                marker = dim("∅") + "    "
1770            row = f"{cursor}{marker}{indent}{glyph}{label}   {tail}"
1771        if selected:
1772            focus = (len(body_lines), len(body_lines) + 1)
1773        body_lines.append(row)
1774
1775    footer = [
1776        HR,
1777        "",
1778        dim(
1779            "p/t perforate·track this path in every block   x remove the rule   "
1780            "←/→ collapse·expand   ↑↓/jk move   e or Esc done"
1781        ),
1782    ]
1783    return lines, body_lines, footer, focus
1784
1785
1786def render_blockrule_overlay(entry, rule, key, choices, selected_index):
1787    """Modal shown when editing a module whose mode comes from a block rule."""
1788    action = {"p": "perforate", "t": "track", "x": "clear"}[key]
1789    lines = [
1790        "",
1791        "",
1792        "  " + color_text(f"{entry['id']} is set by a block rule", "E8EEEC"),
1793        "",
1794        dim(f"  {rule['block']} {rule['path']}: {mode_verb(rule['mode'])}"
1795            " — it applies to every block of that type,"),
1796        dim(f"  so you can't {action} just this module from here."),
1797        "",
1798    ]
1799    for index, (_name, label) in enumerate(choices):
1800        cursor = color_text("▸ ", COLOR_ACCENT) if index == selected_index else "  "
1801        lines.append(f"  {cursor}{label}")
1802    lines += ["", color_text("  ↑↓/jk move · Enter choose · Esc cancel", COLOR_ACCENT)]
1803    return lines
1804
1805
1806def render_run_settings_lines(items, selected_index, describe_name):
1807    """Header + item body + footer for the Run settings screen."""
1808    lines = [
1809        render_tab_bar("run"),
1810        "",
1811        dim("  Run settings — run-wide configuration"),
1812        HR,
1813    ]
1814
1815    body_lines = []
1816    for i, item in enumerate(items):
1817        selected = i == selected_index
1818        cursor = color_text("> ", "E8EEEC") if selected else "  "
1819        if item["type"] == "bucket":
1820            glyph = color_text("▾" if item["is_expanded"] else "▸", COLOR_ACCENT)
1821            body_lines.append(
1822                f"{cursor}{glyph} {item['bucket']} {dim('(' + str(item['count']) + ')')}"
1823            )
1824        elif item["type"] == "divider":
1825            body_lines.append("     " + dim("─ rarely changed ─"))
1826        else:
1827            value_text = format_run_setting_value(item["name"], item["value"])
1828            hint = ""
1829            if get_enum_options(item["name"]) is not None:
1830                hint = dim("  (Enter cycles)")
1831            elif isinstance(item["value"], bool):
1832                hint = dim("  (Enter toggles)")
1833            body_lines.append(f"{cursor}  {item['name']} = {value_text}{hint}")
1834
1835    footer_line = dim(
1836        "→ expand · ← collapse   Enter edit   h describe   "
1837        "↑↓/jk move   Tab switch panel   s start"
1838    )
1839    if describe_name:
1840        footer_line = dim(f"{describe_name} — {get_setting_description(describe_name)}")
1841    footer = [HR, footer_line]
1842    focus = (selected_index, selected_index + 1)
1843    return lines, body_lines, footer, focus
1844
1845
1846def compose_scrolling_screen(header_lines, body_lines, footer_lines, window_start, focus=None):
1847    """Join a header + windowed body + footer into one screen string.
1848
1849    Body rows may wrap to more than one terminal row, so the window is measured
1850    in *rendered* rows (after wrapping), not logical lines — otherwise a narrow
1851    terminal pushes the footer and budget line off-screen.
1852    """
1853    size = terminal_size()
1854    columns = size.columns
1855    reserved = get_visual_line_count(header_lines, columns) + get_visual_line_count(
1856        footer_lines, columns
1857    )
1858    # Two rows held back for the ^^^^ / vvvv overflow indicators.
1859    budget = max(1, size.lines - reserved - 3 - 2)
1860
1861    total = len(body_lines)
1862
1863    def rows_for(line):
1864        return max(1, get_visual_line_count([line], columns))
1865
1866    def window_end_from(start):
1867        used = 0
1868        end = start
1869        while end < total:
1870            height = rows_for(body_lines[end])
1871            if end > start and used + height > budget:
1872                break
1873            used += height
1874            end += 1
1875        return end
1876
1877    def window_start_for_end(end):
1878        used = 0
1879        start = end
1880        while start > 0:
1881            height = rows_for(body_lines[start - 1])
1882            if used + height > budget:
1883                break
1884            used += height
1885            start -= 1
1886        return start
1887
1888    if focus is not None:
1889        focus_start, focus_end = focus
1890        focus_start = max(0, min(focus_start, total))
1891        focus_end = max(focus_start + 1, min(focus_end, total))
1892        if focus_start < window_start:
1893            window_start = focus_start
1894        if window_end_from(window_start) < focus_end:
1895            window_start = window_start_for_end(focus_end)
1896
1897    window_start = max(0, min(window_start, total))
1898    window_end = window_end_from(window_start)
1899    # Grow upward if there is spare room at the bottom of the list.
1900    if window_end >= total:
1901        window_start = min(window_start, window_start_for_end(total))
1902        window_end = total
1903
1904    out = list(header_lines)
1905    if window_start > 0:
1906        out.append(dim("  ^^^^ more above ^^^^"))
1907    out.extend(body_lines[window_start:window_end])
1908    if window_end < total:
1909        out.append(dim("  vvvv more below vvvv"))
1910    out.extend(footer_lines)
1911    return "\n".join(out), window_start
1912
1913
1914def render_static_overlay(lines):
1915    return "\n".join(lines)
1916
1917
1918def render_type_rules_overlay(entries):
1919    rules = type_rule_entries(entries)
1920    rows = []
1921    if rules:
1922        for type_name, mode, count in rules:
1923            plain = f"{type_name} → {mode_verb(mode)}  ({count})"
1924            html = (
1925                type_name
1926                + " "
1927                + color_text(f"→ {mode_verb(mode)}", get_color_hex_for_mode(mode))
1928                + dim(f"  ({count})")
1929            )
1930            rows.append((plain, html))
1931    else:
1932        rows.append(("none yet — P / T on a row sets one",
1933                     dim("none yet — P / T on a row sets one")))
1934
1935    width = max(38, max(len(plain) for plain, _ in rows) + 2)
1936    box = ["  " + dim("┌─ Type rules " + "─" * max(1, width - 12) + "┐")]
1937    for plain, html in rows:
1938        box.append("  " + dim("│ ") + html + " " * (width - len(plain) - 1) + dim("│"))
1939    box.append("  " + dim("└" + "─" * width + "┘"))
1940    box.append("  " + color_text("y or Esc to close", COLOR_ACCENT))
1941    return box
1942
1943
1944def render_overrides_overlay(scope, ov_selected_index, module_settings_overrides,
1945                             existing_module_settings, describe_name):
1946    if scope["kind"] == "id":
1947        title = f"Overrides — {scope['scope_key']}"
1948    else:
1949        title = f"Overrides — every {scope['scope_key']}"
1950
1951    scoped = get_scope_values(
1952        scope["scope_key"], module_settings_overrides, existing_module_settings
1953    )
1954
1955    lines = [render_tab_bar("targets"), "", "  " + color_text(title, COLOR_ACCENT), HR, ""]
1956    if not CUSTOMIZABLE_SETTING_NAMES:
1957        lines.append("  " + dim("No per-target settings are customizable in this build."))
1958    for i, name in enumerate(CUSTOMIZABLE_SETTING_NAMES):
1959        overridden = name in scoped
1960        value = scoped[name] if overridden else get_global_setting_value(name)
1961        cursor = color_text("> ", "E8EEEC") if i == ov_selected_index else "  "
1962        tag = dim("(overridden here)") if overridden else dim("(from run settings)")
1963        lines.append(
1964            f"{cursor}{name} = {format_run_setting_value(name, value)}  {tag}"
1965        )
1966
1967    lines.append("")
1968    footer_line = dim(
1969        "Enter edit · h describe · ↑↓/jk move · Esc / x close"
1970    )
1971    if describe_name:
1972        footer_line = dim(f"{describe_name} — {get_setting_description(describe_name)}")
1973    lines.append(footer_line)
1974    return lines
1975
1976
1977def render_save_overlay(entries, resolved, save_selected_index, config_target_path):
1978    unset = unset_module_entries(entries, resolved)
1979    lines = ["", "  " + color_text("Save configuration", "E8EEEC"), ""]
1980
1981    if unset:
1982        noun = "module has" if len(unset) == 1 else "modules have"
1983        lines.append(
1984            color_text(
1985                f"  ⚠  {len(unset)} {noun} parameters but no mode",
1986                COLOR_ATTENTION,
1987            )
1988        )
1989        lines.append("")
1990        for entry in unset[:5]:
1991            lines.append(f"      {dim(entry['id'] + '   [' + entry['type_name'] + ']')}")
1992        if len(unset) > 5:
1993            lines.append(f"      {dim('(+' + str(len(unset) - 5) + ' more)')}")
1994        lines.append("")
1995        lines.append(
1996            dim(
1997                "  These parameters get no dendrites and are not tracked. "
1998                "Usually a mistake."
1999            )
2000        )
2001        lines.append("")
2002        options = [
2003            "Keep editing",
2004            f"Start anyway — I know these {len(unset)} have no mode",
2005        ]
2006    else:
2007        lines.append(dim("  Start training with this configuration:"))
2008        lines.append("")
2009        options = [
2010            ("just this run", "don't touch my saved config"),
2011            (
2012                "and save it as default",
2013                f"write it to {config_target_path}, skip this screen next time",
2014            ),
2015            ("Keep editing", ""),
2016        ]
2017
2018    for i, option in enumerate(options):
2019        marked = i == save_selected_index
2020        pointer = color_text("  ▸ ", "E8EEEC") if marked else "    "
2021        if isinstance(option, tuple):
2022            label, detail = option
2023            text = color_text(label, "E8EEEC") if marked else label
2024            if detail:
2025                text += dim(f"  — {detail}")
2026            lines.append(pointer + text)
2027        else:
2028            text = color_text(option, "E8EEEC") if marked else dim(option)
2029            lines.append(pointer + text)
2030
2031    lines.append("")
2032    lines.append("")
2033    lines.append(
2034        dim("  ↑↓/jk move · Enter choose · Esc / x back to editing")
2035    )
2036    return lines
2037
2038
2039def render_help_overlay():
2040    p = lambda t: color_text(t, COLOR_PERFORATE)
2041    tr = lambda t: color_text(t, COLOR_TRACK)
2042    return [
2043        "",
2044        "  " + color_text("Keys", "E8EEEC"),
2045        "",
2046        dim("  Targets screen"),
2047        "   p / t     perforate / track this module",
2048        "   P / T     perforate / track every module of this type",
2049        "   x         clear this module (falls back to its type rule)",
2050        "   e         edit a block: set a rule for the same path in every instance",
2051        "             (on a module set by a block rule, p/t/x offer to edit the block)",
2052        "   f         two-step fuse: first press stages a module as the head (↓ runs first);",
2053        "             second press on a different module completes the pair as the norm (↑ runs second).",
2054        "             Pressing f on an already-fused module un-fuses it.",
2055        "             Pressing f again on the staged head cancels staging.",
2056        "   → / ←     expand / collapse a module that will be restructured (↯)",
2057        "   y         show / hide the type-rules list",
2058        "   h         show the marker & colour legend",
2059        "   Enter     open overrides for a perforated module",
2060        "",
2061        dim("  Run settings screen"),
2062        "   → / ←     expand / collapse a bucket",
2063        "   Enter     edit the highlighted setting",
2064        "   h         describe the highlighted setting",
2065        "",
2066        dim("  Everywhere"),
2067        "   ↑↓ / jk   move        Tab  switch panel",
2068        "   s         save & start training",
2069        "   q         quit without configuring",
2070        "",
2071        dim("  Modes"),
2072        "   " + p("perforate") + " = dendrites are added here during training",
2073        "   " + tr("track") + "     = no dendrites, the parameters are just counted",
2074        "   " + dim("↳ inherited") + " = a mode set on an ancestor applies to the whole subtree",
2075        "   " + dim("(see the h legend on the Targets panel for how modes resolve)"),
2076        "",
2077        color_text("  ? or Esc to close", COLOR_ACCENT),
2078    ]
2079
2080
2081def render_legend_overlay():
2082    """Describe the Targets-screen markers and colours."""
2083    perf = color_text("██", COLOR_PERFORATE)
2084    trk = color_text("██", COLOR_TRACK)
2085    att = color_text("██", COLOR_ATTENTION)
2086    return [
2087        "",
2088        "  " + color_text("Targets legend", "E8EEEC"),
2089        "",
2090        dim("  Mode blocks"),
2091        f"   {perf}        " + color_text("perforate", COLOR_PERFORATE)
2092        + " — dendrites are added here during training",
2093        f"   {trk}        " + color_text("track", COLOR_TRACK)
2094        + " — no dendrites, the parameters are just counted",
2095        "",
2096        dim("  Marker prefixes"),
2097        f"     {perf}     set by type name — every module of this class",
2098        f"   * {perf}     mode set directly on this module (by id)",
2099        f"   ▤ {perf}     set by a block rule — the same path in every instance of a block",
2100        f"   ↳ {perf}     inherited from an ancestor; applies to the whole subtree",
2101        f"   ! {att}     has parameters but no mode — needs attention",
2102        f"   * {color_text_on_bg('⚠⚠', '000000', COLOR_PERFORATE)}     norm targeted directly — consider fusing (f) or targeting via parent",
2103        "   ↓ ██      fused head: runs first, perforated as the combined block",
2104        "   ↑         fused norm: runs second inside the head's block, needs no mode",
2105        "   " + dim("∅") + "         not trainable (no parameter requires grad) —",
2106        "             can be tracked but not perforated",
2107        f"   ~ {trk}     direct params auto-tracked (all child modules covered)",
2108        "   ↓         staged as fuse head (runs first) — press f on the norm to complete",
2109        "   ↑         currently selected as the norm candidate (runs second)",
2110        "   fused     a head and a norm are perforated as one block;",
2111        "             the head is perforated, the norm just runs inside it",
2112        "   ↯         will be restructured for PAI before training;",
2113        "             target the modules inside it by type (P/T), not by id",
2114        "   (none)    structural container with no parameters of its own",
2115        "",
2116        dim("  Which mode wins  (highest priority first)"),
2117        "   1. inherited — a mode on an ancestor applies to its whole",
2118        "      subtree; a mode set directly on a descendant is ignored",
2119        "      while the ancestor's mode is in effect",
2120        "   2. by id — a mode set on this exact module",
2121        "   3. by block rule — the same path inside every instance of a block",
2122        "   4. by type — a mode set on the module's class name",
2123        "   So: inherited  >  by id  >  by block rule  >  by type.",
2124        "",
2125        color_text("  h or Esc to close", COLOR_ACCENT),
2126    ]
2127
2128
2129def render_quit_overlay():
2130    return [
2131        "",
2132        "",
2133        "",
2134        "  " + color_text("Quit without configuring?", "E8EEEC"),
2135        "",
2136        dim("  Training will not start. Re-run to configure again, or set"),
2137        dim("  configuration_confirmed=True to skip this screen."),
2138        "",
2139        "  " + color_text("[y] quit", COLOR_ATTENTION) + "     " + dim("[n] keep configuring"),
2140    ]
2141
2142
2143def render_override_scope_choice_overlay(entry):
2144    """Ask whether overrides should apply to this module only or every module of its type."""
2145    type_name = entry["type_name"]
2146    module_id = entry["id"]
2147    return [
2148        "",
2149        "  " + color_text("Override scope", "E8EEEC"),
2150        "",
2151        dim("  This module is perforated by type. Where should the override apply?"),
2152        "",
2153        f"  " + color_text("[1]", COLOR_ACCENT) + f"  just this module  ({module_id})",
2154        f"  " + color_text("[2]", COLOR_ACCENT) + f"  every {type_name}",
2155        "",
2156        dim("  Esc to cancel"),
2157    ]
2158
2159
2160# ---------------------------------------------------------------------------
2161# Key input
2162# ---------------------------------------------------------------------------
2163def read_single_key():
2164    """Read one keypress, including arrow keys, from stdin.
2165
2166    Ctrl-C raises KeyboardInterrupt so the caller can exit cleanly.
2167    """
2168    file_descriptor = sys.stdin.fileno()
2169    old_settings = termios.tcgetattr(file_descriptor)
2170    try:
2171        tty.setraw(file_descriptor)
2172        first = os.read(file_descriptor, 1)
2173        if first == b"\x03":
2174            raise KeyboardInterrupt
2175        if first != b"\x1b":
2176            return first.decode("latin1")
2177
2178        sequence = bytearray(first)
2179        ready, _, _ = select.select([file_descriptor], [], [], 0.05)
2180        if not ready:
2181            return "\x1b"
2182        sequence.extend(os.read(file_descriptor, 1))
2183
2184        if sequence[1] in (ord("["), ord("O")):
2185            ready, _, _ = select.select([file_descriptor], [], [], 0.15)
2186            if ready:
2187                sequence.extend(os.read(file_descriptor, 1))
2188
2189        while True:
2190            last_byte = sequence[-1]
2191            if chr(last_byte).isalpha() or last_byte == ord("~"):
2192                break
2193            ready, _, _ = select.select([file_descriptor], [], [], 0.01)
2194            if not ready:
2195                break
2196            sequence.extend(os.read(file_descriptor, 1))
2197
2198        return bytes(sequence).decode("latin1")
2199    finally:
2200        termios.tcsetattr(file_descriptor, termios.TCSADRAIN, old_settings)
2201
2202
2203def enter_alternate_screen():
2204    """Switch terminal to alternate screen buffer for the interactive UI."""
2205    print("\x1b[?1049h\x1b[?25l\x1b[2J\x1b[H", end="", flush=True)
2206
2207
2208def exit_alternate_screen():
2209    """Return terminal to the normal screen buffer."""
2210    print("\x1b[?25h\x1b[?1049l", end="", flush=True)
2211
2212
2213# ---------------------------------------------------------------------------
2214# Main loop
2215# ---------------------------------------------------------------------------
2216def _config_target_path():
2217    """Human path where 'save as default' would write."""
2218    config_file = GPA.pc.get_config_file()
2219    if config_file:
2220        return config_file
2221    run_config_path = GPA.pc.get_run_config_path()
2222    if run_config_path:
2223        try:
2224            return os.path.relpath(run_config_path, os.getcwd())
2225        except Exception:
2226            return run_config_path
2227    save_name = GPA.pc.get_save_name() or "PAI"
2228    return f"{save_name}/{save_name}_config.json"
2229
2230
2231def _move(index, delta, length):
2232    if length <= 0:
2233        return 0
2234    return max(0, min(length - 1, index + delta))
2235
2236
2237def _distributed_rank():
2238    """Best-effort process rank for common launchers (0 when not distributed)."""
2239    for var in ("RANK", "LOCAL_RANK", "SLURM_PROCID", "OMPI_COMM_WORLD_RANK"):
2240        value = os.environ.get(var)
2241        if value is not None:
2242            try:
2243                return int(value)
2244            except ValueError:
2245                return 0
2246    return 0
2247
2248
2249def require_interactive_session():
2250    """Raise a clear error if the TUI cannot be driven in this process.
2251
2252    The configuration TUI reads raw keystrokes from the terminal. Under CI,
2253    ``nohup``, notebooks, piped stdin, or non-rank-0 distributed workers there is
2254    no usable TTY, so we fail fast with actionable guidance instead of crashing
2255    inside ``termios``.
2256    """
2257    if termios is None:
2258        raise RuntimeError(
2259            "The interactive perforation-configuration TUI is not available on this "
2260            "platform (no termios). Set configuration_confirmed=True in your config "
2261            "file (or call GPA.pc.set_configuration_confirmed(True)) and configure "
2262            "targets via the config file or Perforated Studio instead."
2263        )
2264
2265    try:
2266        is_tty = bool(sys.stdin.isatty() and sys.stdout.isatty())
2267    except (ValueError, AttributeError, OSError):
2268        is_tty = False
2269    rank = _distributed_rank()
2270
2271    if is_tty and rank == 0:
2272        return
2273
2274    reason = "no interactive terminal is attached" if not is_tty else f"process rank is {rank}, not 0"
2275    raise RuntimeError(
2276        "Perforation configuration has not been confirmed, and it cannot be done "
2277        f"interactively here ({reason}).\n"
2278        "Run perforate_model once from an interactive terminal to choose "
2279        "perforation targets, or set configuration_confirmed=True in your config "
2280        "file (or call GPA.pc.set_configuration_confirmed(True) before "
2281        "perforate_model) to skip the interactive step."
2282    )
2283
2284
2285def set_perforation_targets(model):
2286    """Interactive configuration TUI for perforation targets and run settings.
2287
2288    Two screens (Tab to switch): Targets (the module tree) and Run settings.
2289    See the `?` overlay for the full key reference.
2290
2291    Under torch.distributed only rank 0 runs the TUI.  The other ranks wait for
2292    it, then load the config rank 0 saved, or stop as well if rank 0 exited or
2293    failed instead of confirming.
2294    """
2295    import datetime
2296    import torch.distributed as dist
2297
2298    if not (dist.is_available() and dist.is_initialized()):
2299        _set_perforation_targets_interactive(model)
2300        return
2301
2302    # A gloo group so waiting on a human doesn't hit the NCCL timeout or need a GPU
2303    group = (
2304        dist.new_group(backend="gloo", timeout=datetime.timedelta(days=1))
2305        if dist.is_gloo_available()
2306        else None
2307    )
2308    # [outcome, exit code]: outcome is "confirmed", "exit" or "error"
2309    status = ["error", 1]
2310    try:
2311        if dist.get_rank() == 0:
2312            try:
2313                _set_perforation_targets_interactive(model)
2314                status = ["confirmed", 0]
2315            except SystemExit as e:
2316                status = ["exit", e.code]
2317                raise
2318            finally:
2319                dist.broadcast_object_list(status, src=0, group=group)
2320            return
2321        dist.broadcast_object_list(status, src=0, group=group)
2322    finally:
2323        if group is not None:
2324            dist.destroy_process_group(group)
2325
2326    if status[0] == "exit":
2327        sys.exit(status[1])
2328    if status[0] != "confirmed":
2329        raise RuntimeError("Rank 0 failed during perforation configuration; see its error above.")
2330    # Load the configuration rank 0 saved
2331    GPA.pc.sync_config_sources()
2332    GPA.pc.set_configuration_confirmed(True)
2333
2334
2335def _set_perforation_targets_interactive(model):
2336    require_interactive_session()
2337    previous_auto_persist = GPA.pc.__dict__.get("_auto_persist_config", True)
2338    GPA.pc.__dict__["_auto_persist_config"] = False
2339    GPA.pc.__dict__["_tui_editing"] = True
2340    entered_alt_screen = False
2341    quit_requested = False
2342
2343    try:
2344        enter_alternate_screen()
2345        entered_alt_screen = True
2346        normalize_selection_conflicts()
2347
2348        entries = get_module_entries(model)
2349        if len(entries) == 0:
2350            print(model)
2351            input("Press Enter to confirm perforation targets...")
2352            GPA.pc.set_configuration_confirmed(True)
2353            return
2354        entries_by_id = {entry["id"]: entry for entry in entries}
2355
2356        active_screen = "targets"
2357        overlay = None
2358        status_message = ""
2359
2360        target_selected_index = 0
2361        target_window_start = 0
2362        target_depth_baseline = None
2363        target_expanded_overrides = {}
2364
2365        run_selected_index = 0
2366        run_window_start = 0
2367        expanded_buckets = {"Run basics": True}
2368        describe_name = ""
2369
2370        ov_scope = None
2371        ov_selected_index = 0
2372        ov_pending_entry = None
2373        module_settings_overrides = {}
2374        existing_module_settings = load_existing_module_settings()
2375
2376        save_selected_index = 0
2377
2378        scalar_editor_state = None
2379        list_editor_state = None
2380
2381        # Two-step fuse: set when the user has staged a head but not yet picked the norm.
2382        pending_fuse_id = None
2383
2384        # Block mode edits the same path inside every instance of one block.
2385        block_mode = None  # {"block": class name, "template_id": example instance}
2386        block_selected_index = 0
2387        block_window_start = 0
2388        block_expanded_overrides = {}
2389        block_modal = None  # set while the "set by a block rule" modal is open
2390
2391        def finalize_save(choice_index):
2392            auto_track_unset_direct_params(entries, resolved)
2393            if choice_index == 0:
2394                GPA.pc.persist_config_outputs(overwrite_config_file=False)
2395                persist_module_settings_updates(
2396                    module_settings_overrides, overwrite_config_file=False
2397                )
2398                return
2399
2400            config_file = GPA.pc.get_config_file()
2401            if not config_file:
2402                current_save_name = GPA.pc.get_save_name() or "PAI"
2403                relative_config_name = _config_target_path()
2404                exit_alternate_screen()
2405                print("\x1b[2J\x1b[H", end="")
2406                print("No config_file is set.")
2407                print(
2408                    "Enter a local JSON filename/path to create a reusable "
2409                    "configuration file."
2410                )
2411                print(
2412                    f"You currently have save_name='{current_save_name}'. Choose "
2413                    f"'{relative_config_name}' to skip this screen next time without "
2414                    "changing your perforate_model call."
2415                )
2416                filename = input(
2417                    f"Config filename/path [{relative_config_name}] "
2418                    "(blank accepts default): "
2419                ).strip()
2420                GPA.pc.__dict__["_config_file"] = filename or relative_config_name
2421                enter_alternate_screen()
2422
2423            GPA.pc.persist_config_outputs(overwrite_config_file=True)
2424            persist_module_settings_updates(
2425                module_settings_overrides, overwrite_config_file=True
2426            )
2427
2428        def is_target_expanded(entry):
2429            return is_entry_expanded(entry, target_depth_baseline, target_expanded_overrides)
2430
2431        def visible_block_entries():
2432            template_id = block_mode["template_id"]
2433            subtree = [
2434                e
2435                for e in entries
2436                if e["id"] == template_id or e["id"].startswith(template_id + ".")
2437            ]
2438            subtree_by_id = {e["id"]: e for e in subtree}
2439            return [
2440                e
2441                for e in subtree
2442                if is_entry_visible(e, subtree_by_id, None, block_expanded_overrides)
2443            ]
2444
2445        def blockrule_choices(key):
2446            choices = [("edit", "Edit the block  (change or remove the rule for every instance)")]
2447            if key in ("p", "t"):
2448                choices.append(("this", "Change this module only  (set it by id as an exception)"))
2449            choices.append(("cancel", "Cancel"))
2450            return choices
2451
2452        def visible_targets():
2453            out = []
2454            for entry in entries:
2455                if not is_entry_visible(
2456                    entry, entries_by_id, target_depth_baseline, target_expanded_overrides
2457                ):
2458                    continue
2459                out.append(entry)
2460            return out
2461
2462        while True:
2463            normalize_selection_conflicts()
2464            resolved = resolve_entry_modes(entries)
2465
2466            # ---- editors capture input first -------------------------------
2467            if scalar_editor_state is not None:
2468                _render_editor_frame(scalar_editor_state)
2469                key = read_single_key()
2470                done, status_message = _handle_scalar_editor(
2471                    scalar_editor_state, key, module_settings_overrides
2472                )
2473                if done:
2474                    scalar_editor_state = None
2475                continue
2476
2477            if list_editor_state is not None:
2478                _render_editor_frame(list_editor_state)
2479                key = read_single_key()
2480                done, status_message = _handle_list_editor(
2481                    list_editor_state, key, module_settings_overrides
2482                )
2483                if done:
2484                    list_editor_state = None
2485                continue
2486
2487            # ---- draw the current screen ---------------------------------
2488            print("\x1b[2J\x1b[H", end="")
2489
2490            if overlay == "help":
2491                screen_text = render_static_overlay(render_help_overlay())
2492            elif overlay == "legend":
2493                screen_text = render_static_overlay(render_legend_overlay())
2494            elif overlay == "quit":
2495                screen_text = render_static_overlay(render_quit_overlay())
2496            elif overlay == "save":
2497                screen_text = render_static_overlay(
2498                    render_save_overlay(
2499                        entries, resolved, save_selected_index, _config_target_path()
2500                    )
2501                )
2502            elif overlay == "override_scope_choice":
2503                screen_text = render_static_overlay(
2504                    render_override_scope_choice_overlay(ov_pending_entry)
2505                )
2506            elif overlay == "overrides":
2507                screen_text = render_static_overlay(
2508                    render_overrides_overlay(
2509                        ov_scope,
2510                        ov_selected_index,
2511                        module_settings_overrides,
2512                        existing_module_settings,
2513                        describe_name,
2514                    )
2515                )
2516            elif overlay == "blockrule":
2517                screen_text = render_static_overlay(
2518                    render_blockrule_overlay(
2519                        entries_by_id[block_modal["entry_id"]],
2520                        block_modal["rule"],
2521                        block_modal["key"],
2522                        blockrule_choices(block_modal["key"]),
2523                        block_modal["selected"],
2524                    )
2525                )
2526            elif active_screen == "targets" and block_mode is not None:
2527                vis = visible_block_entries()
2528                if block_selected_index >= len(vis):
2529                    block_selected_index = max(0, len(vis) - 1)
2530                header, body, footer, focus = render_block_mode_lines(
2531                    entries,
2532                    vis,
2533                    block_selected_index,
2534                    block_mode["block"],
2535                    block_mode["template_id"],
2536                    lambda e: is_entry_expanded(e, None, block_expanded_overrides),
2537                )
2538                if status_message:
2539                    footer = footer + [color_text("  " + status_message, COLOR_ACCENT)]
2540                screen_text, block_window_start = compose_scrolling_screen(
2541                    header, body, footer, block_window_start, focus
2542                )
2543            elif active_screen == "targets":
2544                vis = visible_targets()
2545                if target_selected_index >= len(vis):
2546                    target_selected_index = max(0, len(vis) - 1)
2547                header, body, footer, focus = render_targets_lines(
2548                    entries, vis, target_selected_index, resolved, is_target_expanded,
2549                    pending_fuse_id=pending_fuse_id,
2550                )
2551                if overlay == "typerules":
2552                    header = header + [""] + render_type_rules_overlay(entries) + [""]
2553                if status_message:
2554                    footer = footer + [color_text("  " + status_message, COLOR_ACCENT)]
2555                screen_text, target_window_start = compose_scrolling_screen(
2556                    header, body, footer, target_window_start, focus
2557                )
2558            else:
2559                items = build_run_items(expanded_buckets)
2560                if run_selected_index >= len(items):
2561                    run_selected_index = max(0, len(items) - 1)
2562                header, body, footer, focus = render_run_settings_lines(
2563                    items, run_selected_index, describe_name
2564                )
2565                if status_message:
2566                    footer = footer + [color_text("  " + status_message, COLOR_ACCENT)]
2567                screen_text, run_window_start = compose_scrolling_screen(
2568                    header, body, footer, run_window_start, focus
2569                )
2570
2571            print(wrap_screen_text_for_terminal(screen_text))
2572            key = read_single_key()
2573
2574            # ---- overlay key handling -----------------------------------
2575            if overlay == "help":
2576                if key == "?" or key == "\x1b":
2577                    overlay = None
2578                continue
2579
2580            if overlay == "legend":
2581                if key == "h" or key == "\x1b":
2582                    overlay = None
2583                continue
2584
2585            if overlay == "quit":
2586                if key in ("y", "Y"):
2587                    quit_requested = True
2588                    break
2589                if key in ("n", "N") or key == "\x1b":
2590                    overlay = None
2591                continue
2592
2593            if overlay == "blockrule":
2594                choices = blockrule_choices(block_modal["key"])
2595                if is_up_key(key):
2596                    block_modal["selected"] = _move(block_modal["selected"], -1, len(choices))
2597                elif is_down_key(key):
2598                    block_modal["selected"] = _move(block_modal["selected"], 1, len(choices))
2599                elif key == "\x1b":
2600                    overlay = None
2601                    block_modal = None
2602                elif is_enter_key(key):
2603                    choice = choices[block_modal["selected"]][0]
2604                    modal_entry = entries_by_id[block_modal["entry_id"]]
2605                    if choice == "edit":
2606                        block_mode = {
2607                            "block": block_modal["rule"]["block"],
2608                            "template_id": block_modal["block_id"],
2609                        }
2610                        block_selected_index = 0
2611                        block_window_start = 0
2612                        block_expanded_overrides.clear()
2613                    elif choice == "this":
2614                        if id_python_owner(modal_entry["id"]):
2615                            status_message = python_owned_message(
2616                                modal_entry["id"], id_python_owner(modal_entry["id"])
2617                            )
2618                        else:
2619                            set_module_id_mode(
2620                                modal_entry["id"],
2621                                "perforated" if block_modal["key"] == "p" else "tracked",
2622                            )
2623                    overlay = None
2624                    block_modal = None
2625                continue
2626
2627            if overlay == "typerules":
2628                if key in ("y", "Y") or key == "\x1b":
2629                    overlay = None
2630                elif key.lower() == "s":
2631                    overlay = "save"
2632                    save_selected_index = 0
2633                continue
2634
2635            if overlay == "save":
2636                unset = unset_module_entries(entries, resolved)
2637                option_count = 2 if unset else 3
2638                if is_up_key(key):
2639                    save_selected_index = _move(save_selected_index, -1, option_count)
2640                elif is_down_key(key):
2641                    save_selected_index = _move(save_selected_index, 1, option_count)
2642                elif key == "\x1b" or key == "x":
2643                    overlay = None
2644                elif is_enter_key(key):
2645                    if unset:
2646                        if save_selected_index == 0:
2647                            overlay = None
2648                        else:
2649                            finalize_save(0)
2650                            GPA.pc.set_configuration_confirmed(True)
2651                            break
2652                    else:
2653                        if save_selected_index == 2:
2654                            overlay = None
2655                        elif save_selected_index == 1:
2656                            GPA.pc.set_configuration_confirmed(True)
2657                            finalize_save(1)
2658                            break
2659                        else:
2660                            finalize_save(0)
2661                            GPA.pc.set_configuration_confirmed(True)
2662                            break
2663                continue
2664
2665            if overlay == "override_scope_choice":
2666                if key == "\x1b":
2667                    overlay = None
2668                    ov_pending_entry = None
2669                elif key == "1":
2670                    ov_scope = {"kind": "id", "scope_key": ov_pending_entry["id"]}
2671                    ov_pending_entry = None
2672                    ov_selected_index = 0
2673                    overlay = "overrides"
2674                elif key == "2":
2675                    ov_pending_entry = None
2676                    ov_selected_index = 0
2677                    overlay = "overrides"
2678                continue
2679
2680            if overlay == "overrides":
2681                names = CUSTOMIZABLE_SETTING_NAMES
2682                if key == "\x1b" or key == "x":
2683                    overlay = None
2684                    describe_name = ""
2685                elif is_up_key(key):
2686                    ov_selected_index = _move(ov_selected_index, -1, len(names))
2687                    describe_name = ""
2688                elif is_down_key(key):
2689                    ov_selected_index = _move(ov_selected_index, 1, len(names))
2690                    describe_name = ""
2691                elif key == "h" and names:
2692                    current = names[ov_selected_index]
2693                    describe_name = "" if describe_name == current else current
2694                elif is_enter_key(key) and names:
2695                    name = names[ov_selected_index]
2696                    scoped = get_scope_values(
2697                        ov_scope["scope_key"],
2698                        module_settings_overrides,
2699                        existing_module_settings,
2700                    )
2701                    value = scoped[name] if name in scoped else get_global_setting_value(name)
2702                    if isinstance(value, bool):
2703                        set_module_scoped_value(
2704                            module_settings_overrides, ov_scope["scope_key"], name, not value
2705                        )
2706                    elif get_enum_options(name) is not None:
2707                        options = get_enum_options(name)
2708                        try:
2709                            index = options.index(value)
2710                        except ValueError:
2711                            index = -1
2712                        set_module_scoped_value(
2713                            module_settings_overrides,
2714                            ov_scope["scope_key"],
2715                            name,
2716                            options[(index + 1) % len(options)],
2717                        )
2718                    elif isinstance(value, list):
2719                        list_editor_state = _new_list_editor(
2720                            name, value, scope_key=ov_scope["scope_key"]
2721                        )
2722                    elif isinstance(value, (int, float)):
2723                        scalar_editor_state = _new_scalar_editor(
2724                            name, value, scope_key=ov_scope["scope_key"]
2725                        )
2726                    else:
2727                        status_message = f"{name} cannot be edited here."
2728                elif key.lower() == "s":
2729                    overlay = "save"
2730                    save_selected_index = 0
2731                continue
2732
2733            # ---- global keys (no overlay) -------------------------------
2734            if key == "?":
2735                overlay = "help"
2736                continue
2737            if key == "q":
2738                overlay = "quit"
2739                continue
2740            if key.lower() == "s":
2741                overlay = "save"
2742                save_selected_index = 0
2743                continue
2744            if is_tab_key(key):
2745                active_screen = "run" if active_screen == "targets" else "targets"
2746                status_message = ""
2747                describe_name = ""
2748                continue
2749
2750            status_message = ""
2751
2752            if active_screen == "targets" and block_mode is not None:
2753                vis = visible_block_entries()
2754                if block_selected_index >= len(vis):
2755                    block_selected_index = max(0, len(vis) - 1)
2756                entry = vis[block_selected_index]
2757                block_name = block_mode["block"]
2758                block_path = entry["id"][len(block_mode["template_id"]):]
2759
2760                if key in ("\x1b", "e"):
2761                    block_mode = None
2762                elif is_page_up_key(key):
2763                    block_selected_index = _move(block_selected_index, -10, len(vis))
2764                elif is_page_down_key(key):
2765                    block_selected_index = _move(block_selected_index, 10, len(vis))
2766                elif is_up_key(key):
2767                    block_selected_index = _move(block_selected_index, -1, len(vis))
2768                elif is_down_key(key):
2769                    block_selected_index = _move(block_selected_index, 1, len(vis))
2770                elif is_right_key(key) or is_left_key(key):
2771                    if entry["has_children"] and block_path != "":
2772                        block_expanded_overrides[entry["id"]] = is_right_key(key)
2773                elif key in ("p", "t", "x") and block_path == "":
2774                    status_message = (
2775                        f"This is the {block_name} itself. Press e to leave, then P/T "
2776                        "to set a mode for the whole type."
2777                    )
2778                elif key == "p" and not entry["trainable"]:
2779                    status_message = (
2780                        f"{block_path} is not trainable: no parameters require grad, "
2781                        "so it can't be perforated."
2782                    )
2783                elif key in ("p", "t"):
2784                    status_message = set_block_rule(
2785                        block_name,
2786                        block_path,
2787                        "perforated" if key == "p" else "tracked",
2788                        entries,
2789                        template_id=block_mode["template_id"],
2790                    )
2791                elif key == "x":
2792                    status_message = remove_block_rule(
2793                        block_name, block_path, entries, template_id=block_mode["template_id"]
2794                    )
2795                continue
2796
2797            if active_screen == "targets":
2798                vis = visible_targets()
2799                if not vis:
2800                    continue
2801                if target_selected_index >= len(vis):
2802                    target_selected_index = len(vis) - 1
2803                entry = vis[target_selected_index]
2804                record = resolved[entry["id"]]
2805
2806                if is_page_up_key(key):
2807                    target_selected_index = _move(target_selected_index, -10, len(vis))
2808                elif is_page_down_key(key):
2809                    target_selected_index = _move(target_selected_index, 10, len(vis))
2810                elif is_up_key(key):
2811                    target_selected_index = _move(target_selected_index, -1, len(vis))
2812                elif is_down_key(key):
2813                    target_selected_index = _move(target_selected_index, 1, len(vis))
2814                elif key == "y":
2815                    overlay = "typerules"
2816                elif key == "h":
2817                    overlay = "legend"
2818                elif is_right_key(key) or is_left_key(key):
2819                    if entry["has_children"]:
2820                        target_expanded_overrides[entry["id"]] = is_right_key(key)
2821                elif is_depth_key(key):
2822                    target_depth_baseline = int(key)
2823                    target_expanded_overrides.clear()
2824                elif key in ("p", "t", "x") and record["source"] == "block":
2825                    block_rule, block_instance_id = get_block_rule_for_entry(
2826                        entry, entries_by_id
2827                    )
2828                    block_modal = {
2829                        "key": key,
2830                        "entry_id": entry["id"],
2831                        "rule": block_rule,
2832                        "block_id": block_instance_id,
2833                        "selected": 0,
2834                    }
2835                    overlay = "blockrule"
2836                elif key == "e":
2837                    status_message = block_mode_refusal(entry, get_block_types(entries))
2838                    if not status_message:
2839                        block_mode = {
2840                            "block": entry["type_name"],
2841                            "template_id": entry["id"],
2842                        }
2843                        block_selected_index = 0
2844                        block_window_start = 0
2845                        block_expanded_overrides.clear()
2846                elif key == "p" and not entry["trainable"]:
2847                    status_message = (
2848                        f"{entry['id']} is not trainable: no parameters require grad, "
2849                        "so it can't be perforated."
2850                    )
2851                elif key in ("p", "t") and id_python_owner(entry["id"]):
2852                    status_message = python_owned_message(
2853                        entry["id"], id_python_owner(entry["id"])
2854                    )
2855                elif key in ("p", "t"):
2856                    if entry["is_replaced_root"] or entry["in_replaced"]:
2857                        status_message = (
2858                            f"{entry['id']} is inside a module that will be restructured "
2859                            "— its id won't exist at training time. Use P/T to target "
2860                            "by type instead."
2861                        )
2862                    else:
2863                        set_module_id_mode(
2864                            entry["id"], "perforated" if key == "p" else "tracked"
2865                        )
2866                        if _is_norm_type(entry["type_name"]):
2867                            status_message = _NORM_DIRECT_WARNING
2868                elif key == "P" and not entry["trainable"]:
2869                    status_message = (
2870                        f"{entry['id']} is not trainable: no parameters require grad, "
2871                        "so it can't be perforated."
2872                    )
2873                elif key in ("P", "T") and type_python_owner(entry["type_name"]):
2874                    status_message = python_owned_message(
2875                        f"the {entry['type_name']} type rule",
2876                        type_python_owner(entry["type_name"]),
2877                    )
2878                elif key in ("P", "T"):
2879                    if entry["is_replaced_root"]:
2880                        status_message = (
2881                            "Set a mode on this module's children by type, not on the "
2882                            "container that will be restructured."
2883                        )
2884                    else:
2885                        set_module_name_mode(
2886                            entry["type_name"], "perforated" if key == "P" else "tracked", entries
2887                        )
2888                        if _is_norm_type(entry["type_name"]):
2889                            status_message = _NORM_DIRECT_WARNING
2890                elif key == "f":
2891                    if entry["id"] in get_fused_pair_map():
2892                        pending_fuse_id = None
2893                        status_message = unfuse_pair(entry["id"], entries)
2894                    elif pending_fuse_id is None:
2895                        pending_fuse_id, status_message = stage_as_fuse_head(entry)
2896                    elif pending_fuse_id == entry["id"]:
2897                        pending_fuse_id = None
2898                        status_message = f"cancelled — {entry['id']} is no longer staged"
2899                    else:
2900                        head_entry = entries_by_id.get(pending_fuse_id)
2901                        pending_fuse_id = None
2902                        if head_entry is None:
2903                            status_message = "staged head no longer in model; staging cancelled"
2904                        else:
2905                            status_message = fuse_pair(head_entry, entry, entries, resolved)
2906                elif key == "x":
2907                    status_message = clear_module_mode(entry)
2908                elif key == "A":
2909                    set_all_types_to_tracking(entries)
2910                    status_message = "all modules set to tracked"
2911                elif is_enter_key(key):
2912                    scope, reason = get_override_scope_for_entry(entry, resolved)
2913                    if scope is None:
2914                        status_message = reason
2915                    elif scope["kind"] == "type":
2916                        ov_pending_entry = entry
2917                        ov_scope = scope
2918                        describe_name = ""
2919                        overlay = "override_scope_choice"
2920                    else:
2921                        ov_scope = scope
2922                        ov_selected_index = 0
2923                        describe_name = ""
2924                        overlay = "overrides"
2925                continue
2926
2927            # ---- run settings screen -----------------------------------
2928            items = build_run_items(expanded_buckets)
2929            if not items:
2930                continue
2931            if run_selected_index >= len(items):
2932                run_selected_index = len(items) - 1
2933            item = items[run_selected_index]
2934
2935            if is_page_up_key(key):
2936                run_selected_index = _move(run_selected_index, -10, len(items))
2937            elif is_page_down_key(key):
2938                run_selected_index = _move(run_selected_index, 10, len(items))
2939            elif is_up_key(key) or is_down_key(key):
2940                step = -1 if is_up_key(key) else 1
2941                run_selected_index = _move(run_selected_index, step, len(items))
2942                while (
2943                    0 < run_selected_index < len(items) - 1
2944                    and items[run_selected_index]["type"] == "divider"
2945                ):
2946                    run_selected_index = _move(run_selected_index, step, len(items))
2947                describe_name = ""
2948            elif is_right_key(key):
2949                if item["type"] == "bucket":
2950                    expanded_buckets[item["bucket"]] = True
2951            elif is_left_key(key):
2952                if item["type"] == "bucket":
2953                    expanded_buckets[item["bucket"]] = False
2954                else:
2955                    expanded_buckets[item["bucket"]] = False
2956                    for idx, other in enumerate(items):
2957                        if other["type"] == "bucket" and other["bucket"] == item["bucket"]:
2958                            run_selected_index = idx
2959                            break
2960            elif key == "h" and item["type"] == "setting":
2961                describe_name = "" if describe_name == item["name"] else item["name"]
2962            elif is_enter_key(key):
2963                describe_name = ""
2964                if item["type"] == "bucket":
2965                    expanded_buckets[item["bucket"]] = not item["is_expanded"]
2966                elif item["type"] == "setting":
2967                    name = item["name"]
2968                    value = item["value"]
2969                    if isinstance(value, bool):
2970                        ok, message = apply_setting_value(name, not value)
2971                        status_message = message
2972                    elif get_enum_options(name) is not None:
2973                        ok, message = cycle_enum_setting(name, value)
2974                        status_message = message
2975                    elif isinstance(value, list):
2976                        list_editor_state = _new_list_editor(name, value, scope_key=None)
2977                    elif isinstance(value, (int, float)):
2978                        scalar_editor_state = _new_scalar_editor(name, value, scope_key=None)
2979                    else:
2980                        status_message = f"{name} cannot be edited from this screen."
2981            continue
2982
2983    except KeyboardInterrupt:
2984        quit_requested = True
2985    finally:
2986        if entered_alt_screen:
2987            exit_alternate_screen()
2988        GPA.pc.__dict__["_auto_persist_config"] = previous_auto_persist
2989        GPA.pc.__dict__["_tui_editing"] = False
2990
2991    if quit_requested:
2992        print("Configuration cancelled — training did not start.")
2993        print(
2994            "Re-run to configure again, or set configuration_confirmed=True "
2995            "(GPA.pc.set_configuration_confirmed(True)) to skip this screen."
2996        )
2997        sys.exit(0)
2998
2999
3000# ---------------------------------------------------------------------------
3001# Inline value editors (scalar + list)
3002# ---------------------------------------------------------------------------
3003def _new_scalar_editor(setting_name, value, scope_key):
3004    text = str(value)
3005    return {
3006        "kind": "scalar",
3007        "setting_name": setting_name,
3008        "sample_value": value,
3009        "input_buffer": text,
3010        "cursor_index": len(text),
3011        "scope_key": scope_key,
3012    }
3013
3014
3015def _new_list_editor(setting_name, value, scope_key):
3016    return {
3017        "kind": "list",
3018        "setting_name": setting_name,
3019        "values": list(value),
3020        "selected_index": 0,
3021        "sample_type": value[0] if value else None,
3022        "typing_active": False,
3023        "edit_index": None,
3024        "input_buffer": "",
3025        "cursor_index": 0,
3026        "scope_key": scope_key,
3027    }
3028
3029
3030def _render_editor_frame(state):
3031    print("\x1b[2J\x1b[H", end="")
3032    name = state["setting_name"]
3033    if state["kind"] == "scalar":
3034        body = render_text_with_cursor(state["input_buffer"], state["cursor_index"])
3035        lines = [
3036            "  " + color_text(f"Edit {name}", "E8EEEC"),
3037            "",
3038            f"  {body}",
3039            "",
3040            dim("  Enter save · Esc cancel"),
3041        ]
3042    else:
3043        lines = [
3044            "  " + color_text(f"Edit {name}", "E8EEEC"),
3045            "",
3046            "  " + _format_list_editor_line(state),
3047            "",
3048            dim(
3049                "  ←/→ move · Enter edit/select · "
3050                "Backspace/Delete remove · Esc cancel"
3051            ),
3052        ]
3053    print(wrap_screen_text_for_terminal("\n".join(lines)))
3054
3055
3056def _format_list_editor_line(state):
3057    values = state["values"]
3058    tokens = []
3059    for i, value in enumerate(values):
3060        if state["typing_active"] and i == state["edit_index"]:
3061            tokens.append(render_text_with_cursor(state["input_buffer"], state["cursor_index"]))
3062        elif i == state["selected_index"] and not state["typing_active"]:
3063            tokens.append(make_inverted_text(str(value)))
3064        else:
3065            tokens.append(str(value))
3066
3067    add_index = len(values)
3068    if state["typing_active"] and state["edit_index"] == add_index:
3069        tokens.append(render_text_with_cursor(state["input_buffer"], state["cursor_index"]))
3070    elif state["selected_index"] == add_index:
3071        tokens.append(make_inverted_text("Add new entry"))
3072    else:
3073        tokens.append("Add new entry")
3074
3075    save_index = len(values) + 1
3076    save_token = "Save list and return"
3077    tokens.append(
3078        make_inverted_text(save_token)
3079        if state["selected_index"] == save_index and not state["typing_active"]
3080        else save_token
3081    )
3082    return " | ".join(tokens)
3083
3084
3085def _persist_edited_value(state, module_settings_overrides, value):
3086    if state["scope_key"] is not None:
3087        set_module_scoped_value(
3088            module_settings_overrides, state["scope_key"], state["setting_name"], value
3089        )
3090        return ""
3091    ok, message = apply_setting_value(state["setting_name"], value)
3092    return "" if ok else message
3093
3094
3095def _handle_scalar_editor(state, key, module_settings_overrides):
3096    buffer_text = state["input_buffer"]
3097    cursor = state["cursor_index"]
3098
3099    if key == "\x1b":
3100        return True, ""
3101    if is_left_key(key):
3102        state["cursor_index"] = max(0, cursor - 1)
3103        return False, ""
3104    if is_right_key(key):
3105        state["cursor_index"] = min(len(buffer_text), cursor + 1)
3106        return False, ""
3107    if key == "\x7f":
3108        if cursor > 0:
3109            state["input_buffer"] = buffer_text[: cursor - 1] + buffer_text[cursor:]
3110            state["cursor_index"] = cursor - 1
3111        return False, ""
3112    if is_delete_key(key):
3113        if cursor < len(buffer_text):
3114            state["input_buffer"] = buffer_text[:cursor] + buffer_text[cursor + 1 :]
3115        return False, ""
3116    if is_enter_key(key):
3117        try:
3118            parsed = parse_value_from_text(state["input_buffer"], state["sample_value"])
3119        except Exception as exc:
3120            return True, f"Invalid value for {state['setting_name']}: {exc}"
3121        return True, _persist_edited_value(state, module_settings_overrides, parsed)
3122    if len(key) == 1 and key >= " ":
3123        state["input_buffer"] = buffer_text[:cursor] + key + buffer_text[cursor:]
3124        state["cursor_index"] = cursor + 1
3125    return False, ""
3126
3127
3128def _handle_list_editor(state, key, module_settings_overrides):
3129    values = state["values"]
3130    add_index = len(values)
3131    save_index = len(values) + 1
3132
3133    if state["typing_active"]:
3134        buffer_text = state["input_buffer"]
3135        cursor = state["cursor_index"]
3136        if key == "\x1b":
3137            state["typing_active"] = False
3138            state["edit_index"] = None
3139            state["input_buffer"] = ""
3140            state["cursor_index"] = 0
3141            return False, ""
3142        if is_left_key(key):
3143            state["cursor_index"] = max(0, cursor - 1)
3144            return False, ""
3145        if is_right_key(key):
3146            state["cursor_index"] = min(len(buffer_text), cursor + 1)
3147            return False, ""
3148        if key == "\x7f":
3149            if cursor > 0:
3150                state["input_buffer"] = buffer_text[: cursor - 1] + buffer_text[cursor:]
3151                state["cursor_index"] = cursor - 1
3152            return False, ""
3153        if is_delete_key(key):
3154            if cursor < len(buffer_text):
3155                state["input_buffer"] = buffer_text[:cursor] + buffer_text[cursor + 1 :]
3156            return False, ""
3157        if is_enter_key(key):
3158            edit_index = state["edit_index"]
3159            sample = state["sample_type"]
3160            if edit_index is not None and edit_index < len(values):
3161                sample = values[edit_index]
3162            try:
3163                parsed = parse_value_from_text(state["input_buffer"], sample)
3164            except Exception as exc:
3165                state["typing_active"] = False
3166                state["edit_index"] = None
3167                state["input_buffer"] = ""
3168                return False, f"Invalid list entry: {exc}"
3169            if edit_index is not None and edit_index < len(values):
3170                values[edit_index] = parsed
3171                state["selected_index"] = edit_index
3172            else:
3173                values.append(parsed)
3174                state["selected_index"] = len(values) - 1
3175            state["typing_active"] = False
3176            state["edit_index"] = None
3177            state["input_buffer"] = ""
3178            state["cursor_index"] = 0
3179            return False, ""
3180        if len(key) == 1 and key >= " ":
3181            state["input_buffer"] = buffer_text[:cursor] + key + buffer_text[cursor:]
3182            state["cursor_index"] = cursor + 1
3183        return False, ""
3184
3185    selected = state["selected_index"]
3186    if key == "\x1b":
3187        return True, ""
3188    if is_left_key(key):
3189        state["selected_index"] = max(0, selected - 1)
3190        return False, ""
3191    if is_right_key(key):
3192        state["selected_index"] = min(save_index, selected + 1)
3193        return False, ""
3194    if key == "\x7f" or is_delete_key(key):
3195        if selected < len(values):
3196            del values[selected]
3197            if state["selected_index"] > len(values) + 1:
3198                state["selected_index"] = len(values) + 1
3199        return False, ""
3200    if is_select_key(key):
3201        if selected == save_index:
3202            return True, _persist_edited_value(
3203                state, module_settings_overrides, list(values)
3204            )
3205        initial_text = str(values[selected]) if selected < len(values) else ""
3206        state["typing_active"] = True
3207        state["edit_index"] = selected
3208        state["input_buffer"] = initial_text
3209        state["cursor_index"] = len(initial_text)
3210    return False, ""
def dedupe_list(values):
29def dedupe_list(values):
30    """Return a list with duplicates removed while preserving order."""
31    seen = set()
32    unique = []
33    for value in values:
34        if value in seen:
35            continue
36        seen.add(value)
37        unique.append(value)
38    return unique

Return a list with duplicates removed while preserving order.

def python_supplied_owner(var_names, item):
41def python_supplied_owner(var_names, item):
42    """The first list in ``var_names`` whose script-supplied items include ``item``."""
43    for var_name in var_names:
44        if item in (GPA.pc.get_python_supplied(var_name) or []):
45            return var_name
46    return None

The first list in var_names whose script-supplied items include item.

def python_owned_message(label, var_name):
49def python_owned_message(label, var_name):
50    return (
51        f"{label} is set by a Python call ({var_name}) — change it in your script; "
52        "the CLI can't override it."
53    )
def id_python_owner(module_id):
56def id_python_owner(module_id):
57    return python_supplied_owner(
58        ("module_ids_to_perforate", "module_ids_to_track"), module_id
59    )
def type_python_owner(type_name):
62def type_python_owner(type_name):
63    return python_supplied_owner(
64        ("module_names_to_perforate", "module_names_to_track"), type_name
65    )
def normalize_selection_conflicts():
68def normalize_selection_conflicts():
69    """Normalize id and name selection lists and remove direct conflicts."""
70    ids_perforate = dedupe_list(GPA.pc.get_module_ids_to_perforate())
71    ids_track = dedupe_list(GPA.pc.get_module_ids_to_track())
72    names_perforate = dedupe_list(GPA.pc.get_module_names_to_perforate())
73    names_track = dedupe_list(GPA.pc.get_module_names_to_track())
74
75    overlap_ids = set(ids_perforate) & set(ids_track)
76    overlap_names = set(names_perforate) & set(names_track)
77
78    if overlap_ids:
79        ids_track = [value for value in ids_track if value not in overlap_ids]
80    if overlap_names:
81        names_track = [value for value in names_track if value not in overlap_names]
82
83    GPA.pc.set_module_ids_to_perforate(ids_perforate)
84    GPA.pc.set_module_ids_to_track(ids_track)
85    GPA.pc.set_module_names_to_perforate(names_perforate)
86    GPA.pc.set_module_names_to_track(names_track)

Normalize id and name selection lists and remove direct conflicts.

def get_module_entries(model):
 89def get_module_entries(model):
 90    """Collect modules for interactive navigation.
 91
 92    Each entry also carries ``is_replaced_root`` (this module's class is in
 93    ``modules_to_replace`` and will be restructured before training) and
 94    ``in_replaced`` / ``replaced_root`` (this module lives under such a module,
 95    so its id will not exist at training time).
 96    """
 97    entries = []
 98    for name, module in model.named_modules(remove_duplicate=False):
 99        if name == "":
100            continue
101        module_id = "." + name
102        depth = name.count(".")
103        entries.append(
104            {
105                "id": module_id,
106                "name": name,
107                "type_name": type(module).__name__,
108                "module": module,
109                "depth": depth,
110                "direct_param_count": sum(
111                    param.numel()
112                    for _param_name, param in module.named_parameters(recurse=False)
113                ),
114                "tree_param_count": sum(
115                    param.numel()
116                    for _param_name, param in module.named_parameters(recurse=True)
117                ),
118                # Trainable: this module or any submodule has a requires_grad
119                # parameter. Only trainable modules may be perforated.
120                "trainable": any(
121                    param.requires_grad
122                    for _param_name, param in module.named_parameters(recurse=True)
123                ),
124            }
125        )
126
127    # named_modules() is a DFS pre-order traversal, so a module's children
128    # (if any) always immediately follow it in `entries`.
129    for i, entry in enumerate(entries):
130        entry["has_children"] = i + 1 < len(entries) and entries[i + 1]["id"].startswith(
131            entry["id"] + "."
132        )
133
134    replace_classes = tuple(GPA.pc.get_modules_to_replace())
135    replaced_root_ids = []
136    for entry in entries:
137        entry["is_replaced_root"] = (
138            len(replace_classes) > 0
139            and isinstance(entry["module"], replace_classes)
140        )
141        if entry["is_replaced_root"]:
142            replaced_root_ids.append(entry["id"])
143
144    for entry in entries:
145        entry["replaced_root"] = None
146        entry["in_replaced"] = False
147        for root_id in replaced_root_ids:
148            if entry["id"].startswith(root_id + "."):
149                entry["replaced_root"] = root_id
150                entry["in_replaced"] = True
151                break
152
153    return entries

Collect modules for interactive navigation.

Each entry also carries is_replaced_root (this module's class is in modules_to_replace and will be restructured before training) and in_replaced / replaced_root (this module lives under such a module, so its id will not exist at training time).

def get_id_mode(module_id):
156def get_id_mode(module_id):
157    """Get explicit id-based mode for a module id ("perforated"/"tracked"/None)."""
158    if module_id in GPA.pc.get_module_ids_to_perforate():
159        return "perforated"
160    if module_id in GPA.pc.get_module_ids_to_track():
161        return "tracked"
162    return None

Get explicit id-based mode for a module id ("perforated"/"tracked"/None).

def get_name_mode(module_type_name):
165def get_name_mode(module_type_name):
166    """Get type-name-based mode for a module type ("perforated"/"tracked"/None)."""
167    if module_type_name in GPA.pc.get_module_names_to_perforate():
168        return "perforated"
169    if module_type_name in GPA.pc.get_module_names_to_track():
170        return "tracked"
171    return None

Get type-name-based mode for a module type ("perforated"/"tracked"/None).

def get_parent_module_id(module_id):
174def get_parent_module_id(module_id):
175    """Return the direct parent module id for a dot-id module path."""
176    parts = module_id.split(".")
177    if len(parts) <= 2:
178        return None
179    return "." + ".".join(parts[1:-1])

Return the direct parent module id for a dot-id module path.

def get_tied_parameters_map(entries):
182def get_tied_parameters_map(entries):
183    """Return a map from module_id to a list of other full param ids sharing memory.
184
185    Detects weight tying by comparing data_ptr() across the direct (non-recursive)
186    parameters of every entry. Only cross-module ties are reported; intra-module
187    shared params are ignored.
188    """
189    ptr_to_params = {}
190    for entry in entries:
191        module_id = entry["id"]
192        for param_name, param in entry["module"].named_parameters(recurse=False):
193            ptr = param.data_ptr()
194            if ptr == 0:
195                continue
196            full_param_id = module_id + "." + param_name
197            if ptr not in ptr_to_params:
198                ptr_to_params[ptr] = []
199            ptr_to_params[ptr].append((full_param_id, module_id))
200
201    tied_map = {}
202    for param_list in ptr_to_params.values():
203        if len(param_list) <= 1:
204            continue
205        for full_param_id, module_id in param_list:
206            others = [fp for fp, mid in param_list if mid != module_id]
207            if others:
208                if module_id not in tied_map:
209                    tied_map[module_id] = []
210                for fp in others:
211                    if fp not in tied_map[module_id]:
212                        tied_map[module_id].append(fp)
213    return tied_map

Return a map from module_id to a list of other full param ids sharing memory.

Detects weight tying by comparing data_ptr() across the direct (non-recursive) parameters of every entry. Only cross-module ties are reported; intra-module shared params are ignored.

def get_block_types(entries):
219def get_block_types(entries):
220    """Class names of blocks: modules with children that occur more than once."""
221    counts = {}
222    for entry in entries:
223        if entry["has_children"] and not entry["in_replaced"] and not entry["is_replaced_root"]:
224            counts[entry["type_name"]] = counts.get(entry["type_name"], 0) + 1
225    return {name for name, count in counts.items() if count > 1}

Class names of blocks: modules with children that occur more than once.

def get_block_instances(entries, block):
228def get_block_instances(entries, block):
229    """Every live instance of a block, in model order."""
230    return [
231        entry
232        for entry in entries
233        if entry["type_name"] == block
234        and entry["has_children"]
235        and not entry["in_replaced"]
236        and not entry["is_replaced_root"]
237    ]

Every live instance of a block, in model order.

def get_block_rule_for_entry(entry, entries_by_id):
240def get_block_rule_for_entry(entry, entries_by_id):
241    """The nearest enclosing block's rule that targets this module, with that block.
242
243    Returns (rule, block_instance_id), or (None, None).
244    """
245    rules = GPA.pc.get_block_rules()
246    if not rules:
247        return None, None
248    all_ids = set(entries_by_id.keys())
249    ancestor_id = entry["id"]
250    while True:
251        split_at = ancestor_id.rfind(".")
252        if split_at <= 0:
253            return None, None
254        ancestor_id = ancestor_id[:split_at]
255        ancestor = entries_by_id.get(ancestor_id)
256        if ancestor is None:
257            continue
258        for rule in rules:
259            if (
260                rule["block"] == ancestor["type_name"]
261                and entry["id"] == ancestor_id + rule["path"]
262            ):
263                rule_structure = rule.get("structure")
264                if rule_structure is not None:
265                    if _instance_structure_from_ids(all_ids, ancestor_id) != rule_structure:
266                        continue
267                return rule, ancestor_id

The nearest enclosing block's rule that targets this module, with that block.

Returns (rule, block_instance_id), or (None, None).

def get_instance_structure(entries, instance_id):
270def get_instance_structure(entries, instance_id):
271    """Sorted list of all relative submodule paths under instance_id."""
272    prefix = instance_id + "."
273    return sorted(e["id"][len(instance_id):] for e in entries if e["id"].startswith(prefix))

Sorted list of all relative submodule paths under instance_id.

def get_block_rule_targets(entries, rule):
282def get_block_rule_targets(entries, rule):
283    """Ids of the modules a block rule hits in the CLI's view of the model.
284
285    Only includes instances whose full internal structure matches the structure
286    stored in the rule. Rules without a stored structure (created before this
287    check was added) apply to all instances that have the path.
288    """
289    ids = {entry["id"] for entry in entries}
290    rule_structure = rule.get("structure")
291
292    def _structure_matches(inst_id):
293        if rule_structure is None:
294            return True
295        return _instance_structure_from_ids(ids, inst_id) == rule_structure
296
297    return [
298        entry["id"] + rule["path"]
299        for entry in get_block_instances(entries, rule["block"])
300        if entry["id"] + rule["path"] in ids and _structure_matches(entry["id"])
301    ]

Ids of the modules a block rule hits in the CLI's view of the model.

Only includes instances whose full internal structure matches the structure stored in the rule. Rules without a stored structure (created before this check was added) apply to all instances that have the path.

def find_block_rule(block, path, structure=None):
304def find_block_rule(block, path, structure=None):
305    """Return the block rule for (block, path), optionally filtered by structure.
306
307    When structure is given, return the rule that has that exact structure (or a
308    rule with no stored structure for backward compat). When structure is None,
309    return the first matching rule regardless of structure.
310    """
311    for rule in GPA.pc.get_block_rules():
312        if rule["block"] == block and rule["path"] == path:
313            if structure is None:
314                return rule
315            if rule.get("structure") == structure:
316                return rule
317    return None

Return the block rule for (block, path), optionally filtered by structure.

When structure is given, return the rule that has that exact structure (or a rule with no stored structure for backward compat). When structure is None, return the first matching rule regardless of structure.

def block_rule_python_owned(rule):
320def block_rule_python_owned(rule):
321    return rule in (GPA.pc.get_python_supplied("block_rules") or [])
def block_rule_scope_text(entries, rule):
324def block_rule_scope_text(entries, rule):
325    """How many blocks a rule really applies to, and why any are excluded."""
326    all_instances = get_block_instances(entries, rule["block"])
327    targets = get_block_rule_targets(entries, rule)
328    resolved = resolve_entry_modes(entries)
329    applied = [
330        target
331        for target in targets
332        if resolved[target]["source"] == "block" and resolved[target]["block_rule"] == rule
333    ]
334
335    rule_structure = rule.get("structure")
336    if rule_structure is not None:
337        ids = {entry["id"] for entry in entries}
338        structure_skipped = sum(
339            1 for inst in all_instances
340            if _instance_structure_from_ids(ids, inst["id"]) != rule_structure
341        )
342        matching_count = len(all_instances) - structure_skipped
343    else:
344        structure_skipped = 0
345        matching_count = len(all_instances)
346
347    text = "%d of %d %s modules" % (len(applied), matching_count, rule["block"])
348    if structure_skipped:
349        text += f" ({structure_skipped} different-structure {rule['block']}s skipped)"
350    ignored = len(targets) - len(applied)
351    if ignored:
352        text += f", {ignored} ignored: a mode on an enclosing module or set by id wins"
353    return text

How many blocks a rule really applies to, and why any are excluded.

def set_block_rule(block, path, mode, entries, template_id=None):
356def set_block_rule(block, path, mode, entries, template_id=None):
357    """Set (or toggle off) a block rule; returns a short message."""
358    structure = get_instance_structure(entries, template_id) if template_id is not None else None
359    existing = find_block_rule(block, path, structure=structure)
360    if existing is not None and block_rule_python_owned(existing):
361        return python_owned_message(f"the {block} {path} block rule", "block_rules")
362    rules = [
363        dict(rule)
364        for rule in GPA.pc.get_block_rules()
365        if not (
366            rule["block"] == block
367            and rule["path"] == path
368            and rule.get("structure") == structure
369        )
370    ]
371    if existing is not None and existing["mode"] == mode:
372        GPA.pc.set_block_rules(rules)
373        return f"removed block rule {block} {path}"
374    rule = {"block": block, "path": path, "mode": mode}
375    if structure is not None:
376        rule["structure"] = structure
377    rules.append(rule)
378    GPA.pc.set_block_rules(rules)
379    return f"{block} {path}: {mode_verb(mode)} ({block_rule_scope_text(entries, rule)})"

Set (or toggle off) a block rule; returns a short message.

def remove_block_rule(block, path, entries, template_id=None):
382def remove_block_rule(block, path, entries, template_id=None):
383    """Remove a block rule; returns a short message."""
384    structure = get_instance_structure(entries, template_id) if template_id is not None else None
385    existing = find_block_rule(block, path, structure=structure)
386    if existing is None:
387        return f"there is no block rule on {block} {path}"
388    if block_rule_python_owned(existing):
389        return python_owned_message(f"the {block} {path} block rule", "block_rules")
390    scope = block_rule_scope_text(entries, existing)
391    GPA.pc.set_block_rules(
392        [dict(rule) for rule in GPA.pc.get_block_rules() if rule != existing]
393    )
394    return f"removed block rule {block} {path} ({scope})"

Remove a block rule; returns a short message.

def block_mode_refusal(entry, block_types):
397def block_mode_refusal(entry, block_types):
398    """Why block mode can't open on this module, or None if it can."""
399    if entry["is_replaced_root"] or entry["in_replaced"]:
400        return (
401            f"{entry['id']} is inside a module that will be restructured — its "
402            "structure isn't known until training, so it can't be edited as a block."
403        )
404    if entry["type_name"] not in block_types:
405        if not entry["has_children"]:
406            return f"{entry['id']} has no submodules, so it is not a block."
407        return (
408            f"{entry['type_name']} occurs only once, so it is not a block. "
409            "Use p/t on its children by id."
410        )
411    return None

Why block mode can't open on this module, or None if it can.

def resolve_entry_modes(entries):
414def resolve_entry_modes(entries):
415    """Resolve every entry's mode, source, and any overridden-by-ancestor state.
416
417    Returns a map of module id to a dict with:
418      - ``eff``:    "perforated" / "tracked" / None
419      - ``source``: "id" / "type" / "inherited" / None
420      - ``origin_id``: the id the mode was set on (for inherited rows)
421      - ``overridden``: {"mode", "source"} when a direct setting here is ignored
422    """
423    resolved = {}
424    by_id = {entry["id"]: entry for entry in entries}
425    for entry in entries:
426        module_id = entry["id"]
427        parent_id = get_parent_module_id(module_id)
428        parent = resolved.get(parent_id) if parent_id in by_id else None
429
430        own_id_mode = get_id_mode(module_id)
431        block_rule, _block_id = get_block_rule_for_entry(entry, by_id)
432        own_block_mode = block_rule["mode"] if block_rule is not None else None
433        own_type_mode = get_name_mode(entry["type_name"])
434        own_mode = own_id_mode or own_block_mode or own_type_mode
435        if own_id_mode:
436            own_source = "id"
437        elif own_block_mode:
438            own_source = "block"
439        else:
440            own_source = "type" if own_type_mode else None
441
442        record = {
443            "eff": None,
444            "source": None,
445            "origin_id": module_id,
446            "overridden": None,
447            "block_rule": None,
448        }
449        if parent is not None and parent["eff"] is not None:
450            record["eff"] = parent["eff"]
451            record["source"] = "inherited"
452            record["origin_id"] = parent["origin_id"]
453            if own_mode is not None:
454                record["overridden"] = {"mode": own_mode, "source": own_source}
455        elif own_mode is not None:
456            record["eff"] = own_mode
457            record["source"] = own_source
458            record["origin_id"] = module_id
459            if own_source == "block":
460                record["block_rule"] = block_rule
461        resolved[module_id] = record
462    return resolved

Resolve every entry's mode, source, and any overridden-by-ancestor state.

Returns a map of module id to a dict with:

  • eff: "perforated" / "tracked" / None
  • source: "id" / "type" / "inherited" / None
  • origin_id: the id the mode was set on (for inherited rows)
  • overridden: {"mode", "source"} when a direct setting here is ignored
COLOR_PERFORATE = '00A5A5'
COLOR_TRACK = '8A95A0'
COLOR_ATTENTION = 'FD4D00'
COLOR_ACCENT = 'D9A441'
def get_color_hex_for_mode(mode):
474def get_color_hex_for_mode(mode):
475    """Map a resolved mode to its color hex value."""
476    if mode == "perforated":
477        return COLOR_PERFORATE
478    if mode == "tracked":
479        return COLOR_TRACK
480    return "000000"

Map a resolved mode to its color hex value.

def format_human_count(value):
483def format_human_count(value):
484    """Format integer counts into compact human-readable units (K/M/B)."""
485    if value < 1000:
486        return str(value)
487    if value < 1000000:
488        scaled = value / 1000.0
489        text = f"{scaled:.1f}"
490        return (text[:-2] if text.endswith(".0") else text) + "K"
491    if value < 1000000000:
492        scaled = value / 1000000.0
493        text = f"{scaled:.1f}"
494        return (text[:-2] if text.endswith(".0") else text) + "M"
495    scaled = value / 1000000000.0
496    text = f"{scaled:.1f}"
497    return (text[:-2] if text.endswith(".0") else text) + "B"

Format integer counts into compact human-readable units (K/M/B).

def color_text(text, hex_color):
504def color_text(text, hex_color):
505    """Render text in an ANSI truecolor foreground."""
506    r = int(hex_color[0:2], 16)
507    g = int(hex_color[2:4], 16)
508    b = int(hex_color[4:6], 16)
509    return f"\x1b[38;2;{r};{g};{b}m{text}\x1b[0m"

Render text in an ANSI truecolor foreground.

def color_text_on_bg(text, fg_hex, bg_hex):
512def color_text_on_bg(text, fg_hex, bg_hex):
513    """Render text with an ANSI truecolor foreground and background."""
514    fr, fg, fb = int(fg_hex[0:2], 16), int(fg_hex[2:4], 16), int(fg_hex[4:6], 16)
515    br, bg, bb = int(bg_hex[0:2], 16), int(bg_hex[2:4], 16), int(bg_hex[4:6], 16)
516    return f"\x1b[38;2;{fr};{fg};{fb}m\x1b[48;2;{br};{bg};{bb}m{text}\x1b[0m"

Render text with an ANSI truecolor foreground and background.

def make_color_square(hex_color):
519def make_color_square(hex_color):
520    """Create one colored block character using ANSI truecolor."""
521    return color_text("█", hex_color)

Create one colored block character using ANSI truecolor.

def dim(text):
524def dim(text):
525    """Render text dimmed."""
526    return _ansi(text, "90")

Render text dimmed.

def make_inverted_text(text):
529def make_inverted_text(text):
530    """Render text with inverted foreground/background colors."""
531    return f"\x1b[7m{text}\x1b[0m"

Render text with inverted foreground/background colors.

ANSI_ESCAPE_RE = re.compile('\\x1b\\[[0-9;]*m')
def strip_ansi(text):
537def strip_ansi(text):
538    """Remove ANSI color/style escape codes for width calculation."""
539    return ANSI_ESCAPE_RE.sub("", text)

Remove ANSI color/style escape codes for width calculation.

def get_visual_line_count(lines, terminal_columns):
542def get_visual_line_count(lines, terminal_columns):
543    """Count rendered terminal rows, including wrapped long lines."""
544    if terminal_columns < 1:
545        return len(lines)
546    total = 0
547    for line in lines:
548        plain = strip_ansi(line)
549        if len(plain) == 0:
550            total += 1
551            continue
552        total += (len(plain) + terminal_columns - 1) // terminal_columns
553    return total

Count rendered terminal rows, including wrapped long lines.

def wrap_ansi_line_on_words(line, terminal_columns):
556def wrap_ansi_line_on_words(line, terminal_columns):
557    """Wrap one ANSI-colored line on word boundaries for terminal display."""
558    if terminal_columns < 1:
559        return [line]
560
561    plain = strip_ansi(line)
562    if len(plain) <= terminal_columns:
563        return [line]
564
565    visible_to_raw = []
566    raw_index = 0
567    while raw_index < len(line):
568        if line[raw_index] == "\x1b":
569            match = ANSI_ESCAPE_RE.match(line, raw_index)
570            if match is not None:
571                raw_index = match.end()
572                continue
573        visible_to_raw.append(raw_index)
574        raw_index += 1
575
576    if len(visible_to_raw) == 0:
577        return [line]
578
579    wrapped = []
580    start = 0
581    visible_len = len(plain)
582    while start < visible_len:
583        while start < visible_len and plain[start] == " ":
584            start += 1
585        if start >= visible_len:
586            break
587
588        max_end = min(visible_len, start + terminal_columns)
589        if max_end == visible_len:
590            end = visible_len
591        else:
592            split_at = plain.rfind(" ", start, max_end)
593            end = split_at if split_at > start else max_end
594
595        raw_start = visible_to_raw[start]
596        raw_end = len(line) if end >= visible_len else visible_to_raw[end]
597        wrapped.append(line[raw_start:raw_end].rstrip())
598
599        if end < visible_len and plain[end] == " ":
600            start = end + 1
601        else:
602            start = end
603
604    return wrapped if wrapped else [line]

Wrap one ANSI-colored line on word boundaries for terminal display.

def wrap_screen_text_for_terminal(screen_text):
607def wrap_screen_text_for_terminal(screen_text):
608    """Wrap full screen text to terminal width without mid-word breaks."""
609    terminal_columns = shutil.get_terminal_size(fallback=(120, 40)).columns
610    wrapped_lines = []
611    for raw_line in screen_text.split("\n"):
612        wrapped_lines.extend(wrap_ansi_line_on_words(raw_line, terminal_columns))
613    return "\n".join(wrapped_lines)

Wrap full screen text to terminal width without mid-word breaks.

def render_text_with_cursor(text, cursor_index):
616def render_text_with_cursor(text, cursor_index):
617    """Render text with a CLI-style inverted-character cursor."""
618    if cursor_index < 0:
619        cursor_index = 0
620    if cursor_index > len(text):
621        cursor_index = len(text)
622    if cursor_index == len(text):
623        return text + make_inverted_text(" ")
624    current_char = text[cursor_index]
625    return (
626        text[:cursor_index]
627        + make_inverted_text(current_char)
628        + text[cursor_index + 1 :]
629    )

Render text with a CLI-style inverted-character cursor.

def is_up_key(key):
635def is_up_key(key):
636    if key in ("k",):
637        return True
638    if not key.startswith("\x1b"):
639        return False
640    return key in ("\x1b[A", "\x1bOA") or (key.startswith("\x1b[") and key.endswith("A"))
def is_down_key(key):
643def is_down_key(key):
644    if key in ("j",):
645        return True
646    if not key.startswith("\x1b"):
647        return False
648    return key in ("\x1b[B", "\x1bOB") or (key.startswith("\x1b[") and key.endswith("B"))
def is_left_key(key):
651def is_left_key(key):
652    if not key.startswith("\x1b"):
653        return False
654    return key in ("\x1b[D", "\x1bOD") or (key.startswith("\x1b[") and key.endswith("D"))
def is_right_key(key):
657def is_right_key(key):
658    if not key.startswith("\x1b"):
659        return False
660    return key in ("\x1b[C", "\x1bOC") or (key.startswith("\x1b[") and key.endswith("C"))
def is_page_up_key(key):
663def is_page_up_key(key):
664    if key in ("K",):
665        return True
666    if key == "\x1b[1;2A":
667        # Shift+Up (laptop-friendly alias; no PgUp key without Fn).
668        return True
669    return key == "\x1b[5~" or (key.startswith("\x1b[") and "[5" in key and key.endswith("~"))
def is_page_down_key(key):
672def is_page_down_key(key):
673    if key in ("J",):
674        return True
675    if key == "\x1b[1;2B":
676        # Shift+Down (laptop-friendly alias; no PgDn key without Fn).
677        return True
678    return key == "\x1b[6~" or (key.startswith("\x1b[") and "[6" in key and key.endswith("~"))
def is_delete_key(key):
681def is_delete_key(key):
682    return key == "\x1b[3~" or (key.startswith("\x1b[") and "[3" in key and key.endswith("~"))
def is_enter_key(key):
685def is_enter_key(key):
686    return key in ("\r", "\n")
def is_tab_key(key):
689def is_tab_key(key):
690    return key == "\t"
def is_select_key(key):
693def is_select_key(key):
694    """Space/Enter — used only inside the inline value editors."""
695    return key in (" ", "\r", "\n")

Space/Enter — used only inside the inline value editors.

def is_depth_key(key):
698def is_depth_key(key):
699    return key in tuple("0123456789")
def entry_default_expanded(entry, depth_baseline):
705def entry_default_expanded(entry, depth_baseline):
706    """Whether an entry's children show when there is no explicit manual
707    override for it.
708
709    ``depth_baseline`` is None before any digit key has been pressed this
710    session (only replaced-root containers start collapsed); otherwise it's
711    the last digit (0-9) pressed: 0 expands everything, N in 1-9 shows
712    through depth N-1 and collapses anything deeper.
713    """
714    if depth_baseline is None:
715        return not entry["is_replaced_root"]
716    if depth_baseline == 0:
717        return True
718    return entry["depth"] < depth_baseline - 1

Whether an entry's children show when there is no explicit manual override for it.

depth_baseline is None before any digit key has been pressed this session (only replaced-root containers start collapsed); otherwise it's the last digit (0-9) pressed: 0 expands everything, N in 1-9 shows through depth N-1 and collapses anything deeper.

def is_entry_expanded(entry, depth_baseline, expanded_overrides):
721def is_entry_expanded(entry, depth_baseline, expanded_overrides):
722    """Effective expand state: a manual ←/→ override, else the baseline."""
723    if entry["id"] in expanded_overrides:
724        return expanded_overrides[entry["id"]]
725    return entry_default_expanded(entry, depth_baseline)

Effective expand state: a manual ←/→ override, else the baseline.

def is_entry_visible(entry, entries_by_id, depth_baseline, expanded_overrides):
728def is_entry_visible(entry, entries_by_id, depth_baseline, expanded_overrides):
729    """False if any ancestor of ``entry`` is currently collapsed."""
730    ancestor_id = entry["id"]
731    while True:
732        split_at = ancestor_id.rfind(".")
733        if split_at <= 0:
734            return True
735        ancestor_id = ancestor_id[:split_at]
736        ancestor = entries_by_id.get(ancestor_id)
737        if (
738            ancestor is not None
739            and ancestor["has_children"]
740            and not is_entry_expanded(ancestor, depth_baseline, expanded_overrides)
741        ):
742            return False

False if any ancestor of entry is currently collapsed.

def set_module_id_mode(module_id, mode):
758def set_module_id_mode(module_id, mode):
759    """Set (or toggle off) an id-based mode, enforcing id-list exclusivity."""
760    ids_perforate = dedupe_list(GPA.pc.get_module_ids_to_perforate())
761    ids_track = dedupe_list(GPA.pc.get_module_ids_to_track())
762
763    if mode == "perforated":
764        if module_id in ids_perforate:
765            ids_perforate = [value for value in ids_perforate if value != module_id]
766        else:
767            ids_perforate.append(module_id)
768            ids_track = [value for value in ids_track if value != module_id]
769            _clear_tracked_params_for_module_id(module_id)
770    elif mode == "tracked":
771        if module_id in ids_track:
772            ids_track = [value for value in ids_track if value != module_id]
773        else:
774            ids_track.append(module_id)
775            ids_perforate = [value for value in ids_perforate if value != module_id]
776            _clear_tracked_params_for_module_id(module_id)
777
778    GPA.pc.set_module_ids_to_perforate(ids_perforate)
779    GPA.pc.set_module_ids_to_track(ids_track)

Set (or toggle off) an id-based mode, enforcing id-list exclusivity.

def set_module_name_mode(module_type_name, mode, entries=None):
782def set_module_name_mode(module_type_name, mode, entries=None):
783    """Set (or toggle off) a type-name-based mode, enforcing name-list exclusivity."""
784    names_perforate = dedupe_list(GPA.pc.get_module_names_to_perforate())
785    names_track = dedupe_list(GPA.pc.get_module_names_to_track())
786
787    if mode == "perforated":
788        if module_type_name in names_perforate:
789            names_perforate = [v for v in names_perforate if v != module_type_name]
790        else:
791            names_perforate.append(module_type_name)
792            names_track = [v for v in names_track if v != module_type_name]
793            if entries is not None:
794                for entry in entries:
795                    if entry["type_name"] == module_type_name:
796                        _clear_tracked_params_for_module_id(entry["id"])
797    elif mode == "tracked":
798        if module_type_name in names_track:
799            names_track = [v for v in names_track if v != module_type_name]
800        else:
801            names_track.append(module_type_name)
802            names_perforate = [v for v in names_perforate if v != module_type_name]
803            if entries is not None:
804                for entry in entries:
805                    if entry["type_name"] == module_type_name:
806                        _clear_tracked_params_for_module_id(entry["id"])
807
808    GPA.pc.set_module_names_to_perforate(names_perforate)
809    GPA.pc.set_module_names_to_track(names_track)

Set (or toggle off) a type-name-based mode, enforcing name-list exclusivity.

def get_fused_pair_map():
815def get_fused_pair_map():
816    """Map each fused module id to its role and partner: id -> (role, partner_id)."""
817    fused = {}
818    for head_id, norm_id in GPA.pc.get_modules_to_fuse():
819        fused[head_id] = ("head", norm_id)
820        fused[norm_id] = ("norm", head_id)
821    return fused

Map each fused module id to its role and partner: id -> (role, partner_id).

def unfuse_pair(module_id, entries):
824def unfuse_pair(module_id, entries):
825    """Remove the pair containing this module and track both of its modules."""
826    pairs = [list(pair) for pair in GPA.pc.get_modules_to_fuse()]
827    pair = next(p for p in pairs if module_id in p)
828    if pair in (GPA.pc.get_python_supplied("modules_to_fuse") or []):
829        return (
830            f"{pair[0]} + {pair[1]} is fused by a Python call (modules_to_fuse) — "
831            "change it in your script; the CLI can't override it."
832        )
833    GPA.pc.set_modules_to_fuse([p for p in pairs if p != pair])
834    by_id = {entry["id"]: entry for entry in entries}
835    for member_id in pair:
836        entry = by_id.get(member_id)
837        if entry is None or not entry["trainable"] or id_python_owner(member_id):
838            continue
839        if member_id not in GPA.pc.get_module_ids_to_track():
840            set_module_id_mode(member_id, "tracked")
841    return f"un-fused {pair[0]} + {pair[1]}; both are now tracked"

Remove the pair containing this module and track both of its modules.

def stage_as_fuse_head(entry):
844def stage_as_fuse_head(entry):
845    """Validate that a module can be the head of a fused pair.
846
847    Returns (module_id, message) on success or (None, message) on failure.
848    """
849    if entry["is_replaced_root"] or entry["in_replaced"]:
850        return None, (
851            f"{entry['id']} is inside a module that will be restructured — its id "
852            "won't exist at training time, so it can't be fused."
853        )
854    if not entry["trainable"]:
855        return None, (
856            f"{entry['id']} is not trainable, so it can't be the head of a fused pair."
857        )
858    if entry["id"] in get_fused_pair_map():
859        return None, f"{entry['id']} is already fused."
860    return entry["id"], (
861        f"↓ {entry['id']} staged as head (runs first) — navigate to the norm and press f"
862    )

Validate that a module can be the head of a fused pair.

Returns (module_id, message) on success or (None, message) on failure.

def fuse_pair(head_entry, norm_entry, entries, resolved):
865def fuse_pair(head_entry, norm_entry, entries, resolved):
866    """Fuse head_entry with norm_entry.
867
868    Returns a short message describing what happened or why nothing did.
869    """
870    head_id = head_entry["id"]
871    norm_id = norm_entry["id"]
872    if head_id == norm_id:
873        return "Select two different modules to form a fused pair."
874    if any(e["is_replaced_root"] or e["in_replaced"] for e in (head_entry, norm_entry)):
875        return (
876            "One of the selected modules is inside a module that will be restructured "
877            "— its id won't exist at training time, so it can't be fused."
878        )
879    if not head_entry["trainable"]:
880        return (
881            f"{head_id} is not trainable, so it can't be the head of a fused pair. "
882            "Stage a trainable module as the head first."
883        )
884    fused = get_fused_pair_map()
885    for module_id in (head_id, norm_id):
886        if module_id in fused:
887            return f"{module_id} is already fused with {fused[module_id][1]}."
888        for other_id in fused:
889            if other_id.startswith(module_id + ".") or module_id.startswith(other_id + "."):
890                return f"{module_id} overlaps {other_id}, which is already fused."
891    module_counts = {}
892    for e in entries:
893        module_counts[id(e["module"])] = module_counts.get(id(e["module"]), 0) + 1
894    for e in (head_entry, norm_entry):
895        if module_counts[id(e["module"])] > 1:
896            return f"{e['id']} is used in more than one place, so it can't be fused."
897    if id_python_owner(head_id) == "module_ids_to_track":
898        return python_owned_message(head_id, "module_ids_to_track")
899    if resolved[head_id]["source"] == "inherited":
900        return (
901            f"{head_id} gets its mode from {resolved[head_id]['origin_id']}; "
902            "clear that first so the head can be perforated on its own."
903        )
904    pairs = [list(pair) for pair in GPA.pc.get_modules_to_fuse()]
905    pairs.append([head_id, norm_id])
906    GPA.pc.set_modules_to_fuse(pairs)
907    if head_id not in GPA.pc.get_module_ids_to_perforate():
908        set_module_id_mode(head_id, "perforated")
909    return f"fused {head_id} (head) with {norm_id} (norm); head is perforated"

Fuse head_entry with norm_entry.

Returns a short message describing what happened or why nothing did.

def set_all_types_to_tracking(entries):
923def set_all_types_to_tracking(entries):
924    """Reset every module to tracked: clear id/type perforate marks, then
925    track every type that owns parameters directly. A quick way to start from
926    "track everything" before manually perforating the head/last layer.
927    """
928    GPA.pc.set_module_ids_to_perforate(
929        GPA.pc.get_python_supplied("module_ids_to_perforate") or []
930    )
931    GPA.pc.set_module_names_to_perforate(
932        GPA.pc.get_python_supplied("module_names_to_perforate") or []
933    )
934    # Only types that own parameters directly. Tracking a container would apply
935    # to everything inside it and make ids and block rules there unreachable.
936    all_type_names = dedupe_list(
937        entry["type_name"] for entry in entries if entry["direct_param_count"] > 0
938    )
939    GPA.pc.set_module_names_to_track(all_type_names)

Reset every module to tracked: clear id/type perforate marks, then track every type that owns parameters directly. A quick way to start from "track everything" before manually perforating the head/last layer.

def auto_track_unset_direct_params(entries, resolved):
963def auto_track_unset_direct_params(entries, resolved):
964    """Auto-track direct params for modules whose all child-module params are covered."""
965    param_ids = list(GPA.pc.get_parameter_ids_to_track())
966    changed = False
967
968    for entry in entries:
969        if entry["in_replaced"] or entry["is_replaced_root"]:
970            continue
971        if not _would_auto_track_params(entry, entries, resolved):
972            continue
973        module_id = entry["id"]
974        for param_name, _ in entry["module"].named_parameters(recurse=False):
975            param_id = module_id + "." + param_name
976            if param_id not in param_ids:
977                param_ids.append(param_id)
978                changed = True
979
980    if changed:
981        GPA.pc.set_parameter_ids_to_track(param_ids)

Auto-track direct params for modules whose all child-module params are covered.

def clear_module_mode(entry):
 984def clear_module_mode(entry):
 985    """Clear a direct id rule on this module; if none, clear its type rule.
 986
 987    Returns a short human message describing what was cleared.
 988    """
 989    module_id = entry["id"]
 990    type_name = entry["type_name"]
 991
 992    ids_perforate = [v for v in GPA.pc.get_module_ids_to_perforate() if v != module_id]
 993    ids_track = [v for v in GPA.pc.get_module_ids_to_track() if v != module_id]
 994    if (
 995        module_id in GPA.pc.get_module_ids_to_perforate()
 996        or module_id in GPA.pc.get_module_ids_to_track()
 997    ):
 998        owner = id_python_owner(module_id)
 999        if owner:
1000            return python_owned_message(module_id, owner)
1001        GPA.pc.set_module_ids_to_perforate(ids_perforate)
1002        GPA.pc.set_module_ids_to_track(ids_track)
1003        return f"cleared {module_id}"
1004
1005    if (
1006        type_name in GPA.pc.get_module_names_to_perforate()
1007        or type_name in GPA.pc.get_module_names_to_track()
1008    ):
1009        owner = type_python_owner(type_name)
1010        if owner:
1011            return python_owned_message(f"the {type_name} type rule", owner)
1012        GPA.pc.set_module_names_to_perforate(
1013            [v for v in GPA.pc.get_module_names_to_perforate() if v != type_name]
1014        )
1015        GPA.pc.set_module_names_to_track(
1016            [v for v in GPA.pc.get_module_names_to_track() if v != type_name]
1017        )
1018        return f"cleared the {type_name} type rule"
1019
1020    return "nothing to clear on this module"

Clear a direct id rule on this module; if none, clear its type rule.

Returns a short human message describing what was cleared.

def type_rule_entries(entries):
1026def type_rule_entries(entries):
1027    """Active type-name rules as (type_name, mode, live count) tuples."""
1028    counts = {}
1029    for entry in entries:
1030        if entry["in_replaced"]:
1031            continue
1032        counts[entry["type_name"]] = counts.get(entry["type_name"], 0) + 1
1033
1034    rules = []
1035    for type_name in sorted(GPA.pc.get_module_names_to_perforate()):
1036        rules.append((type_name, "perforated", counts.get(type_name, 0)))
1037    for type_name in sorted(GPA.pc.get_module_names_to_track()):
1038        rules.append((type_name, "tracked", counts.get(type_name, 0)))
1039    return rules

Active type-name rules as (type_name, mode, live count) tuples.

def unset_module_entries(entries, resolved):
1042def unset_module_entries(entries, resolved):
1043    """Entries that own parameters, have no resolved mode, and are not auto-trackable."""
1044    unset = []
1045    fused = get_fused_pair_map()
1046    for entry in entries:
1047        if entry["in_replaced"] or entry["is_replaced_root"]:
1048            continue
1049        if entry["direct_param_count"] <= 0:
1050            continue
1051        if fused.get(entry["id"], (None,))[0] == "norm":
1052            continue
1053        if resolved[entry["id"]]["eff"] is None:
1054            if not _would_auto_track_params(entry, entries, resolved):
1055                unset.append(entry)
1056    return unset

Entries that own parameters, have no resolved mode, and are not auto-trackable.

def build_budget_line(entries, resolved):
1059def build_budget_line(entries, resolved):
1060    """The perforation-budget line: parameter cost of the current selection."""
1061    added = 0
1062    total_model_params = 0
1063    seen_added = set()
1064    seen_total = set()
1065    fused = get_fused_pair_map()
1066
1067    for entry in entries:
1068        for _name, parameter in entry["module"].named_parameters(recurse=False):
1069            pid = id(parameter)
1070            if pid not in seen_total:
1071                seen_total.add(pid)
1072                total_model_params += parameter.numel()
1073
1074        fused_role = fused.get(entry["id"])
1075        norm_of_perforated_head = (
1076            fused_role is not None
1077            and fused_role[0] == "norm"
1078            and resolved[fused_role[1]]["eff"] == "perforated"
1079        )
1080        if norm_of_perforated_head or (
1081            resolved[entry["id"]]["eff"] == "perforated" and entry["trainable"]
1082        ):
1083            for _name, parameter in entry["module"].named_parameters(recurse=False):
1084                pid = id(parameter)
1085                if pid not in seen_added:
1086                    seen_added.add(pid)
1087                    added += parameter.numel()
1088
1089    pct = (100.0 * added / total_model_params) if total_model_params else 0.0
1090    return (
1091        f"Perforation budget:  +{format_human_count(added)} params per dendrite cycle"
1092        f"  ·  model {format_human_count(total_model_params)}"
1093        f"  (+{pct:.1f}% / cycle)"
1094    )

The perforation-budget line: parameter cost of the current selection.

RUNTIME_ONLY_CONFIG_KEYS = {'config_file'}
DESCRIPTION_FILE_NAME = 'configuration_descriptions.json'
DESCRIPTION_CACHE = None
LABEL_IMPACTFUL = 'impactful'
LABEL_SUPPORTING = 'supporting'
def load_description_data():
1119def load_description_data():
1120    """Load bucket and setting metadata from local JSON."""
1121    global DESCRIPTION_CACHE
1122    if DESCRIPTION_CACHE is not None:
1123        return DESCRIPTION_CACHE
1124
1125    description_file = os.path.join(os.path.dirname(__file__), DESCRIPTION_FILE_NAME)
1126    payload = {}
1127    try:
1128        with open(description_file, "r") as file_handle:
1129            payload = json.load(file_handle)
1130    except Exception:
1131        payload = {}
1132
1133    bucket_entries = payload.get("buckets", {})
1134    bucket_descriptions = {}
1135    setting_descriptions = {}
1136    setting_labels = {}
1137    setting_to_bucket = {}
1138    settings_by_bucket = {}
1139    bucket_order = []
1140
1141    if isinstance(bucket_entries, dict):
1142        for bucket_name, bucket_payload in bucket_entries.items():
1143            bucket_order.append(bucket_name)
1144            if isinstance(bucket_payload, dict):
1145                bucket_descriptions[bucket_name] = bucket_payload.get("description", "")
1146                bucket_settings = bucket_payload.get("settings", {})
1147                ordered_setting_names = []
1148                if isinstance(bucket_settings, dict):
1149                    for setting_name, setting_payload in bucket_settings.items():
1150                        ordered_setting_names.append(setting_name)
1151                        setting_to_bucket[setting_name] = bucket_name
1152                        if isinstance(setting_payload, dict):
1153                            setting_descriptions[setting_name] = setting_payload.get(
1154                                "description", ""
1155                            )
1156                            setting_labels[setting_name] = _normalize_label(
1157                                setting_payload.get("label")
1158                            )
1159                        elif isinstance(setting_payload, str):
1160                            setting_descriptions[setting_name] = setting_payload
1161                            setting_labels[setting_name] = LABEL_SUPPORTING
1162                settings_by_bucket[bucket_name] = ordered_setting_names
1163            elif isinstance(bucket_payload, str):
1164                bucket_descriptions[bucket_name] = bucket_payload
1165
1166    DESCRIPTION_CACHE = {
1167        "buckets": bucket_descriptions,
1168        "bucket_order": bucket_order,
1169        "settings": setting_descriptions,
1170        "setting_labels": setting_labels,
1171        "setting_to_bucket": setting_to_bucket,
1172        "settings_by_bucket": settings_by_bucket,
1173    }
1174    return DESCRIPTION_CACHE

Load bucket and setting metadata from local JSON.

def get_setting_label(setting_name):
1177def get_setting_label(setting_name):
1178    """Get the tier (impactful / supporting) for one setting."""
1179    setting_labels = load_description_data().get("setting_labels", {})
1180    if setting_name in setting_labels:
1181        return _normalize_label(setting_labels[setting_name])
1182    return LABEL_SUPPORTING

Get the tier (impactful / supporting) for one setting.

def format_setting_value(value):
1185def format_setting_value(value):
1186    """Format setting values for compact configuration screen display."""
1187    if value is None:
1188        return "None"
1189    if callable(value):
1190        text = GPA.callable_config_repr(value)
1191    else:
1192        text = str(value)
1193    if len(text) > 140:
1194        return text[:137] + "..."
1195    return text

Format setting values for compact configuration screen display.

SWITCH_MODE_NAMES = ['DOING_SWITCH_EVERY_TIME', 'DOING_HISTORY', 'DOING_FIXED_SWITCH', 'DOING_NO_SWITCH']
FORWARD_FUNCTION_NAMES = ['relu', 'tanh', 'sigmoid']
def get_enum_options(setting_name):
1216def get_enum_options(setting_name):
1217    """Return the ordered set of values for an enum-like setting, else None."""
1218    if setting_name == "switch_mode":
1219        return list(_switch_mode_values())
1220    if setting_name == "pai_forward_function":
1221        return list(FORWARD_FUNCTION_NAMES)
1222    return None

Return the ordered set of values for an enum-like setting, else None.

def format_run_setting_value(setting_name, value):
1225def format_run_setting_value(setting_name, value):
1226    """Display string for a run setting, naming enum values."""
1227    if setting_name == "switch_mode":
1228        try:
1229            return SWITCH_MODE_NAMES[list(_switch_mode_values()).index(value)]
1230        except (ValueError, IndexError):
1231            return str(value)
1232    if setting_name == "pai_forward_function":
1233        name = getattr(value, "__name__", None)
1234        if name in FORWARD_FUNCTION_NAMES:
1235            return name
1236        return format_setting_value(value)
1237    return format_setting_value(value)

Display string for a run setting, naming enum values.

def cycle_enum_setting(setting_name, current_value):
1240def cycle_enum_setting(setting_name, current_value):
1241    """Compute and apply the next value for an enum setting."""
1242    options = get_enum_options(setting_name)
1243    if not options:
1244        return False, f"{setting_name} is not an enum setting."
1245
1246    if setting_name == "pai_forward_function":
1247        current_name = getattr(current_value, "__name__", None)
1248        index = options.index(current_name) if current_name in options else -1
1249        next_name = options[(index + 1) % len(options)]
1250        next_value = getattr(torch, next_name) if torch is not None else next_name
1251        return apply_setting_value(setting_name, next_value)
1252
1253    index = options.index(current_value) if current_value in options else -1
1254    next_value = options[(index + 1) % len(options)]
1255    return apply_setting_value(setting_name, next_value)

Compute and apply the next value for an enum setting.

def get_global_setting_value(setting_name):
1258def get_global_setting_value(setting_name):
1259    """Read one setting value from the global config object."""
1260    getter = getattr(GPA.pc, f"get_{setting_name}", None)
1261    if getter is not None:
1262        try:
1263            return getter()
1264        except Exception:
1265            return "<unavailable>"
1266    if hasattr(GPA.pc, setting_name) and not callable(getattr(GPA.pc, setting_name)):
1267        return getattr(GPA.pc, setting_name)
1268    return "<unavailable>"

Read one setting value from the global config object.

def apply_setting_value(setting_name, value):
1271def apply_setting_value(setting_name, value):
1272    """Apply one setting value through a setter when available."""
1273    setter = getattr(GPA.pc, f"set_{setting_name}", None)
1274    if setter is not None:
1275        setter(value)
1276        return True, ""
1277    if hasattr(GPA.pc, setting_name) and not callable(getattr(GPA.pc, setting_name)):
1278        setattr(GPA.pc, setting_name, value)
1279        return True, ""
1280    return False, f"Setting {setting_name} is not editable."

Apply one setting value through a setter when available.

def parse_value_from_text(text, sample_value):
1283def parse_value_from_text(text, sample_value):
1284    """Parse user text into the same type as a sample value where possible."""
1285    if isinstance(sample_value, bool):
1286        lowered = text.strip().lower()
1287        if lowered in ("1", "true", "t", "yes", "y", "on"):
1288            return True
1289        if lowered in ("0", "false", "f", "no", "n", "off"):
1290            return False
1291        raise ValueError("Expected boolean value (true/false).")
1292    if isinstance(sample_value, int) and not isinstance(sample_value, bool):
1293        return int(text.strip())
1294    if isinstance(sample_value, float):
1295        return float(text.strip())
1296    return text

Parse user text into the same type as a sample value where possible.

def get_all_global_parameters():
1299def get_all_global_parameters():
1300    """Collect JSON-declared run settings as name -> current value."""
1301    description_data = load_description_data()
1302    visible_names = []
1303    for bucket_name in description_data.get("bucket_order", []):
1304        visible_names.extend(
1305            description_data.get("settings_by_bucket", {}).get(bucket_name, [])
1306        )
1307    values = {}
1308    for setting_name in visible_names:
1309        if setting_name in RUNTIME_ONLY_CONFIG_KEYS:
1310            continue
1311        values[setting_name] = get_global_setting_value(setting_name)
1312    return values

Collect JSON-declared run settings as name -> current value.

def build_run_items(expanded_buckets):
1315def build_run_items(expanded_buckets):
1316    """Build the Run settings list: bucket rows, tier-sorted settings, dividers."""
1317    values = get_all_global_parameters()
1318    description_data = load_description_data()
1319    items = []
1320
1321    for bucket_name in description_data.get("bucket_order", []):
1322        names = [
1323            name
1324            for name in description_data.get("settings_by_bucket", {}).get(bucket_name, [])
1325            if name not in RUNTIME_ONLY_CONFIG_KEYS
1326        ]
1327        if not names:
1328            continue
1329
1330        is_expanded = expanded_buckets.get(bucket_name, False)
1331        items.append(
1332            {
1333                "type": "bucket",
1334                "bucket": bucket_name,
1335                "is_expanded": is_expanded,
1336                "count": len(names),
1337            }
1338        )
1339        if not is_expanded:
1340            continue
1341
1342        impactful = [n for n in names if get_setting_label(n) == LABEL_IMPACTFUL]
1343        supporting = [n for n in names if get_setting_label(n) != LABEL_IMPACTFUL]
1344
1345        def _setting_item(setting_name):
1346            return {
1347                "type": "setting",
1348                "bucket": bucket_name,
1349                "name": setting_name,
1350                "value": values.get(setting_name, "<unavailable>"),
1351            }
1352
1353        for setting_name in impactful:
1354            items.append(_setting_item(setting_name))
1355        if impactful and supporting:
1356            items.append({"type": "divider", "bucket": bucket_name})
1357        for setting_name in supporting:
1358            items.append(_setting_item(setting_name))
1359
1360    return items

Build the Run settings list: bucket rows, tier-sorted settings, dividers.

def load_existing_module_settings():
1366def load_existing_module_settings():
1367    """Load existing module_settings from local config sources."""
1368    merged = {}
1369    source_paths = []
1370    config_file = GPA.pc.get_config_file()
1371    run_config = GPA.pc.get_run_config_path()
1372    if config_file:
1373        source_paths.append(config_file)
1374    if run_config:
1375        source_paths.append(run_config)
1376
1377    for source_path in source_paths:
1378        if not source_path or not os.path.exists(source_path):
1379            continue
1380        try:
1381            with open(source_path, "r") as file_handle:
1382                payload = json.load(file_handle)
1383            module_settings = payload.get("module_settings", {})
1384            for scope_key, values in module_settings.items():
1385                if isinstance(values, dict):
1386                    merged[scope_key] = dict(values)
1387        except Exception:
1388            continue
1389    return merged

Load existing module_settings from local config sources.

def get_scope_values(scope_key, module_settings_overrides, existing_module_settings):
1392def get_scope_values(scope_key, module_settings_overrides, existing_module_settings):
1393    """Merged override values for one scope: saved data plus in-session edits."""
1394    values = {}
1395    if scope_key in existing_module_settings:
1396        values.update(existing_module_settings[scope_key])
1397    if scope_key in module_settings_overrides:
1398        values.update(module_settings_overrides[scope_key])
1399    return values

Merged override values for one scope: saved data plus in-session edits.

def set_module_scoped_value(module_settings_overrides, scope_key, setting_name, value):
1402def set_module_scoped_value(module_settings_overrides, scope_key, setting_name, value):
1403    """Write one override value into in-session state."""
1404    module_settings_overrides.setdefault(scope_key, {})[setting_name] = value

Write one override value into in-session state.

def get_override_scope_for_entry(entry, resolved):
1407def get_override_scope_for_entry(entry, resolved):
1408    """Determine the override scope for a target, or a reason it is blocked."""
1409    record = resolved[entry["id"]]
1410    if entry["is_replaced_root"] or entry["in_replaced"]:
1411        return None, (
1412            "Overrides are not available inside a module that will be restructured."
1413        )
1414    if record["eff"] is None:
1415        return None, (
1416            "Overrides are only for perforated modules. Perforate this one first "
1417            "(p), or track it if you just want it monitored."
1418        )
1419    if record["source"] == "inherited":
1420        origin = record["origin_id"]
1421        return None, (
1422            f"This module inherits {origin}'s mode. Open overrides on {origin} to "
1423            "change settings for the whole subtree."
1424        )
1425    if record["eff"] != "perforated":
1426        return None, "Overrides are only for perforated modules — this one is tracked."
1427
1428    if record["source"] == "type":
1429        return (
1430            {"kind": "type", "scope_key": entry["type_name"]},
1431            None,
1432        )
1433    return ({"kind": "id", "scope_key": entry["id"]}, None)

Determine the override scope for a target, or a reason it is blocked.

def persist_module_settings_updates(module_settings_overrides, overwrite_config_file=False):
1436def persist_module_settings_updates(module_settings_overrides, overwrite_config_file=False):
1437    """Persist in-session module_settings updates to local config JSON files."""
1438    if not module_settings_overrides:
1439        return
1440
1441    destinations = []
1442    run_config = GPA.pc.get_run_config_path()
1443    if run_config:
1444        destinations.append(run_config)
1445    if overwrite_config_file:
1446        config_file = GPA.pc.get_config_file()
1447        if config_file and config_file not in destinations:
1448            destinations.append(config_file)
1449
1450    for destination in destinations:
1451        payload = {}
1452        if os.path.exists(destination):
1453            try:
1454                with open(destination, "r") as file_handle:
1455                    payload = json.load(file_handle)
1456            except Exception:
1457                payload = {}
1458
1459        module_settings = payload.get("module_settings", {})
1460        if not isinstance(module_settings, dict):
1461            module_settings = {}
1462        for scope_key, values in module_settings_overrides.items():
1463            existing = module_settings.get(scope_key, {})
1464            if not isinstance(existing, dict):
1465                existing = {}
1466            existing.update(values)
1467            module_settings[scope_key] = existing
1468        payload["module_settings"] = module_settings
1469
1470        directory = os.path.dirname(destination)
1471        if directory:
1472            os.makedirs(directory, exist_ok=True)
1473        with open(destination, "w") as file_handle:
1474            json.dump(payload, file_handle, indent=2)

Persist in-session module_settings updates to local config JSON files.

CUSTOMIZABLE_SETTING_NAMES = ['output_dimensions']
def get_setting_description(setting_name):
1480def get_setting_description(setting_name):
1481    """Help text for one setting."""
1482    descriptions = load_description_data().get("settings", {})
1483    return descriptions.get(setting_name, f"No description available for {setting_name}.")

Help text for one setting.

def get_bucket_description(bucket_name):
1486def get_bucket_description(bucket_name):
1487    descriptions = load_description_data().get("buckets", {})
1488    return descriptions.get(bucket_name, "No description available.")
HR = ' ──────────────────────────────────────────────────────────────────────'
def terminal_size():
1497def terminal_size():
1498    return shutil.get_terminal_size(fallback=(120, 40))
def render_tab_bar(active_screen):
1501def render_tab_bar(active_screen):
1502    """The `[ Targets | Run settings ]` tab bar with the active screen lit."""
1503    targets = "Targets"
1504    run = "Run settings"
1505    if active_screen == "targets":
1506        targets = color_text(targets, COLOR_ACCENT)
1507    else:
1508        run = color_text(run, COLOR_ACCENT)
1509    return f"[ {targets} │ {run} ]" + " " * 12 + dim("[Tab] switch panel    h legend    ? help")

The [ Targets | Run settings ] tab bar with the active screen lit.

MODE_VERB = {'perforated': 'perforate', 'tracked': 'track'}
def mode_verb(mode):
1515def mode_verb(mode):
1516    """Present-tense verb form of a resolved mode for user-facing display."""
1517    return MODE_VERB.get(mode, str(mode))

Present-tense verb form of a resolved mode for user-facing display.

def make_target_marker(entry, record, entries=None, resolved=None):
1520def make_target_marker(entry, record, entries=None, resolved=None):
1521    """(display, plain) marker for one target row."""
1522    if entry["in_replaced"]:
1523        return "     ", "     "
1524
1525    mode = record["eff"]
1526    fuse_role = get_fused_pair_map().get(entry["id"], (None,))[0]
1527    if fuse_role == "norm":
1528        return color_text("↑", COLOR_ACCENT) + "    ", "↑    "
1529    if not entry["trainable"] and record["source"] != "inherited" and (mode == "perforated" or entry["tree_param_count"] > 0):
1530        # Ineligible for perforation; takes precedence over a stale perforate mark.
1531        if mode != "tracked":
1532            return dim("∅") + "    ", "∅    "
1533    if mode is None:
1534        if entry["direct_param_count"] > 0:
1535            if entries is not None and resolved is not None and _would_auto_track_params(entry, entries, resolved):
1536                block_display = color_text("██", COLOR_TRACK)
1537                return f"~ {block_display} ", "~ ██ "
1538            glyph_display = color_text("!", COLOR_ATTENTION)
1539            block_display = color_text("██", COLOR_ATTENTION)
1540            return f"{glyph_display} {block_display} ", "! ██ "
1541        return "     ", "     "
1542
1543    block_display = make_block(mode)
1544    if fuse_role == "head":
1545        return color_text("↓", COLOR_ACCENT) + f" {block_display} ", "↓ ██ "
1546    norm_direct = _is_norm_type(entry["type_name"]) and record["source"] != "inherited"
1547    if norm_direct:
1548        block_display = color_text_on_bg("⚠⚠", "000000", get_color_hex_for_mode(mode))
1549    block_plain = "⚠█" if norm_direct else "██"
1550    if record["source"] == "inherited":
1551        return f"↳ {block_display} ", "↳ ██ "
1552    if record["source"] == "id":
1553        return f"* {block_display} ", f"* {block_plain} "
1554    if record["source"] == "block":
1555        return f"▤ {block_display} ", f"▤ {block_plain} "
1556    return f"  {block_display} ", f"  {block_plain} "

(display, plain) marker for one target row.

def make_block(mode):
1559def make_block(mode):
1560    return color_text("██", get_color_hex_for_mode(mode))
def render_targets_lines( entries, visible_entries, selected_index, resolved, is_expanded_fn, pending_fuse_id=None):
1563def render_targets_lines(entries, visible_entries, selected_index, resolved, is_expanded_fn, pending_fuse_id=None):
1564    """Header + tree + footer for the Targets screen, as a list of lines.
1565
1566    ``is_expanded_fn(entry) -> bool`` reports the current expand state of a
1567    collapsible (``has_children``) entry.
1568    """
1569    need = len(unset_module_entries(entries, resolved))
1570    rules = type_rule_entries(entries)
1571    tied_map = get_tied_parameters_map(entries)
1572    fused_map = get_fused_pair_map()
1573
1574    lines = [render_tab_bar("targets"), ""]
1575    lines.append(
1576        dim(
1577            "  perforate = add dendrites   ·   track = not perforated"
1578            "   "
1579        )
1580    )
1581    lines.append("")
1582
1583    hint = color_text(f"[y] type rules ({len(rules)})", COLOR_ACCENT)
1584    if need > 0:
1585        noun = "module" if need == 1 else "modules"
1586        verb = "needs" if need == 1 else "need"
1587        status = color_text(f"  ⚠ {need} {noun} still {verb} a mode", COLOR_ATTENTION)
1588    else:
1589        status = color_text("  ✓ every parameter is perforated or tracked", COLOR_PERFORATE)
1590    pad = max(2, 58 - len(strip_ansi(status)))
1591    lines.append(status + " " * pad + hint)
1592    lines.append(HR)
1593
1594    def entry_lines(entry, selected):
1595        cursor = color_text("> ", "E8EEEC") if selected else "  "
1596        indent = "  " * entry["depth"]
1597        record = resolved[entry["id"]]
1598
1599        if entry["is_replaced_root"]:
1600            child_count = sum(1 for e in entries if e["replaced_root"] == entry["id"])
1601            glyph = color_text("↯", COLOR_ACCENT)
1602            is_open = is_expanded_fn(entry)
1603            toggle = "[← collapse]" if is_open else "[→ expand]"
1604            return [
1605                f"{cursor}{glyph}   {indent}{entry['id']}  "
1606                f"{dim('[' + entry['type_name'] + ']')}   "
1607                f"{dim('will be restructured for PAI before training')}",
1608                "      "
1609                + dim(
1610                    f"└ {child_count} modules below — ids won't exist at "
1611                    f"train time · target by type (P/T), not id  "
1612                )
1613                + color_text(toggle, COLOR_ACCENT),
1614            ]
1615
1616        collapse_glyph_plain = ""
1617        collapse_glyph = ""
1618        if entry["has_children"]:
1619            is_open = is_expanded_fn(entry)
1620            collapse_glyph_plain = "▾ " if is_open else "▸ "
1621            collapse_glyph = color_text(collapse_glyph_plain.strip(), COLOR_ACCENT) + " "
1622
1623        marker_display, marker_plain = make_target_marker(entry, record, entries, resolved)
1624
1625        if entry["in_replaced"]:
1626            id_part = dim(f"{entry['id']}  [{entry['type_name']}] (id stale)")
1627            return [f"{cursor}{marker_display} {indent}{collapse_glyph}{id_part}"]
1628
1629        id_part = f"{entry['id']}  {dim('[' + entry['type_name'] + ']')}"
1630
1631        tail = ""
1632        if record["eff"] is not None:
1633            mode_color = get_color_hex_for_mode(record["eff"])
1634            tail = color_text(f"mode={mode_verb(record['eff'])}", mode_color)
1635            if record["source"] == "block":
1636                rule = record["block_rule"]
1637                tail += dim(f"  (via {rule['block']} {rule['path']})")
1638            if record["source"] == "inherited":
1639                tail += dim(f"  (via {record['origin_id']})")
1640                if record["overridden"] is not None:
1641                    tail += dim(
1642                        f"  — your {mode_verb(record['overridden']['mode'])} here is ignored"
1643                    )
1644        elif entry["direct_param_count"] > 0:
1645            if _would_auto_track_params(entry, entries, resolved):
1646                tail = color_text("mode=params_tracked", COLOR_TRACK)
1647            else:
1648                tail = color_text("needs a mode", COLOR_ATTENTION)
1649
1650        fuse_role = fused_map.get(entry["id"])
1651        if fuse_role is not None and fuse_role[0] == "norm":
1652            tail = color_text(f"fused into {fuse_role[1]}", COLOR_ACCENT)
1653        elif fuse_role is not None:
1654            tail += "  " + color_text(f"fused with {fuse_role[1]}", COLOR_ACCENT)
1655        elif entry["id"] == pending_fuse_id:
1656            tail += "  " + color_text("↓ runs first", COLOR_ACCENT)
1657        elif (
1658            pending_fuse_id is not None
1659            and selected
1660            and fuse_role is None
1661            and not (entry["is_replaced_root"] or entry["in_replaced"])
1662        ):
1663            tail += "  " + color_text("↑ this module runs second", COLOR_ACCENT)
1664
1665        _direct = entry["direct_param_count"]
1666        _child = entry["tree_param_count"] - entry["direct_param_count"]
1667        if _direct > 0 and _child > 0:
1668            params = dim(f"   params={format_human_count(_direct)}   child-params={format_human_count(_child)}")
1669        elif _direct > 0:
1670            params = dim(f"   params={format_human_count(_direct)}")
1671        elif _child > 0:
1672            params = dim(f"   child-params={format_human_count(_child)}")
1673        else:
1674            params = ""
1675
1676        tied_others = tied_map.get(entry["id"], [])
1677        tie_warning = (
1678            color_text("  ⚠ tied to " + ", ".join(tied_others), COLOR_ATTENTION)
1679            if tied_others else ""
1680        )
1681
1682        lead = (
1683            2 + len(marker_plain) + 1 + len(indent) + len(collapse_glyph_plain)
1684            + len(entry["id"]) + 2 + len(entry["type_name"]) + 2
1685        )
1686        gap = max(2, 46 - lead)
1687        return [
1688            f"{cursor}{marker_display} {indent}{collapse_glyph}{id_part}"
1689            + " " * gap + tail + params + tie_warning
1690        ]
1691
1692    body_lines = []
1693    focus = (0, 1)
1694    for i, entry in enumerate(visible_entries):
1695        rendered = entry_lines(entry, i == selected_index)
1696        if i == selected_index:
1697            focus = (len(body_lines), len(body_lines) + len(rendered))
1698        body_lines.extend(rendered)
1699
1700    footer = [
1701        HR,
1702        dim(build_budget_line(entries, resolved)),
1703        "",
1704        dim(
1705            "p/t perforate·track this module   P/T whole type   x clear   "
1706            "e edit block   "
1707            "A track all   ←/→ collapse·expand   0-9 collapse depth   "
1708            "f stage head / fuse with staged head / unfuse   A track all   ←/→ collapse·expand   0-9 collapse depth   "
1709            "h legend   ↑↓/jk move   s start"
1710        ),
1711    ]
1712    return lines, body_lines, footer, focus

Header + tree + footer for the Targets screen, as a list of lines.

is_expanded_fn(entry) -> bool reports the current expand state of a collapsible (has_children) entry.

def render_block_mode_lines( entries, visible_entries, selected_index, block, template_id, is_expanded_fn):
1715def render_block_mode_lines(entries, visible_entries, selected_index, block, template_id, is_expanded_fn):
1716    """Header + subtree + footer for block mode, shaped like render_targets_lines."""
1717    template_depth = next(e for e in entries if e["id"] == template_id)["depth"]
1718    all_instances = get_block_instances(entries, block)
1719    template_structure = get_instance_structure(entries, template_id)
1720    matching_instances = [
1721        inst for inst in all_instances
1722        if get_instance_structure(entries, inst["id"]) == template_structure
1723    ]
1724    other_count = len(all_instances) - len(matching_instances)
1725
1726    lines = [render_tab_bar("targets"), ""]
1727    heading = color_text(
1728        f"  Editing {len(matching_instances)} {block} module"
1729        + ("s" if len(matching_instances) != 1 else ""),
1730        COLOR_ACCENT,
1731    ) + dim(f"   (showing {template_id} as the example)")
1732    if other_count:
1733        heading += dim(
1734            f"   · {other_count} other {block}"
1735            + ("s have" if other_count != 1 else " has")
1736            + " a different structure — open one with e to edit separately"
1737        )
1738    lines.append(heading)
1739    lines.append(
1740        dim("  A block rule applies to the same path inside every instance with this structure.")
1741    )
1742    lines.append(HR)
1743
1744    body_lines = []
1745    focus = (0, 1)
1746    for i, entry in enumerate(visible_entries):
1747        selected = i == selected_index
1748        cursor = color_text("> ", "E8EEEC") if selected else "  "
1749        indent = "  " * (entry["depth"] - template_depth)
1750        glyph = ""
1751        if entry["has_children"] and entry["id"] != template_id:
1752            glyph = color_text("▾" if is_expanded_fn(entry) else "▸", COLOR_ACCENT) + " "
1753        if entry["id"] == template_id:
1754            label = f"{dim('(' + block + ')')}"
1755            row = f"{cursor}     {label}   {dim('the block itself — use P/T to set a whole type')}"
1756        else:
1757            path = entry["id"][len(template_id):]
1758            rule = find_block_rule(block, path, structure=template_structure)
1759            label = f"{path}  {dim('[' + entry['type_name'] + ']')}"
1760            if rule is not None:
1761                marker = "▤ " + make_block(rule["mode"]) + " "
1762                tail = color_text(f"mode={mode_verb(rule['mode'])}", get_color_hex_for_mode(rule["mode"]))
1763                tail += dim(f"  applies to {block_rule_scope_text(entries, rule)}")
1764                if block_rule_python_owned(rule):
1765                    tail += dim("  (set in your script)")
1766            else:
1767                marker = "     "
1768                tail = dim("no block rule")
1769            if not entry["trainable"] and entry["tree_param_count"] > 0:
1770                marker = dim("∅") + "    "
1771            row = f"{cursor}{marker}{indent}{glyph}{label}   {tail}"
1772        if selected:
1773            focus = (len(body_lines), len(body_lines) + 1)
1774        body_lines.append(row)
1775
1776    footer = [
1777        HR,
1778        "",
1779        dim(
1780            "p/t perforate·track this path in every block   x remove the rule   "
1781            "←/→ collapse·expand   ↑↓/jk move   e or Esc done"
1782        ),
1783    ]
1784    return lines, body_lines, footer, focus

Header + subtree + footer for block mode, shaped like render_targets_lines.

def render_blockrule_overlay(entry, rule, key, choices, selected_index):
1787def render_blockrule_overlay(entry, rule, key, choices, selected_index):
1788    """Modal shown when editing a module whose mode comes from a block rule."""
1789    action = {"p": "perforate", "t": "track", "x": "clear"}[key]
1790    lines = [
1791        "",
1792        "",
1793        "  " + color_text(f"{entry['id']} is set by a block rule", "E8EEEC"),
1794        "",
1795        dim(f"  {rule['block']} {rule['path']}: {mode_verb(rule['mode'])}"
1796            " — it applies to every block of that type,"),
1797        dim(f"  so you can't {action} just this module from here."),
1798        "",
1799    ]
1800    for index, (_name, label) in enumerate(choices):
1801        cursor = color_text("▸ ", COLOR_ACCENT) if index == selected_index else "  "
1802        lines.append(f"  {cursor}{label}")
1803    lines += ["", color_text("  ↑↓/jk move · Enter choose · Esc cancel", COLOR_ACCENT)]
1804    return lines

Modal shown when editing a module whose mode comes from a block rule.

def render_run_settings_lines(items, selected_index, describe_name):
1807def render_run_settings_lines(items, selected_index, describe_name):
1808    """Header + item body + footer for the Run settings screen."""
1809    lines = [
1810        render_tab_bar("run"),
1811        "",
1812        dim("  Run settings — run-wide configuration"),
1813        HR,
1814    ]
1815
1816    body_lines = []
1817    for i, item in enumerate(items):
1818        selected = i == selected_index
1819        cursor = color_text("> ", "E8EEEC") if selected else "  "
1820        if item["type"] == "bucket":
1821            glyph = color_text("▾" if item["is_expanded"] else "▸", COLOR_ACCENT)
1822            body_lines.append(
1823                f"{cursor}{glyph} {item['bucket']} {dim('(' + str(item['count']) + ')')}"
1824            )
1825        elif item["type"] == "divider":
1826            body_lines.append("     " + dim("─ rarely changed ─"))
1827        else:
1828            value_text = format_run_setting_value(item["name"], item["value"])
1829            hint = ""
1830            if get_enum_options(item["name"]) is not None:
1831                hint = dim("  (Enter cycles)")
1832            elif isinstance(item["value"], bool):
1833                hint = dim("  (Enter toggles)")
1834            body_lines.append(f"{cursor}  {item['name']} = {value_text}{hint}")
1835
1836    footer_line = dim(
1837        "→ expand · ← collapse   Enter edit   h describe   "
1838        "↑↓/jk move   Tab switch panel   s start"
1839    )
1840    if describe_name:
1841        footer_line = dim(f"{describe_name} — {get_setting_description(describe_name)}")
1842    footer = [HR, footer_line]
1843    focus = (selected_index, selected_index + 1)
1844    return lines, body_lines, footer, focus

Header + item body + footer for the Run settings screen.

def compose_scrolling_screen(header_lines, body_lines, footer_lines, window_start, focus=None):
1847def compose_scrolling_screen(header_lines, body_lines, footer_lines, window_start, focus=None):
1848    """Join a header + windowed body + footer into one screen string.
1849
1850    Body rows may wrap to more than one terminal row, so the window is measured
1851    in *rendered* rows (after wrapping), not logical lines — otherwise a narrow
1852    terminal pushes the footer and budget line off-screen.
1853    """
1854    size = terminal_size()
1855    columns = size.columns
1856    reserved = get_visual_line_count(header_lines, columns) + get_visual_line_count(
1857        footer_lines, columns
1858    )
1859    # Two rows held back for the ^^^^ / vvvv overflow indicators.
1860    budget = max(1, size.lines - reserved - 3 - 2)
1861
1862    total = len(body_lines)
1863
1864    def rows_for(line):
1865        return max(1, get_visual_line_count([line], columns))
1866
1867    def window_end_from(start):
1868        used = 0
1869        end = start
1870        while end < total:
1871            height = rows_for(body_lines[end])
1872            if end > start and used + height > budget:
1873                break
1874            used += height
1875            end += 1
1876        return end
1877
1878    def window_start_for_end(end):
1879        used = 0
1880        start = end
1881        while start > 0:
1882            height = rows_for(body_lines[start - 1])
1883            if used + height > budget:
1884                break
1885            used += height
1886            start -= 1
1887        return start
1888
1889    if focus is not None:
1890        focus_start, focus_end = focus
1891        focus_start = max(0, min(focus_start, total))
1892        focus_end = max(focus_start + 1, min(focus_end, total))
1893        if focus_start < window_start:
1894            window_start = focus_start
1895        if window_end_from(window_start) < focus_end:
1896            window_start = window_start_for_end(focus_end)
1897
1898    window_start = max(0, min(window_start, total))
1899    window_end = window_end_from(window_start)
1900    # Grow upward if there is spare room at the bottom of the list.
1901    if window_end >= total:
1902        window_start = min(window_start, window_start_for_end(total))
1903        window_end = total
1904
1905    out = list(header_lines)
1906    if window_start > 0:
1907        out.append(dim("  ^^^^ more above ^^^^"))
1908    out.extend(body_lines[window_start:window_end])
1909    if window_end < total:
1910        out.append(dim("  vvvv more below vvvv"))
1911    out.extend(footer_lines)
1912    return "\n".join(out), window_start

Join a header + windowed body + footer into one screen string.

Body rows may wrap to more than one terminal row, so the window is measured in rendered rows (after wrapping), not logical lines — otherwise a narrow terminal pushes the footer and budget line off-screen.

def render_static_overlay(lines):
1915def render_static_overlay(lines):
1916    return "\n".join(lines)
def render_type_rules_overlay(entries):
1919def render_type_rules_overlay(entries):
1920    rules = type_rule_entries(entries)
1921    rows = []
1922    if rules:
1923        for type_name, mode, count in rules:
1924            plain = f"{type_name} → {mode_verb(mode)}  ({count})"
1925            html = (
1926                type_name
1927                + " "
1928                + color_text(f"→ {mode_verb(mode)}", get_color_hex_for_mode(mode))
1929                + dim(f"  ({count})")
1930            )
1931            rows.append((plain, html))
1932    else:
1933        rows.append(("none yet — P / T on a row sets one",
1934                     dim("none yet — P / T on a row sets one")))
1935
1936    width = max(38, max(len(plain) for plain, _ in rows) + 2)
1937    box = ["  " + dim("┌─ Type rules " + "─" * max(1, width - 12) + "┐")]
1938    for plain, html in rows:
1939        box.append("  " + dim("│ ") + html + " " * (width - len(plain) - 1) + dim("│"))
1940    box.append("  " + dim("└" + "─" * width + "┘"))
1941    box.append("  " + color_text("y or Esc to close", COLOR_ACCENT))
1942    return box
def render_overrides_overlay( scope, ov_selected_index, module_settings_overrides, existing_module_settings, describe_name):
1945def render_overrides_overlay(scope, ov_selected_index, module_settings_overrides,
1946                             existing_module_settings, describe_name):
1947    if scope["kind"] == "id":
1948        title = f"Overrides — {scope['scope_key']}"
1949    else:
1950        title = f"Overrides — every {scope['scope_key']}"
1951
1952    scoped = get_scope_values(
1953        scope["scope_key"], module_settings_overrides, existing_module_settings
1954    )
1955
1956    lines = [render_tab_bar("targets"), "", "  " + color_text(title, COLOR_ACCENT), HR, ""]
1957    if not CUSTOMIZABLE_SETTING_NAMES:
1958        lines.append("  " + dim("No per-target settings are customizable in this build."))
1959    for i, name in enumerate(CUSTOMIZABLE_SETTING_NAMES):
1960        overridden = name in scoped
1961        value = scoped[name] if overridden else get_global_setting_value(name)
1962        cursor = color_text("> ", "E8EEEC") if i == ov_selected_index else "  "
1963        tag = dim("(overridden here)") if overridden else dim("(from run settings)")
1964        lines.append(
1965            f"{cursor}{name} = {format_run_setting_value(name, value)}  {tag}"
1966        )
1967
1968    lines.append("")
1969    footer_line = dim(
1970        "Enter edit · h describe · ↑↓/jk move · Esc / x close"
1971    )
1972    if describe_name:
1973        footer_line = dim(f"{describe_name} — {get_setting_description(describe_name)}")
1974    lines.append(footer_line)
1975    return lines
def render_save_overlay(entries, resolved, save_selected_index, config_target_path):
1978def render_save_overlay(entries, resolved, save_selected_index, config_target_path):
1979    unset = unset_module_entries(entries, resolved)
1980    lines = ["", "  " + color_text("Save configuration", "E8EEEC"), ""]
1981
1982    if unset:
1983        noun = "module has" if len(unset) == 1 else "modules have"
1984        lines.append(
1985            color_text(
1986                f"  ⚠  {len(unset)} {noun} parameters but no mode",
1987                COLOR_ATTENTION,
1988            )
1989        )
1990        lines.append("")
1991        for entry in unset[:5]:
1992            lines.append(f"      {dim(entry['id'] + '   [' + entry['type_name'] + ']')}")
1993        if len(unset) > 5:
1994            lines.append(f"      {dim('(+' + str(len(unset) - 5) + ' more)')}")
1995        lines.append("")
1996        lines.append(
1997            dim(
1998                "  These parameters get no dendrites and are not tracked. "
1999                "Usually a mistake."
2000            )
2001        )
2002        lines.append("")
2003        options = [
2004            "Keep editing",
2005            f"Start anyway — I know these {len(unset)} have no mode",
2006        ]
2007    else:
2008        lines.append(dim("  Start training with this configuration:"))
2009        lines.append("")
2010        options = [
2011            ("just this run", "don't touch my saved config"),
2012            (
2013                "and save it as default",
2014                f"write it to {config_target_path}, skip this screen next time",
2015            ),
2016            ("Keep editing", ""),
2017        ]
2018
2019    for i, option in enumerate(options):
2020        marked = i == save_selected_index
2021        pointer = color_text("  ▸ ", "E8EEEC") if marked else "    "
2022        if isinstance(option, tuple):
2023            label, detail = option
2024            text = color_text(label, "E8EEEC") if marked else label
2025            if detail:
2026                text += dim(f"  — {detail}")
2027            lines.append(pointer + text)
2028        else:
2029            text = color_text(option, "E8EEEC") if marked else dim(option)
2030            lines.append(pointer + text)
2031
2032    lines.append("")
2033    lines.append("")
2034    lines.append(
2035        dim("  ↑↓/jk move · Enter choose · Esc / x back to editing")
2036    )
2037    return lines
def render_help_overlay():
2040def render_help_overlay():
2041    p = lambda t: color_text(t, COLOR_PERFORATE)
2042    tr = lambda t: color_text(t, COLOR_TRACK)
2043    return [
2044        "",
2045        "  " + color_text("Keys", "E8EEEC"),
2046        "",
2047        dim("  Targets screen"),
2048        "   p / t     perforate / track this module",
2049        "   P / T     perforate / track every module of this type",
2050        "   x         clear this module (falls back to its type rule)",
2051        "   e         edit a block: set a rule for the same path in every instance",
2052        "             (on a module set by a block rule, p/t/x offer to edit the block)",
2053        "   f         two-step fuse: first press stages a module as the head (↓ runs first);",
2054        "             second press on a different module completes the pair as the norm (↑ runs second).",
2055        "             Pressing f on an already-fused module un-fuses it.",
2056        "             Pressing f again on the staged head cancels staging.",
2057        "   → / ←     expand / collapse a module that will be restructured (↯)",
2058        "   y         show / hide the type-rules list",
2059        "   h         show the marker & colour legend",
2060        "   Enter     open overrides for a perforated module",
2061        "",
2062        dim("  Run settings screen"),
2063        "   → / ←     expand / collapse a bucket",
2064        "   Enter     edit the highlighted setting",
2065        "   h         describe the highlighted setting",
2066        "",
2067        dim("  Everywhere"),
2068        "   ↑↓ / jk   move        Tab  switch panel",
2069        "   s         save & start training",
2070        "   q         quit without configuring",
2071        "",
2072        dim("  Modes"),
2073        "   " + p("perforate") + " = dendrites are added here during training",
2074        "   " + tr("track") + "     = no dendrites, the parameters are just counted",
2075        "   " + dim("↳ inherited") + " = a mode set on an ancestor applies to the whole subtree",
2076        "   " + dim("(see the h legend on the Targets panel for how modes resolve)"),
2077        "",
2078        color_text("  ? or Esc to close", COLOR_ACCENT),
2079    ]
def render_legend_overlay():
2082def render_legend_overlay():
2083    """Describe the Targets-screen markers and colours."""
2084    perf = color_text("██", COLOR_PERFORATE)
2085    trk = color_text("██", COLOR_TRACK)
2086    att = color_text("██", COLOR_ATTENTION)
2087    return [
2088        "",
2089        "  " + color_text("Targets legend", "E8EEEC"),
2090        "",
2091        dim("  Mode blocks"),
2092        f"   {perf}        " + color_text("perforate", COLOR_PERFORATE)
2093        + " — dendrites are added here during training",
2094        f"   {trk}        " + color_text("track", COLOR_TRACK)
2095        + " — no dendrites, the parameters are just counted",
2096        "",
2097        dim("  Marker prefixes"),
2098        f"     {perf}     set by type name — every module of this class",
2099        f"   * {perf}     mode set directly on this module (by id)",
2100        f"   ▤ {perf}     set by a block rule — the same path in every instance of a block",
2101        f"   ↳ {perf}     inherited from an ancestor; applies to the whole subtree",
2102        f"   ! {att}     has parameters but no mode — needs attention",
2103        f"   * {color_text_on_bg('⚠⚠', '000000', COLOR_PERFORATE)}     norm targeted directly — consider fusing (f) or targeting via parent",
2104        "   ↓ ██      fused head: runs first, perforated as the combined block",
2105        "   ↑         fused norm: runs second inside the head's block, needs no mode",
2106        "   " + dim("∅") + "         not trainable (no parameter requires grad) —",
2107        "             can be tracked but not perforated",
2108        f"   ~ {trk}     direct params auto-tracked (all child modules covered)",
2109        "   ↓         staged as fuse head (runs first) — press f on the norm to complete",
2110        "   ↑         currently selected as the norm candidate (runs second)",
2111        "   fused     a head and a norm are perforated as one block;",
2112        "             the head is perforated, the norm just runs inside it",
2113        "   ↯         will be restructured for PAI before training;",
2114        "             target the modules inside it by type (P/T), not by id",
2115        "   (none)    structural container with no parameters of its own",
2116        "",
2117        dim("  Which mode wins  (highest priority first)"),
2118        "   1. inherited — a mode on an ancestor applies to its whole",
2119        "      subtree; a mode set directly on a descendant is ignored",
2120        "      while the ancestor's mode is in effect",
2121        "   2. by id — a mode set on this exact module",
2122        "   3. by block rule — the same path inside every instance of a block",
2123        "   4. by type — a mode set on the module's class name",
2124        "   So: inherited  >  by id  >  by block rule  >  by type.",
2125        "",
2126        color_text("  h or Esc to close", COLOR_ACCENT),
2127    ]

Describe the Targets-screen markers and colours.

def render_quit_overlay():
2130def render_quit_overlay():
2131    return [
2132        "",
2133        "",
2134        "",
2135        "  " + color_text("Quit without configuring?", "E8EEEC"),
2136        "",
2137        dim("  Training will not start. Re-run to configure again, or set"),
2138        dim("  configuration_confirmed=True to skip this screen."),
2139        "",
2140        "  " + color_text("[y] quit", COLOR_ATTENTION) + "     " + dim("[n] keep configuring"),
2141    ]
def render_override_scope_choice_overlay(entry):
2144def render_override_scope_choice_overlay(entry):
2145    """Ask whether overrides should apply to this module only or every module of its type."""
2146    type_name = entry["type_name"]
2147    module_id = entry["id"]
2148    return [
2149        "",
2150        "  " + color_text("Override scope", "E8EEEC"),
2151        "",
2152        dim("  This module is perforated by type. Where should the override apply?"),
2153        "",
2154        f"  " + color_text("[1]", COLOR_ACCENT) + f"  just this module  ({module_id})",
2155        f"  " + color_text("[2]", COLOR_ACCENT) + f"  every {type_name}",
2156        "",
2157        dim("  Esc to cancel"),
2158    ]

Ask whether overrides should apply to this module only or every module of its type.

def read_single_key():
2164def read_single_key():
2165    """Read one keypress, including arrow keys, from stdin.
2166
2167    Ctrl-C raises KeyboardInterrupt so the caller can exit cleanly.
2168    """
2169    file_descriptor = sys.stdin.fileno()
2170    old_settings = termios.tcgetattr(file_descriptor)
2171    try:
2172        tty.setraw(file_descriptor)
2173        first = os.read(file_descriptor, 1)
2174        if first == b"\x03":
2175            raise KeyboardInterrupt
2176        if first != b"\x1b":
2177            return first.decode("latin1")
2178
2179        sequence = bytearray(first)
2180        ready, _, _ = select.select([file_descriptor], [], [], 0.05)
2181        if not ready:
2182            return "\x1b"
2183        sequence.extend(os.read(file_descriptor, 1))
2184
2185        if sequence[1] in (ord("["), ord("O")):
2186            ready, _, _ = select.select([file_descriptor], [], [], 0.15)
2187            if ready:
2188                sequence.extend(os.read(file_descriptor, 1))
2189
2190        while True:
2191            last_byte = sequence[-1]
2192            if chr(last_byte).isalpha() or last_byte == ord("~"):
2193                break
2194            ready, _, _ = select.select([file_descriptor], [], [], 0.01)
2195            if not ready:
2196                break
2197            sequence.extend(os.read(file_descriptor, 1))
2198
2199        return bytes(sequence).decode("latin1")
2200    finally:
2201        termios.tcsetattr(file_descriptor, termios.TCSADRAIN, old_settings)

Read one keypress, including arrow keys, from stdin.

Ctrl-C raises KeyboardInterrupt so the caller can exit cleanly.

def enter_alternate_screen():
2204def enter_alternate_screen():
2205    """Switch terminal to alternate screen buffer for the interactive UI."""
2206    print("\x1b[?1049h\x1b[?25l\x1b[2J\x1b[H", end="", flush=True)

Switch terminal to alternate screen buffer for the interactive UI.

def exit_alternate_screen():
2209def exit_alternate_screen():
2210    """Return terminal to the normal screen buffer."""
2211    print("\x1b[?25h\x1b[?1049l", end="", flush=True)

Return terminal to the normal screen buffer.

def require_interactive_session():
2250def require_interactive_session():
2251    """Raise a clear error if the TUI cannot be driven in this process.
2252
2253    The configuration TUI reads raw keystrokes from the terminal. Under CI,
2254    ``nohup``, notebooks, piped stdin, or non-rank-0 distributed workers there is
2255    no usable TTY, so we fail fast with actionable guidance instead of crashing
2256    inside ``termios``.
2257    """
2258    if termios is None:
2259        raise RuntimeError(
2260            "The interactive perforation-configuration TUI is not available on this "
2261            "platform (no termios). Set configuration_confirmed=True in your config "
2262            "file (or call GPA.pc.set_configuration_confirmed(True)) and configure "
2263            "targets via the config file or Perforated Studio instead."
2264        )
2265
2266    try:
2267        is_tty = bool(sys.stdin.isatty() and sys.stdout.isatty())
2268    except (ValueError, AttributeError, OSError):
2269        is_tty = False
2270    rank = _distributed_rank()
2271
2272    if is_tty and rank == 0:
2273        return
2274
2275    reason = "no interactive terminal is attached" if not is_tty else f"process rank is {rank}, not 0"
2276    raise RuntimeError(
2277        "Perforation configuration has not been confirmed, and it cannot be done "
2278        f"interactively here ({reason}).\n"
2279        "Run perforate_model once from an interactive terminal to choose "
2280        "perforation targets, or set configuration_confirmed=True in your config "
2281        "file (or call GPA.pc.set_configuration_confirmed(True) before "
2282        "perforate_model) to skip the interactive step."
2283    )

Raise a clear error if the TUI cannot be driven in this process.

The configuration TUI reads raw keystrokes from the terminal. Under CI, nohup, notebooks, piped stdin, or non-rank-0 distributed workers there is no usable TTY, so we fail fast with actionable guidance instead of crashing inside termios.

def set_perforation_targets(model):
2286def set_perforation_targets(model):
2287    """Interactive configuration TUI for perforation targets and run settings.
2288
2289    Two screens (Tab to switch): Targets (the module tree) and Run settings.
2290    See the `?` overlay for the full key reference.
2291
2292    Under torch.distributed only rank 0 runs the TUI.  The other ranks wait for
2293    it, then load the config rank 0 saved, or stop as well if rank 0 exited or
2294    failed instead of confirming.
2295    """
2296    import datetime
2297    import torch.distributed as dist
2298
2299    if not (dist.is_available() and dist.is_initialized()):
2300        _set_perforation_targets_interactive(model)
2301        return
2302
2303    # A gloo group so waiting on a human doesn't hit the NCCL timeout or need a GPU
2304    group = (
2305        dist.new_group(backend="gloo", timeout=datetime.timedelta(days=1))
2306        if dist.is_gloo_available()
2307        else None
2308    )
2309    # [outcome, exit code]: outcome is "confirmed", "exit" or "error"
2310    status = ["error", 1]
2311    try:
2312        if dist.get_rank() == 0:
2313            try:
2314                _set_perforation_targets_interactive(model)
2315                status = ["confirmed", 0]
2316            except SystemExit as e:
2317                status = ["exit", e.code]
2318                raise
2319            finally:
2320                dist.broadcast_object_list(status, src=0, group=group)
2321            return
2322        dist.broadcast_object_list(status, src=0, group=group)
2323    finally:
2324        if group is not None:
2325            dist.destroy_process_group(group)
2326
2327    if status[0] == "exit":
2328        sys.exit(status[1])
2329    if status[0] != "confirmed":
2330        raise RuntimeError("Rank 0 failed during perforation configuration; see its error above.")
2331    # Load the configuration rank 0 saved
2332    GPA.pc.sync_config_sources()
2333    GPA.pc.set_configuration_confirmed(True)

Interactive configuration TUI for perforation targets and run settings.

Two screens (Tab to switch): Targets (the module tree) and Run settings. See the ? overlay for the full key reference.

Under torch.distributed only rank 0 runs the TUI. The other ranks wait for it, then load the config rank 0 saved, or stop as well if rank 0 exited or failed instead of confirming.