{
  "meta": {
    "title": "Nejimakidori model catalog",
    "scope": "Current working source; not a production checkpoint inventory",
    "source_digest": "348a40890f5e3159b46794a08a93303b5fe5a7ef2c3d99c315a33ed54d4a53d9",
    "feature_count": 103,
    "feature_elements": 6436,
    "feature_bytes": 8966,
    "actor_input_count": 208,
    "sparse_call_transport": "Base decision rows plus sparse accepted chi/pon feature rows, owner indices and call options; no dense four-call expansion. The ordinary discard network is shared.",
    "output_count": 17,
    "description": "Public tensors, shared representations, predictions and training flow."
  },
  "features": [
    {
      "id": "candidate_hand_counts",
      "name": "candidate_hand_counts",
      "title": "Candidate hand counts",
      "dtype": "int8",
      "shape": [
        16,
        34
      ],
      "subject": "hand",
      "group": "hand-bank",
      "description": "Integer occupancy tensor over deduplicated candidate hands and 34 ordinary tile types; red fives contribute to their ordinary type counts.",
      "encoding": "First axis: hand-bank slot, with slot 0 the current hand. Validity is determined by candidate_hand_valid.",
      "neural_encoding": "One-hot 5 occupancy classes per tile in HandBank; no asinh.",
      "elements": 544,
      "bytes": 544,
      "offset": 0,
      "status": "active",
      "consumers": [
        {
          "path": "model/actor.py",
          "line": 241,
          "role": "Named reference"
        },
        {
          "path": "model/beliefs.py",
          "line": 355,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 495,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 228,
          "role": "Named reference"
        },
        {
          "path": "model/payment_scoring.py",
          "line": 252,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 87
        },
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 16
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 65
      }
    },
    {
      "id": "candidate_hand_red",
      "name": "candidate_hand_red",
      "title": "Candidate hand red",
      "dtype": "int8",
      "shape": [
        16,
        3
      ],
      "subject": "hand",
      "group": "hand-bank",
      "description": "Per-candidate red-five occupancy by suit, represented separately from ordinary type counts.",
      "encoding": "First axis: hand-bank slot, with slot 0 the current hand. Validity is determined by candidate_hand_valid.",
      "neural_encoding": "Identity red-occupancy channel per tile; no asinh.",
      "elements": 48,
      "bytes": 48,
      "offset": 544,
      "status": "active",
      "consumers": [
        {
          "path": "model/beliefs.py",
          "line": 352,
          "role": "Named reference"
        },
        {
          "path": "model/beliefs.py",
          "line": 22,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 490,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 232,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 88
        },
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 17
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 66
      }
    },
    {
      "id": "candidate_hand_yaku_possibility",
      "name": "candidate_hand_yaku_possibility",
      "title": "Candidate hand yaku possibility",
      "dtype": "int8",
      "shape": [
        16,
        19
      ],
      "subject": "hand",
      "group": "hand-bank",
      "description": "Nineteen coarse yaku-feasibility flags for each resulting hand-bank slot, combining its fixed-meld compatibility and public tile availability. They enter that hand’s readout; they are not completed-hand yaku labels.",
      "encoding": "Last axis (boolean public feasibility, not win probability): 0 tanyao, 1 haku, 2 hatsu, 3 chun, 4 round wind, 5 seat wind, 6 honitsu, 7 chinitsu, 8 toitoi, 9 chiitoitsu, 10 shousangen, 11 daisangen, 12 tsuuiisou, 13 chinroutou, 14 honroutou, 15 kokushi, 16 chanta, 17 junchan, 18 iipeikou.",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 304,
      "bytes": 304,
      "offset": 592,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 377,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 192,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 89
        },
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 161
        },
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 44
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 67
      }
    },
    {
      "id": "candidate_meld_tiles",
      "name": "candidate_meld_tiles",
      "title": "Candidate meld tiles",
      "dtype": "int8",
      "shape": [
        16,
        4
      ],
      "subject": "hand",
      "group": "hand-bank",
      "description": "Compact lowest-tile code per fixed meld in each local hand.",
      "encoding": "16 × 4 slots; ordinary 0–33, absent 34. Decodes with candidate_meld_types into 16 × 34 × 6 neural channels.",
      "neural_encoding": "Decode with meld types into 34×6 histogram channels per hand; histogram channels enter HandBank directly.",
      "elements": 64,
      "bytes": 64,
      "offset": 896,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 695,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 12,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 38,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 81
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 68
      }
    },
    {
      "id": "candidate_meld_types",
      "name": "candidate_meld_types",
      "title": "Candidate meld types",
      "dtype": "int8",
      "shape": [
        16,
        4
      ],
      "subject": "hand",
      "group": "hand-bank",
      "description": "Fixed-meld type aligned with candidate_meld_tiles.",
      "encoding": "0 chi, 1 pon, 2 open kan, 3 closed kan, 4 added kan; tile code 34 suppresses absent slots.",
      "neural_encoding": "Categorical decode paired with lowest-tile codes; contributes to 34×6 fixed-meld histograms, not ordinal scalar inputs.",
      "elements": 64,
      "bytes": 64,
      "offset": 960,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 696,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 18,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 41,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 83
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 69
      }
    },
    {
      "id": "candidate_meld_red",
      "name": "candidate_meld_red",
      "title": "Candidate meld red",
      "dtype": "int8",
      "shape": [
        16,
        3
      ],
      "subject": "hand",
      "group": "hand-bank",
      "description": "Red-five counts by suit across each local hand’s fixed melds.",
      "encoding": "16 × 3; expands into red channels at ordinary tile IDs 4/13/22.",
      "neural_encoding": "Red counts expand to the red channel of each 34×6 meld histogram; no asinh in HandBank.",
      "elements": 48,
      "bytes": 48,
      "offset": 1024,
      "status": "active",
      "consumers": [
        {
          "path": "model/input_features.py",
          "line": 19,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 47,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 86
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 70
      }
    },
    {
      "id": "candidate_hand_valid",
      "name": "candidate_hand_valid",
      "title": "Candidate hand valid",
      "dtype": "int8",
      "shape": [
        16
      ],
      "subject": "hand",
      "group": "hand-bank",
      "description": "Binary occupancy mask for the 16-entry candidate-hand axis.",
      "encoding": "First axis: hand-bank slot, with slot 0 the current hand. Validity is determined by candidate_hand_valid.",
      "neural_encoding": "Occupancy support for sparse hand encoding and dense-bank restoration; not a learned numeric covariate.",
      "elements": 16,
      "bytes": 16,
      "offset": 1072,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 224,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 393,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 186,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 93
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 71
      }
    },
    {
      "id": "discard_candidate_hand",
      "name": "discard_candidate_hand",
      "title": "Discard candidate hand",
      "dtype": "int8",
      "shape": [
        37
      ],
      "subject": "actions",
      "group": "hand-bank",
      "description": "Gather indices from 37 discard actions into the deduplicated candidate-hand bank. Routing only; excluded from the learned board projection.",
      "encoding": "Integer index into the 16-slot hand bank. Action legality masks determine which entries are meaningful.",
      "neural_encoding": "Integer gather routing only; excluded from shared learned projections.",
      "elements": 37,
      "bytes": 37,
      "offset": 1088,
      "status": "active",
      "consumers": [
        {
          "path": "model/actions.py",
          "line": 374,
          "role": "Named reference"
        },
        {
          "path": "model/actions.py",
          "line": 366,
          "role": "Hand-bank gather routing only"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 198
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 72
      }
    },
    {
      "id": "kan_candidate_hand",
      "name": "kan_candidate_hand",
      "title": "Kan candidate hand",
      "dtype": "int8",
      "shape": [
        34
      ],
      "subject": "actions",
      "group": "hand-bank",
      "description": "Gather indices from tile-specific kan candidates into the candidate-hand bank. Routing only; excluded from the learned board projection.",
      "encoding": "Integer index into the 16-slot hand bank. Action legality masks determine which entries are meaningful.",
      "neural_encoding": "Integer gather routing only; excluded from shared learned projections.",
      "elements": 34,
      "bytes": 34,
      "offset": 1125,
      "status": "active",
      "consumers": [
        {
          "path": "model/actions.py",
          "line": 383,
          "role": "Named reference"
        },
        {
          "path": "model/actions.py",
          "line": 366,
          "role": "Hand-bank gather routing only"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 231
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 73
      }
    },
    {
      "id": "river_pre_tile_id",
      "name": "river_pre_tile_id",
      "title": "River pre tile id",
      "dtype": "int8",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Pre-riichi opponent-sequence channel: ordinary tile-type IDs.",
      "encoding": "Axes: opponent (seats 1–3), right-aligned recent discard slot (32). Validity is determined by the corresponding sequence mask.",
      "neural_encoding": "RiverEncoding reuses the shared 34 × 8 tile projection and applies river validity. Red flags remain separate.",
      "elements": 96,
      "bytes": 96,
      "offset": 1159,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 411,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 236
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 74
      }
    },
    {
      "id": "river_pre_is_red",
      "name": "river_pre_is_red",
      "title": "River pre is red",
      "dtype": "int8",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Pre-riichi opponent-sequence channel: binary red-five attributes.",
      "encoding": "Axes: opponent (seats 1–3), right-aligned recent discard slot (32). Validity is determined by the corresponding sequence mask.",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 96,
      "bytes": 96,
      "offset": 1255,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 237
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 75
      }
    },
    {
      "id": "river_pre_tsumogiri",
      "name": "river_pre_tsumogiri",
      "title": "River pre tsumogiri",
      "dtype": "int8",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Pre-riichi opponent-sequence channel: binary draw-discard attributes.",
      "encoding": "Axes: opponent (seats 1–3), right-aligned recent discard slot (32). Validity is determined by the corresponding sequence mask.",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 96,
      "bytes": 96,
      "offset": 1351,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 238
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 76
      }
    },
    {
      "id": "river_pre_origin",
      "name": "river_pre_origin",
      "title": "River pre origin",
      "dtype": "int8",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Pre-riichi opponent-sequence channel: categorical discard-origin codes.",
      "encoding": "0 padding; 1 dealer initial discard; 2 drawn-tile discard; 3 hand discard; 4 after chi; 5 after pon. Axes: opponent (seats 1–3), right-aligned discard slot (32); the sequence validity mask excludes padding.",
      "neural_encoding": "Learned 6×2 categorical embedding; shared across pre/post streams within each SemanticFields instance. Validity-masked.",
      "elements": 96,
      "bytes": 96,
      "offset": 1447,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 240
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 77
      }
    },
    {
      "id": "river_pre_riichi",
      "name": "river_pre_riichi",
      "title": "River pre riichi",
      "dtype": "int8",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Pre-riichi opponent-sequence channel: binary declaration-discard attributes.",
      "encoding": "Axes: opponent (seats 1–3), right-aligned recent discard slot (32). Validity is determined by the corresponding sequence mask.",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 96,
      "bytes": 96,
      "offset": 1543,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 475,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 209,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 263
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 78
      }
    },
    {
      "id": "river_pre_call_resolution",
      "name": "river_pre_call_resolution",
      "title": "River pre call resolution",
      "dtype": "int8",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Pre-riichi opponent-sequence channel: offset categorical response-resolution codes.",
      "encoding": "0 padding, 1 pending, 2 no call, 3 chi, 4 pon, 5 daiminkan. River validity masks padded slots.",
      "neural_encoding": "Learned 6×2 categorical embedding; shared across pre/post streams within each SemanticFields instance. Validity-masked.",
      "elements": 96,
      "bytes": 96,
      "offset": 1639,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 241
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 79
      }
    },
    {
      "id": "river_pre_caller",
      "name": "river_pre_caller",
      "title": "River pre caller",
      "dtype": "int8",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Pre-riichi opponent-sequence channel: offset actor-relative caller codes with separate unresolved/no-caller categories.",
      "encoding": "0 no caller; 1 pending; 2 self; 3 next seat; 4 opposite seat; 5 previous seat. Axes: opponent (seats 1–3), right-aligned discard slot (32); the sequence validity mask excludes padding.",
      "neural_encoding": "Learned 6×2 categorical embedding; shared across pre/post streams within each SemanticFields instance. Validity-masked.",
      "elements": 96,
      "bytes": 96,
      "offset": 1735,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 242
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 80
      }
    },
    {
      "id": "river_pre_event_age",
      "name": "river_pre_event_age",
      "title": "River pre event age",
      "dtype": "float16",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Pre-riichi opponent-sequence channel: event-distance scalars normalized by 100 and clipped at 1.",
      "encoding": "Axes: opponent (seats 1–3), right-aligned recent discard slot (32). Validity is determined by the corresponding sequence mask.",
      "neural_encoding": "Already normalized: identity channels; no second scaling or asinh transform.",
      "elements": 96,
      "bytes": 192,
      "offset": 1831,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 243
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 81
      }
    },
    {
      "id": "river_pre_own_gap",
      "name": "river_pre_own_gap",
      "title": "River pre own gap",
      "dtype": "float16",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Pre-riichi opponent-sequence channel: self-discard-count differences normalized by 24 and clipped at 1.",
      "encoding": "Axes: opponent (seats 1–3), right-aligned recent discard slot (32). Validity is determined by the corresponding sequence mask.",
      "neural_encoding": "Already normalized: identity channels; no second scaling or asinh transform.",
      "elements": 96,
      "bytes": 192,
      "offset": 2023,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 244
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 82
      }
    },
    {
      "id": "river_pre_live_wall",
      "name": "river_pre_live_wall",
      "title": "River pre live wall",
      "dtype": "float16",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Pre-riichi opponent-sequence channel: discard-time live-wall counts normalized by 70.",
      "encoding": "Axes: opponent (seats 1–3), right-aligned recent discard slot (32). Validity is determined by the corresponding sequence mask.",
      "neural_encoding": "Already normalized: identity channels; no second scaling or asinh transform.",
      "elements": 96,
      "bytes": 192,
      "offset": 2215,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 245
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 83
      }
    },
    {
      "id": "river_pre_current_dora_multiplicity",
      "name": "river_pre_current_dora_multiplicity",
      "title": "River pre current dora multiplicity",
      "dtype": "int8",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Pre-riichi opponent-sequence channel: current integer dora multiplicities.",
      "encoding": "Axes: opponent (seats 1–3), right-aligned recent discard slot (32). Validity is determined by the corresponding sequence mask.",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 96,
      "bytes": 96,
      "offset": 2407,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 246
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 84
      }
    },
    {
      "id": "river_pre_dora_multiplicity_at_discard",
      "name": "river_pre_dora_multiplicity_at_discard",
      "title": "River pre dora multiplicity at discard",
      "dtype": "int8",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Pre-riichi opponent-sequence channel: discard-time integer dora multiplicities.",
      "encoding": "Axes: opponent (seats 1–3), right-aligned recent discard slot (32). Validity is determined by the corresponding sequence mask.",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 96,
      "bytes": 96,
      "offset": 2503,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 247
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 85
      }
    },
    {
      "id": "river_pre_valid",
      "name": "river_pre_valid",
      "title": "River pre valid",
      "dtype": "int8",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Pre-riichi opponent-sequence channel: binary sequence occupancy masks.",
      "encoding": "Axes: opponent (seats 1–3), right-aligned recent discard slot (32). Validity is determined by the corresponding sequence mask.",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 96,
      "bytes": 96,
      "offset": 2599,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 411,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 239
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 86
      }
    },
    {
      "id": "river_post_tile_id",
      "name": "river_post_tile_id",
      "title": "River post tile id",
      "dtype": "int8",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Post-riichi opponent-sequence channel: ordinary tile-type IDs.",
      "encoding": "Axes: opponent (seats 1–3), right-aligned recent discard slot (32). Validity is determined by the corresponding sequence mask.",
      "neural_encoding": "RiverEncoding reuses the shared 34 × 8 tile projection and applies river validity. Red flags remain separate.",
      "elements": 96,
      "bytes": 96,
      "offset": 2695,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 236
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 87
      }
    },
    {
      "id": "river_post_is_red",
      "name": "river_post_is_red",
      "title": "River post is red",
      "dtype": "int8",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Post-riichi opponent-sequence channel: binary red-five attributes.",
      "encoding": "Axes: opponent (seats 1–3), right-aligned recent discard slot (32). Validity is determined by the corresponding sequence mask.",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 96,
      "bytes": 96,
      "offset": 2791,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 237
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 88
      }
    },
    {
      "id": "river_post_tsumogiri",
      "name": "river_post_tsumogiri",
      "title": "River post tsumogiri",
      "dtype": "int8",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Post-riichi opponent-sequence channel: binary draw-discard attributes.",
      "encoding": "Axes: opponent (seats 1–3), right-aligned recent discard slot (32). Validity is determined by the corresponding sequence mask.",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 96,
      "bytes": 96,
      "offset": 2887,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 238
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 89
      }
    },
    {
      "id": "river_post_origin",
      "name": "river_post_origin",
      "title": "River post origin",
      "dtype": "int8",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Post-riichi opponent-sequence channel: categorical discard-origin codes.",
      "encoding": "0 padding; 1 dealer initial discard; 2 drawn-tile discard; 3 hand discard; 4 after chi; 5 after pon. Axes: opponent (seats 1–3), right-aligned discard slot (32); the sequence validity mask excludes padding.",
      "neural_encoding": "Learned 6×2 categorical embedding; shared across pre/post streams within each SemanticFields instance. Validity-masked.",
      "elements": 96,
      "bytes": 96,
      "offset": 2983,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 240
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 90
      }
    },
    {
      "id": "river_post_call_resolution",
      "name": "river_post_call_resolution",
      "title": "River post call resolution",
      "dtype": "int8",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Post-riichi opponent-sequence channel: offset categorical response-resolution codes.",
      "encoding": "0 padding, 1 pending, 2 no call, 3 chi, 4 pon, 5 daiminkan. River validity masks padded slots.",
      "neural_encoding": "Learned 6×2 categorical embedding; shared across pre/post streams within each SemanticFields instance. Validity-masked.",
      "elements": 96,
      "bytes": 96,
      "offset": 3079,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 241
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 91
      }
    },
    {
      "id": "river_post_caller",
      "name": "river_post_caller",
      "title": "River post caller",
      "dtype": "int8",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Post-riichi opponent-sequence channel: offset actor-relative caller codes with separate unresolved/no-caller categories.",
      "encoding": "0 no caller; 1 pending; 2 self; 3 next seat; 4 opposite seat; 5 previous seat. Axes: opponent (seats 1–3), right-aligned discard slot (32); the sequence validity mask excludes padding.",
      "neural_encoding": "Learned 6×2 categorical embedding; shared across pre/post streams within each SemanticFields instance. Validity-masked.",
      "elements": 96,
      "bytes": 96,
      "offset": 3175,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 242
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 92
      }
    },
    {
      "id": "river_post_event_age",
      "name": "river_post_event_age",
      "title": "River post event age",
      "dtype": "float16",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Post-riichi opponent-sequence channel: event-distance scalars normalized by 100 and clipped at 1.",
      "encoding": "Axes: opponent (seats 1–3), right-aligned recent discard slot (32). Validity is determined by the corresponding sequence mask.",
      "neural_encoding": "Already normalized: identity channels; no second scaling or asinh transform.",
      "elements": 96,
      "bytes": 192,
      "offset": 3271,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 243
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 93
      }
    },
    {
      "id": "river_post_own_gap",
      "name": "river_post_own_gap",
      "title": "River post own gap",
      "dtype": "float16",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Post-riichi opponent-sequence channel: self-discard-count differences normalized by 24 and clipped at 1.",
      "encoding": "Axes: opponent (seats 1–3), right-aligned recent discard slot (32). Validity is determined by the corresponding sequence mask.",
      "neural_encoding": "Already normalized: identity channels; no second scaling or asinh transform.",
      "elements": 96,
      "bytes": 192,
      "offset": 3463,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 244
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 94
      }
    },
    {
      "id": "river_post_live_wall",
      "name": "river_post_live_wall",
      "title": "River post live wall",
      "dtype": "float16",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Post-riichi opponent-sequence channel: discard-time live-wall counts normalized by 70.",
      "encoding": "Axes: opponent (seats 1–3), right-aligned recent discard slot (32). Validity is determined by the corresponding sequence mask.",
      "neural_encoding": "Already normalized: identity channels; no second scaling or asinh transform.",
      "elements": 96,
      "bytes": 192,
      "offset": 3655,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 245
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 95
      }
    },
    {
      "id": "river_post_current_dora_multiplicity",
      "name": "river_post_current_dora_multiplicity",
      "title": "River post current dora multiplicity",
      "dtype": "int8",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Post-riichi opponent-sequence channel: current integer dora multiplicities.",
      "encoding": "Axes: opponent (seats 1–3), right-aligned recent discard slot (32). Validity is determined by the corresponding sequence mask.",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 96,
      "bytes": 96,
      "offset": 3847,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 246
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 96
      }
    },
    {
      "id": "river_post_dora_multiplicity_at_discard",
      "name": "river_post_dora_multiplicity_at_discard",
      "title": "River post dora multiplicity at discard",
      "dtype": "int8",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Post-riichi opponent-sequence channel: discard-time integer dora multiplicities.",
      "encoding": "Axes: opponent (seats 1–3), right-aligned recent discard slot (32). Validity is determined by the corresponding sequence mask.",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 96,
      "bytes": 96,
      "offset": 3943,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 247
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 97
      }
    },
    {
      "id": "river_post_valid",
      "name": "river_post_valid",
      "title": "River post valid",
      "dtype": "int8",
      "shape": [
        3,
        32
      ],
      "subject": "opponents",
      "group": "rivers",
      "description": "Post-riichi opponent-sequence channel: binary sequence occupancy masks.",
      "encoding": "Axes: opponent (seats 1–3), right-aligned recent discard slot (32). Validity is determined by the corresponding sequence mask.",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 96,
      "bytes": 96,
      "offset": 4039,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 399,
          "role": "Shared river stream"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 239
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 98
      }
    },
    {
      "id": "meld_type",
      "name": "meld_type",
      "title": "Meld type",
      "dtype": "int8",
      "shape": [
        4,
        4
      ],
      "subject": "table",
      "group": "melds",
      "description": "Categorical observed-meld kind with zero padding, indexed by relative player and meld slot.",
      "encoding": "0 padding, 1 chi, 2 pon, 3 open kan, 4 closed kan, 5 added kan. A slot is occupied when its first meld_tiles code is below the padding value 37.",
      "neural_encoding": "One-hot 6 categories; no ordinal numeric transform. Invalid fields are masked.",
      "elements": 16,
      "bytes": 16,
      "offset": 4135,
      "status": "active",
      "consumers": [
        {
          "path": "model/critic.py",
          "line": 68,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 620,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 168,
          "role": "Named reference"
        },
        {
          "path": "model/payment_scoring.py",
          "line": 457,
          "role": "Named reference"
        },
        {
          "path": "model/payment_scoring.py",
          "line": 216,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 211
        },
        {
          "path": "log_dataset/native_collection/src/features.rs",
          "line": 27
        },
        {
          "path": "log_dataset/native_collection/src/features.rs",
          "line": 40
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 99
      }
    },
    {
      "id": "meld_tiles",
      "name": "meld_tiles",
      "title": "Meld tiles",
      "dtype": "int8",
      "shape": [
        4,
        4,
        4
      ],
      "subject": "table",
      "group": "melds",
      "description": "Public meld constituent codes; reconstruct ordinary IDs, red flags and valid flags.",
      "encoding": "0–33 ordinary, 34/35/36 red fives, 37 absent; 4 players × 4 melds × 4 tiles.",
      "neural_encoding": "Decode base ID, red and valid channels; identity reuses the shared 34 × 8 projection, with red flags separate and padding masked.",
      "elements": 64,
      "bytes": 64,
      "offset": 4151,
      "status": "active",
      "consumers": [
        {
          "path": "model/actions.py",
          "line": 360,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 54,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 70,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 27,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 65,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 65,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 213
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 68
      }
    },
    {
      "id": "meld_source",
      "name": "meld_source",
      "title": "Meld source",
      "dtype": "int8",
      "shape": [
        4,
        4
      ],
      "subject": "table",
      "group": "melds",
      "description": "Categorical actor-relative source-seat index for each public call, with zero for closed/no-source entries.",
      "encoding": "0 closed/no source; otherwise actor-relative source seat + 1.",
      "neural_encoding": "One-hot 5 categories; no ordinal numeric transform. Invalid fields are masked.",
      "elements": 16,
      "bytes": 16,
      "offset": 4215,
      "status": "active",
      "consumers": [
        {
          "path": "model/input_features.py",
          "line": 169,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 215
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 101
      }
    },
    {
      "id": "meld_call_age",
      "name": "meld_call_age",
      "title": "Meld call age",
      "dtype": "float16",
      "shape": [
        4,
        4
      ],
      "subject": "table",
      "group": "melds",
      "description": "Clipped event-distance scalar from the original meld event, normalized by 100.",
      "encoding": "min(1, elapsed public events / 100); axes: four relative players × four meld slots.",
      "neural_encoding": "Already normalized: identity channels; no second scaling or asinh transform.",
      "elements": 16,
      "bytes": 32,
      "offset": 4231,
      "status": "active",
      "consumers": [
        {
          "path": "model/input_features.py",
          "line": 222,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 216
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 102
      }
    },
    {
      "id": "meld_upgrade_age",
      "name": "meld_upgrade_age",
      "title": "Meld upgrade age",
      "dtype": "float16",
      "shape": [
        4,
        4
      ],
      "subject": "table",
      "group": "melds",
      "description": "Clipped event-distance scalar from an added-kan upgrade, normalized by 100.",
      "encoding": "min(1, elapsed public events / 100); axes: four relative players × four meld slots.",
      "neural_encoding": "Already normalized: identity channels; no second scaling or asinh transform.",
      "elements": 16,
      "bytes": 32,
      "offset": 4263,
      "status": "active",
      "consumers": [
        {
          "path": "model/input_features.py",
          "line": 223,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 218
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 103
      }
    },
    {
      "id": "current_draw_tile_id",
      "name": "current_draw_tile_id",
      "title": "Current draw tile id",
      "dtype": "int8",
      "shape": [],
      "subject": "hand",
      "group": "self",
      "description": "Ordinary tile-type ID of the current self draw, interpreted under current_draw_valid.",
      "encoding": "",
      "neural_encoding": "Shared 34×8 base-tile projection, gated by validity. Red flags remain separate; hand, river, table and candidate encoders reuse the same weights.",
      "elements": 1,
      "bytes": 1,
      "offset": 4295,
      "status": "active",
      "consumers": [
        {
          "path": "model/input_features.py",
          "line": 178,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 47
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 104
      }
    },
    {
      "id": "current_draw_is_red",
      "name": "current_draw_is_red",
      "title": "Current draw is red",
      "dtype": "int8",
      "shape": [],
      "subject": "hand",
      "group": "self",
      "description": "Binary red-five indicator for the current self draw.",
      "encoding": "",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 1,
      "bytes": 1,
      "offset": 4296,
      "status": "active",
      "consumers": [
        {
          "path": "model/input_features.py",
          "line": 190,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 264,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 48
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 105
      }
    },
    {
      "id": "current_draw_valid",
      "name": "current_draw_valid",
      "title": "Current draw valid",
      "dtype": "int8",
      "shape": [],
      "subject": "hand",
      "group": "self",
      "description": "Binary validity mask for current-draw identity channels.",
      "encoding": "",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 1,
      "bytes": 1,
      "offset": 4297,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 609,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 189,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 266,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 46
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 106
      }
    },
    {
      "id": "normal_self_shanten",
      "name": "normal_self_shanten",
      "title": "Normal self shanten",
      "dtype": "int8",
      "shape": [],
      "subject": "hand",
      "group": "self",
      "description": "Clipped categorical standard-hand shanten encoding; category equals actual shanten + 1 until saturation.",
      "encoding": "0 complete, 1 tenpai, 2 one-shanten, 3 two-shanten, 4 three-or-more shanten; 5 marks an unavailable special family with fixed melds.",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 1,
      "bytes": 1,
      "offset": 4298,
      "status": "active",
      "consumers": [
        {
          "path": "training/corrections/collection.py",
          "line": 130,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 24
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 107
      }
    },
    {
      "id": "chiitoitsu_self_shanten",
      "name": "chiitoitsu_self_shanten",
      "title": "Chiitoitsu self shanten",
      "dtype": "int8",
      "shape": [],
      "subject": "hand",
      "group": "self",
      "description": "Clipped categorical seven-pairs shanten encoding with a distinct infeasible-family sentinel when fixed melds exist.",
      "encoding": "0 complete, 1 tenpai, 2 one-shanten, 3 two-shanten, 4 three-or-more shanten; 5 marks an unavailable special family with fixed melds.",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 1,
      "bytes": 1,
      "offset": 4299,
      "status": "active",
      "consumers": [
        {
          "path": "training/corrections/collection.py",
          "line": 131,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 24
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 108
      }
    },
    {
      "id": "kokushi_self_shanten",
      "name": "kokushi_self_shanten",
      "title": "Kokushi self shanten",
      "dtype": "int8",
      "shape": [],
      "subject": "hand",
      "group": "self",
      "description": "Clipped categorical thirteen-orphans shanten encoding with a distinct infeasible-family sentinel when fixed melds exist.",
      "encoding": "0 complete, 1 tenpai, 2 one-shanten, 3 two-shanten, 4 three-or-more shanten; 5 marks an unavailable special family with fixed melds.",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 1,
      "bytes": 1,
      "offset": 4300,
      "status": "active",
      "consumers": [
        {
          "path": "training/corrections/collection.py",
          "line": 132,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 25
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 109
      }
    },
    {
      "id": "closed_hand",
      "name": "closed_hand",
      "title": "Closed hand",
      "dtype": "int8",
      "shape": [],
      "subject": "hand",
      "group": "self",
      "description": "Binary closed-hand predicate used by structural/scoring constraints.",
      "encoding": "",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 1,
      "bytes": 1,
      "offset": 4301,
      "status": "active",
      "consumers": [
        {
          "path": "model/input_features.py",
          "line": 191,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 21
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 110
      }
    },
    {
      "id": "self_efficiency",
      "name": "self_efficiency",
      "title": "Self efficiency",
      "dtype": "float32",
      "shape": [
        3
      ],
      "subject": "hand",
      "group": "self",
      "description": "Three normalized self-hand statistics: actual shanten, improving-type cardinality and available improving-copy count.",
      "encoding": "Last axis: [actual shanten / 8, improving tile types / 34, available improving copies / 80].",
      "neural_encoding": "Already normalized: identity channels; no second scaling or asinh transform.",
      "elements": 3,
      "bytes": 12,
      "offset": 4302,
      "status": "active",
      "consumers": [
        {
          "path": "model/input_features.py",
          "line": 219,
          "role": "Named reference"
        },
        {
          "path": "training/self_play.py",
          "line": 152,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 220
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 111
      }
    },
    {
      "id": "dora_multiplicity",
      "name": "dora_multiplicity",
      "title": "Dora multiplicity",
      "dtype": "int8",
      "shape": [
        34
      ],
      "subject": "table",
      "group": "table",
      "description": "Per-ordinary-tile integer multiplicity induced by visible dora indicators.",
      "encoding": "34 ordinary tile types; each count records how many visible indicators award dora to that tile type.",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 34,
      "bytes": 34,
      "offset": 4314,
      "status": "active",
      "consumers": [
        {
          "path": "model/actor.py",
          "line": 244,
          "role": "Named reference"
        },
        {
          "path": "model/actor.py",
          "line": 282,
          "role": "Named reference"
        },
        {
          "path": "model/actor.py",
          "line": 287,
          "role": "Named reference"
        },
        {
          "path": "model/beliefs.py",
          "line": 577,
          "role": "Named reference"
        },
        {
          "path": "model/beliefs.py",
          "line": 376,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 152,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 439,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 501,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 593,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 27,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 295,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 176,
          "role": "Per-tile hand evidence"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 61
        },
        {
          "path": "log_dataset/native_collection/src/features.rs",
          "line": 343
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 84
      }
    },
    {
      "id": "public_visible_red_counts",
      "name": "public_visible_red_counts",
      "title": "Public visible red counts",
      "dtype": "int8",
      "shape": [
        3
      ],
      "subject": "table",
      "group": "table",
      "description": "Public red-five occupancy by suit, excluding concealed self occupancy.",
      "encoding": "",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 3,
      "bytes": 3,
      "offset": 4348,
      "status": "active",
      "consumers": [
        {
          "path": "model/beliefs.py",
          "line": 23,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 69
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 113
      }
    },
    {
      "id": "known_unavailable_counts",
      "name": "known_unavailable_counts",
      "title": "Known unavailable counts",
      "dtype": "int8",
      "shape": [
        34
      ],
      "subject": "table",
      "group": "table",
      "description": "Per-ordinary-tile unavailable-copy count combining public exposures and the self hand.",
      "encoding": "",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 34,
      "bytes": 34,
      "offset": 4351,
      "status": "active",
      "consumers": [
        {
          "path": "model/actions.py",
          "line": 338,
          "role": "Named reference"
        },
        {
          "path": "model/beliefs.py",
          "line": 19,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 438,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 592,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 525,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 28,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 296,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 99,
          "role": "Named reference"
        },
        {
          "path": "model/payment_scoring.py",
          "line": 251,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 176,
          "role": "Per-tile hand evidence"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 68
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 114
      }
    },
    {
      "id": "prevailing_wind",
      "name": "prevailing_wind",
      "title": "Prevailing wind",
      "dtype": "int8",
      "shape": [],
      "subject": "table",
      "group": "table",
      "description": "Categorical current-round wind ID.",
      "encoding": "0 East, 1 South, 2 West, 3 North.",
      "neural_encoding": "One-hot 4 categories; no ordinal numeric transform. Invalid fields are masked.",
      "elements": 1,
      "bytes": 1,
      "offset": 4385,
      "status": "active",
      "consumers": [
        {
          "path": "model/actor.py",
          "line": 290,
          "role": "Named reference"
        },
        {
          "path": "model/beliefs.py",
          "line": 567,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 577,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 161,
          "role": "Named reference"
        },
        {
          "path": "model/payment_scoring.py",
          "line": 288,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 70
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 115
      }
    },
    {
      "id": "hands_remaining",
      "name": "hands_remaining",
      "title": "Hands remaining",
      "dtype": "int8",
      "shape": [],
      "subject": "table",
      "group": "table",
      "description": "Signed scheduled hands remaining after this hand in a South game.",
      "encoding": "7 at East 1, 0 at South 4, −1 at West 1. Count is 7 − (4 × round wind + zero-based hand number); extension values remain negative.",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 1,
      "bytes": 1,
      "offset": 4386,
      "status": "active",
      "consumers": [
        {
          "path": "model/joint_settlement.py",
          "line": 327,
          "role": "Named reference"
        },
        {
          "path": "model/joint_settlement.py",
          "line": 324,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 71
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 116
      }
    },
    {
      "id": "dealer_relative_seat",
      "name": "dealer_relative_seat",
      "title": "Dealer relative seat",
      "dtype": "int8",
      "shape": [],
      "subject": "table",
      "group": "table",
      "description": "Categorical dealer index in actor-relative seat coordinates.",
      "encoding": "",
      "neural_encoding": "One-hot 4 categories; no ordinal numeric transform. Invalid fields are masked.",
      "elements": 1,
      "bytes": 1,
      "offset": 4387,
      "status": "active",
      "consumers": [
        {
          "path": "model/actor.py",
          "line": 31,
          "role": "Named reference"
        },
        {
          "path": "model/beliefs.py",
          "line": 306,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 103,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 100,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 99,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 403,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 162,
          "role": "Named reference"
        },
        {
          "path": "model/joint_settlement.py",
          "line": 323,
          "role": "Named reference"
        },
        {
          "path": "training/trainer.py",
          "line": 51,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 72
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 117
      }
    },
    {
      "id": "honba",
      "name": "honba",
      "title": "Honba",
      "dtype": "int16",
      "shape": [],
      "subject": "table",
      "group": "table",
      "description": "Integer repeat-counter scalar conditioning settlement transfers.",
      "encoding": "",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 1,
      "bytes": 2,
      "offset": 4388,
      "status": "active",
      "consumers": [
        {
          "path": "model/joint_settlement.py",
          "line": 320,
          "role": "Named reference"
        },
        {
          "path": "model/joint_settlement.py",
          "line": 320,
          "role": "Named reference"
        },
        {
          "path": "model/joint_settlement.py",
          "line": 340,
          "role": "Named reference"
        },
        {
          "path": "model/outcomes.py",
          "line": 177,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 73
        },
        {
          "path": "log_dataset/native_collection/src/features.rs",
          "line": 118
        },
        {
          "path": "log_dataset/native_collection/src/features.rs",
          "line": 374
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 118
      }
    },
    {
      "id": "riichi_sticks",
      "name": "riichi_sticks",
      "title": "Riichi sticks",
      "dtype": "int8",
      "shape": [],
      "subject": "table",
      "group": "table",
      "description": "Integer count of accepted riichi deposits in the current table pot.",
      "encoding": "",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 1,
      "bytes": 1,
      "offset": 4390,
      "status": "active",
      "consumers": [
        {
          "path": "model/joint_settlement.py",
          "line": 321,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 74
        },
        {
          "path": "log_dataset/native_collection/src/features.rs",
          "line": 375
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 119
      }
    },
    {
      "id": "live_wall_count",
      "name": "live_wall_count",
      "title": "Live wall count",
      "dtype": "int8",
      "shape": [],
      "subject": "table",
      "group": "table",
      "description": "Integer remaining ordinary-draw count; excludes replacement draws.",
      "encoding": "",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 1,
      "bytes": 1,
      "offset": 4391,
      "status": "active",
      "consumers": [
        {
          "path": "model/actor.py",
          "line": 230,
          "role": "Named reference"
        },
        {
          "path": "model/beliefs.py",
          "line": 317,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 312,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 516,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 661,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 595,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 561,
          "role": "Named reference"
        },
        {
          "path": "training/corrections/collection.py",
          "line": 144,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 75
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 120
      }
    },
    {
      "id": "total_kan_count",
      "name": "total_kan_count",
      "title": "Total kan count",
      "dtype": "int8",
      "shape": [],
      "subject": "table",
      "group": "table",
      "description": "Integer kan count in the current hand.",
      "encoding": "",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 1,
      "bytes": 1,
      "offset": 4392,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 88
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 121
      }
    },
    {
      "id": "scores",
      "name": "scores",
      "title": "Scores",
      "dtype": "int32",
      "shape": [
        4
      ],
      "subject": "table",
      "group": "table",
      "description": "Current points in wind-seat order: East, South, West, North.",
      "encoding": "Four signed int32 point totals in current wind order; no wire normalization.",
      "neural_encoding": "Table features divide by 100000 in wind order. Critic player descriptors gather by seat_wind into actor-relative order, then divide by 100000. Settlement gathers raw points by seat_wind.",
      "elements": 4,
      "bytes": 16,
      "offset": 4393,
      "status": "active",
      "consumers": [
        {
          "path": "model/critic.py",
          "line": 80,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 566,
          "role": "Named reference"
        },
        {
          "path": "model/export.py",
          "line": 139,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 245,
          "role": "Named reference"
        },
        {
          "path": "model/joint_settlement.py",
          "line": 315,
          "role": "Named reference"
        },
        {
          "path": "model/joint_settlement.py",
          "line": 316,
          "role": "Named reference"
        },
        {
          "path": "model/joint_settlement.py",
          "line": 343,
          "role": "Named reference"
        },
        {
          "path": "model/outcomes.py",
          "line": 147,
          "role": "Named reference"
        },
        {
          "path": "model/outcomes.py",
          "line": 149,
          "role": "Named reference"
        },
        {
          "path": "model/outcomes.py",
          "line": 149,
          "role": "Named reference"
        },
        {
          "path": "training/evaluate.py",
          "line": 73,
          "role": "Named reference"
        },
        {
          "path": "training/evaluate.py",
          "line": 212,
          "role": "Named reference"
        },
        {
          "path": "training/evaluate.py",
          "line": 81,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 116
        },
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 117
        },
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 162
        },
        {
          "path": "log_dataset/native_collection/src/features.rs",
          "line": 120
        },
        {
          "path": "log_dataset/native_collection/src/features.rs",
          "line": 376
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 122
      }
    },
    {
      "id": "ranks",
      "name": "ranks",
      "title": "Ranks",
      "dtype": "int8",
      "shape": [
        4
      ],
      "subject": "table",
      "group": "table",
      "description": "Current ranks in wind-seat order: East, South, West, North.",
      "encoding": "Four int8 ranks: 1 first through 4 fourth, with the game’s tie ordering; entries follow current wind order.",
      "neural_encoding": "Table features divide by 4 in wind order. Critic player descriptors gather by seat_wind into actor-relative order, then divide by 4.",
      "elements": 4,
      "bytes": 4,
      "offset": 4409,
      "status": "active",
      "consumers": [
        {
          "path": "model/critic.py",
          "line": 566,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 247,
          "role": "Named reference"
        },
        {
          "path": "training/evaluate.py",
          "line": 73,
          "role": "Named reference"
        },
        {
          "path": "training/evaluate.py",
          "line": 211,
          "role": "Named reference"
        },
        {
          "path": "training/evaluate.py",
          "line": 77,
          "role": "Named reference"
        },
        {
          "path": "training/evaluate.py",
          "line": 78,
          "role": "Named reference"
        },
        {
          "path": "training/evaluate.py",
          "line": 79,
          "role": "Named reference"
        },
        {
          "path": "training/evaluate.py",
          "line": 82,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 163
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 123
      }
    },
    {
      "id": "seat_wind",
      "name": "seat_wind",
      "title": "Seat wind",
      "dtype": "int8",
      "shape": [
        4
      ],
      "subject": "table",
      "group": "table",
      "description": "Categorical player-wind IDs in actor-relative player order.",
      "encoding": "0 East, 1 South, 2 West, 3 North. seat_wind uses actor-relative player order.",
      "neural_encoding": "One-hot 4 categories; no ordinal numeric transform. Invalid fields are masked.",
      "elements": 4,
      "bytes": 4,
      "offset": 4413,
      "status": "active",
      "consumers": [
        {
          "path": "model/actor.py",
          "line": 289,
          "role": "Named reference"
        },
        {
          "path": "model/actor.py",
          "line": 288,
          "role": "Named reference"
        },
        {
          "path": "model/beliefs.py",
          "line": 566,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 81,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 563,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 574,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 576,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 584,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 163,
          "role": "Named reference"
        },
        {
          "path": "model/joint_settlement.py",
          "line": 317,
          "role": "Named reference"
        },
        {
          "path": "model/payment_scoring.py",
          "line": 282,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 161
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 124
      }
    },
    {
      "id": "open_opponent_yaku_possibility",
      "name": "open_opponent_yaku_possibility",
      "title": "Open opponent yaku possibility",
      "dtype": "int8",
      "shape": [
        4,
        13
      ],
      "subject": "opponents",
      "group": "opponents",
      "description": "Thirteen-channel fixed-meld/public-supply feasibility subset, populated for opponents with observed open calls.",
      "encoding": "Last axis (boolean public feasibility, not win probability): 0 tanyao, 1 haku, 2 hatsu, 3 chun, 4 round wind, 5 seat wind, 6 honitsu, 7 chinitsu, 8 toitoi, 9 shousangen, 10 honroutou, 11 chanta, 12 junchan.",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 52,
      "bytes": 52,
      "offset": 4417,
      "status": "active",
      "consumers": [
        {
          "path": "model/critic.py",
          "line": 616,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 193,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 203
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 125
      }
    },
    {
      "id": "opponent_called_tile_count",
      "name": "opponent_called_tile_count",
      "title": "Opponent called tile count",
      "dtype": "int8",
      "shape": [
        4
      ],
      "subject": "opponents",
      "group": "opponents",
      "description": "Observed open-meld tile cardinality per opponent; self slot remains zero.",
      "encoding": "",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 4,
      "bytes": 4,
      "offset": 4469,
      "status": "active",
      "consumers": [
        {
          "path": "model/critic.py",
          "line": 390,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 604,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 199
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 126
      }
    },
    {
      "id": "opponent_discard_count",
      "name": "opponent_discard_count",
      "title": "Opponent discard count",
      "dtype": "int8",
      "shape": [
        4
      ],
      "subject": "opponents",
      "group": "opponents",
      "description": "Integer public discard-sequence length per relative player.",
      "encoding": "",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 4,
      "bytes": 4,
      "offset": 4473,
      "status": "active",
      "consumers": [
        {
          "path": "model/actor.py",
          "line": 30,
          "role": "Named reference"
        },
        {
          "path": "model/beliefs.py",
          "line": 312,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 396,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 605,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 167
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 127
      }
    },
    {
      "id": "nagashi_possible",
      "name": "nagashi_possible",
      "title": "Nagashi possible",
      "dtype": "int8",
      "shape": [
        4
      ],
      "subject": "table",
      "group": "table",
      "description": "Exact per-player public nagashi eligibility from full discard history: every discard is terminal/honor and none has been called.",
      "encoding": "Four actor-relative binary flags; an empty river remains eligible.",
      "neural_encoding": "Constraint-only identity flags; excluded from learned encoder covariates.",
      "elements": 4,
      "bytes": 4,
      "offset": 4477,
      "status": "active",
      "consumers": [
        {
          "path": "model/actor.py",
          "line": 227,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 73,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 20,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 174
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 128
      }
    },
    {
      "id": "pao_payer",
      "name": "pao_payer",
      "title": "Pao payer",
      "dtype": "int8",
      "shape": [
        4
      ],
      "subject": "table",
      "group": "table",
      "description": "Known public responsibility payer for each player after the completing dragon or wind call.",
      "encoding": "Actor-relative payer seat; negative sentinel means responsibility is not yet established.",
      "neural_encoding": "Constraint-only categorical context; excluded from learned encoder covariates.",
      "elements": 4,
      "bytes": 4,
      "offset": 4481,
      "status": "active",
      "consumers": [
        {
          "path": "model/critic.py",
          "line": 74,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 197,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 198,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 74,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 75,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 1066,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 206,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 270,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 201,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 984,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 21,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 193
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 129
      }
    },
    {
      "id": "last_tedashi_tile_id",
      "name": "last_tedashi_tile_id",
      "title": "Last tedashi tile id",
      "dtype": "int8",
      "shape": [
        4
      ],
      "subject": "opponents",
      "group": "opponents",
      "description": "Compact latest non-tsumogiri discard code per player.",
      "encoding": "0–36 red-aware tile code; 37 absent.",
      "neural_encoding": "Shared table encoder: base-tile identity 16 + red bit, zero for absence. Private shanten/player observations retain their existing 37-class one-hot readouts.",
      "elements": 4,
      "bytes": 4,
      "offset": 4485,
      "status": "active",
      "consumers": [
        {
          "path": "model/beliefs.py",
          "line": 323,
          "role": "Named reference"
        },
        {
          "path": "model/beliefs.py",
          "line": 326,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 181,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 24,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 75,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 111,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 112,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 294,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 158
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 130
      }
    },
    {
      "id": "riichi_push_count",
      "name": "riichi_push_count",
      "title": "Riichi push count",
      "dtype": "int8",
      "shape": [
        4,
        4
      ],
      "subject": "opponents",
      "group": "opponents",
      "description": "Player×riichi-target count of non-tsumogiri discards lacking established safe-tile evidence.",
      "encoding": "",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 16,
      "bytes": 16,
      "offset": 4489,
      "status": "active",
      "consumers": [
        {
          "path": "model/critic.py",
          "line": 457,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 149
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 131
      }
    },
    {
      "id": "genbutsu_to_seat",
      "name": "genbutsu_to_seat",
      "title": "Genbutsu to seat",
      "dtype": "int8",
      "shape": [
        4,
        34
      ],
      "subject": "opponents",
      "group": "opponents",
      "description": "Binary player×tile public safe-tile relation derived from observed discard and riichi history.",
      "encoding": "",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 136,
      "bytes": 136,
      "offset": 4505,
      "status": "active",
      "consumers": [
        {
          "path": "model/actions.py",
          "line": 354,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 351,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 352,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 617,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 419,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 30,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 313,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 196,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 176,
          "role": "Per-tile hand evidence"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 286
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 132
      }
    },
    {
      "id": "passed_unchanged_to_seat",
      "name": "passed_unchanged_to_seat",
      "title": "Passed unchanged to seat",
      "dtype": "int8",
      "shape": [
        4,
        34
      ],
      "subject": "opponents",
      "group": "opponents",
      "description": "Binary player×tile passed-discard relation retained across intervals without relevant hand changes.",
      "encoding": "",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 136,
      "bytes": 136,
      "offset": 4641,
      "status": "active",
      "consumers": [
        {
          "path": "model/critic.py",
          "line": 618,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 448,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 31,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 314,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 32,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 197,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 176,
          "role": "Per-tile hand evidence"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 231
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 133
      }
    },
    {
      "id": "sotogawa_earliest_turn_to_seat",
      "name": "sotogawa_earliest_turn_to_seat",
      "title": "Sotogawa earliest turn to seat",
      "dtype": "int8",
      "shape": [
        4,
        34
      ],
      "subject": "opponents",
      "group": "opponents",
      "description": "Earliest qualifying opening-discard index for each player×outside-tile relation; zero encodes absence.",
      "encoding": "",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 136,
      "bytes": 136,
      "offset": 4777,
      "status": "active",
      "consumers": [
        {
          "path": "model/critic.py",
          "line": 619,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 420,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 32,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 315,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 176,
          "role": "Per-tile hand evidence"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 287
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 134
      }
    },
    {
      "id": "win_kind",
      "name": "win_kind",
      "title": "Win kind",
      "dtype": "int8",
      "shape": [],
      "subject": "actions",
      "group": "decision",
      "description": "Categorical optional-win context: none, ron or tsumo.",
      "encoding": "0 outside a win decision, 1 ron, 2 tsumo.",
      "neural_encoding": "One-hot 3 categories; no ordinal numeric transform. Invalid fields are masked.",
      "elements": 1,
      "bytes": 1,
      "offset": 4913,
      "status": "active",
      "consumers": [
        {
          "path": "model/actions.py",
          "line": 116,
          "role": "Named reference"
        },
        {
          "path": "model/actions.py",
          "line": 313,
          "role": "Named reference"
        },
        {
          "path": "model/actions.py",
          "line": 314,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 164,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 52
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 135
      }
    },
    {
      "id": "decision_phase",
      "name": "decision_phase",
      "title": "Decision phase",
      "dtype": "int8",
      "shape": [],
      "subject": "actions",
      "group": "decision",
      "description": "Categorical phase selecting the native action contract; numeric phase IDs differ from TRAIN_POLICY_HEADS indices.",
      "encoding": "0 DISCARD, 1 RESPONSE, 2 KAN, 3 RIICHI, 4 WIN.",
      "neural_encoding": "One-hot 5 categories; no ordinal numeric transform. Invalid fields are masked.",
      "elements": 1,
      "bytes": 1,
      "offset": 4914,
      "status": "active",
      "consumers": [
        {
          "path": "model/actions.py",
          "line": 115,
          "role": "Named reference"
        },
        {
          "path": "model/actions.py",
          "line": 393,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 1384,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 115,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 1360,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 645,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 1442,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 1411,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 1432,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 597,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 564,
          "role": "Named reference"
        },
        {
          "path": "model/export.py",
          "line": 150,
          "role": "Named reference"
        },
        {
          "path": "model/inference.py",
          "line": 140,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 165,
          "role": "Named reference"
        },
        {
          "path": "training/collection_workers.py",
          "line": 147,
          "role": "Named reference"
        },
        {
          "path": "training/corrections/collection.py",
          "line": 66,
          "role": "Named reference"
        },
        {
          "path": "training/fixed_reference.py",
          "line": 44,
          "role": "Named reference"
        },
        {
          "path": "training/fixed_reference.py",
          "line": 70,
          "role": "Named reference"
        },
        {
          "path": "training/imitation_rollouts.py",
          "line": 131,
          "role": "Named reference"
        },
        {
          "path": "training/imitation_rollouts.py",
          "line": 70,
          "role": "Named reference"
        },
        {
          "path": "training/match_records.py",
          "line": 56,
          "role": "Named reference"
        },
        {
          "path": "training/match_records.py",
          "line": 121,
          "role": "Named reference"
        },
        {
          "path": "training/self_play.py",
          "line": 100,
          "role": "Named reference"
        },
        {
          "path": "training/self_play.py",
          "line": 251,
          "role": "Named reference"
        },
        {
          "path": "training/self_play.py",
          "line": 392,
          "role": "Named reference"
        },
        {
          "path": "training/trainer.py",
          "line": 92,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 50
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 136
      }
    },
    {
      "id": "trigger_tile_id",
      "name": "trigger_tile_id",
      "title": "Trigger tile id",
      "dtype": "int8",
      "shape": [],
      "subject": "actions",
      "group": "decision",
      "description": "Ordinary tile-type ID of the event-conditioned trigger.",
      "encoding": "",
      "neural_encoding": "Shared 34×8 base-tile projection, gated by validity. Red flags remain separate; hand, river, table and candidate encoders reuse the same weights.",
      "elements": 1,
      "bytes": 1,
      "offset": 4915,
      "status": "active",
      "consumers": [
        {
          "path": "model/critic.py",
          "line": 179,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 1433,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 1372,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 1397,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 179,
          "role": "Named reference"
        },
        {
          "path": "model/payment_scoring.py",
          "line": 265,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 291
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 137
      }
    },
    {
      "id": "trigger_is_red",
      "name": "trigger_is_red",
      "title": "Trigger is red",
      "dtype": "int8",
      "shape": [],
      "subject": "actions",
      "group": "decision",
      "description": "Binary red-five attribute of the trigger tile.",
      "encoding": "",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 1,
      "bytes": 1,
      "offset": 4916,
      "status": "active",
      "consumers": [
        {
          "path": "model/input_features.py",
          "line": 200,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 260,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 292
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 138
      }
    },
    {
      "id": "trigger_valid",
      "name": "trigger_valid",
      "title": "Trigger valid",
      "dtype": "int8",
      "shape": [],
      "subject": "actions",
      "group": "decision",
      "description": "Binary validity mask for trigger identity channels.",
      "encoding": "",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 1,
      "bytes": 1,
      "offset": 4917,
      "status": "active",
      "consumers": [
        {
          "path": "model/input_features.py",
          "line": 199,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 262,
          "role": "Named reference"
        },
        {
          "path": "model/payment_scoring.py",
          "line": 266,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 290
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 139
      }
    },
    {
      "id": "trigger_source",
      "name": "trigger_source",
      "title": "Trigger source",
      "dtype": "int8",
      "shape": [],
      "subject": "actions",
      "group": "decision",
      "description": "Actor-relative source-seat ID of the triggering event.",
      "encoding": "",
      "neural_encoding": "One-hot 4 categories; no ordinal numeric transform. Invalid fields are masked.",
      "elements": 1,
      "bytes": 1,
      "offset": 4918,
      "status": "active",
      "consumers": [
        {
          "path": "model/critic.py",
          "line": 203,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 295,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 649,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 599,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 566,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 166,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 260,
          "role": "Named reference"
        },
        {
          "path": "model/payment_scoring.py",
          "line": 269,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 293
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 140
      }
    },
    {
      "id": "riichi_state",
      "name": "riichi_state",
      "title": "Riichi state",
      "dtype": "int8",
      "shape": [
        4
      ],
      "subject": "table",
      "group": "decision",
      "description": "Per-player categorical state encoded as declared + accepted flags.",
      "encoding": "Actor-relative seats; declared flag + accepted flag: 0 none, 1 declared, 2 accepted.",
      "neural_encoding": "One-hot 3 categories; no ordinal numeric transform. Invalid fields are masked.",
      "elements": 4,
      "bytes": 4,
      "offset": 4919,
      "status": "active",
      "consumers": [
        {
          "path": "model/beliefs.py",
          "line": 310,
          "role": "Named reference"
        },
        {
          "path": "model/beliefs.py",
          "line": 477,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 86,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 87,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 88,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 101,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 102,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 77,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 218,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 380,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 602,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 664,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 167,
          "role": "Named reference"
        },
        {
          "path": "model/payment_scoring.py",
          "line": 460,
          "role": "Named reference"
        },
        {
          "path": "model/payment_scoring.py",
          "line": 509,
          "role": "Named reference"
        },
        {
          "path": "training/restoration.py",
          "line": 45,
          "role": "Named reference"
        },
        {
          "path": "training/self_play.py",
          "line": 406,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 165
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 141
      }
    },
    {
      "id": "ippatsu_alive",
      "name": "ippatsu_alive",
      "title": "Ippatsu alive",
      "dtype": "int8",
      "shape": [
        4
      ],
      "subject": "table",
      "group": "decision",
      "description": "Binary per-player ippatsu eligibility under observed intervening events.",
      "encoding": "",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 4,
      "bytes": 4,
      "offset": 4923,
      "status": "active",
      "consumers": [
        {
          "path": "model/critic.py",
          "line": 385,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 603,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 194,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 166
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 142
      }
    },
    {
      "id": "rinshan_state",
      "name": "rinshan_state",
      "title": "Rinshan state",
      "dtype": "int8",
      "shape": [],
      "subject": "hand",
      "group": "decision",
      "description": "Binary predicate that the current replacement draw belongs to self.",
      "encoding": "",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 1,
      "bytes": 1,
      "offset": 4927,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 614,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 195,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 906,
          "role": "Shared public-context projection"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 53
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 143
      }
    },
    {
      "id": "riichi_legal_mask",
      "name": "riichi_legal_mask",
      "title": "Riichi legal mask",
      "dtype": "int8",
      "shape": [
        2
      ],
      "subject": "actions",
      "group": "decision",
      "description": "Binary support mask for decline/declaration branches.",
      "encoding": "",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 2,
      "bytes": 2,
      "offset": 4928,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 44,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 201,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 143
        },
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 150
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 144
      }
    },
    {
      "id": "riichi_discard_legal_mask",
      "name": "riichi_discard_legal_mask",
      "title": "Riichi discard legal mask",
      "dtype": "int8",
      "shape": [
        37
      ],
      "subject": "actions",
      "group": "decision",
      "description": "Binary support mask over declaration-compatible discard classes.",
      "encoding": "",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 37,
      "bytes": 37,
      "offset": 4930,
      "status": "active",
      "consumers": [
        {
          "path": "model/actions.py",
          "line": 309,
          "role": "Named reference"
        },
        {
          "path": "model/actions.py",
          "line": 195,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 45,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 202,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 147
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 145
      }
    },
    {
      "id": "response_legal_mask",
      "name": "response_legal_mask",
      "title": "Response legal mask",
      "dtype": "int8",
      "shape": [
        4
      ],
      "subject": "actions",
      "group": "decision",
      "description": "Binary support mask over pass/chi/pon/open-kan branches.",
      "encoding": "",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 4,
      "bytes": 4,
      "offset": 4967,
      "status": "active",
      "consumers": [
        {
          "path": "model/actions.py",
          "line": 322,
          "role": "Named reference"
        },
        {
          "path": "model/actions.py",
          "line": 326,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 46,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 203,
          "role": "Named reference"
        },
        {
          "path": "training/self_play.py",
          "line": 165,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 144
        },
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 225
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 146
      }
    },
    {
      "id": "call_discard_legal",
      "name": "call_discard_legal",
      "title": "Call discard legal",
      "dtype": "int8",
      "shape": [
        4,
        37
      ],
      "subject": "actions",
      "group": "calls",
      "description": "Legal follow-up discards for each call option, including its kuikae exclusions.",
      "encoding": "Call option: 0–2 chi patterns, 3 pon. Second axis: 37 ordinary/red discard classes.",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 148,
      "bytes": 148,
      "offset": 4971,
      "status": "active",
      "consumers": [
        {
          "path": "model/actions.py",
          "line": 324,
          "role": "Named reference"
        },
        {
          "path": "model/actions.py",
          "line": 225,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 204,
          "role": "Named reference"
        },
        {
          "path": "training/self_play.py",
          "line": 153,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 257
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 147
      }
    },
    {
      "id": "call_discard_shanten",
      "name": "call_discard_shanten",
      "title": "Call discard shanten",
      "dtype": "int8",
      "shape": [
        4,
        37
      ],
      "subject": "actions",
      "group": "calls",
      "description": "Call-option × follow-up-discard shanten categories, actual shanten + 1.",
      "encoding": "Call option: 0–2 chi patterns, 3 pon. Second axis: 37 ordinary/red discard classes.",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 148,
      "bytes": 148,
      "offset": 5119,
      "status": "active",
      "consumers": [
        {
          "path": "training/self_play.py",
          "line": 154,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 258
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 148
      }
    },
    {
      "id": "call_discard_ukeire_count",
      "name": "call_discard_ukeire_count",
      "title": "Call discard ukeire count",
      "dtype": "int16",
      "shape": [
        4,
        37
      ],
      "subject": "actions",
      "group": "calls",
      "description": "Call-option × follow-up-discard available improving-copy counts.",
      "encoding": "Call option: 0–2 chi patterns, 3 pon. Second axis: 37 ordinary/red discard classes.",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 148,
      "bytes": 296,
      "offset": 5267,
      "status": "active",
      "consumers": [],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 260
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 149
      }
    },
    {
      "id": "kan_legal_mask",
      "name": "kan_legal_mask",
      "title": "Kan legal mask",
      "dtype": "int8",
      "shape": [
        35
      ],
      "subject": "actions",
      "group": "calls",
      "description": "Binary support mask over decline and 34 tile-specific kan actions.",
      "encoding": "",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 35,
      "bytes": 35,
      "offset": 5563,
      "status": "active",
      "consumers": [
        {
          "path": "model/actions.py",
          "line": 330,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 205,
          "role": "Named reference"
        },
        {
          "path": "training/self_play.py",
          "line": 157,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 145
        },
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 230
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 150
      }
    },
    {
      "id": "call_efficiency",
      "name": "call_efficiency",
      "title": "Call efficiency",
      "dtype": "float32",
      "shape": [
        4,
        3
      ],
      "subject": "actions",
      "group": "calls",
      "description": "Normalized shanten/improving-type/improving-copy statistics after each call option.",
      "encoding": "Call option: 0–2 chi patterns, 3 pon. Last axis: [actual shanten / 8, improving tile types / 34, available improving copies / 80].",
      "neural_encoding": "Already normalized: identity channels; no second scaling or asinh transform.",
      "elements": 12,
      "bytes": 48,
      "offset": 5598,
      "status": "active",
      "consumers": [
        {
          "path": "model/input_features.py",
          "line": 220,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 251
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 151
      }
    },
    {
      "id": "kan_efficiency",
      "name": "kan_efficiency",
      "title": "Kan efficiency",
      "dtype": "float32",
      "shape": [
        34,
        3
      ],
      "subject": "actions",
      "group": "calls",
      "description": "Per-tile kan-candidate normalized shanten/improving-type/improving-copy statistics before the replacement draw.",
      "encoding": "Last axis: [actual shanten / 8, improving tile types / 34, available improving copies / 80].",
      "neural_encoding": "Already normalized: identity channels; no second scaling or asinh transform.",
      "elements": 102,
      "bytes": 408,
      "offset": 5646,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 764,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 221,
          "role": "Named reference"
        },
        {
          "path": "training/self_play.py",
          "line": 158,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 236
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 152
      }
    },
    {
      "id": "discard_abort",
      "name": "discard_abort",
      "title": "Discard abort",
      "dtype": "int8",
      "shape": [
        2,
        37
      ],
      "subject": "actions",
      "group": "discards",
      "description": "Binary discard-conditioned abort indicators for ordinary and declaration branches.",
      "encoding": "",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 74,
      "bytes": 74,
      "offset": 6054,
      "status": "active",
      "consumers": [
        {
          "path": "model/critic.py",
          "line": 242,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 768,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 769,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 206,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 95
        },
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 108
        },
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 109
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 153
      }
    },
    {
      "id": "discard_action_legal",
      "name": "discard_action_legal",
      "title": "Discard action legal",
      "dtype": "int8",
      "shape": [
        37
      ],
      "subject": "actions",
      "group": "discards",
      "description": "Binary support mask over 37 ordinary/red discard classes.",
      "encoding": "",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 37,
      "bytes": 37,
      "offset": 6128,
      "status": "active",
      "consumers": [
        {
          "path": "model/actions.py",
          "line": 308,
          "role": "Named reference"
        },
        {
          "path": "model/actions.py",
          "line": 182,
          "role": "Named reference"
        },
        {
          "path": "model/actions.py",
          "line": 176,
          "role": "Named reference"
        },
        {
          "path": "model/input_features.py",
          "line": 207,
          "role": "Named reference"
        },
        {
          "path": "training/corrections/collection.py",
          "line": 50,
          "role": "Named reference"
        },
        {
          "path": "training/restoration.py",
          "line": 54,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 146
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 154
      }
    },
    {
      "id": "discard_tedashi_legal",
      "name": "discard_tedashi_legal",
      "title": "Discard tedashi legal",
      "dtype": "int8",
      "shape": [
        37
      ],
      "subject": "actions",
      "group": "discards",
      "description": "Binary predicate that a discard class admits a held-tile physical realization.",
      "encoding": "",
      "neural_encoding": "Identity binary channels; no asinh transform.",
      "elements": 37,
      "bytes": 37,
      "offset": 6165,
      "status": "active",
      "consumers": [
        {
          "path": "model/input_features.py",
          "line": 208,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 158
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 155
      }
    },
    {
      "id": "discard_action_normal_shanten",
      "name": "discard_action_normal_shanten",
      "title": "Discard action normal shanten",
      "dtype": "int8",
      "shape": [
        37
      ],
      "subject": "actions",
      "group": "discards",
      "description": "Standard-hand post-discard shanten category.",
      "encoding": "37 ordinary/red discard classes; shanten uses actual value + 1.",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 37,
      "bytes": 37,
      "offset": 6202,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 750,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 173
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 156
      }
    },
    {
      "id": "discard_action_normal_ukeire_count",
      "name": "discard_action_normal_ukeire_count",
      "title": "Discard action normal ukeire count",
      "dtype": "int16",
      "shape": [
        37
      ],
      "subject": "actions",
      "group": "discards",
      "description": "Standard-hand post-discard available improving-copy count.",
      "encoding": "",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 37,
      "bytes": 74,
      "offset": 6239,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 751,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 174
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 157
      }
    },
    {
      "id": "discard_action_all_shanten",
      "name": "discard_action_all_shanten",
      "title": "Discard action all shanten",
      "dtype": "int8",
      "shape": [
        37
      ],
      "subject": "actions",
      "group": "discards",
      "description": "Minimum-shanten hand-family post-discard shanten category.",
      "encoding": "37 ordinary/red discard classes; shanten uses actual value + 1.",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 37,
      "bytes": 37,
      "offset": 6313,
      "status": "active",
      "consumers": [
        {
          "path": "model/actor.py",
          "line": 232,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 321,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 673,
          "role": "Named reference"
        },
        {
          "path": "training/corrections/collection.py",
          "line": 147,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 173
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 158
      }
    },
    {
      "id": "discard_action_all_ukeire_count",
      "name": "discard_action_all_ukeire_count",
      "title": "Discard action all ukeire count",
      "dtype": "int16",
      "shape": [
        37
      ],
      "subject": "actions",
      "group": "discards",
      "description": "Minimum-shanten hand-family post-discard available improving-copy count.",
      "encoding": "",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 37,
      "bytes": 74,
      "offset": 6350,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 676,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 175
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 159
      }
    },
    {
      "id": "discard_retained_genbutsu",
      "name": "discard_retained_genbutsu",
      "title": "Discard retained genbutsu",
      "dtype": "int8",
      "shape": [
        37,
        4
      ],
      "subject": "actions",
      "group": "discards",
      "description": "Discard×player statistic for safe-tile occupancy retained after the candidate discard.",
      "encoding": "",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 148,
      "bytes": 148,
      "offset": 6424,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 754,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 209
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 160
      }
    },
    {
      "id": "action_win_value_range",
      "name": "action_win_value_range",
      "title": "Action win value range",
      "dtype": "float32",
      "shape": [
        110,
        2,
        2
      ],
      "subject": "actions",
      "group": "scoring",
      "description": "Action-conditioned completion min/max points. Reconstruct the closed/open neural axis from resulting-meld openness; used only in the corresponding local action query.",
      "encoding": "110 rows: 0–36 ordinary discard and decline alias; 37–73 riichi discard; 74 pass (old 111); 75 current/WIN (old 260); 76–109 kan (old 261–294). Trailing axes: ron/tsumo × min/max points.",
      "neural_encoding": "Gather 110 compact rows into 147 local queries; reconstruct openness channels and apply asinh to point magnitudes.",
      "elements": 440,
      "bytes": 1760,
      "offset": 6572,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 20,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 709,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 632,
          "role": "Candidate-local scoring descriptor only"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 30
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 161
      }
    },
    {
      "id": "action_win_value_valid",
      "name": "action_win_value_valid",
      "title": "Action win value valid",
      "dtype": "int8",
      "shape": [
        110,
        2
      ],
      "subject": "actions",
      "group": "scoring",
      "description": "Binary support for action-conditioned completion bounds. Reconstruct the closed/open neural axis from resulting-meld openness.",
      "encoding": "110 rows: 0–36 ordinary discard and decline alias; 37–73 riichi discard; 74 pass (old 111); 75 current/WIN (old 260); 76–109 kan (old 261–294). Trailing axis: ron/tsumo validity.",
      "neural_encoding": "Gather compact support into local queries and reconstruct openness channels; identity mask, no asinh.",
      "elements": 220,
      "bytes": 220,
      "offset": 8332,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 21,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 717,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 632,
          "role": "Candidate-local scoring descriptor only"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 31
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 162
      }
    },
    {
      "id": "action_value_eligible",
      "name": "action_value_eligible",
      "title": "Action value eligible",
      "dtype": "int8",
      "shape": [
        110
      ],
      "subject": "actions",
      "group": "scoring",
      "description": "Native action-conditioned completion-search eligibility, gathered by the compact-to-local scoring row map.",
      "encoding": "110 rows: 0–36 ordinary discard and decline alias; 37–73 riichi discard; 74 pass (old 111); 75 current/WIN (old 260); 76–109 kan (old 261–294).",
      "neural_encoding": "Gather compact eligibility into local queries; identity binary mask.",
      "elements": 110,
      "bytes": 110,
      "offset": 8552,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 22,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 728,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 632,
          "role": "Candidate-local scoring descriptor only"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 33
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 163
      }
    },
    {
      "id": "action_open_yaku_restricted",
      "name": "action_open_yaku_restricted",
      "title": "Action open yaku restricted",
      "dtype": "int8",
      "shape": [
        110,
        2
      ],
      "subject": "actions",
      "group": "scoring",
      "description": "Native action-conditioned open-yaku restriction channels, gathered into the corresponding local action descriptor.",
      "encoding": "110 rows: 0–36 ordinary discard and decline alias; 37–73 riichi discard; 74 pass (old 111); 75 current/WIN (old 260); 76–109 kan (old 261–294).",
      "neural_encoding": "Gather compact restriction channels into local queries; identity binary masks.",
      "elements": 220,
      "bytes": 220,
      "offset": 8662,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 23,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 734,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 632,
          "role": "Candidate-local scoring descriptor only"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 32
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 164
      }
    },
    {
      "id": "candidate_yaku_shanten",
      "name": "candidate_yaku_shanten",
      "title": "Candidate yaku shanten",
      "dtype": "int8",
      "shape": [
        16,
        3
      ],
      "subject": "hand",
      "group": "scoring",
      "description": "Candidate×route-family integer distances for tanyao, flush and outside-hand routes.",
      "encoding": "Axes: hand slot, [tanyao, flush, outside-hand] route family. Values are actual route shanten (−1 complete, 0 tenpai).",
      "neural_encoding": "Numeric magnitude channels use elementwise asinh.",
      "elements": 48,
      "bytes": 48,
      "offset": 8882,
      "status": "active",
      "consumers": [
        {
          "path": "model/encoder.py",
          "line": 815,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 92
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 165
      }
    },
    {
      "id": "public_bonus",
      "name": "public_bonus",
      "title": "Public bonus",
      "dtype": "int8",
      "shape": [
        4
      ],
      "subject": "table",
      "group": "scoring",
      "description": "Per-player deterministic bonus-han contribution from observed fixed melds and visible dora.",
      "encoding": "",
      "neural_encoding": "Deterministic scoring support; excluded from shared board/hand projections.",
      "elements": 4,
      "bytes": 4,
      "offset": 8930,
      "status": "active",
      "consumers": [
        {
          "path": "model/critic.py",
          "line": 105,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 162,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 105,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 978,
          "role": "Named reference"
        },
        {
          "path": "model/critic.py",
          "line": 950,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 14,
          "role": "Named reference"
        },
        {
          "path": "model/payment_scoring.py",
          "line": 540,
          "role": "Named reference"
        },
        {
          "path": "model/payment_scoring.py",
          "line": 472,
          "role": "Named reference"
        },
        {
          "path": "model/payment_scoring.py",
          "line": 483,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/features.cpp",
          "line": 152
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 166
      }
    },
    {
      "id": "candidate_fu",
      "name": "candidate_fu",
      "title": "Candidate fu",
      "dtype": "int16",
      "shape": [
        16
      ],
      "subject": "hand",
      "group": "scoring",
      "description": "Candidate-dependent fixed-meld fu contribution for each resulting hand; not the final winning-hand fu total.",
      "encoding": "16 hand-bank slots; slot 0 is the current hand. candidate_hand_valid defines support. After-call positions carry their resulting meld contribution.",
      "neural_encoding": "Excluded from shared board/hand projections. Fixed-meld fu constrains score support and enters conditional critic scoring scaled by 1/128.",
      "elements": 16,
      "bytes": 32,
      "offset": 8934,
      "status": "active",
      "consumers": [
        {
          "path": "model/critic.py",
          "line": 160,
          "role": "Named reference"
        },
        {
          "path": "model/encoder.py",
          "line": 15,
          "role": "Named reference"
        },
        {
          "path": "model/payment_scoring.py",
          "line": 235,
          "role": "Named reference"
        }
      ],
      "producers": [
        {
          "path": "log_dataset/native_collection/cpp/candidate.cpp",
          "line": 94
        }
      ],
      "source": {
        "path": "log_dataset/native_collection/src/schema.rs",
        "line": 167
      }
    }
  ],
  "groups": [
    {
      "id": "hand-bank",
      "subject": "hand",
      "title": "Candidate hands",
      "description": "Deduplicated candidate occupancy tensors and action-to-bank gather indices."
    },
    {
      "id": "rivers",
      "subject": "opponents",
      "title": "Opponent rivers",
      "description": "Masked temporal channels over pre/post-riichi opponent discard sequences."
    },
    {
      "id": "melds",
      "subject": "table",
      "title": "Public melds",
      "description": "Padded categorical, occupancy and event-age tensors for observed melds."
    },
    {
      "id": "self",
      "subject": "hand",
      "title": "Current hand",
      "description": "Self-state categorical features and normalized hand-efficiency statistics."
    },
    {
      "id": "table",
      "subject": "table",
      "title": "Table and match",
      "description": "Public score, round, wind, wall and tile-availability covariates."
    },
    {
      "id": "opponents",
      "subject": "opponents",
      "title": "Public opponent evidence",
      "description": "Player-indexed public behavioral, feasibility and safe-tile evidence."
    },
    {
      "id": "decision",
      "subject": "actions",
      "title": "Decision context",
      "description": "Categorical event context and native action-support masks."
    },
    {
      "id": "calls",
      "subject": "actions",
      "title": "Calls and kans",
      "description": "Call-pattern/discard product-space masks and post-call covariates."
    },
    {
      "id": "discards",
      "subject": "actions",
      "title": "Discard alternatives",
      "description": "Discard-indexed support, structural-efficiency and safety covariates."
    },
    {
      "id": "scoring",
      "subject": "actions",
      "title": "Scoring constraints",
      "description": "Deterministic public score constraints and action-conditioned completion support."
    }
  ],
  "architecture": {
    "nodes": [
      {
        "id": "inputs",
        "title": "Public state tensors",
        "kind": "input",
        "summary": "Actor-relative native feature tensors and deterministic post-action hand indices.",
        "dimensions": [
          "100 native fields",
          "Shapes exclude batch",
          "34 ordinary / 37 red-aware tile classes",
          "16 local hand slots"
        ],
        "details": [
          "Inference inputs exclude opponent concealed-hand state and supervised hidden-state labels.",
          "The native schema fixes tensor order, scalar dtype, shape and byte offset.",
          "The model reads the same 103 fields at the decision and after each possible chi or pon. Two indices match each after-call position to its decision and call option."
        ],
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 64
        }
      },
      {
        "id": "hand-bank",
        "title": "Context-conditioned hand bank",
        "kind": "encoder",
        "summary": "Observed decision context conditions all 16 local hand slots before suit convolutions. After-call positions rerun shared weights with changed table/hand facts.",
        "dimensions": [
          "Shared 34 × 8 tile identity",
          "128 tile channels",
          "Dilations 1, 2, 4",
          "512 output width"
        ],
        "details": [
          "Each suit stack uses kernel-3 convolutions with dilation rates 1, 2 and 4 and residual LayerNorm/GELU updates.",
          "Honor-tile features use a separate 128-dimensional GELU projection.",
          "Ordinary/red occupancy, melds and tile-aligned public evidence join the projected shared public context.",
          "Occupied hand entries use 16-row buckets up to 128 rows and 512-row buckets above that; deduplicated suit rows use 16/512/1024/4096 buckets. Padding is removed before occupancy-indexed gather restores 512-wide encodings into the hand bank."
        ],
        "source": {
          "path": "model/encoder.py",
          "line": 176
        }
      },
      {
        "id": "rivers",
        "title": "Shared river encoder",
        "kind": "encoder",
        "summary": "One shared convolutional encoder and masked cross-river attention process all opponent discard streams.",
        "dimensions": [
          "3 opponents × 32 slots × 2 streams",
          "Shared 34 × 8 tile identity",
          "64 token channels",
          "3 convolutions: dilations 1, 2, 4"
        ],
        "details": [
          "Validity masking is reapplied after each convolution; padded tokens and empty streams remain zero.",
          "Ordered stream embeddings and max-pooled summaries enter shared public context.",
          "Mean- and max-pooled stream embeddings also enter per-player critic descriptors.",
          "Four-head attention connects observed events across opponents and riichi segments; its residual output starts at zero."
        ],
        "source": {
          "path": "model/encoder.py",
          "line": 399
        }
      },
      {
        "id": "board",
        "title": "Critic/belief upper encoder",
        "kind": "encoder",
        "summary": "Observed public context and current hand slot 0 feed three residual blocks, separately from the private actor upper encoder.",
        "dimensions": [
          "512 board width",
          "3 residual blocks",
          "512 → 576 → 576 → 512 per block"
        ],
        "details": [
          "Each pre-normalized block uses two 576-channel GELU layers and a 512-channel residual stream.",
          "Belief and settlement objectives train this branch and the shared lower encodings.",
          "The actor has separate upper weights and reads shared lower features through a gradient stop."
        ],
        "source": {
          "path": "model/encoder.py",
          "line": 906
        },
        "notes": [
          "Current model: 18,929,944 trainable parameters; three actor and three critic/belief board residual blocks use 512 → 576 → 576 → 512."
        ]
      },
      {
        "id": "candidates",
        "title": "Action candidate queries",
        "kind": "encoder",
        "summary": "Action queries combine resulting hands, board context and action facts.",
        "dimensions": [
          "147 local addresses per row",
          "295 joint original-window IDs",
          "761 → 384"
        ],
        "details": [
          "The canonical index space partitions into 37 discard, 74 riichi/discard, 149 response and 35 kan slots.",
          "The response head factorizes six call choices at the original decision with the ordinary discard network on after-call positions.",
          "Only active candidate rows enter learned evaluation; absent candidate slots are constant padding.",
          "WIN maps both policy branches to current-hand candidate 260; there is no separate accept/decline value estimator.",
          "Raw candidate states feed route and critic predictions directly. The actor attends to detached legal candidates separately."
        ],
        "source": {
          "path": "model/encoder.py",
          "line": 632
        }
      },
      {
        "id": "beliefs",
        "title": "Shared beliefs and completion",
        "kind": "belief",
        "summary": "Opponent marginals and completion yaku/total-han-fu heads share a refined board representation consumed by actor and critic.",
        "dimensions": [
          "Shanten: 3 × 4",
          "Conditional ukeire: 3 × 4 × 34",
          "Held counts: 3 × 37 × 5"
        ],
        "details": [
          "Observed meld counts define support lower bounds; unavailable-copy counts define support upper bounds.",
          "Count projection enforces concealed-hand cardinality and tile-copy availability constraints.",
          "Riichi or four fixed melds mask non-tenpai shanten logits.",
          "Outputs are constrained marginals; they do not parameterize a normalized joint distribution over concealed hands."
        ],
        "source": {
          "path": "model/beliefs.py",
          "line": 408
        }
      },
      {
        "id": "tile-attention",
        "title": "Tile interaction refinement",
        "kind": "attention",
        "summary": "Two opponent-shared transformer blocks apply additive residual corrections to count and conditional-ukeire logits.",
        "dimensions": [
          "34 tokens per opponent",
          "2 blocks, width 128",
          "4 heads × key dimension 32",
          "256-wide GELU feed-forward",
          "34 × 8 tile identity embedding"
        ],
        "details": [
          "Pre-LayerNorm self-attention and 128 → 256 → 128 GELU residual MLPs share parameters across opponents.",
          "Token inputs concatenate initial marginal probabilities, tile identity, availability, meld lower bounds, shanten probabilities and projected board context.",
          "A zero-initialized 128 → 14 projection produces ordinary/red count and four shanten-conditioned ukeire corrections.",
          "The shanten logits are not modified by this residual attention output."
        ],
        "source": {
          "path": "model/beliefs.py",
          "line": 157
        }
      },
      {
        "id": "actor",
        "title": "Private actor encoder and policy",
        "kind": "policy",
        "summary": "Three private board blocks read detached shared lower encodings, then two actor refinements and shared action readouts select actions.",
        "dimensions": [
          "3 × 512→576→576→512 board blocks",
          "2 × 768→384→768 policy refinements",
          "1158→512→1 candidate scorer",
          "6,091,273 private parameters"
        ],
        "details": [
          "Final scoring consumes three bounded route probabilities and three constrained ron probabilities.",
          "The actor owns binary win/pass logits and a 256-channel policy-context projection; completion predictions are owned by shared Beliefs.",
          "Native legality masks, opening-symmetry pooling and final-wall safety transforms precede action selection.",
          "MMD uses detached Q, fixed reference policies and structural constraints. The supervised heads train on their own observed targets.",
          "A learned six-way call choice combines with the same discard network evaluated on sparse after-call positions. Actor and critic reuse these after-call encodings.",
          "Private actor-query attention reads detached legal candidates and adds a context residual."
        ],
        "source": {
          "path": "model/actor.py",
          "line": 155
        }
      },
      {
        "id": "player-context",
        "title": "Public player descriptors",
        "kind": "critic",
        "summary": "Collect original decision-board facts and river summaries for all four seats.",
        "dimensions": [
          "4 player descriptors",
          "Self/opponent projection: 64",
          "Common candidate projection: 256"
        ],
        "details": [
          "The self indicator and dealer indicator are independent descriptor coordinates; they can both equal one for the acting player.",
          "Descriptors concatenate observed meld identities, seat-wind scoring consequences, dora, score/rank context and public opponent evidence.",
          "Action-conditioned coordinates encode projected ordinary draws, chi-turn eligibility and discard-source identity.",
          "Parameter sharing does not imply identical player embeddings or permutation invariance of the full seat-ordered encoder."
        ],
        "source": {
          "path": "model/critic.py",
          "line": 542
        }
      },
      {
        "id": "critic",
        "title": "Joint hand critic",
        "kind": "critic",
        "summary": "Shared player/role projections parameterize event, conditional-deposit and claim-score factors of a current-hand outcome model.",
        "dimensions": [
          "49 readouts → 60 joint events",
          "16 conditional deposit masks",
          "Event context/roles: 32",
          "Deposit context/roles: 8",
          "Claim state: 96",
          "Pao allocation: 16 claims × 4 seats"
        ],
        "details": [
          "Ordinary outcomes remain joint events. Four constrained nagashi outputs derive the 15 nonempty qualifier sets.",
          "Claim heads predict one total han/fu distribution using public scoring evidence.",
          "Hand-score factors for simultaneous winning claimants retain the conditional product factorization.",
          "Call-conditioned predictions model attempted calls, including priority preemption by competing claims."
        ],
        "source": {
          "path": "model/critic.py",
          "line": 770
        },
        "notes": [
          "Critic: 3,357,361 trainable parameters, including six 384 → 480 → 384 residual blocks."
        ]
      },
      {
        "id": "settlement",
        "title": "Rule-based settlement",
        "kind": "rules",
        "summary": "A deterministic support decoder maps event, claim-score and deposit states to transfers, scores and ranks.",
        "dimensions": [
          "Ron, tsumo, exhaustive draw, abort",
          "Dealer shares, honba, deposits",
          "Joint multiple-ron claims"
        ],
        "details": [
          "Triple-ron support is mapped to the simulator’s abort event.",
          "Public yaku, fu, bonus and settlement-legality masks restrict probability support.",
          "Pao and all nagashi qualifier sets are supported; observed unsupported targets fail validation instead of producing a coverage curve."
        ],
        "source": {
          "path": "model/joint_settlement.py",
          "line": 21
        }
      },
      {
        "id": "continuation",
        "title": "Fixed match continuation",
        "kind": "value",
        "summary": "A fixed score-to-rank continuation model supplies per-settlement payoffs for critic expectations.",
        "dimensions": [
          "J = ST3 / 100 + P(first) − P(fourth)",
          "4 final placement probabilities",
          "Single Gumbel; 4 fitted parameters"
        ],
        "details": [
          "Terminal settlements use realized score/rank state, deterministic tie priority and rounded ST3.",
          "Nonterminal forecasts condition on post-hand scores, scheduled hands remaining and future dealer counts.",
          "The common Gumbel scale is the square root of a positive quadratic variance; a positive dealer-count coefficient shifts score locations.",
          "The graph contains no learned state-value head or final-match-return regression target."
        ],
        "source": {
          "path": "model/joint_settlement.py",
          "line": 828
        }
      }
    ],
    "blocks": [
      {
        "id": "native-input-contract",
        "area": "input",
        "title": "Decision and after-call positions",
        "parent": "inputs",
        "kind": "input",
        "summary": "The decision board is the position before the player acts. Each legal chi or pon option has a hypothetical post-call board before the follow-up discard. Both use the same encoder.",
        "dimensions": [
          "6,428 scalars / local row",
          "B positions",
          "103 at decision + 103 after call + 2 indices",
          "16 local hand slots"
        ],
        "sharing": "Deterministic schema",
        "residual": "None",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 64
        },
        "operations": [
          {
            "id": "input-schema",
            "title": "Tensor specification",
            "description": "Native field order, fixed trailing dimensions and scalar dtypes determine the packed input layout.",
            "dimensions": [
              "Shapes exclude batch"
            ],
            "residual": "None",
            "sharing": "No trainable parameters",
            "source": {
              "path": "log_dataset/native_collection/src/schema.rs",
              "line": 64
            }
          },
          {
            "id": "keras-inputs",
            "title": "Keras input dictionary",
            "description": "Construct one named Keras Input per native schema field.",
            "dimensions": [
              "B × schema shape"
            ],
            "residual": "None",
            "sharing": "No trainable parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 907
            }
          },
          {
            "id": "compact-input-decode",
            "title": "Lossless semantic input decoding",
            "description": "Reconstruct candidate meld histograms, public meld ID/red/valid channels, tedashi one-hots and blocker counts before unchanged learned projections. Blockers derive from known_unavailable_counts.",
            "dimensions": [
              "100 wire fields → neural channels"
            ],
            "sharing": "No learned parameters",
            "residual": "None",
            "source": {
              "path": "model/input_features.py",
              "line": 106
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              0
            ]
          }
        ],
        "purpose": "Supplies the observed position and each hypothetical call as separate rows.",
        "parameters": 0
      },
      {
        "id": "shared-tile-projection",
        "area": "board",
        "title": "Shared tile identity projection",
        "parent": "board",
        "kind": "projection",
        "summary": "Project the fixed 34-class one-hot basis once into 8 identity channels. Hand, river, table and candidate branches reuse these 272 weights; red flags and padding masks stay separate.",
        "dimensions": [
          "34 one-hot → 8 channels",
          "One 34 × 8 weight matrix"
        ],
        "parameter_detail": "34 × 8 = 272 weights; no bias.",
        "sharing": "One NeuralFeatures.tile_projection shared by all four encoder branches",
        "residual": "None",
        "source": {
          "path": "model/input_features.py",
          "line": 128
        },
        "operations": [
          {
            "id": "tile-identity-basis",
            "title": "One-hot basis projection",
            "description": "Apply one bias-free Dense 8 to the 34 × 34 identity basis. Branches select base-tile rows; padding returns zero and red fives use the ordinary five row plus a separate red bit.",
            "dimensions": [
              "34 × 34 → 34 × 8"
            ],
            "sharing": "Exactly one trainable projection",
            "residual": "None",
            "source": {
              "path": "model/input_features.py",
              "line": 139
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              14
            ]
          }
        ],
        "purpose": "Gives the same tile the same learned identity across shared encoder branches.",
        "notes": [
          "Private predictor last-discard one-hot observations remain separate inputs to their own Dense readouts."
        ],
        "parameters": 272
      },
      {
        "id": "shared-public-context",
        "area": "board",
        "title": "Shared public context",
        "parent": "board",
        "kind": "projection",
        "summary": "Encode observed public fields and river summaries once into 512 channels. Candidate analysis and legality stay outside the board representation.",
        "dimensions": [
          "1412 → 384 → 512",
          "384 river channels + typed public fields",
          "One context vector per position"
        ],
        "sharing": "One public-field encoding and one river encoder shared by hand conditioning and joint board fusion",
        "residual": "None",
        "source": {
          "path": "model/encoder.py",
          "line": 52
        },
        "operations": [
          {
            "id": "board-input-projection-semantic-fields",
            "title": "Semantic field encoding",
            "description": "Tile IDs reuse the shared 34 × 8 identity projection; nominal categories use one-hot, red flags and masks stay binary, and numeric magnitudes use asinh.",
            "dimensions": [
              "Field-specific channel widths"
            ],
            "sharing": "One SemanticFields instance for shared public context; river metadata is encoded in RiverEncoding",
            "residual": "None",
            "source": {
              "path": "model/input_features.py",
              "line": 276
            }
          },
          {
            "id": "board-numeric",
            "title": "Flatten semantic channels",
            "description": "Flatten already encoded categorical, mask and numeric channels; no second transform of embeddings or normalized values.",
            "dimensions": [
              "B × D_numeric"
            ],
            "residual": "None",
            "sharing": "No trainable parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 125
            }
          },
          {
            "id": "board-yaku-bases",
            "title": "Opponent yaku basis",
            "description": "Compress each opponent’s thirteen public fixed-meld/public-supply feasibility flags with one shared bias-free basis.",
            "dimensions": [
              "13 → 6"
            ],
            "residual": "None",
            "sharing": "Same basis for the three opponents",
            "source": {
              "path": "model/encoder.py",
              "line": 72
            }
          },
          {
            "id": "board-factor",
            "title": "Bias-free linear factor",
            "description": "First low-rank affine factor; no bias or activation between the two projection matrices.",
            "dimensions": [
              "1412 → 384"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 81
            }
          },
          {
            "id": "board-dense",
            "title": "GELU output projection",
            "description": "Project the 384-channel linear factor to 512 channels with GELU.",
            "dimensions": [
              "384 → 512"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 84
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              7
            ]
          }
        ],
        "purpose": "Shares the same encoded public evidence with the hand and board branches.",
        "notes": [
          "Raw river slots enter only RiverEncoding. Per-tile public arrays enter the hand tokens."
        ],
        "parameters": 739406
      },
      {
        "id": "table-conditioning",
        "parameter_detail": "512 × 128 = 65,536 weights.",
        "area": "board",
        "title": "Shared-context hand conditioning",
        "parent": "hand-bank",
        "kind": "projection",
        "summary": "Project the shared 512-channel public context to a 128-channel offset for every tile in each occupied hand.",
        "dimensions": [
          "512 → 128",
          "Encoded public context",
          "Same offset for H[n,0…15]"
        ],
        "sharing": "One bias-free projection; the public context is reused rather than encoded again",
        "residual": "Add to tile projection before GELU",
        "source": {
          "path": "model/encoder.py",
          "line": 181
        },
        "operations": [
          {
            "id": "hand-board-project",
            "title": "Shared-context projection",
            "description": "Map the shared context to the owning row’s hand-token offset.",
            "dimensions": [
              "512 → 128"
            ],
            "residual": "Added to each local tile projection before GELU",
            "sharing": "One projection and one offset per position",
            "source": {
              "path": "model/encoder.py",
              "line": 181
            }
          }
        ],
        "equations": [
          {
            "topic": "decision-conditioning",
            "equations": [
              0,
              1
            ]
          }
        ],
        "purpose": "Conditions local hands on the shared public evidence before suit convolutions.",
        "parameters": 65536
      },
      {
        "id": "hand-tokenization",
        "area": "board",
        "title": "Context-conditioned hand tokens",
        "parent": "hand-bank",
        "kind": "encoder",
        "summary": "Gather each occupied local hand and its owning row’s decision-context offset. Sum tile and table affine maps before GELU; all 16 local hands share that row’s table, not the same hand state.",
        "dimensions": [
          "N × 34 × 39 → N × 34 × 128",
          "N occupied hands × 34 × 39",
          "N × 34 × 128"
        ],
        "sharing": "HandBank weights shared across candidate slots",
        "residual": "None",
        "source": {
          "path": "model/encoder.py",
          "line": 176
        },
        "operations": [
          {
            "id": "hand-embedding",
            "title": "Shared tile identity lookup",
            "description": "Reuse the single 34 × 8 identity projection from NeuralFeatures. This branch has no separate tile embedding.",
            "dimensions": [
              "34 × 8"
            ],
            "residual": "None",
            "sharing": "Same identity weights as the other encoder branches",
            "source": {
              "path": "model/encoder.py",
              "line": 278
            }
          },
          {
            "id": "hand-token-project",
            "title": "Tile projection",
            "description": "Affine map of the 39-dimensional per-tile descriptor.",
            "dimensions": [
              "39 → 128"
            ],
            "residual": "None",
            "sharing": "Shared over 34 tiles and all hands",
            "source": {
              "path": "model/encoder.py",
              "line": 184
            }
          },
          {
            "id": "hand-condition-gelu",
            "title": "Conditional GELU",
            "description": "Sum the tile and public affine projections before the first nonlinearity.",
            "dimensions": [
              "N × 34 × 128"
            ],
            "residual": "None",
            "sharing": "Same conditioning for every tile of a hand",
            "source": {
              "path": "model/encoder.py",
              "line": 336
            }
          }
        ],
        "equations": [
          {
            "topic": "decision-conditioning",
            "equations": [
              0,
              1
            ]
          }
        ],
        "purpose": "Combines tile identity and local hand contents with the decision context before hand encoding.",
        "notes": [
          "Each occupied hand has 34 tile types: 3 suits × 9 ranks, plus 7 honors. N counts occupied hand rows across the batch."
        ],
        "parameters": 5120
      },
      {
        "id": "hand-suit-0",
        "parameter_detail": "3 residual blocks × 98,816 parameters = 296,448 shared across the three suits.",
        "area": "board",
        "title": "Suit residual block 1",
        "parent": "hand-bank",
        "kind": "residual",
        "summary": "Two suit-local kernel-3 convolutions at dilation 1.",
        "dimensions": [
          "U unique suits × 9 × 128",
          "Dilation 1"
        ],
        "sharing": "Distinct weights per depth; tied across the three suits",
        "residual": "GELU(LayerNorm(x + Conv 2(GELU(Conv 1(x)))))",
        "source": {
          "path": "model/encoder.py",
          "line": 137
        },
        "operations": [
          {
            "id": "suit-0-first",
            "title": "Conv 1 D + GELU",
            "description": "128 filters, kernel 3, same padding, dilation 1.",
            "dimensions": [
              "128 → 128"
            ],
            "residual": "None",
            "sharing": "Shared across suits and candidate hands",
            "source": {
              "path": "model/encoder.py",
              "line": 141
            }
          },
          {
            "id": "suit-0-second",
            "title": "Conv 1 D",
            "description": "Linear 128-filter convolution with the same dilation 1.",
            "dimensions": [
              "128 → 128"
            ],
            "residual": "None",
            "sharing": "Shared across suits and candidate hands",
            "source": {
              "path": "model/encoder.py",
              "line": 149
            }
          },
          {
            "id": "suit-0-norm",
            "title": "Residual LayerNorm + GELU",
            "description": "Add the original token sequence, normalize over channels, then apply GELU.",
            "dimensions": [
              "9 × 128 → 9 × 128"
            ],
            "residual": "x + Conv 2(GELU(Conv 1(x)))",
            "sharing": "Shared across suits and candidate hands",
            "source": {
              "path": "model/encoder.py",
              "line": 168
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              3
            ]
          }
        ],
        "purpose": "Learns rank relationships within a suit; increasing dilation extends the range of tile interactions.",
        "notes": [
          "Each hand splits into 3 suits of 9 ranks. The same convolution weights process all suits. U counts unique suit sequences after deduplication within their decision context."
        ],
        "parameters": 98816
      },
      {
        "id": "hand-suit-1",
        "area": "board",
        "title": "Suit residual block 2",
        "parent": "hand-bank",
        "kind": "residual",
        "summary": "Two suit-local kernel-3 convolutions at dilation 2.",
        "dimensions": [
          "U unique suits × 9 × 128",
          "Dilation 2"
        ],
        "sharing": "Distinct weights per depth; tied across the three suits",
        "residual": "GELU(LayerNorm(x + Conv 2(GELU(Conv 1(x)))))",
        "source": {
          "path": "model/encoder.py",
          "line": 137
        },
        "operations": [
          {
            "id": "suit-1-first",
            "title": "Conv 1 D + GELU",
            "description": "128 filters, kernel 3, same padding, dilation 2.",
            "dimensions": [
              "128 → 128"
            ],
            "residual": "None",
            "sharing": "Shared across suits and candidate hands",
            "source": {
              "path": "model/encoder.py",
              "line": 141
            }
          },
          {
            "id": "suit-1-second",
            "title": "Conv 1 D",
            "description": "Linear 128-filter convolution with the same dilation 2.",
            "dimensions": [
              "128 → 128"
            ],
            "residual": "None",
            "sharing": "Shared across suits and candidate hands",
            "source": {
              "path": "model/encoder.py",
              "line": 149
            }
          },
          {
            "id": "suit-1-norm",
            "title": "Residual LayerNorm + GELU",
            "description": "Add the original token sequence, normalize over channels, then apply GELU.",
            "dimensions": [
              "9 × 128 → 9 × 128"
            ],
            "residual": "x + Conv 2(GELU(Conv 1(x)))",
            "sharing": "Shared across suits and candidate hands",
            "source": {
              "path": "model/encoder.py",
              "line": 168
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              3
            ]
          }
        ],
        "purpose": "Learns rank relationships within a suit; increasing dilation extends the range of tile interactions.",
        "notes": [
          "Each hand splits into 3 suits of 9 ranks. The same convolution weights process all suits. U counts unique suit sequences after deduplication within their decision context."
        ],
        "parameters": 98816
      },
      {
        "id": "hand-suit-2",
        "area": "board",
        "title": "Suit residual block 3",
        "parent": "hand-bank",
        "kind": "residual",
        "summary": "Two suit-local kernel-3 convolutions at dilation 4.",
        "dimensions": [
          "U unique suits × 9 × 128",
          "Dilation 4"
        ],
        "sharing": "Distinct weights per depth; tied across the three suits",
        "residual": "GELU(LayerNorm(x + Conv 2(GELU(Conv 1(x)))))",
        "source": {
          "path": "model/encoder.py",
          "line": 137
        },
        "operations": [
          {
            "id": "suit-2-first",
            "title": "Conv 1 D + GELU",
            "description": "128 filters, kernel 3, same padding, dilation 4.",
            "dimensions": [
              "128 → 128"
            ],
            "residual": "None",
            "sharing": "Shared across suits and candidate hands",
            "source": {
              "path": "model/encoder.py",
              "line": 141
            }
          },
          {
            "id": "suit-2-second",
            "title": "Conv 1 D",
            "description": "Linear 128-filter convolution with the same dilation 4.",
            "dimensions": [
              "128 → 128"
            ],
            "residual": "None",
            "sharing": "Shared across suits and candidate hands",
            "source": {
              "path": "model/encoder.py",
              "line": 149
            }
          },
          {
            "id": "suit-2-norm",
            "title": "Residual LayerNorm + GELU",
            "description": "Add the original token sequence, normalize over channels, then apply GELU.",
            "dimensions": [
              "9 × 128 → 9 × 128"
            ],
            "residual": "x + Conv 2(GELU(Conv 1(x)))",
            "sharing": "Shared across suits and candidate hands",
            "source": {
              "path": "model/encoder.py",
              "line": 168
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              3
            ]
          }
        ],
        "purpose": "Learns rank relationships within a suit; increasing dilation extends the range of tile interactions.",
        "notes": [
          "Each hand splits into 3 suits of 9 ranks. The same convolution weights process all suits. U counts unique suit sequences after deduplication within their decision context."
        ],
        "parameters": 98816
      },
      {
        "id": "hand-honors",
        "parameter_detail": "128 × 128 weights + 128 biases = 16,512 parameters shared across all seven honors.",
        "area": "board",
        "title": "Honor tile projection",
        "parent": "hand-bank",
        "kind": "projection",
        "summary": "Honor tiles use a pointwise dense path without suit convolution.",
        "dimensions": [
          "N × 7 × 128 → N × 7 × 128"
        ],
        "sharing": "Shared across hands; distinct from suit weights",
        "residual": "None",
        "source": {
          "path": "model/encoder.py",
          "line": 193
        },
        "operations": [
          {
            "id": "honor-dense",
            "title": "Dense + GELU",
            "description": "Process the seven honor tokens with one shared affine map.",
            "dimensions": [
              "128 → 128"
            ],
            "residual": "None",
            "sharing": "Tied over the seven honor tiles",
            "source": {
              "path": "model/encoder.py",
              "line": 193
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              1
            ]
          }
        ],
        "purpose": "Honors need their own encoding because they have no consecutive-rank sequence structure.",
        "notes": [
          "The 7 honor types are the four winds and three dragons."
        ],
        "parameters": 16512
      },
      {
        "id": "hand-bank-output",
        "area": "board",
        "title": "Conditioned local hand bank",
        "parent": "hand-bank",
        "kind": "projection",
        "summary": "H[n,k] encodes local hand slot k under table row n. All 16 slots use the same decision-context offset; distinct legal actions may gather the same hand slot. Suit deduplication includes row identity. Nineteen yaku-feasibility flags join the flattened tile encoding for that same hand.",
        "dimensions": [
          "B × 16 × 512",
          "H[n,k]: B × 16 × 512",
          "4371 → 384 → 512"
        ],
        "sharing": "One hand representation function across all occupied slots",
        "residual": "None",
        "source": {
          "path": "model/encoder.py",
          "line": 196
        },
        "operations": [
          {
            "id": "hand-output-factor",
            "title": "Bias-free linear factor",
            "description": "First low-rank affine factor; no bias or activation between the two projection matrices.",
            "dimensions": [
              "4371 → 384"
            ],
            "residual": "None",
            "sharing": "Shared across hands",
            "source": {
              "path": "model/encoder.py",
              "line": 199
            }
          },
          {
            "id": "hand-output-dense",
            "title": "GELU output projection",
            "description": "Project the 384-channel linear factor to 512 channels with GELU.",
            "dimensions": [
              "384 → 512"
            ],
            "residual": "None",
            "sharing": "Shared across hands",
            "source": {
              "path": "model/encoder.py",
              "line": 202
            }
          },
          {
            "id": "hand-output-norm",
            "title": "LayerNorm",
            "description": "Learned centering and scaling over the 512-channel hand embedding.",
            "dimensions": [
              "512 → 512"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 208
            }
          },
          {
            "id": "hand-bank-restore",
            "title": "Occupancy-indexed scatter",
            "description": "Scatter occupied encodings into their original 16-slot hand bank. Unoccupied slots remain zero.",
            "dimensions": [
              "N × 512 → B × 16 × 512"
            ],
            "residual": "None",
            "sharing": "No trainable parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 389
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              4
            ]
          }
        ],
        "purpose": "Lets multiple actions reuse the encoding of the same resulting hand.",
        "notes": [
          "Each local decision reserves 16 hand slots. Actions that produce the same hand can share a slot; invalid slots are masked. After-call positions each have their own local bank."
        ],
        "parameters": 1876608
      },
      {
        "id": "river-tokenization",
        "area": "board",
        "title": "River token projection",
        "parent": "rivers",
        "kind": "encoder",
        "summary": "Concatenate tile embedding 8 and typed metadata 17, then project 25→64. Nominal river categories use shared 2-channel embeddings; masks stay binary and numeric values use asinh.",
        "dimensions": [
          "(6 B) × 32 × 64",
          "B × 3 opponents × 2 phases × 32 slots"
        ],
        "sharing": "Same encoder for every opponent and pre/post-riichi stream",
        "residual": "None",
        "source": {
          "path": "model/encoder.py",
          "line": 399
        },
        "operations": [
          {
            "id": "river-embedding",
            "title": "Shared tile identity lookup",
            "description": "Reuse the single 34 × 8 identity projection from NeuralFeatures. This branch has no separate tile embedding.",
            "dimensions": [
              "34 × 8"
            ],
            "residual": "None",
            "sharing": "Same identity weights as the other encoder branches",
            "source": {
              "path": "model/encoder.py",
              "line": 503
            }
          },
          {
            "id": "river-tokens",
            "title": "Dense + GELU + validity mask",
            "description": "Concatenate identity and scalar metadata, project to 64 channels and zero padding.",
            "dimensions": [
              "8 tile embedding +17 metadata →64"
            ],
            "residual": "None",
            "sharing": "Shared across streams and time slots",
            "source": {
              "path": "model/encoder.py",
              "line": 417
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              1
            ]
          }
        ],
        "purpose": "Turns ordered discard observations and their metadata into learned temporal features.",
        "notes": [
          "There are 3 opponents. Each river has 2 phases, before and after riichi, with 32 padded discard slots per phase. This gives 6 river sequences per decision; padding is masked."
        ],
        "parameters": 1508
      },
      {
        "id": "river-conv-0",
        "area": "board",
        "title": "River residual block 1",
        "parent": "rivers",
        "kind": "residual",
        "summary": "Masked temporal convolution with dilation 1.",
        "dimensions": [
          "(6 B) × 32 × 64",
          "Dilation 1"
        ],
        "sharing": "Distinct parameters per depth; same parameters for all streams",
        "residual": "GELU(LayerNorm(x + Conv 1 D(x))) × valid",
        "source": {
          "path": "model/encoder.py",
          "line": 420
        },
        "operations": [
          {
            "id": "river-0-conv",
            "title": "Conv 1 D",
            "description": "64 filters, kernel 3, same padding; no activation inside the convolution.",
            "dimensions": [
              "64 → 64"
            ],
            "residual": "None",
            "sharing": "Tied across the six streams",
            "source": {
              "path": "model/encoder.py",
              "line": 420
            }
          },
          {
            "id": "river-0-norm",
            "title": "Residual LayerNorm + GELU + mask",
            "description": "Normalize the convolution skip sum and reapply observed-token validity.",
            "dimensions": [
              "32 × 64 → 32 × 64"
            ],
            "residual": "x + Conv 1 D(x)",
            "sharing": "Tied across streams; separate weights at each depth",
            "source": {
              "path": "model/encoder.py",
              "line": 528
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              5
            ]
          }
        ],
        "purpose": "Learns temporal patterns in opponent discards; increasing dilation incorporates more distant history.",
        "notes": [
          "There are 3 opponents. Each river has 2 phases, before and after riichi, with 32 padded discard slots per phase. This gives 6 river sequences per decision; padding is masked."
        ],
        "parameters": 12480
      },
      {
        "id": "river-conv-1",
        "area": "board",
        "title": "River residual block 2",
        "parent": "rivers",
        "kind": "residual",
        "summary": "Masked temporal convolution with dilation 2.",
        "dimensions": [
          "(6 B) × 32 × 64",
          "Dilation 2"
        ],
        "sharing": "Distinct parameters per depth; same parameters for all streams",
        "residual": "GELU(LayerNorm(x + Conv 1 D(x))) × valid",
        "source": {
          "path": "model/encoder.py",
          "line": 420
        },
        "operations": [
          {
            "id": "river-1-conv",
            "title": "Conv 1 D",
            "description": "64 filters, kernel 3, same padding; no activation inside the convolution.",
            "dimensions": [
              "64 → 64"
            ],
            "residual": "None",
            "sharing": "Tied across the six streams",
            "source": {
              "path": "model/encoder.py",
              "line": 420
            }
          },
          {
            "id": "river-1-norm",
            "title": "Residual LayerNorm + GELU + mask",
            "description": "Normalize the convolution skip sum and reapply observed-token validity.",
            "dimensions": [
              "32 × 64 → 32 × 64"
            ],
            "residual": "x + Conv 1 D(x)",
            "sharing": "Tied across streams; separate weights at each depth",
            "source": {
              "path": "model/encoder.py",
              "line": 528
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              5
            ]
          }
        ],
        "purpose": "Learns temporal patterns in opponent discards; increasing dilation incorporates more distant history.",
        "notes": [
          "There are 3 opponents. Each river has 2 phases, before and after riichi, with 32 padded discard slots per phase. This gives 6 river sequences per decision; padding is masked."
        ],
        "parameters": 12480
      },
      {
        "id": "river-conv-2",
        "area": "board",
        "title": "River residual block 3",
        "parent": "rivers",
        "kind": "residual",
        "summary": "Masked temporal convolution with dilation 4.",
        "dimensions": [
          "(6 B) × 32 × 64",
          "Dilation 4"
        ],
        "sharing": "Distinct parameters per depth; same parameters for all streams",
        "residual": "GELU(LayerNorm(x + Conv 1 D(x))) × valid",
        "source": {
          "path": "model/encoder.py",
          "line": 420
        },
        "operations": [
          {
            "id": "river-2-conv",
            "title": "Conv 1 D",
            "description": "64 filters, kernel 3, same padding; no activation inside the convolution.",
            "dimensions": [
              "64 → 64"
            ],
            "residual": "None",
            "sharing": "Tied across the six streams",
            "source": {
              "path": "model/encoder.py",
              "line": 420
            }
          },
          {
            "id": "river-2-norm",
            "title": "Residual LayerNorm + GELU + mask",
            "description": "Normalize the convolution skip sum and reapply observed-token validity.",
            "dimensions": [
              "32 × 64 → 32 × 64"
            ],
            "residual": "x + Conv 1 D(x)",
            "sharing": "Tied across streams; separate weights at each depth",
            "source": {
              "path": "model/encoder.py",
              "line": 528
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              5
            ]
          }
        ],
        "purpose": "Learns temporal patterns in opponent discards; increasing dilation incorporates more distant history.",
        "notes": [
          "There are 3 opponents. Each river has 2 phases, before and after riichi, with 32 padded discard slots per phase. This gives 6 river sequences per decision; padding is masked."
        ],
        "parameters": 12480
      },
      {
        "id": "river-attention",
        "area": "board",
        "parent": "rivers",
        "title": "Cross-river event attention",
        "kind": "attention",
        "summary": "Observed discard events attend across all three opponents and both riichi segments after the river convolutions.",
        "dimensions": [
          "192 events × 64 channels",
          "4 heads × 16 channels"
        ],
        "sharing": "One attention layer across all observed opponent events",
        "residual": "Convolution tokens + zero-initialized attention correction",
        "source": {
          "path": "model/river_attention.py",
          "line": 7
        },
        "operations": [
          {
            "id": "river-event-attention",
            "title": "Masked event attention",
            "description": "Add position and relative-seat embeddings, then apply four-head attention over observed query and key slots. Padding is masked.",
            "dimensions": [
              "192 × 64 → 192 × 64"
            ],
            "sharing": "Shared across events",
            "residual": "Zero-initialized bias-free 64 → 64 projection added to convolution tokens",
            "source": {
              "path": "model/river_attention.py",
              "line": 31
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              13
            ]
          }
        ],
        "purpose": "Makes cross-opponent and cross-segment discard evidence available before river pooling.",
        "notes": [
          "Seat embeddings identify the three opponents; 64 position embeddings distinguish the two 32-slot segments."
        ],
        "parameters": 25024
      },
      {
        "id": "river-summaries",
        "area": "board",
        "title": "River board and player summaries",
        "parent": "rivers",
        "kind": "pooling",
        "summary": "Use ordered tokens for the board embedding and masked pooled summaries for player descriptors.",
        "dimensions": [
          "384 board · 3 × 256 player",
          "6 × 64 = 384 board channels",
          "3 × 256 player channels"
        ],
        "sharing": "Same pooling/projection for each opponent stream",
        "residual": "None",
        "source": {
          "path": "model/encoder.py",
          "line": 539
        },
        "operations": [
          {
            "id": "river-pool",
            "title": "Masked mean and maximum",
            "description": "Each 32-token stream yields mean 64 + max 64; concatenate both phases per opponent.",
            "dimensions": [
              "2 × (64 + 64) = 256"
            ],
            "residual": "None",
            "sharing": "Parameter-free; empty streams produce zeros",
            "source": {
              "path": "model/encoder.py",
              "line": 539
            }
          },
          {
            "id": "river-project",
            "title": "Dense + GELU",
            "description": "Flatten 32 ordered tokens plus max 64 and project each stream to 64; concatenate six streams.",
            "dimensions": [
              "33 × 64 = 2112 → 64",
              "6 × 64 → 384"
            ],
            "residual": "None",
            "sharing": "Projection tied across all streams",
            "source": {
              "path": "model/encoder.py",
              "line": 434
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              6
            ]
          }
        ],
        "purpose": "Supplies both table-wide discard context and opponent-specific evidence.",
        "notes": [
          "The board receives all 6 river sequences. Player descriptors retain a separate summary for each of the 3 opponents."
        ],
        "parameters": 135232
      },
      {
        "id": "board-input-projection",
        "area": "board",
        "title": "Joint hand-board fusion",
        "parent": "board",
        "kind": "projection",
        "summary": "Fuse observed public context and the current hand into three critic/belief board residual blocks.",
        "dimensions": [
          "1024 → 512",
          "512 context + 512 current hand"
        ],
        "sharing": "One parameter set for this block",
        "residual": "None",
        "source": {
          "path": "model/encoder.py",
          "line": 869
        },
        "operations": [
          {
            "id": "board-fusion-dense",
            "title": "Joint fusion projection",
            "description": "Concatenate observed public context and current-hand slot 0, then apply one Dense GELU.",
            "dimensions": [
              "1024 → 512"
            ],
            "sharing": "One projection shared across decision and after-call rows",
            "residual": "None",
            "source": {
              "path": "model/encoder.py",
              "line": 869
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              12
            ]
          }
        ],
        "purpose": "Combines public context with context-conditioned hand structure before the three critic/belief board blocks.",
        "notes": [
          "Only hand-bank slot 0 enters board fusion; hypothetical hands enter action queries."
        ],
        "parameters": 524800
      },
      {
        "id": "board-block-0",
        "area": "board",
        "title": "Board residual block 1",
        "parent": "board",
        "kind": "residual",
        "summary": "Pre-normalized residual MLP with two 576-channel GELU hidden layers.",
        "dimensions": [
          "512 → 576 → 576 → 512",
          "B × 512 → B × 512"
        ],
        "sharing": "Separate weights for blocks 0–2; critic/belief branch; actor has independent upper weights",
        "residual": "Identity skip from block input to final Add",
        "source": {
          "path": "model/encoder.py",
          "line": 871
        },
        "operations": [
          {
            "id": "board-0-norm",
            "title": "LayerNorm",
            "description": "Normalize the incoming 512-channel representation with learned center and scale.",
            "dimensions": [
              "512 → 512"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 873
            }
          },
          {
            "id": "board-0-expand",
            "title": "Dense + GELU",
            "description": "Expand the normalized residual branch.",
            "dimensions": [
              "512 → 576"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 878
            }
          },
          {
            "id": "board-0-hidden",
            "title": "Hidden Dense + GELU",
            "description": "Second nonlinear transform at the expanded width.",
            "dimensions": [
              "576 → 576"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 884
            }
          },
          {
            "id": "board-0-contract",
            "title": "Dense",
            "description": "Linear contraction back to the trunk width.",
            "dimensions": [
              "576 → 512"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 888
            }
          },
          {
            "id": "board-0-add",
            "title": "Add",
            "description": "Add the residual branch to the unchanged block input.",
            "dimensions": [
              "512 + 512 → 512"
            ],
            "residual": "x + Dense 512(GELU(Dense 576(GELU(Dense 576(LayerNorm(x))))))",
            "sharing": "Parameter-free addition",
            "source": {
              "path": "model/encoder.py",
              "line": 891
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              8
            ]
          }
        ],
        "purpose": "Refines interactions among hand, river and table features while preserving the existing state through a residual connection.",
        "parameters": 924288
      },
      {
        "id": "board-block-1",
        "area": "board",
        "title": "Board residual block 2",
        "parent": "board",
        "kind": "residual",
        "summary": "Pre-normalized residual MLP with two 576-channel GELU hidden layers.",
        "dimensions": [
          "512 → 576 → 576 → 512",
          "B × 512 → B × 512"
        ],
        "sharing": "Separate weights for blocks 0–2; critic/belief branch; actor has independent upper weights",
        "residual": "Identity skip from block input to final Add",
        "source": {
          "path": "model/encoder.py",
          "line": 871
        },
        "operations": [
          {
            "id": "board-1-norm",
            "title": "LayerNorm",
            "description": "Normalize the incoming 512-channel representation with learned center and scale.",
            "dimensions": [
              "512 → 512"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 873
            }
          },
          {
            "id": "board-1-expand",
            "title": "Dense + GELU",
            "description": "Expand the normalized residual branch.",
            "dimensions": [
              "512 → 576"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 878
            }
          },
          {
            "id": "board-1-hidden",
            "title": "Hidden Dense + GELU",
            "description": "Second nonlinear transform at the expanded width.",
            "dimensions": [
              "576 → 576"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 884
            }
          },
          {
            "id": "board-1-contract",
            "title": "Dense",
            "description": "Linear contraction back to the trunk width.",
            "dimensions": [
              "576 → 512"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 888
            }
          },
          {
            "id": "board-1-add",
            "title": "Add",
            "description": "Add the residual branch to the unchanged block input.",
            "dimensions": [
              "512 + 512 → 512"
            ],
            "residual": "x + Dense 512(GELU(Dense 576(GELU(Dense 576(LayerNorm(x))))))",
            "sharing": "Parameter-free addition",
            "source": {
              "path": "model/encoder.py",
              "line": 891
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              8
            ]
          }
        ],
        "purpose": "Refines interactions among hand, river and table features while preserving the existing state through a residual connection.",
        "parameters": 924288
      },
      {
        "id": "board-block-2",
        "area": "board",
        "title": "Board residual block 3",
        "parent": "board",
        "kind": "residual",
        "summary": "Pre-normalized residual MLP with two 576-channel GELU hidden layers.",
        "dimensions": [
          "512 → 576 → 576 → 512",
          "B × 512 → B × 512"
        ],
        "sharing": "Separate weights for blocks 0–2; critic/belief branch; actor has independent upper weights",
        "residual": "Identity skip from block input to final Add",
        "source": {
          "path": "model/encoder.py",
          "line": 871
        },
        "operations": [
          {
            "id": "board-2-norm",
            "title": "LayerNorm",
            "description": "Normalize the incoming 512-channel representation with learned center and scale.",
            "dimensions": [
              "512 → 512"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 873
            }
          },
          {
            "id": "board-2-expand",
            "title": "Dense + GELU",
            "description": "Expand the normalized residual branch.",
            "dimensions": [
              "512 → 576"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 878
            }
          },
          {
            "id": "board-2-hidden",
            "title": "Hidden Dense + GELU",
            "description": "Second nonlinear transform at the expanded width.",
            "dimensions": [
              "576 → 576"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 884
            }
          },
          {
            "id": "board-2-contract",
            "title": "Dense",
            "description": "Linear contraction back to the trunk width.",
            "dimensions": [
              "576 → 512"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 888
            }
          },
          {
            "id": "board-2-add",
            "title": "Add",
            "description": "Add the residual branch to the unchanged block input.",
            "dimensions": [
              "512 + 512 → 512"
            ],
            "residual": "x + Dense 512(GELU(Dense 576(GELU(Dense 576(LayerNorm(x))))))",
            "sharing": "Parameter-free addition",
            "source": {
              "path": "model/encoder.py",
              "line": 891
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              8
            ]
          }
        ],
        "purpose": "Refines interactions among hand, river and table features while preserving the existing state through a residual connection.",
        "parameters": 924288
      },
      {
        "id": "board-output",
        "area": "board",
        "title": "Shared decision state",
        "parent": "board",
        "kind": "projection",
        "summary": "Normalize the critic/belief upper state; its candidate and belief consumers retain their direct supervised gradients.",
        "dimensions": [
          "B × 512"
        ],
        "sharing": "One parameter set for this block",
        "residual": "None",
        "source": {
          "path": "model/encoder.py",
          "line": 901
        },
        "operations": [
          {
            "id": "board-state-dense",
            "title": "Dense + GELU",
            "description": "Final learned board transformation after all three residual blocks.",
            "dimensions": [
              "512 → 512"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 894
            }
          },
          {
            "id": "board-state-norm",
            "title": "Fixed LayerNorm",
            "description": "Float 32 normalization with center=False, scale=False and epsilon 1e-5.",
            "dimensions": [
              "512 → 512"
            ],
            "residual": "None",
            "sharing": "No learned scale or offset",
            "source": {
              "path": "model/encoder.py",
              "line": 901
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              1,
              9
            ]
          },
          {
            "topic": "representation-ownership",
            "equations": [
              0,
              1
            ]
          }
        ],
        "purpose": "Supplies the critic, candidate evidence and belief branch with the observed board representation.",
        "parameters": 262656
      },
      {
        "id": "candidate-projection",
        "area": "board",
        "title": "Local action queries",
        "parent": "candidates",
        "kind": "projection",
        "summary": "Action query A[n,a] gathers H[n,hand_index(a)] plus board 192 and action metadata 57. Action kind is one-hot 7 with a declaration flag; scoring magnitudes use asinh and masks stay binary. Candidate tiles use the shared 8-channel identity plus a red bit; absent tiles give zero identity.",
        "dimensions": [
          "761 → 384",
          "A[n,a]: active local action rows × 384",
          "H[n,hand_index(a)]512 + board 192 + metadata 57 → 384",
          "147 local address slots; 295 original-window IDs"
        ],
        "sharing": "One candidate encoder across discard, riichi, response and kan slots",
        "residual": "None",
        "source": {
          "path": "model/encoder.py",
          "line": 632
        },
        "operations": [
          {
            "id": "candidate-context",
            "title": "Dense + GELU",
            "description": "Compress the 512-wide board state into 192 shared context channels before candidate gather.",
            "dimensions": [
              "512 → 192"
            ],
            "residual": "None",
            "sharing": "One vector per position",
            "source": {
              "path": "model/encoder.py",
              "line": 637
            }
          },
          {
            "id": "candidate-dense",
            "title": "Dense + GELU",
            "description": "Concatenate hand 512, board 192 and action metadata 57, including resulting-hand yaku distances, normal shanten/ukeire, retained safety, kan efficiency and abort support.",
            "dimensions": [
              "512 + 192 + 57 = 761 → 384"
            ],
            "residual": "None",
            "sharing": "Same map across all action kinds",
            "source": {
              "path": "model/encoder.py",
              "line": 640
            }
          },
          {
            "id": "candidate-norm",
            "title": "Fixed LayerNorm",
            "description": "Float 32 normalization without learned centering/scaling; epsilon 1e-5.",
            "dimensions": [
              "M × 384"
            ],
            "residual": "None",
            "sharing": "Parameter-free per candidate",
            "source": {
              "path": "model/encoder.py",
              "line": 947
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              1,
              9
            ]
          },
          {
            "topic": "candidate-mass",
            "equations": [
              0
            ]
          }
        ],
        "purpose": "Distinguishes legal actions by their resulting hand and action-specific metadata.",
        "notes": [
          "A candidate is a legal action paired with its resulting hand. The local query layout has 147 address slots: 37 discards, 2 × 37 riichi/discard choices, pass, and 35 kan choices. Legality masks select the active candidates.",
          "Candidate analysis affects action representations without changing current opponent beliefs."
        ],
        "parameters": 391104
      },
      {
        "id": "actor-candidate-pool",
        "area": "actor",
        "title": "Legal candidate attention",
        "parent": "actor",
        "kind": "attention",
        "summary": "Query detached legal candidates with the actor context, then add their attention-weighted value as a policy residual.",
        "dimensions": [
          "Q / K / V: 128",
          "Query 768 → 128; keys/values 384 → 128",
          "Attention value: 128 → 768",
          "298,368 actor parameters"
        ],
        "sharing": "One query per original decision; shared key/value projections across all legal local and call-plus-discard candidates",
        "residual": "Zero-initialized 128 → 768 correction",
        "source": {
          "path": "model/actor.py",
          "line": 86
        },
        "operations": [
          {
            "id": "candidate-pool-projection",
            "title": "Actor query and detached keys/values",
            "description": "Normalize actor context and project to a 128-channel query; normalize detached 384-channel candidates and project to 128-channel keys and values.",
            "dimensions": [
              "Query 768 → 128",
              "Keys/values 384 → 128"
            ],
            "sharing": "Shared projections with one query per original decision",
            "residual": "None",
            "source": {
              "path": "model/actor.py",
              "line": 86
            }
          },
          {
            "id": "candidate-pool-reduction",
            "title": "Decision-local candidate attention",
            "description": "Scale query-key scores by √128 and apply softmax within each original decision. Sum the legal candidate values with those weights.",
            "dimensions": [
              "N × 128 → attention-weighted 128"
            ],
            "sharing": "No mixing between decisions",
            "residual": "None",
            "source": {
              "path": "model/actor.py",
              "line": 86
            }
          },
          {
            "id": "candidate-pool-residual",
            "title": "Policy context correction",
            "description": "Project the attended 128 channels and add the result to each corresponding actor context.",
            "dimensions": [
              "128 → 768"
            ],
            "sharing": "One correction per original decision",
            "residual": "Output kernel and bias start at zero",
            "source": {
              "path": "model/actor.py",
              "line": 86
            }
          }
        ],
        "equations": [
          {
            "topic": "candidate-set-pooling",
            "equations": [
              0,
              1,
              2
            ]
          }
        ],
        "purpose": "Let the actor compare the available alternatives without changing candidate states used by supervised readouts.",
        "notes": [
          "Only actor losses train this attention; detached candidates stop gradients into the shared candidate encoder.",
          "The query trains the private actor context. Local action, call-choice and win decisions consume the corrected context."
        ],
        "parameters": 298368
      },
      {
        "id": "belief-refinement",
        "area": "belief",
        "title": "Belief residual refinement",
        "parent": "beliefs",
        "kind": "residual",
        "summary": "Pre-normalized 512 → 1152 → 512 residual transform; the zero-initialized output kernel and bias make the branch initially identity.",
        "dimensions": [
          "512 → 1152 → 512"
        ],
        "sharing": "Shared refinement before opponent/completion readouts and tile attention",
        "residual": "Identity skip plus learned branch",
        "source": {
          "path": "model/beliefs.py",
          "line": 451
        },
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              11
            ]
          }
        ],
        "operations": [
          {
            "id": "belief-refinement-norm",
            "title": "LayerNorm",
            "description": "Normalize the refinement input with learned scale and offset.",
            "dimensions": [
              "512 → 512"
            ],
            "residual": "None",
            "sharing": "Shared refinement before opponent/completion readouts and tile attention",
            "source": {
              "path": "model/beliefs.py",
              "line": 415
            }
          },
          {
            "id": "belief-refinement-hidden",
            "title": "Dense + GELU",
            "description": "Nonlinear hidden transform.",
            "dimensions": [
              "512 → 1152"
            ],
            "residual": "None",
            "sharing": "Shared refinement before opponent/completion readouts and tile attention",
            "source": {
              "path": "model/beliefs.py",
              "line": 416
            }
          },
          {
            "id": "belief-refinement-output",
            "title": "Zero-initialized output Dense",
            "description": "Output kernel and default bias start at zero; upstream hidden-layer gradients through this branch are initially zero.",
            "dimensions": [
              "1152 → 512"
            ],
            "residual": "None",
            "sharing": "Shared refinement before opponent/completion readouts and tile attention",
            "source": {
              "path": "model/beliefs.py",
              "line": 418
            }
          },
          {
            "id": "belief-refinement-add",
            "title": "Residual Add",
            "description": "Add the refinement branch to its unchanged input.",
            "dimensions": [
              "512 + 512 → 512"
            ],
            "residual": "Identity skip",
            "sharing": "Shared refinement before opponent/completion readouts and tile attention",
            "source": {
              "path": "model/beliefs.py",
              "line": 451
            }
          }
        ],
        "purpose": "Adds capacity for predicting hidden opponent information from the shared board state.",
        "parameters": 1182336
      },
      {
        "id": "belief-readouts",
        "area": "belief",
        "title": "Initial belief readouts",
        "parent": "beliefs",
        "kind": "heads",
        "summary": "Shared opponent shanten readout combines refined board prior, existing per-opponent river summary 256 and 49public channels. Improving/count heads retain independent opponent/category coefficient slices.",
        "dimensions": [
          "3×4 · 3×4×34 · 3×37×5",
          "B × 512",
          "3 × 4; 3 × 4 × 34; 3 × 37 × 5"
        ],
        "sharing": "Shanten coefficients tied across opponents; improving/count output slices remain distinct",
        "residual": "None",
        "source": {
          "path": "model/beliefs.py",
          "line": 424
        },
        "operations": [
          {
            "id": "shanten-board",
            "title": "Shanten board prior",
            "description": "Bias-free board prior shared across all three opponents.",
            "dimensions": [
              "512 →48"
            ],
            "sharing": "Shared across opponents and decision rows",
            "residual": "None",
            "source": {
              "path": "model/beliefs.py",
              "line": 281
            }
          },
          {
            "id": "shanten-observation",
            "title": "Opponent observation projection",
            "description": "Existing river summary 256 plus meldcount5, dealer1, riichi3, scaled discard/wall2 and last-tedashi37+presence1.",
            "dimensions": [
              "256 + 49 = 305 → 48"
            ],
            "sharing": "Shared across opponents and decision rows",
            "residual": "None",
            "source": {
              "path": "model/beliefs.py",
              "line": 282
            }
          },
          {
            "id": "shanten-readout",
            "title": "Shared four-class shanten readout",
            "description": "Add board and local evidence, GELU, then shared zero-initialized output projection.",
            "dimensions": [
              "3 ×48 →3 ×4"
            ],
            "sharing": "Shared across opponents and decision rows",
            "residual": "None",
            "source": {
              "path": "model/beliefs.py",
              "line": 283
            }
          },
          {
            "id": "ukeire-head",
            "title": "Conditional-ukeire Dense",
            "description": "Bernoulli improving-tile logits conditioned on four shanten categories.",
            "dimensions": [
              "512 → 408 → 3 × 4 × 34"
            ],
            "residual": "None",
            "sharing": "Separate output coefficients per opponent/shanten/tile",
            "source": {
              "path": "model/beliefs.py",
              "line": 424
            }
          },
          {
            "id": "count-head",
            "title": "Held-count Dense",
            "description": "Five-way count logits for 37 red-aware tile identities.",
            "dimensions": [
              "512 → 555 → 3 × 37 × 5"
            ],
            "residual": "None",
            "sharing": "Separate output coefficients per opponent/tile/count",
            "source": {
              "path": "model/beliefs.py",
              "line": 424
            }
          }
        ],
        "equations": [
          {
            "topic": "policy-readouts",
            "equations": [
              0
            ]
          },
          {
            "topic": "shared-opponent-shanten",
            "equations": [
              0
            ]
          }
        ],
        "purpose": "Provides opponent readiness, improving-tile and held-count estimates for policy and settlement reasoning.",
        "notes": [
          "Opponent axes have size 3. Shanten has 4 classes; improving-tile predictions have 34 tile types per shanten class; held-count predictions use 37 tile/red channels and 5 count classes, 0 through 4."
        ],
        "parameters": 533479
      },
      {
        "id": "tile-tokenization",
        "area": "belief",
        "title": "Tile attention tokenization",
        "parent": "tile-attention",
        "kind": "attention",
        "summary": "Assemble one 34-token sequence per opponent from initial marginals, public limits and board context.",
        "dimensions": [
          "(3 B) × 34 × 128",
          "B × 3 × 34 × 94 → (3 B) × 34 × 128"
        ],
        "sharing": "Attention sequences remain separate for the three opponents",
        "residual": "None",
        "source": {
          "path": "model/beliefs.py",
          "line": 157
        },
        "operations": [
          {
            "id": "tile-identity",
            "title": "Tile embedding",
            "description": "Ordinary tile identity embedding used by the refinement stack.",
            "dimensions": [
              "34 × 8"
            ],
            "residual": "None",
            "sharing": "Tied across opponents",
            "source": {
              "path": "model/beliefs.py",
              "line": 162
            }
          },
          {
            "id": "tile-context",
            "title": "Board context Dense",
            "description": "Project board 512 into three 64-channel opponent context vectors.",
            "dimensions": [
              "512 → 192 → 3 × 64"
            ],
            "residual": "None",
            "sharing": "Opponent-specific output slices",
            "source": {
              "path": "model/beliefs.py",
              "line": 163
            }
          },
          {
            "id": "tile-tokens",
            "title": "Token Dense",
            "description": "Concatenate count/ukeire/availability 18, identity 8, board 64 and shanten 4.",
            "dimensions": [
              "94 → 128"
            ],
            "residual": "None",
            "sharing": "Tied over opponents and tile types",
            "source": {
              "path": "model/beliefs.py",
              "line": 166
            }
          }
        ],
        "equations": [
          {
            "topic": "policy-readouts",
            "equations": [
              0
            ]
          }
        ],
        "purpose": "Puts belief estimates and public evidence for each tile into a common attention sequence.",
        "notes": [
          "Each of the 3 opponents has a separate sequence of 34 tile types. Attention mixes tile evidence within that opponent’s sequence, using shared weights across opponents."
        ],
        "parameters": 110928
      },
      {
        "id": "tile-attention-0",
        "area": "belief",
        "title": "Tile attention block 1",
        "parent": "tile-attention",
        "kind": "attention",
        "summary": "Pre-LayerNorm multi-head self-attention followed by a residual feed-forward sublayer.",
        "dimensions": [
          "(3 B) × 34 × 128",
          "4 heads × key_dim 32"
        ],
        "sharing": "Distinct block parameters; weights shared across opponents",
        "residual": "Two identity skips: attention and feed-forward",
        "source": {
          "path": "model/beliefs.py",
          "line": 167
        },
        "operations": [
          {
            "id": "tile-0-attn-norm",
            "title": "Attention LayerNorm",
            "description": "Learned normalization over 128 channels before attention.",
            "dimensions": [
              "34 × 128 → 34 × 128"
            ],
            "residual": "None",
            "sharing": "Tied across opponents",
            "source": {
              "path": "model/beliefs.py",
              "line": 259
            }
          },
          {
            "id": "tile-0-attn",
            "title": "MultiHeadAttention",
            "description": "Four heads attend across the 34 tile types within one opponent sequence; query/key/value derive from the same normalized tokens.",
            "dimensions": [
              "Q/K/V: 4 × 32",
              "34 × 34 attention per head"
            ],
            "residual": "x + MHA(LN(x), LN(x))",
            "sharing": "Tied across opponents; distinct between the two blocks",
            "source": {
              "path": "model/beliefs.py",
              "line": 169
            }
          },
          {
            "id": "tile-0-ffnorm",
            "title": "Feed-forward LayerNorm",
            "description": "Separate pre-normalization for the residual MLP.",
            "dimensions": [
              "128 → 128"
            ],
            "residual": "None",
            "sharing": "Tied across opponents",
            "source": {
              "path": "model/beliefs.py",
              "line": 177
            }
          },
          {
            "id": "tile-0-ff",
            "title": "Dense + GELU + Dense",
            "description": "Pointwise feed-forward expansion and contraction, then residual addition.",
            "dimensions": [
              "128 → 256 → 128"
            ],
            "residual": "y + Dense 128(GELU(Dense 256(LN(y))))",
            "sharing": "Tied across all tile tokens/opponents",
            "source": {
              "path": "model/beliefs.py",
              "line": 181
            }
          }
        ],
        "equations": [
          {
            "topic": "tile-attention-math",
            "equations": [
              0,
              1
            ]
          }
        ],
        "purpose": "Allows evidence about one tile to inform beliefs about other tiles in the same opponent hand.",
        "notes": [
          "Each of the 3 opponents has a separate sequence of 34 tile types. Attention mixes tile evidence within that opponent’s sequence, using shared weights across opponents."
        ],
        "parameters": 132480
      },
      {
        "id": "tile-attention-1",
        "area": "belief",
        "title": "Tile attention block 2",
        "parent": "tile-attention",
        "kind": "attention",
        "summary": "Pre-LayerNorm multi-head self-attention followed by a residual feed-forward sublayer.",
        "dimensions": [
          "(3 B) × 34 × 128",
          "4 heads × key_dim 32"
        ],
        "sharing": "Distinct block parameters; weights shared across opponents",
        "residual": "Two identity skips: attention and feed-forward",
        "source": {
          "path": "model/beliefs.py",
          "line": 167
        },
        "operations": [
          {
            "id": "tile-1-attn-norm",
            "title": "Attention LayerNorm",
            "description": "Learned normalization over 128 channels before attention.",
            "dimensions": [
              "34 × 128 → 34 × 128"
            ],
            "residual": "None",
            "sharing": "Tied across opponents",
            "source": {
              "path": "model/beliefs.py",
              "line": 259
            }
          },
          {
            "id": "tile-1-attn",
            "title": "MultiHeadAttention",
            "description": "Four heads attend across the 34 tile types within one opponent sequence; query/key/value derive from the same normalized tokens.",
            "dimensions": [
              "Q/K/V: 4 × 32",
              "34 × 34 attention per head"
            ],
            "residual": "x + MHA(LN(x), LN(x))",
            "sharing": "Tied across opponents; distinct between the two blocks",
            "source": {
              "path": "model/beliefs.py",
              "line": 169
            }
          },
          {
            "id": "tile-1-ffnorm",
            "title": "Feed-forward LayerNorm",
            "description": "Separate pre-normalization for the residual MLP.",
            "dimensions": [
              "128 → 128"
            ],
            "residual": "None",
            "sharing": "Tied across opponents",
            "source": {
              "path": "model/beliefs.py",
              "line": 177
            }
          },
          {
            "id": "tile-1-ff",
            "title": "Dense + GELU + Dense",
            "description": "Pointwise feed-forward expansion and contraction, then residual addition.",
            "dimensions": [
              "128 → 256 → 128"
            ],
            "residual": "y + Dense 128(GELU(Dense 256(LN(y))))",
            "sharing": "Tied across all tile tokens/opponents",
            "source": {
              "path": "model/beliefs.py",
              "line": 181
            }
          }
        ],
        "equations": [
          {
            "topic": "tile-attention-math",
            "equations": [
              0,
              1
            ]
          }
        ],
        "purpose": "Allows evidence about one tile to inform beliefs about other tiles in the same opponent hand.",
        "notes": [
          "Each of the 3 opponents has a separate sequence of 34 tile types. Attention mixes tile evidence within that opponent’s sequence, using shared weights across opponents."
        ],
        "parameters": 132480
      },
      {
        "id": "tile-correction",
        "area": "belief",
        "title": "Residual belief correction",
        "parent": "tile-attention",
        "kind": "heads",
        "summary": "Add learned corrections to ordinary/red count logits and conditional ukeire logits.",
        "dimensions": [
          "128 → 14",
          "3 × 34 × (5 + 5 + 4)"
        ],
        "sharing": "Same correction map for every opponent",
        "residual": "Add to initial belief logits",
        "source": {
          "path": "model/beliefs.py",
          "line": 195
        },
        "operations": [
          {
            "id": "tile-correction-dense",
            "title": "Zero-initialized Dense",
            "description": "Five ordinary count, five red count and four conditional-ukeire corrections per tile.",
            "dimensions": [
              "128 → 14"
            ],
            "residual": "None",
            "sharing": "Tied across opponents and tile tokens",
            "source": {
              "path": "model/beliefs.py",
              "line": 195
            }
          },
          {
            "id": "tile-correction-add",
            "title": "Gather and residual add",
            "description": "Red corrections gather only tile types 4,13,22; ukeire correction transposes into shanten-major order. Shanten logits are unchanged.",
            "dimensions": [
              "Counts: 3 × 37 × 5",
              "Ukeire: 3 × 4 × 34"
            ],
            "residual": "Initial logits + attention corrections",
            "sharing": "No additional trainable parameters",
            "source": {
              "path": "model/beliefs.py",
              "line": 262
            }
          }
        ],
        "equations": [
          {
            "topic": "tile-attention-math",
            "equations": [
              2
            ]
          }
        ],
        "purpose": "Lets cross-tile evidence refine the initial independent belief readouts.",
        "parameters": 1806
      },
      {
        "id": "belief-constraints",
        "area": "belief",
        "title": "Belief support and count projection",
        "parent": "beliefs",
        "kind": "constraints",
        "summary": "Apply public support and constrained marginal projection after attention refinement.",
        "dimensions": [
          "3 × 4 · 3 × 37 × 5",
          "3 × 4 shanten logits",
          "3 × 37 × 5 count logits"
        ],
        "sharing": "No separate learned constraint network",
        "residual": "None",
        "source": {
          "path": "model/beliefs.py",
          "line": 408
        },
        "operations": [
          {
            "id": "belief-shanten-mask",
            "title": "Shanten support mask",
            "description": "Riichi or four fixed melds restrict the categorical support to tenpai.",
            "dimensions": [
              "3 × 4"
            ],
            "residual": "None",
            "sharing": "Deterministic",
            "source": {
              "path": "model/beliefs.py",
              "line": 474
            }
          },
          {
            "id": "belief-count-mask",
            "title": "HeldCountMask",
            "description": "Exclude count classes outside known meld-copy lower and available-copy upper bounds.",
            "dimensions": [
              "3 × 37 × 5"
            ],
            "residual": "None",
            "sharing": "Deterministic",
            "source": {
              "path": "model/beliefs.py",
              "line": 37
            }
          },
          {
            "id": "belief-count-project",
            "title": "CountProjection",
            "description": "Weighted minimum-KL marginal projection. Alternate size and shared-copy dual updates using sign(r/v)·log1p(4|r/v|)/4, with v floored at 1e-7 and copy multipliers capped at zero. Iterate to residual 1e-5 or 2048 steps; validate feasibility within 1e-4. Custom implicit VJP differentiates projected logits; not a joint legal-hand sampler or exact finite-precision count solver.",
            "dimensions": [
              "3 × 37 × 5"
            ],
            "residual": "None",
            "sharing": "Parameter-free solver; gradients propagate into logits",
            "source": {
              "path": "model/beliefs.py",
              "line": 585
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              10
            ]
          },
          {
            "topic": "constraint-targets",
            "equations": [
              0
            ]
          },
          {
            "topic": "count-projection-solver",
            "equations": [
              0,
              1
            ]
          }
        ],
        "purpose": "Keeps inferred hidden hands consistent with public tile availability and support.",
        "parameters": 0
      },
      {
        "id": "actor-candidate-aux",
        "area": "belief",
        "title": "Shared route prediction",
        "parent": "candidates",
        "kind": "heads",
        "summary": "Shared candidate module predicts three bounded route affinities after public support masking. Actor and critic consume the same route prediction.",
        "dimensions": [
          "384 → 3",
          "384 →3 logits →sigmoid"
        ],
        "sharing": "Each readout tied across active action candidates",
        "residual": "None",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 8
        },
        "operations": [
          {
            "id": "actor-route",
            "title": "Route Dense + support mask",
            "description": "Three route-affinity logits; sigmoid probabilities feed the final scorer after public route masking.",
            "dimensions": [
              "384 → 3"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/candidate_predictions.py",
              "line": 10
            }
          }
        ],
        "equations": [
          {
            "topic": "policy-readouts",
            "equations": [
              0
            ]
          },
          {
            "topic": "constraint-targets",
            "equations": [
              1
            ]
          }
        ],
        "purpose": "Provides action-conditioned route evidence to both policy and critic. Candidate states first attend across all legal alternatives, including call-plus-discard actions.",
        "parameters": 1155
      },
      {
        "id": "candidate-ron-prediction",
        "area": "belief",
        "title": "Ron-risk prediction",
        "parent": "beliefs",
        "kind": "heads",
        "summary": "Each opponent shares a 599→128→34 eligibility network fed by the observed board, attached yaku-evidence hidden state and detached ron-yaku probabilities. Eligibility and detached structural wait are gathered by discarded base tile; public safe-tile and non-discard masks enforce support. Calls reuse parent tables.",
        "dimensions": [
          "3 × (512 + 64 + 23) → 128 → 34",
          "Gather tile → 3 ron logits per candidate"
        ],
        "sharing": "One 599→128→34 parameter set shared across opponents, decisions and call alternatives; 81,186 parameters",
        "residual": "None",
        "source": {
          "path": "model/network.py",
          "line": 44
        },
        "operations": [
          {
            "id": "actor-ron",
            "title": "Shared opponent eligibility",
            "description": "Join board512, attached opponent yaku hidden64 and detached ron-yaku probabilities23. Apply Dense128 + GELU, then Dense34 per opponent.",
            "dimensions": [
              "3 × 599 → 3 × 128 → 3 × 34"
            ],
            "residual": "None",
            "sharing": "One 599→128→34 parameter set shared across opponents, decisions and call alternatives; 81,186 parameters",
            "source": {
              "path": "model/network.py",
              "line": 50
            }
          },
          {
            "id": "ron-wait-eligibility",
            "title": "Wait ×eligibility with support",
            "description": "Gather eligibility and detached structural wait by base tile, combine in log space, and apply discard/safe-tile support.",
            "dimensions": [
              "3 wait +3 eligibility →3 ron logits"
            ],
            "sharing": "Derived probability uses upstream learned heads; no extra parameters",
            "residual": "None",
            "source": {
              "path": "model/candidate_predictions.py",
              "line": 25
            }
          }
        ],
        "equations": [
          {
            "topic": "candidate-ron-factorization",
            "equations": [
              0,
              1,
              2
            ]
          }
        ],
        "purpose": "Estimate immediate ron risk from current opponent evidence and the offered tile.",
        "parameters": 81186
      },
      {
        "id": "actor-completion",
        "area": "belief",
        "title": "Shared completion potential",
        "parent": "beliefs",
        "kind": "heads",
        "summary": "Predict yaku and han/fu for the same highest-point ordinary finish of the next observed tenpai shape. Direct scorer labels supervise both heads; actor and critic share their detached predictions.",
        "dimensions": [
          "4 × 2 × 23 · 1 × 2 × 38",
          "Refined latent 512",
          "Yaku 4 × 2 × 23; score 1 × 2 × 38"
        ],
        "sharing": "Actor and critic consume the same completion predictions; output coefficients remain distinct by player/win-kind/category",
        "residual": "Opponent evidence residual before support; self unchanged by this branch",
        "source": {
          "path": "model/beliefs.py",
          "line": 458
        },
        "operations": [
          {
            "id": "actor-completion-yaku",
            "title": "Completion-yaku Dense + mask",
            "description": "Independent binary logits per player, win kind and 23 yaku categories. Opponent raw logits include the aligned evidence residual before support/coupling; self does not.",
            "dimensions": [
              "512 → 184 → 4 × 2 × 23"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/beliefs.py",
              "line": 458
            }
          },
          {
            "id": "actor-completion-score",
            "title": "Completion potential readout",
            "description": "Best ordinary finish of the next observed tenpai shape, for our own hand, separately for ron/tsumo. Includes actual riichi, visible dora/red and applicable menzen tsumo; excludes hypothetical ura, ippatsu and special-event bonuses. Predicts completion potential, not win probability or the eventual winning score. Actor and critic consume these detached probabilities.",
            "dimensions": [
              "512 → 76 → 1 × 2 × 38"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/beliefs.py",
              "line": 458
            }
          }
        ],
        "equations": [
          {
            "topic": "policy-readouts",
            "equations": [
              0
            ]
          }
        ],
        "purpose": "Provides yaku and score evidence used by action selection and settlement prediction.",
        "notes": [
          "Completion yaku covers all four players; completion score covers only our hand. Both distinguish ron and tsumo. Yaku has 23 channels; score has 38 states."
        ],
        "parameters": 133380
      },
      {
        "id": "actor-policy-context",
        "area": "actor",
        "title": "Policy context projection",
        "parent": "actor",
        "kind": "projection",
        "summary": "Combine the policy-trained actor board with detached beliefs through Dense 256, then append the actor board for a 768-channel policy context.",
        "dimensions": [
          "1747 → 256",
          "512 + 256 → 768"
        ],
        "sharing": "Actor-only context projection; shared across ordinary and follow-up discard decisions",
        "residual": "None",
        "source": {
          "path": "model/network.py",
          "line": 75
        },
        "operations": [
          {
            "id": "actor-context",
            "title": "Dense + GELU",
            "description": "Concatenate private actor board 512 and detached probabilities 1235; weight each conditional improving slice by shanten mass. The actor trains this float32 projection without changing shared representations.",
            "dimensions": [
              "1747 → 256",
              "512 + 256 → 768"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/network.py",
              "line": 75
            }
          }
        ],
        "equations": [
          {
            "topic": "policy-readouts",
            "equations": [
              1
            ]
          },
          {
            "topic": "representation-ownership",
            "equations": [
              0,
              1
            ]
          }
        ],
        "purpose": "Makes predicted opponent and completion evidence available to every policy branch.",
        "parameters": 447488
      },
      {
        "id": "actor-refinement",
        "area": "actor",
        "title": "Actor refinement block 1",
        "parent": "actor",
        "kind": "residual",
        "summary": "Pre-normalized 768 → 384 → 768 residual over private actor board features and learned policy evidence. Its output projection starts at zero.",
        "dimensions": [
          "768 → 384 → 768"
        ],
        "sharing": "One private actor residual shared by discard, riichi, kan, win and call decisions",
        "residual": "Identity skip plus learned branch",
        "source": {
          "path": "model/network.py",
          "line": 108
        },
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              11
            ]
          }
        ],
        "operations": [
          {
            "id": "actor-private-residual",
            "title": "LayerNorm → GELU projection → residual",
            "description": "Learned LayerNorm and 768 → 384 GELU projection feed a zero-initialized 384 → 768 output, added to the input context.",
            "dimensions": [
              "768 → 384 → 768"
            ],
            "sharing": "Shared across policy branches",
            "residual": "Identity skip; output kernel and bias initially zero",
            "source": {
              "path": "model/network.py",
              "line": 108
            }
          }
        ],
        "purpose": "Adds private policy capacity after the shared-encoder gradient boundary.",
        "parameters": 592512
      },
      {
        "id": "actor-final-score",
        "area": "actor",
        "title": "Final candidate scorer",
        "parent": "actor",
        "kind": "policy",
        "summary": "One scalar scorer reads detached raw candidate states, detached route/ron predictions and policy context. The same weights score ordinary and post-call discards, riichi and kan choices.",
        "dimensions": [
          "1158 → 512 → 1",
          "Local widths 37,74,35; follow-up discard width 37"
        ],
        "sharing": "All active candidate kinds use the same final MLP and scalar output",
        "residual": "None",
        "source": {
          "path": "model/actor.py",
          "line": 432
        },
        "operations": [
          {
            "id": "actor-final-input",
            "title": "Candidate/context concatenation",
            "description": "Concatenate detached raw candidate 384, detached route/ron 3+3 and gathered policy context 768.",
            "dimensions": [
              "384 + 6 + 768 = 1158"
            ],
            "residual": "None",
            "sharing": "No trainable parameters",
            "source": {
              "path": "model/actor.py",
              "line": 316
            }
          },
          {
            "id": "actor-final-dense",
            "title": "Dense + GELU",
            "description": "Final learned candidate representation. This policy projection is float32.",
            "dimensions": [
              "1158 → 512"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/actor.py",
              "line": 171
            }
          },
          {
            "id": "actor-final-norm",
            "title": "Fixed LayerNorm",
            "description": "Normalize 512 channels in float 32 without learned center/scale; epsilon 1e-5.",
            "dimensions": [
              "512 → 512"
            ],
            "residual": "None",
            "sharing": "Parameter-free",
            "source": {
              "path": "model/actor.py",
              "line": 179
            }
          },
          {
            "id": "actor-final-readout",
            "title": "Dense scalar",
            "description": "One shared candidate score, scattered into canonical action slots; illegal slots are constant padding. This policy projection is float32.",
            "dimensions": [
              "512 → 1"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/actor.py",
              "line": 185
            }
          },
          {
            "id": "actor-phase-masks",
            "title": "Phase gather and masks",
            "description": "Apply legality and opening-symmetry pooling. At zero live-wall count with no legal cut reaching shanten≤1, redistribute ordinary/dama branch mass uniformly over available cuts guaranteed safe against every opponent, preserving possible nagashi. Accepted calls apply the same rule to the follow-up discard. Response policy is assembled separately.",
            "dimensions": [
              "295 padded scores → local heads 37/74/35"
            ],
            "residual": "None",
            "sharing": "No separate learned per-phase candidate scorer",
            "source": {
              "path": "model/actor.py",
              "line": 192
            }
          }
        ],
        "equations": [
          {
            "topic": "policy-readouts",
            "equations": [
              2
            ]
          },
          {
            "topic": "legal-policy",
            "equations": [
              0,
              1
            ]
          }
        ],
        "purpose": "Ranks candidate actions with a common scoring function.",
        "notes": [
          "The same scorer evaluates every active local candidate and every follow-up discard. The 37 discard addresses distinguish 34 tile types and 3 red fives; only discards present and legal in the current hand are used."
        ],
        "parameters": 593921
      },
      {
        "id": "actor-win",
        "area": "actor",
        "title": "Win/pass head",
        "parent": "actor",
        "kind": "policy",
        "summary": "A separate board readout produces the optional accept/decline logits.",
        "dimensions": [
          "B × 768 → B × 2"
        ],
        "sharing": "Separate weights from candidate-scoring head",
        "residual": "None",
        "source": {
          "path": "model/actor.py",
          "line": 204
        },
        "operations": [
          {
            "id": "actor-win-dense",
            "title": "Dense 2",
            "description": "Linear board-state readout for pass and win.",
            "dimensions": [
              "768 → 2"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/actor.py",
              "line": 204
            }
          },
          {
            "id": "actor-win-mask",
            "title": "Legality mask",
            "description": "Apply native win/pass support. Both branches use the same current-hand Q in MMD.",
            "dimensions": [
              "2 → 2"
            ],
            "residual": "None",
            "sharing": "Deterministic mask",
            "source": {
              "path": "model/actor.py",
              "line": 208
            }
          }
        ],
        "equations": [
          {
            "topic": "policy-readouts",
            "equations": [
              0
            ]
          },
          {
            "topic": "legal-policy",
            "equations": [
              0,
              1
            ]
          }
        ],
        "purpose": "Supports choosing whether to accept an available win.",
        "parameters": 1538
      },
      {
        "id": "player-descriptors",
        "area": "critic",
        "title": "Deterministic player descriptors",
        "parent": "player-context",
        "kind": "features",
        "summary": "Construct four public player descriptors and action-conditioned role coordinates.",
        "dimensions": [
          "M × 4 × 461"
        ],
        "sharing": "No learned player-specific descriptor encoder",
        "residual": "None",
        "source": {
          "path": "model/critic.py",
          "line": 542
        },
        "operations": [
          {
            "id": "player-public",
            "title": "Public descriptor assembly",
            "description": "Concatenate self flag 1, river 256, score and rank 2, wind effects 4, scalar state 4, tile/meld channels 156, meld histogram 34 and red 1.",
            "dimensions": [
              "458 public coordinates per seat"
            ],
            "residual": "None",
            "sharing": "Same feature definition for every seat; self river summary is zero",
            "source": {
              "path": "model/critic.py",
              "line": 547
            }
          },
          {
            "id": "player-action",
            "title": "Action role append",
            "description": "Append projected ordinary draws, chi-turn eligibility and active-discard source.",
            "dimensions": [
              "458 + 3 → 461"
            ],
            "residual": "None",
            "sharing": "Deterministic action-relative coordinates",
            "source": {
              "path": "model/critic.py",
              "line": 657
            }
          }
        ],
        "equations": [
          {
            "topic": "four-player-context",
            "equations": [
              1
            ]
          }
        ],
        "purpose": "Preserves each player’s public situation and role in the candidate outcome.",
        "notes": [
          "The player axis has 4 seats: self and 3 opponents. Seat ordering is relative to the acting player."
        ],
        "parameters": 0
      },
      {
        "id": "critic-state-assembly",
        "area": "critic",
        "title": "Critic state assembly",
        "parent": "critic",
        "kind": "concatenation",
        "summary": "Join candidate/board/hand/public state, opponent probabilities, route/completion predictions and original-window player descriptors before all critic projections.",
        "dimensions": [
          "M × (2268 + 4 × 461)"
        ],
        "sharing": "Deterministic concatenation; same state feeds original path and residual belief adapter",
        "residual": "None",
        "source": {
          "path": "model/network.py",
          "line": 201
        },
        "operations": [
          {
            "id": "critic-state-assembly",
            "title": "Common context concatenation",
            "description": "Concatenate candidate 384, belief 975, board 512, hand/public contexts, route 3 and completion 184+76; player descriptors remain a separate trailing block.",
            "dimensions": [
              "M × D_common"
            ],
            "residual": "None",
            "sharing": "Shared actor/encoder predictions enter the critic",
            "source": {
              "path": "model/network.py",
              "line": 201
            }
          }
        ],
        "equations": [
          {
            "topic": "critic-belief-adapter",
            "equations": [
              2
            ]
          },
          {
            "topic": "representation-ownership",
            "equations": [
              0,
              1
            ]
          }
        ],
        "purpose": "Collects the action-specific evidence needed to predict settlement outcomes.",
        "notes": [
          "Each row represents one legal candidate and includes descriptors for all four players."
        ],
        "parameters": 0
      },
      {
        "id": "critic-common-projection",
        "area": "critic",
        "title": "Critic candidate projection",
        "parent": "critic",
        "kind": "projection",
        "summary": "Project the assembled candidate state. A chi or pon candidate combines its post-call encoding with public evidence from the original decision board.",
        "dimensions": [
          "2268 → 384"
        ],
        "sharing": "One common projection for all action candidates",
        "residual": "None",
        "source": {
          "path": "model/critic.py",
          "line": 776
        },
        "operations": [
          {
            "id": "critic-state-dense",
            "title": "Dense + GELU",
            "description": "Project all common channels, excluding the trailing 4 ×461 player descriptors.",
            "dimensions": [
              "D_common → 384"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/critic.py",
              "line": 776
            }
          }
        ],
        "equations": [
          {
            "topic": "four-player-context",
            "equations": [
              0
            ]
          }
        ],
        "purpose": "Gives all settlement factors a shared representation of the candidate and original call window.",
        "parameters": 871296
      },
      {
        "id": "critic-refinement",
        "area": "critic",
        "title": "Critic residual block 1",
        "parent": "critic",
        "kind": "residual",
        "summary": "Pre-normalized 384 → 480 → 384 residual block with zero-initialized output.",
        "dimensions": [
          "384 → 480 → 384"
        ],
        "sharing": "Independent weights per depth; shared across active candidates",
        "residual": "Identity skip plus learned branch",
        "source": {
          "path": "model/critic.py",
          "line": 832
        },
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              11
            ]
          }
        ],
        "operations": [
          {
            "id": "critic-refinement-norm",
            "title": "LayerNorm",
            "description": "Normalize the refinement input with learned scale and offset.",
            "dimensions": [
              "384 → 384"
            ],
            "residual": "None",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 782
            }
          },
          {
            "id": "critic-refinement-hidden",
            "title": "Dense + GELU",
            "description": "Nonlinear hidden transform.",
            "dimensions": [
              "384 → 480"
            ],
            "residual": "None",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 784
            }
          },
          {
            "id": "critic-refinement-output",
            "title": "Zero-initialized output Dense",
            "description": "Output kernel and default bias start at zero; upstream hidden-layer gradients through this branch are initially zero.",
            "dimensions": [
              "480 → 384"
            ],
            "residual": "None",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 787
            }
          },
          {
            "id": "critic-refinement-add",
            "title": "Residual Add",
            "description": "Add the refinement branch to its unchanged input.",
            "dimensions": [
              "384 + 384 → 384"
            ],
            "residual": "Identity skip",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 832
            }
          }
        ],
        "purpose": "Adds nonlinear capacity to the common settlement representation.",
        "parameters": 370272
      },
      {
        "id": "critic-refinement-1",
        "area": "critic",
        "title": "Critic residual block 2",
        "parent": "critic",
        "kind": "residual",
        "summary": "Pre-normalized 384 → 480 → 384 residual block with zero-initialized output.",
        "dimensions": [
          "384 → 480 → 384"
        ],
        "sharing": "Independent weights per depth; shared across active candidates",
        "residual": "Identity skip plus learned branch",
        "source": {
          "path": "model/critic.py",
          "line": 832
        },
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              11
            ]
          }
        ],
        "operations": [
          {
            "id": "critic-refinement-1-norm",
            "title": "LayerNorm",
            "description": "Normalize the refinement input with learned scale and offset.",
            "dimensions": [
              "384 → 384"
            ],
            "residual": "None",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 782
            }
          },
          {
            "id": "critic-refinement-1-hidden",
            "title": "Dense + GELU",
            "description": "Nonlinear hidden transform.",
            "dimensions": [
              "384 → 480"
            ],
            "residual": "None",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 784
            }
          },
          {
            "id": "critic-refinement-1-output",
            "title": "Zero-initialized output Dense",
            "description": "Output kernel and default bias start at zero; upstream hidden-layer gradients through this branch are initially zero.",
            "dimensions": [
              "480 → 384"
            ],
            "residual": "None",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 787
            }
          },
          {
            "id": "critic-refinement-1-add",
            "title": "Residual Add",
            "description": "Add the refinement branch to its unchanged input.",
            "dimensions": [
              "384 + 384 → 384"
            ],
            "residual": "Identity skip",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 832
            }
          }
        ],
        "purpose": "Adds nonlinear capacity to the common settlement representation.",
        "parameters": 370272
      },
      {
        "id": "critic-refinement-2",
        "area": "critic",
        "title": "Critic residual block 3",
        "parent": "critic",
        "kind": "residual",
        "summary": "Pre-normalized 384 → 480 → 384 residual block with zero-initialized output.",
        "dimensions": [
          "384 → 480 → 384"
        ],
        "sharing": "Independent weights per depth; shared across active candidates",
        "residual": "Identity skip plus learned branch",
        "source": {
          "path": "model/critic.py",
          "line": 832
        },
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              11
            ]
          }
        ],
        "operations": [
          {
            "id": "critic-refinement-2-norm",
            "title": "LayerNorm",
            "description": "Normalize the refinement input with learned scale and offset.",
            "dimensions": [
              "384 → 384"
            ],
            "residual": "None",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 782
            }
          },
          {
            "id": "critic-refinement-2-hidden",
            "title": "Dense + GELU",
            "description": "Nonlinear hidden transform.",
            "dimensions": [
              "384 → 480"
            ],
            "residual": "None",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 784
            }
          },
          {
            "id": "critic-refinement-2-output",
            "title": "Zero-initialized output Dense",
            "description": "Output kernel and default bias start at zero; upstream hidden-layer gradients through this branch are initially zero.",
            "dimensions": [
              "480 → 384"
            ],
            "residual": "None",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 787
            }
          },
          {
            "id": "critic-refinement-2-add",
            "title": "Residual Add",
            "description": "Add the refinement branch to its unchanged input.",
            "dimensions": [
              "384 + 384 → 384"
            ],
            "residual": "Identity skip",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 832
            }
          }
        ],
        "purpose": "Adds nonlinear capacity to the common settlement representation.",
        "parameters": 370272
      },
      {
        "id": "critic-refinement-3",
        "area": "critic",
        "title": "Critic residual block 4",
        "parent": "critic",
        "kind": "residual",
        "summary": "Pre-normalized 384 → 480 → 384 residual block with zero-initialized output.",
        "dimensions": [
          "384 → 480 → 384"
        ],
        "sharing": "Independent weights per depth; shared across active candidates",
        "residual": "Identity skip plus learned branch",
        "source": {
          "path": "model/critic.py",
          "line": 832
        },
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              11
            ]
          }
        ],
        "operations": [
          {
            "id": "critic-refinement-3-norm",
            "title": "LayerNorm",
            "description": "Normalize the refinement input with learned scale and offset.",
            "dimensions": [
              "384 → 384"
            ],
            "residual": "None",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 782
            }
          },
          {
            "id": "critic-refinement-3-hidden",
            "title": "Dense + GELU",
            "description": "Nonlinear hidden transform.",
            "dimensions": [
              "384 → 480"
            ],
            "residual": "None",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 784
            }
          },
          {
            "id": "critic-refinement-3-output",
            "title": "Zero-initialized output Dense",
            "description": "Output kernel and default bias start at zero; upstream hidden-layer gradients through this branch are initially zero.",
            "dimensions": [
              "480 → 384"
            ],
            "residual": "None",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 787
            }
          },
          {
            "id": "critic-refinement-3-add",
            "title": "Residual Add",
            "description": "Add the refinement branch to its unchanged input.",
            "dimensions": [
              "384 + 384 → 384"
            ],
            "residual": "Identity skip",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 832
            }
          }
        ],
        "purpose": "Adds nonlinear capacity to the common settlement representation.",
        "parameters": 370272
      },
      {
        "id": "critic-refinement-4",
        "area": "critic",
        "title": "Critic residual block 5",
        "parent": "critic",
        "kind": "residual",
        "summary": "Pre-normalized 384 → 480 → 384 residual block with zero-initialized output.",
        "dimensions": [
          "384 → 480 → 384"
        ],
        "sharing": "Independent weights per depth; shared across active candidates",
        "residual": "Identity skip plus learned branch",
        "source": {
          "path": "model/critic.py",
          "line": 832
        },
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              11
            ]
          }
        ],
        "operations": [
          {
            "id": "critic-refinement-4-norm",
            "title": "LayerNorm",
            "description": "Normalize the refinement input with learned scale and offset.",
            "dimensions": [
              "384 → 384"
            ],
            "residual": "None",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 782
            }
          },
          {
            "id": "critic-refinement-4-hidden",
            "title": "Dense + GELU",
            "description": "Nonlinear hidden transform.",
            "dimensions": [
              "384 → 480"
            ],
            "residual": "None",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 784
            }
          },
          {
            "id": "critic-refinement-4-output",
            "title": "Zero-initialized output Dense",
            "description": "Output kernel and default bias start at zero; upstream hidden-layer gradients through this branch are initially zero.",
            "dimensions": [
              "480 → 384"
            ],
            "residual": "None",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 787
            }
          },
          {
            "id": "critic-refinement-4-add",
            "title": "Residual Add",
            "description": "Add the refinement branch to its unchanged input.",
            "dimensions": [
              "384 + 384 → 384"
            ],
            "residual": "Identity skip",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 832
            }
          }
        ],
        "purpose": "Adds nonlinear capacity to the common settlement representation.",
        "parameters": 370272
      },
      {
        "id": "critic-refinement-5",
        "area": "critic",
        "title": "Critic residual block 6",
        "parent": "critic",
        "kind": "residual",
        "summary": "Pre-normalized 384 → 480 → 384 residual block with zero-initialized output.",
        "dimensions": [
          "384 → 480 → 384"
        ],
        "sharing": "Independent weights per depth; shared across active candidates",
        "residual": "Identity skip plus learned branch",
        "source": {
          "path": "model/critic.py",
          "line": 832
        },
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              11
            ]
          }
        ],
        "operations": [
          {
            "id": "critic-refinement-5-norm",
            "title": "LayerNorm",
            "description": "Normalize the refinement input with learned scale and offset.",
            "dimensions": [
              "384 → 384"
            ],
            "residual": "None",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 782
            }
          },
          {
            "id": "critic-refinement-5-hidden",
            "title": "Dense + GELU",
            "description": "Nonlinear hidden transform.",
            "dimensions": [
              "384 → 480"
            ],
            "residual": "None",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 784
            }
          },
          {
            "id": "critic-refinement-5-output",
            "title": "Zero-initialized output Dense",
            "description": "Output kernel and default bias start at zero; upstream hidden-layer gradients through this branch are initially zero.",
            "dimensions": [
              "480 → 384"
            ],
            "residual": "None",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 787
            }
          },
          {
            "id": "critic-refinement-5-add",
            "title": "Residual Add",
            "description": "Add the refinement branch to its unchanged input.",
            "dimensions": [
              "384 + 384 → 384"
            ],
            "residual": "Identity skip",
            "sharing": "Independent weights per depth; shared across active candidates",
            "source": {
              "path": "model/critic.py",
              "line": 832
            }
          }
        ],
        "purpose": "Adds nonlinear capacity to the common settlement representation.",
        "parameters": 370272
      },
      {
        "id": "critic-player-projection",
        "area": "critic",
        "title": "Self and opponent player projections",
        "parent": "critic",
        "kind": "projection",
        "summary": "Concatenate each player descriptor with common context, then apply the self map or shared-opponent map.",
        "dimensions": [
          "845 → 96",
          "461 + 384 = 845 → 96",
          "M × 4 × 96"
        ],
        "sharing": "Self uses one Dense 96; three opponents share a second Dense 96, initialized from the incumbent projection",
        "residual": "None",
        "source": {
          "path": "model/critic.py",
          "line": 797
        },
        "operations": [
          {
            "id": "critic-player-dense",
            "title": "Dense 96 + GELU",
            "description": "Self has one parameter set; three opponents share another. Dealer status conditions both maps through descriptor inputs.",
            "dimensions": [
              "845 → 96"
            ],
            "residual": "None",
            "sharing": "Separate self and shared-opponent projections, shared across action candidates",
            "source": {
              "path": "model/critic.py",
              "line": 797
            }
          }
        ],
        "equations": [
          {
            "topic": "four-player-context",
            "equations": [
              0
            ]
          }
        ],
        "purpose": "Models the distinct self role while reusing the same opponent transformation across seats.",
        "parameters": 162432
      },
      {
        "id": "critic-event",
        "area": "critic",
        "title": "Joint-event role pooling",
        "parent": "critic",
        "kind": "representation",
        "summary": "Pool 45 ordinary whole-event hypotheses and four per-player nagashi readout states.",
        "dimensions": [
          "49 events × 32 channels",
          "Common state 384 + 4 players × 96",
          "Fixed role masks: 49 × 4 × 3"
        ],
        "sharing": "Three role projections share weights across seats and events. Result attention reads the pooled vectors; deposit conditioning retains the fixed role masks.",
        "residual": "None",
        "source": {
          "path": "model/critic.py",
          "line": 855
        },
        "operations": [
          {
            "id": "critic-event-common",
            "title": "Common event Dense",
            "description": "Project common context into 32 event channels.",
            "dimensions": [
              "384 → 32"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/critic.py",
              "line": 806
            }
          },
          {
            "id": "critic-event-kind",
            "title": "Event-kind embedding",
            "description": "Four terminal-event kinds receive learned 32-channel embeddings.",
            "dimensions": [
              "4 × 32"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/critic.py",
              "line": 810
            }
          },
          {
            "id": "critic-event-roles",
            "title": "Three player-role Dense maps",
            "description": "Separate winner/source/ready projections are shared over players, then pooled according to each whole-event role mask.",
            "dimensions": [
              "3 × (96 → 32)"
            ],
            "residual": "None",
            "sharing": "Distinct by role; tied across seats and 49 events",
            "source": {
              "path": "model/critic.py",
              "line": 807
            }
          },
          {
            "id": "critic-event-gelu",
            "title": "Sum + GELU",
            "description": "Combine common, kind and pooled player-role terms before event scoring.",
            "dimensions": [
              "M × 49 × 32"
            ],
            "residual": "None",
            "sharing": "One functional form for all events",
            "source": {
              "path": "model/critic.py",
              "line": 875
            }
          }
        ],
        "equations": [
          {
            "topic": "four-player-context",
            "equations": [
              2
            ]
          }
        ],
        "purpose": "Retains 49 learned hypotheses; four nagashi signals derive all nonempty qualifier sets without independent combination heads.",
        "parameters": 21792
      },
      {
        "id": "critic-claim-state",
        "area": "critic",
        "title": "Claim-state projection",
        "parent": "critic",
        "kind": "projection",
        "summary": "Embed recipient, ron payer and win-kind coordinates and public scoring evidence for 16 unique winning claims.",
        "dimensions": [
          "16 × 198 → 16 × 96",
          "12 ron + 4 tsumo claim slots",
          "96 + 96 + 4 + 2 = 198 → 96"
        ],
        "sharing": "One claim encoder; tsumo payer shares are not separately learned",
        "residual": "None",
        "source": {
          "path": "model/critic.py",
          "line": 915
        },
        "operations": [
          {
            "id": "critic-claim-gather",
            "title": "Recipient/payer gather",
            "description": "Gather recipient 96, payer 96 for ron only (zero for tsumo), four public scoring features (fu /128, bonus han /5, opened and required riichi), and two-way win-kind one-hot.",
            "dimensions": [
              "M × 16 × 198"
            ],
            "residual": "None",
            "sharing": "Same descriptor construction for all claims",
            "source": {
              "path": "model/critic.py",
              "line": 915
            }
          },
          {
            "id": "critic-claim-dense",
            "title": "Dense + GELU",
            "description": "Shared claim-state transform. Tsumo payer shares later reuse the same winner state.",
            "dimensions": [
              "198 → 96"
            ],
            "residual": "None",
            "sharing": "Shared across 12 ron and 4 tsumo winners",
            "source": {
              "path": "model/critic.py",
              "line": 803
            }
          }
        ],
        "equations": [
          {
            "topic": "critic-factor-heads",
            "equations": [
              0
            ]
          }
        ],
        "purpose": "Conditions scoring on who wins, who pays and how the win occurs.",
        "parameters": 19104
      },
      {
        "id": "critic-score-head",
        "area": "critic",
        "title": "Settlement value decoder",
        "parent": "critic",
        "kind": "heads",
        "summary": "Single total han/fu distribution for each winning claim, conditioned on action, claimant, win method and public scoring evidence. Trained through observed settlement likelihood.",
        "dimensions": [
          "16 × 96 → 16 × 38",
          "24 payment shares × 38"
        ],
        "sharing": "One total-score decoder across claims",
        "residual": "None",
        "source": {
          "path": "model/critic.py",
          "line": 824
        },
        "operations": [
          {
            "id": "critic-score-dense",
            "title": "Dense 38",
            "description": "Read total han/fu logits from the claim state, which includes public fu, bonus han, open-hand and riichi evidence.",
            "dimensions": [
              "96 → 38"
            ],
            "residual": "None",
            "sharing": "One score head across claims",
            "source": {
              "path": "model/critic.py",
              "line": 824
            }
          },
          {
            "id": "critic-visible-candidate-bonus",
            "title": "Visible meld bonus",
            "description": "Count the tiles in the selected hand’s chi, pon and kan melds. Weight those counts by the decision position’s visible dora multiplicities and add red fives in the melds. Call responses use the public bonus on the original decision board.",
            "dimensions": [
              "34 tile counts → 1 visible bonus per selected hand"
            ],
            "residual": "None",
            "sharing": "Fixed scoring rule",
            "source": {
              "path": "model/critic.py",
              "line": 149
            }
          },
          {
            "id": "critic-score-support",
            "title": "Share gather + legal-score mask",
            "description": "Reuse each tsumo winner score for its three payer shares and apply public score constraints.",
            "dimensions": [
              "16 unique states →24 payment shares"
            ],
            "residual": "None",
            "sharing": "Identical tsumo score distribution across its payer shares",
            "source": {
              "path": "model/critic.py",
              "line": 971
            }
          }
        ],
        "equations": [
          {
            "topic": "critic-factor-heads",
            "equations": [
              2
            ]
          },
          {
            "topic": "payment-likelihood",
            "equations": [
              2
            ]
          }
        ],
        "purpose": "Predict the total winning score from claim context and public evidence.",
        "parameters": 3686
      },
      {
        "id": "critic-pao-allocation",
        "area": "critic",
        "title": "Pao allocation",
        "parent": "critic",
        "kind": "heads",
        "summary": "Predict four payer allocations per claim, constrained by known responsibility and true-yakuman support.",
        "dimensions": [
          "16 claims × 4 allocations",
          "Claim96 + player96 + role3 → 16 → 1"
        ],
        "sharing": "Shared claimant, player and role projections; scalar readout tied across claims and seats.",
        "residual": "None",
        "source": {
          "path": "model/critic.py",
          "line": 820
        },
        "operations": [
          {
            "id": "pao-allocation-logits",
            "title": "Shared allocation readout",
            "description": "Combine claim/player projections and ordinary/source/candidate-trigger role flags; winner-as-payer denotes ordinary settlement.",
            "dimensions": [
              "16 × 4 × 16 → 16 × 4"
            ],
            "sharing": "One set of projections and one scalar output",
            "residual": "None",
            "source": {
              "path": "model/critic.py",
              "line": 820
            }
          }
        ],
        "equations": [
          {
            "topic": "exceptional-settlement",
            "equations": [
              0
            ]
          }
        ],
        "purpose": "Represents responsibility payments without separate score distributions or extra event-attention tokens.",
        "parameters": 3185
      },
      {
        "id": "critic-deposits",
        "area": "critic",
        "title": "Deposit-mask conditioning",
        "parent": "critic",
        "kind": "representation",
        "summary": "Condition deposit subsets on 60 derived event contexts; nagashi combinations pool the corresponding four readout states.",
        "dimensions": [
          "60 events × 16 masks × 8 channels"
        ],
        "sharing": "The same conditional feature maps apply to every event and mask.",
        "residual": "None",
        "source": {
          "path": "model/critic.py",
          "line": 1008
        },
        "operations": [
          {
            "id": "critic-deposit-context",
            "title": "Event-context Dense",
            "description": "Project 16 event channels into 8 deposit-context channels.",
            "dimensions": [
              "32 → 8"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/critic.py",
              "line": 816
            }
          },
          {
            "id": "critic-deposit-players",
            "title": "Player Dense and mask pooling",
            "description": "Project each player 96→8 and sum selected players for each deposit mask.",
            "dimensions": [
              "96 → 8; masks 16"
            ],
            "residual": "None",
            "sharing": "Shared over all seats and masks",
            "source": {
              "path": "model/critic.py",
              "line": 817
            }
          },
          {
            "id": "critic-deposit-roles",
            "title": "Role-count Dense",
            "description": "Project three event-role counts induced by each deposit mask.",
            "dimensions": [
              "3 → 8"
            ],
            "residual": "None",
            "sharing": "Shared over event/mask pairs",
            "source": {
              "path": "model/critic.py",
              "line": 818
            }
          },
          {
            "id": "critic-deposit-score",
            "title": "Combine deposit features",
            "description": "Sum the event context, pooled depositor features and event-role counts, then apply GELU. The deposit head scores each resulting vector.",
            "dimensions": [
              "M × 60 × 16 × 8"
            ],
            "residual": "None",
            "sharing": "One combination rule across all event and mask pairs.",
            "source": {
              "path": "model/critic.py",
              "line": 1008
            }
          }
        ],
        "equations": [
          {
            "topic": "critic-factor-heads",
            "equations": [
              3
            ]
          }
        ],
        "purpose": "Supplies an eight-channel input to the deposit-mask readout for each event and depositor subset.",
        "parameters": 1081
      },
      {
        "id": "settlement-decoder",
        "area": "critic",
        "title": "Deterministic settlement decoder",
        "parent": "settlement",
        "kind": "rules",
        "summary": "Decode total han/fu, pao allocation and constrained nagashi qualifier masks into exact payments, deposits and continuation states.",
        "dimensions": [
          "60 × 16 masks · 38 scores",
          "60 events ×16 deposit masks",
          "38 score states per claim"
        ],
        "sharing": "No learned settlement-rule branch",
        "residual": "None",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 523
        },
        "operations": [
          {
            "id": "settlement-events",
            "title": "Event/deposit support",
            "description": "The 45 ordinary endings plus 15 nonempty nagashi qualifier sets form 60 derived events. Four learned nagashi outputs generate those sets. Public eligibility and paid deposits restrict support.",
            "dimensions": [
              "60 ×16"
            ],
            "residual": "None",
            "sharing": "No learned parameters",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 462
            }
          },
          {
            "id": "settlement-decode",
            "title": "Transfer and marginal decoding",
            "description": "Combine conditioned claim-score support and joint masks into payment marginals.",
            "dimensions": [
              "Payment cells and value support"
            ],
            "residual": "None",
            "sharing": "Deterministic rules",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 523
            }
          }
        ],
        "equations": [
          {
            "topic": "payment-likelihood",
            "equations": [
              1,
              2
            ]
          }
        ],
        "purpose": "Converts learned factors into distributions that obey settlement rules.",
        "notes": [
          "Pao redirects only true-yakuman score mass under full-stack Tenhou liability rules. Known public payers constrain allocations.",
          "Nagashi uses exact gross mangan transfers, carries the bank, and obtains dealer continuation from existing draw-tenpai predictions."
        ],
        "parameters": 0
      },
      {
        "id": "continuation-payoffs",
        "area": "critic",
        "title": "Fixed continuation and expected value",
        "parent": "continuation",
        "kind": "value",
        "summary": "Map settlement score states to fixed rank forecasts and compute expected normalized objective.",
        "dimensions": [
          "4 ranks · scalar J",
          "4 placement probabilities",
          "Scalar J"
        ],
        "sharing": "Fixed continuation mapping for all candidates",
        "residual": "None",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 828
        },
        "operations": [
          {
            "id": "continuation-ranks",
            "title": "Fixed Gumbel continuation",
            "description": "Use score locations, future dealer counts and a time-dependent common scale to estimate final placement probabilities.",
            "dimensions": [
              "4 scores →4 rank probabilities"
            ],
            "residual": "None",
            "sharing": "Fixed fitted parameters; not trained by current MMD",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 828
            }
          },
          {
            "id": "continuation-objective",
            "title": "Objective expectation",
            "description": "Convert each settlement payoff to J=ST3/100+P(first)−P(fourth), then integrate under the critic distribution.",
            "dimensions": [
              "Settlement payoffs →scalar expected J"
            ],
            "residual": "None",
            "sharing": "No learned state-value readout",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 879
            }
          }
        ],
        "equations": [
          {
            "topic": "settlement-value",
            "equations": [
              0,
              1
            ]
          },
          {
            "topic": "continuation-model",
            "equations": [
              0,
              2
            ]
          }
        ],
        "purpose": "Makes immediate settlements comparable through their implications for final placement and utility.",
        "parameters": 0
      },
      {
        "id": "call-choice",
        "area": "actor",
        "title": "Call choice on decision board",
        "parent": "actor",
        "kind": "head",
        "summary": "Score pass, three chi patterns, pon and open kan from the original decision board and its detached belief context. Normalize over legal call options.",
        "dimensions": [
          "768 → 6",
          "Pass,3 chi patterns,pon,daiminkan"
        ],
        "sharing": "The ordinary local network and critic reuse the same decision and after-call encodings.",
        "residual": "None",
        "source": {
          "path": "model/actor.py",
          "line": 338
        },
        "operations": [
          {
            "id": "call-choice-0",
            "title": "Dense 6",
            "description": "Independent learned branch readout; output kernel/bias initialize to zero.",
            "dimensions": [
              "768 → 6"
            ],
            "sharing": "Shared across decision positions and supported call options",
            "residual": "None",
            "source": {
              "path": "model/actor.py",
              "line": 423
            }
          },
          {
            "id": "call-choice-1",
            "title": "Legal normalization",
            "description": "Mask unavailable call branches before log-softmax.",
            "dimensions": [
              "B × 6"
            ],
            "sharing": "Shared across decision positions and supported call options",
            "residual": "None",
            "source": {
              "path": "model/actor.py",
              "line": 553
            }
          }
        ],
        "equations": [
          {
            "topic": "policy-readouts",
            "equations": [
              0
            ]
          }
        ],
        "purpose": "Chooses the call branch using the original decision window.",
        "parameters": 4614
      },
      {
        "id": "call-factorization",
        "area": "actor",
        "title": "Post-call discard policy",
        "parent": "actor",
        "kind": "factorization",
        "summary": "On each hypothetical chi or pon board, the ordinary discard policy scores legal cuts. Multiply each conditional discard probability by its call probability on the decision board. Pass and open kan use their call probability alone. Opponent beliefs, waits and ron eligibility come from the parent; child completion potential follows the changed hand and board.",
        "dimensions": [
          "B × 6 + C × 37 → B × 150"
        ],
        "sharing": "The ordinary local network and critic reuse the same decision and after-call encodings.",
        "residual": "None",
        "source": {
          "path": "model/actor.py",
          "line": 338
        },
        "operations": [
          {
            "id": "call-factorization-0",
            "title": "Score after-call positions",
            "description": "Encode changed hand/board and recompute completion potential with inherited opponent beliefs; reuse the ordinary discard scorer.",
            "dimensions": [
              "C sparse rows → shared policy"
            ],
            "sharing": "Shared across decision positions and supported call options",
            "residual": "None",
            "source": {
              "path": "model/actor.py",
              "line": 465
            }
          },
          {
            "id": "call-factorization-1",
            "title": "Joint response",
            "description": "Pass and daiminkan have no same-turn discard factor; chi/pon multiply branch mass by follow-up discard mass.",
            "dimensions": [
              "1 + 4 × 37 + 1 = 150"
            ],
            "sharing": "Shared across decision positions and supported call options",
            "residual": "None",
            "source": {
              "path": "model/actor.py",
              "line": 559
            }
          }
        ],
        "equations": [
          {
            "topic": "call-factorization",
            "equations": [
              0
            ]
          }
        ],
        "purpose": "Evaluates the discard after a call using the hand and table state that the call actually creates.",
        "notes": [
          "A response can have up to four post-call boards, one per legal chi pattern or pon. Each board has its own hand, melds and legal discards."
        ],
        "parameters": 0
      },
      {
        "id": "call-candidate-merge",
        "area": "critic",
        "title": "Map post-call discards to actions",
        "parent": "candidates",
        "kind": "routing",
        "summary": "Map each call and discard to one original-window action. Its candidate state has attended to every legal alternative at that decision. Hand and board follow the candidate position; opponent beliefs and settlement legality stay at the original observed window.",
        "dimensions": [
          "M × 2 (decision, action)",
          "Decision actions + post-call discards",
          "Post-call action = 112 + 37 × option + discard"
        ],
        "sharing": "The ordinary local network and critic reuse the same decision and after-call encodings.",
        "residual": "None",
        "source": {
          "path": "model/actor.py",
          "line": 338
        },
        "operations": [
          {
            "id": "call-candidate-merge-0",
            "title": "Shared context",
            "description": "Assemble raw candidates with their local board and hand context plus inherited observed-opponent beliefs.",
            "dimensions": [
              "Decision and after-call states"
            ],
            "sharing": "Shared across decision positions and supported call options",
            "residual": "None",
            "source": {
              "path": "model/actor.py",
              "line": 574
            }
          },
          {
            "id": "call-candidate-merge-1",
            "title": "Map after-call actions",
            "description": "Use owner/option indices to map accepted-call discards back to original-window rows.",
            "dimensions": [
              "selected pairs [position,action]"
            ],
            "sharing": "Shared across decision positions and supported call options",
            "residual": "None",
            "source": {
              "path": "model/actor.py",
              "line": 501
            }
          },
          {
            "id": "call-candidate-merge-2",
            "title": "Stable candidate merge",
            "description": "Join and sort decision and after-call states under shared original action IDs.",
            "dimensions": [
              "M × state width"
            ],
            "sharing": "Shared across decision positions and supported call options",
            "residual": "None",
            "source": {
              "path": "model/actor.py",
              "line": 606
            }
          }
        ],
        "equations": [
          {
            "topic": "call-factorization",
            "equations": [
              1
            ]
          }
        ],
        "purpose": "Aligns after-call predictions with original action IDs for joint candidate evaluation.",
        "notes": [
          "M counts active candidates after merging decision and after-call positions. Original action IDs use 295 slots. Follow-up discards map to 112 + 37 × call option + discard, where the 4 options are 3 chi patterns and pon. Legality determines which rows exist."
        ],
        "parameters": 0
      },
      {
        "id": "critic-belief-uncertainty",
        "area": "critic",
        "title": "Per-opponent belief moments",
        "parent": "critic",
        "kind": "deterministic",
        "summary": "147 deterministic features per opponent: shanten probabilities 4, structural wait 34, marginal improving 34, count means 37, count variances 37 and normalized shanten entropy 1.",
        "dimensions": [
          "M × 3 × 147"
        ],
        "sharing": "Parameter-free; same reductions for each opponent",
        "residual": "None",
        "source": {
          "path": "model/critic.py",
          "line": 677
        },
        "operations": [
          {
            "id": "critic-belief-moments",
            "title": "Probability moments",
            "description": "Count mean and variance divided by 4; nonnegative variance clamp. Entropy uses log floor 1e-6 and normalization log 4.",
            "dimensions": [
              "4 + 34 + 34 + 37 + 37 + 1 = 147"
            ],
            "sharing": "Shared deterministic transform",
            "residual": "None",
            "source": {
              "path": "model/critic.py",
              "line": 690
            }
          }
        ],
        "equations": [
          {
            "topic": "critic-belief-adapter",
            "equations": [
              0
            ]
          }
        ],
        "purpose": "Exposes belief uncertainty and tile-level moments to the settlement model.",
        "parameters": 0
      },
      {
        "id": "critic-belief-adapter",
        "area": "critic",
        "title": "Shared opponent moment residual",
        "parent": "critic",
        "kind": "residual",
        "summary": "Concatenate each existing opponent token with its own 147 belief moments. Shared FP32 243→128 GELU→96 zero-initialized projection adds to that opponent token; the residual is not added to self or common tokens, whose existing paths still train.",
        "dimensions": [
          "243 → 128 → 96",
          "M × 3 × (96 + 147)"
        ],
        "sharing": "One parameter set shared across opponents and candidate rows",
        "residual": "Opponent token + zero-initialized moment residual",
        "source": {
          "path": "model/critic.py",
          "line": 677
        },
        "operations": [
          {
            "id": "critic-belief-adapter-0",
            "title": "Shared Dense 128 + GELU",
            "description": "FP32 hidden map of opponent token and aligned moments.",
            "dimensions": [
              "243 → 128"
            ],
            "sharing": "One parameter set shared across opponents and candidate rows",
            "residual": "None",
            "source": {
              "path": "model/critic.py",
              "line": 683
            }
          },
          {
            "id": "critic-belief-adapter-1",
            "title": "Dense 96 + opponent residual",
            "description": "FP32 output kernel and bias start at zero; self token passes through unchanged.",
            "dimensions": [
              "128 → 96"
            ],
            "sharing": "One parameter set shared across opponents and candidate rows",
            "residual": "Opponent token + zero-initialized moment residual",
            "source": {
              "path": "model/critic.py",
              "line": 686
            }
          }
        ],
        "equations": [
          {
            "topic": "critic-belief-adapter",
            "equations": [
              1
            ]
          }
        ],
        "purpose": "Lets each opponent representation use its own belief uncertainty.",
        "parameters": 43616
      },
      {
        "id": "shared-probabilities",
        "area": "belief",
        "title": "Shared FP32 probabilities",
        "parent": "beliefs",
        "kind": "probabilities",
        "summary": "Convert constrained predictions in FP32. Opponent probabilities are inherited from the observed decision; completion probabilities follow each local hand and board. Actor and critic consume detached values. Actor weights conditional ukeire by shanten probability; critic retains conditional slices.",
        "dimensions": [
          "975 + 260 = 1235"
        ],
        "sharing": "One conversion reused by actor and critic; no parameters",
        "residual": "None",
        "source": {
          "path": "model/network.py",
          "line": 35
        },
        "operations": [
          {
            "id": "constrained-probability-conversion",
            "title": "Softmax / sigmoid",
            "description": "Apply categorical softmax or Bernoulli sigmoid according to head semantics.",
            "dimensions": [
              "Head dimensions preserved"
            ],
            "sharing": "No parameters",
            "residual": "None",
            "source": {
              "path": "model/beliefs.py",
              "line": 145
            }
          }
        ],
        "equations": [
          {
            "topic": "policy-readouts",
            "equations": [
              1
            ]
          }
        ],
        "purpose": "Supplies consistent bounded belief features to policy and critic while reusing the conversion.",
        "parameters": 0
      },
      {
        "id": "structural-wait",
        "area": "belief",
        "title": "Structural wait prediction",
        "parent": "beliefs",
        "kind": "derived prediction",
        "summary": "Compute joint tenpai-and-improving probability per opponent/tile from constrained shanten and conditional improving logits, using stable log-domain arithmetic. This is the only derived wait tensor on the forward path; reporting-only marginal improving diagnostics are removed.",
        "dimensions": [
          "3 × 34",
          "3 ×4 shanten +3 ×4 ×34 improving →3 ×34 wait"
        ],
        "sharing": "No parameters; reuses opponent predictions",
        "residual": "None",
        "source": {
          "path": "model/beliefs.py",
          "line": 47
        },
        "operations": [
          {
            "id": "structural-wait-logit",
            "title": "Joint wait logit",
            "description": "Stable logit of P(shanten=0) ×P(improving tile|shanten=0).",
            "dimensions": [
              "3 ×34"
            ],
            "sharing": "No parameters",
            "residual": "None",
            "source": {
              "path": "model/beliefs.py",
              "line": 47
            }
          }
        ],
        "equations": [
          {
            "topic": "candidate-ron-factorization",
            "equations": [
              0
            ]
          }
        ],
        "purpose": "Combines readiness and improving-tile evidence into the wait probability used by ron prediction.",
        "parameters": 0
      },
      {
        "id": "completion-evidence",
        "area": "belief",
        "title": "Opponent completion evidence",
        "parent": "beliefs",
        "kind": "residual",
        "summary": "Own current-hand slot 0, remaining physical supply and each opponent’s projected held counts yield 33 suit/dora/red features. Concatenate the opponent river summary, then add a shared 46-channel yaku residual only to opponent yaku logits before support masks. Self logits receive no residual. There is no separate suit-specific honitsu output. The attached 64-channel hidden state also feeds ron eligibility.",
        "dimensions": [
          "289 → 64 → 46",
          "3 × (33 + 256)",
          "46 yaku logits"
        ],
        "sharing": "One FP32 parameter set shared across the three opponents and all decision rows; 21,550 parameters",
        "residual": "Opponent raw yaku logits + zero-initialized output; self raw logits pass through",
        "source": {
          "path": "model/beliefs.py",
          "line": 336
        },
        "operations": [
          {
            "id": "completion-evidence-summary",
            "title": "Suit, dora and red summaries",
            "description": "Each of own hand, remaining supply and inferred opponent counts contributes 11 features: four suit/honor totals /14, four ordinary-dora-weighted totals /14 and three red counts. Inferred counts include known exposed meld copies; remaining supply excludes known own/public copies. Red tiles contribute ordinary dora through their base tile as well as separate red counts.",
            "dimensions": [
              "3 × 11 = 33"
            ],
            "sharing": "One FP32 parameter set shared across the three opponents and all decision rows; 21,550 parameters",
            "residual": "None",
            "source": {
              "path": "model/beliefs.py",
              "line": 350
            }
          },
          {
            "id": "completion-evidence-hidden",
            "title": "Shared Dense 64 + GELU",
            "description": "Join 33 evidence channels with the aligned existing opponent river vector. No labels or outcome targets enter these features. Ron eligibility consumes this hidden state with gradients attached.",
            "dimensions": [
              "33 + 256 = 289 → 64"
            ],
            "sharing": "One FP32 parameter set shared across the three opponents and all decision rows; 21,550 parameters",
            "residual": "None",
            "source": {
              "path": "model/beliefs.py",
              "line": 341
            }
          },
          {
            "id": "completion-evidence-readout",
            "title": "Zero-initialized Dense 46",
            "description": "Predict 46 yaku-logit residuals per opponent. After the zero-initialized readout learns, completion gradients can reach the river features. The count inputs stay detached.",
            "dimensions": [
              "64 → 46"
            ],
            "sharing": "One FP32 parameter set shared across the three opponents and all decision rows; 21,550 parameters",
            "residual": "Opponent raw yaku logits + zero-initialized output; self raw logits pass through",
            "source": {
              "path": "model/beliefs.py",
              "line": 344
            }
          }
        ],
        "equations": [
          {
            "topic": "completion-evidence",
            "equations": [
              0,
              1
            ]
          }
        ],
        "purpose": "Uses visible suit, dora and supply evidence to refine opponent completion predictions.",
        "parameters": 21550
      },
      {
        "id": "actor-board-input-projection",
        "area": "actor",
        "title": "Actor hand-board fusion",
        "parent": "actor",
        "kind": "projection",
        "summary": "Fuse observed public context and the current hand into three actor board residual blocks.",
        "dimensions": [
          "1024 → 512",
          "512 context + 512 current hand"
        ],
        "sharing": "Private actor parameters; shared across decision and after-call positions",
        "residual": "None",
        "source": {
          "path": "model/encoder.py",
          "line": 869
        },
        "operations": [
          {
            "id": "actor-board-fusion-dense",
            "title": "Joint fusion projection",
            "description": "Concatenate observed public context and current-hand slot 0, then apply one Dense GELU.",
            "dimensions": [
              "1024 → 512"
            ],
            "sharing": "One projection shared across decision and after-call rows",
            "residual": "None",
            "source": {
              "path": "model/encoder.py",
              "line": 869
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              12
            ]
          }
        ],
        "purpose": "Processes detached shared public and hand features through a policy-trained upper encoder.",
        "notes": [
          "Only hand-bank slot 0 enters board fusion; hypothetical hands enter action queries."
        ],
        "parameters": 524800
      },
      {
        "id": "actor-board-block-0",
        "area": "actor",
        "title": "Actor residual block 1",
        "parent": "actor",
        "kind": "residual",
        "summary": "Pre-normalized residual MLP with two 576-channel GELU hidden layers.",
        "dimensions": [
          "512 → 576 → 576 → 512",
          "B × 512 → B × 512"
        ],
        "sharing": "Private actor parameters; shared across decision and after-call positions",
        "residual": "Identity skip from block input to final Add",
        "source": {
          "path": "model/encoder.py",
          "line": 871
        },
        "operations": [
          {
            "id": "actor-board-0-norm",
            "title": "LayerNorm",
            "description": "Normalize the incoming 512-channel representation with learned center and scale.",
            "dimensions": [
              "512 → 512"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 873
            }
          },
          {
            "id": "actor-board-0-expand",
            "title": "Dense + GELU",
            "description": "Expand the normalized residual branch.",
            "dimensions": [
              "512 → 576"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 878
            }
          },
          {
            "id": "actor-board-0-hidden",
            "title": "Hidden Dense + GELU",
            "description": "Second nonlinear transform at the expanded width.",
            "dimensions": [
              "576 → 576"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 884
            }
          },
          {
            "id": "actor-board-0-contract",
            "title": "Dense",
            "description": "Linear contraction back to the trunk width.",
            "dimensions": [
              "576 → 512"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 888
            }
          },
          {
            "id": "actor-board-0-add",
            "title": "Add",
            "description": "Add the residual branch to the unchanged block input.",
            "dimensions": [
              "512 + 512 → 512"
            ],
            "residual": "x + Dense 512(GELU(Dense 576(GELU(Dense 576(LayerNorm(x))))))",
            "sharing": "Parameter-free addition",
            "source": {
              "path": "model/encoder.py",
              "line": 891
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              8
            ]
          }
        ],
        "purpose": "Processes detached shared public and hand features through a policy-trained upper encoder.",
        "parameters": 924288
      },
      {
        "id": "actor-board-block-1",
        "area": "actor",
        "title": "Actor residual block 2",
        "parent": "actor",
        "kind": "residual",
        "summary": "Pre-normalized residual MLP with two 576-channel GELU hidden layers.",
        "dimensions": [
          "512 → 576 → 576 → 512",
          "B × 512 → B × 512"
        ],
        "sharing": "Private actor parameters; shared across decision and after-call positions",
        "residual": "Identity skip from block input to final Add",
        "source": {
          "path": "model/encoder.py",
          "line": 871
        },
        "operations": [
          {
            "id": "actor-board-1-norm",
            "title": "LayerNorm",
            "description": "Normalize the incoming 512-channel representation with learned center and scale.",
            "dimensions": [
              "512 → 512"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 873
            }
          },
          {
            "id": "actor-board-1-expand",
            "title": "Dense + GELU",
            "description": "Expand the normalized residual branch.",
            "dimensions": [
              "512 → 576"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 878
            }
          },
          {
            "id": "actor-board-1-hidden",
            "title": "Hidden Dense + GELU",
            "description": "Second nonlinear transform at the expanded width.",
            "dimensions": [
              "576 → 576"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 884
            }
          },
          {
            "id": "actor-board-1-contract",
            "title": "Dense",
            "description": "Linear contraction back to the trunk width.",
            "dimensions": [
              "576 → 512"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 888
            }
          },
          {
            "id": "actor-board-1-add",
            "title": "Add",
            "description": "Add the residual branch to the unchanged block input.",
            "dimensions": [
              "512 + 512 → 512"
            ],
            "residual": "x + Dense 512(GELU(Dense 576(GELU(Dense 576(LayerNorm(x))))))",
            "sharing": "Parameter-free addition",
            "source": {
              "path": "model/encoder.py",
              "line": 891
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              8
            ]
          }
        ],
        "purpose": "Processes detached shared public and hand features through a policy-trained upper encoder.",
        "parameters": 924288
      },
      {
        "id": "actor-board-block-2",
        "area": "actor",
        "title": "Actor residual block 3",
        "parent": "actor",
        "kind": "residual",
        "summary": "Pre-normalized residual MLP with two 576-channel GELU hidden layers.",
        "dimensions": [
          "512 → 576 → 576 → 512",
          "B × 512 → B × 512"
        ],
        "sharing": "Private actor parameters; shared across decision and after-call positions",
        "residual": "Identity skip from block input to final Add",
        "source": {
          "path": "model/encoder.py",
          "line": 871
        },
        "operations": [
          {
            "id": "actor-board-2-norm",
            "title": "LayerNorm",
            "description": "Normalize the incoming 512-channel representation with learned center and scale.",
            "dimensions": [
              "512 → 512"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 873
            }
          },
          {
            "id": "actor-board-2-expand",
            "title": "Dense + GELU",
            "description": "Expand the normalized residual branch.",
            "dimensions": [
              "512 → 576"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 878
            }
          },
          {
            "id": "actor-board-2-hidden",
            "title": "Hidden Dense + GELU",
            "description": "Second nonlinear transform at the expanded width.",
            "dimensions": [
              "576 → 576"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 884
            }
          },
          {
            "id": "actor-board-2-contract",
            "title": "Dense",
            "description": "Linear contraction back to the trunk width.",
            "dimensions": [
              "576 → 512"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 888
            }
          },
          {
            "id": "actor-board-2-add",
            "title": "Add",
            "description": "Add the residual branch to the unchanged block input.",
            "dimensions": [
              "512 + 512 → 512"
            ],
            "residual": "x + Dense 512(GELU(Dense 576(GELU(Dense 576(LayerNorm(x))))))",
            "sharing": "Parameter-free addition",
            "source": {
              "path": "model/encoder.py",
              "line": 891
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              8
            ]
          }
        ],
        "purpose": "Processes detached shared public and hand features through a policy-trained upper encoder.",
        "parameters": 924288
      },
      {
        "id": "actor-board-output",
        "area": "actor",
        "title": "Actor Shared decision state",
        "parent": "actor",
        "kind": "projection",
        "summary": "Normalize the private actor upper state before policy context and final action scoring.",
        "dimensions": [
          "B × 512"
        ],
        "sharing": "Private actor parameters; shared across decision and after-call positions",
        "residual": "None",
        "source": {
          "path": "model/encoder.py",
          "line": 901
        },
        "operations": [
          {
            "id": "actor-board-state-dense",
            "title": "Dense + GELU",
            "description": "Final learned board transformation after all three residual blocks.",
            "dimensions": [
              "512 → 512"
            ],
            "residual": "None",
            "sharing": "Block-local parameters",
            "source": {
              "path": "model/encoder.py",
              "line": 894
            }
          },
          {
            "id": "actor-board-state-norm",
            "title": "Fixed LayerNorm",
            "description": "Float 32 normalization with center=False, scale=False and epsilon 1e-5.",
            "dimensions": [
              "512 → 512"
            ],
            "residual": "None",
            "sharing": "No learned scale or offset",
            "source": {
              "path": "model/encoder.py",
              "line": 901
            }
          }
        ],
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              1,
              9
            ]
          },
          {
            "topic": "representation-ownership",
            "equations": [
              0,
              1
            ]
          }
        ],
        "purpose": "Processes detached shared public and hand features through a policy-trained upper encoder.",
        "parameters": 262656
      },
      {
        "id": "actor-refinement-1",
        "area": "actor",
        "title": "Actor refinement block 2",
        "parent": "actor",
        "kind": "residual",
        "summary": "Pre-normalized 768 → 384 → 768 residual over private actor board features and learned policy evidence. Its output projection starts at zero.",
        "dimensions": [
          "768 → 384 → 768"
        ],
        "sharing": "One private actor residual shared by discard, riichi, kan, win and call decisions",
        "residual": "Identity skip plus learned branch",
        "source": {
          "path": "model/network.py",
          "line": 108
        },
        "equations": [
          {
            "topic": "encoder-operators",
            "equations": [
              11
            ]
          }
        ],
        "operations": [
          {
            "id": "actor-private-residual-1",
            "title": "LayerNorm → GELU projection → residual",
            "description": "Learned LayerNorm and 768 → 384 GELU projection feed a zero-initialized 384 → 768 output, added to the input context.",
            "dimensions": [
              "768 → 384 → 768"
            ],
            "sharing": "Shared across policy branches",
            "residual": "Identity skip; output kernel and bias initially zero",
            "source": {
              "path": "model/network.py",
              "line": 108
            }
          }
        ],
        "purpose": "Adds private policy capacity after the shared-encoder gradient boundary.",
        "parameters": 592512
      },
      {
        "id": "critic-result-attention",
        "area": "critic",
        "title": "Result attention and event readout",
        "parent": "critic",
        "kind": "attention",
        "summary": "Attention mixes 49 readout states: 45 ordinary events and four per-player nagashi signals.",
        "dimensions": [
          "49 × 32 → 49 × 32",
          "4 heads × 16 key/value channels",
          "32 → 1 shared event readout"
        ],
        "sharing": "One attention block and scalar readout shared across candidates; attention never mixes candidates or positions.",
        "residual": "Identity plus zero-initialized 32 → 32 correction",
        "source": {
          "path": "model/critic.py",
          "line": 741
        },
        "operations": [
          {
            "id": "result-attention-norm",
            "title": "Pre-LayerNorm",
            "description": "Normalize each 32-channel whole-event token before attention.",
            "dimensions": [
              "M × 49 × 32"
            ],
            "residual": "None",
            "sharing": "One learned scale and offset per channel",
            "source": {
              "path": "model/critic.py",
              "line": 746
            }
          },
          {
            "id": "result-attention-mha",
            "title": "Four-head event attention",
            "description": "Each event attends to the 49 event hypotheses from the same candidate. No event padding or positional IDs are introduced.",
            "dimensions": [
              "4 heads × 16 channels",
              "M × 49 × 32 → M × 49 × 32"
            ],
            "residual": "Read by the correction branch",
            "sharing": "Weights shared across candidates and event tokens",
            "source": {
              "path": "model/critic.py",
              "line": 749
            }
          },
          {
            "id": "result-attention-correction",
            "title": "Zero-initialized correction + Add",
            "description": "Apply a bias-free 32 → 32 correction and add the unchanged event tokens. Initial output equals the role-pooled input.",
            "dimensions": [
              "32 → 32"
            ],
            "residual": "events + correction(attention(LayerNorm(events)))",
            "sharing": "One correction projection",
            "source": {
              "path": "model/critic.py",
              "line": 767
            }
          },
          {
            "id": "result-attention-event-readout",
            "title": "Shared scalar event readout",
            "description": "Score each attended 32-channel event token with the same affine 32 → 1 map. Deposit conditioning also consumes the attended vectors.",
            "dimensions": [
              "M × 49 × 32 → M × 49"
            ],
            "residual": "None",
            "sharing": "One affine readout across all 49 events",
            "source": {
              "path": "model/critic.py",
              "line": 815
            }
          },
          {
            "id": "nagashi-mask-expansion",
            "title": "Four nagashi outputs → qualifier sets",
            "description": "Keep 45 ordinary logits and sum the four per-player nagashi logits over each nonempty eligible qualifier set. No additional learned combination heads.",
            "dimensions": [
              "45 + 4 learned outputs → 60 event logits"
            ],
            "sharing": "Fixed subset expansion",
            "residual": "None",
            "source": {
              "path": "model/critic.py",
              "line": 895
            }
          }
        ],
        "equations": [
          {
            "topic": "result-attention",
            "equations": [
              0,
              1
            ]
          },
          {
            "topic": "exceptional-settlement",
            "equations": [
              1,
              2
            ]
          }
        ],
        "purpose": "Lets competing or related settlement hypotheses exchange information before event and deposit prediction.",
        "notes": [
          "Four nagashi logits derive 15 nonempty qualifier masks. Public eligibility masks impossible qualifiers.",
          "Settlement and direct per-player nagashi losses supervise the same constrained event law."
        ],
        "parameters": 9537
      }
    ],
    "block_edges": [
      {
        "from": "native-input-contract",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "native-input-contract",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "native-input-contract",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "hand-tokenization",
        "to": "hand-suit-0",
        "label": "Conditioned suit tokens",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 343
        }
      },
      {
        "from": "hand-tokenization",
        "to": "hand-honors",
        "label": "Conditioned honor tokens",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 368
        }
      },
      {
        "from": "hand-suit-0",
        "to": "hand-suit-1",
        "label": "Residual suit sequence",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 357
        }
      },
      {
        "from": "hand-suit-1",
        "to": "hand-suit-2",
        "label": "Residual suit sequence",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 357
        }
      },
      {
        "from": "hand-suit-2",
        "to": "hand-bank-output",
        "label": "Reconstructed 27 suit-tile tokens",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 368
        }
      },
      {
        "from": "hand-honors",
        "to": "hand-bank-output",
        "label": "Seven honor-tile tokens",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 368
        }
      },
      {
        "from": "hand-bank-output",
        "to": "board-input-projection",
        "label": "Current hand slot 0 only: 512 channels",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 935
        }
      },
      {
        "from": "river-tokenization",
        "to": "river-conv-0",
        "label": "Masked 64-channel stream tokens",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 521
        }
      },
      {
        "from": "river-conv-0",
        "to": "river-conv-1",
        "label": "Masked residual stream",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 528
        }
      },
      {
        "from": "river-conv-1",
        "to": "river-conv-2",
        "label": "Masked residual stream",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 528
        }
      },
      {
        "from": "river-attention",
        "to": "river-summaries",
        "label": "Final masked stream tokens",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 539
        }
      },
      {
        "from": "river-summaries",
        "to": "shared-public-context",
        "label": "Six learned river summaries, 384 channels",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "board-input-projection",
        "to": "board-block-0",
        "label": "Fused 512-channel hand-board state",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 869
        }
      },
      {
        "from": "board-block-0",
        "to": "board-block-1",
        "label": "Residual board state",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 890
        }
      },
      {
        "from": "board-block-1",
        "to": "board-block-2",
        "label": "Residual board state",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 890
        }
      },
      {
        "from": "board-block-2",
        "to": "board-output",
        "label": "Final residual trunk state",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 894
        }
      },
      {
        "from": "native-input-contract",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "hand-bank-output",
        "to": "candidate-projection",
        "label": "H[n,hand_index(a)]; multiple legal actions may reuse one hand",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 801
        }
      },
      {
        "from": "board-output",
        "to": "candidate-projection",
        "label": "Same local board 512 → 192 for all local action queries",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 847
        }
      },
      {
        "from": "belief-refinement",
        "to": "belief-readouts",
        "label": "Refined shared 512-channel board representation",
        "kind": "state",
        "source": {
          "path": "model/beliefs.py",
          "line": 458
        }
      },
      {
        "from": "belief-refinement",
        "to": "tile-tokenization",
        "label": "Refined three opponent context slices",
        "kind": "state",
        "source": {
          "path": "model/beliefs.py",
          "line": 241
        }
      },
      {
        "from": "belief-readouts",
        "to": "tile-tokenization",
        "label": "Initial count, ukeire and shanten marginals",
        "kind": "logits",
        "source": {
          "path": "model/beliefs.py",
          "line": 207
        }
      },
      {
        "from": "native-input-contract",
        "to": "tile-tokenization",
        "label": "Known meld copies and available tile counts",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 203
        }
      },
      {
        "from": "tile-tokenization",
        "to": "tile-attention-0",
        "label": "34 tokens per opponent",
        "kind": "state",
        "source": {
          "path": "model/beliefs.py",
          "line": 252
        }
      },
      {
        "from": "tile-attention-0",
        "to": "tile-attention-1",
        "label": "Refined token sequence",
        "kind": "state",
        "source": {
          "path": "model/beliefs.py",
          "line": 261
        }
      },
      {
        "from": "tile-attention-1",
        "to": "tile-correction",
        "label": "Final 128-channel tile tokens",
        "kind": "state",
        "source": {
          "path": "model/beliefs.py",
          "line": 262
        }
      },
      {
        "from": "belief-readouts",
        "to": "tile-correction",
        "label": "Initial count and ukeire logits for residual add",
        "kind": "residual",
        "source": {
          "path": "model/beliefs.py",
          "line": 267
        }
      },
      {
        "from": "tile-correction",
        "to": "belief-constraints",
        "label": "Refined held-count logits for public support and projection",
        "kind": "logits",
        "source": {
          "path": "model/beliefs.py",
          "line": 473
        }
      },
      {
        "from": "belief-readouts",
        "to": "belief-constraints",
        "label": "Unmodified shanten logits",
        "kind": "logits",
        "source": {
          "path": "model/beliefs.py",
          "line": 474
        }
      },
      {
        "from": "native-input-contract",
        "to": "belief-constraints",
        "label": "Meld, riichi and tile-capacity support",
        "kind": "constraint",
        "source": {
          "path": "model/beliefs.py",
          "line": 496
        }
      },
      {
        "from": "board-output",
        "to": "candidate-ron-prediction",
        "label": "Observed-board eligibility for each opponent/tile",
        "kind": "state",
        "source": {
          "path": "model/network.py",
          "line": 44
        }
      },
      {
        "from": "candidate-projection",
        "to": "actor-candidate-aux",
        "label": "Raw 384-channel candidate states",
        "kind": "state",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 10
        }
      },
      {
        "from": "native-input-contract",
        "to": "actor-candidate-aux",
        "label": "Public route-support mask",
        "kind": "constraint",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 13
        }
      },
      {
        "from": "belief-refinement",
        "to": "actor-completion",
        "label": "Shared refined latent into completion readouts",
        "kind": "state",
        "source": {
          "path": "model/beliefs.py",
          "line": 458
        }
      },
      {
        "from": "native-input-contract",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "constraint",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "candidate-projection",
        "to": "actor-final-score",
        "label": "Detached raw candidate; policy gradients stop here",
        "kind": "state",
        "source": {
          "path": "model/network.py",
          "line": 156
        }
      },
      {
        "from": "candidate-ron-prediction",
        "to": "actor-final-score",
        "label": "Bounded candidate ron probabilities",
        "kind": "state",
        "source": {
          "path": "model/actor.py",
          "line": 160
        }
      },
      {
        "from": "actor-candidate-aux",
        "to": "actor-final-score",
        "label": "Bounded route probabilities",
        "kind": "state",
        "source": {
          "path": "model/actor.py",
          "line": 160
        }
      },
      {
        "from": "actor-candidate-pool",
        "to": "actor-final-score",
        "label": "768-channel refined actor context plus legal-set residual",
        "kind": "state",
        "source": {
          "path": "model/actor.py",
          "line": 530
        }
      },
      {
        "from": "native-input-contract",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "constraint",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "actor-candidate-pool",
        "to": "actor-win",
        "label": "768-channel refined actor context plus legal-set residual",
        "kind": "state",
        "source": {
          "path": "model/actor.py",
          "line": 530
        }
      },
      {
        "from": "native-input-contract",
        "to": "actor-win",
        "label": "Native win/pass support",
        "kind": "constraint",
        "source": {
          "path": "model/actor.py",
          "line": 208
        }
      },
      {
        "from": "river-summaries",
        "to": "player-descriptors",
        "label": "Three 256-channel opponent river summaries",
        "kind": "state",
        "source": {
          "path": "model/network.py",
          "line": 214
        }
      },
      {
        "from": "native-input-contract",
        "to": "player-descriptors",
        "label": "Public seat facts and action-relative roles",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 546
        }
      },
      {
        "from": "call-candidate-merge",
        "to": "player-descriptors",
        "label": "Original decision row and joint action after matching post-call discards",
        "kind": "features",
        "source": {
          "path": "model/network.py",
          "line": 206
        }
      },
      {
        "from": "candidate-projection",
        "to": "call-candidate-merge",
        "label": "Raw 384-channel candidate states",
        "kind": "state",
        "source": {
          "path": "model/actor.py",
          "line": 577
        }
      },
      {
        "from": "board-output",
        "to": "call-candidate-merge",
        "label": "Shared board state",
        "kind": "state",
        "source": {
          "path": "model/actor.py",
          "line": 580
        }
      },
      {
        "from": "actor-candidate-aux",
        "to": "critic-state-assembly",
        "label": "Detached route probabilities for the matched action",
        "kind": "state",
        "source": {
          "path": "model/network.py",
          "line": 208
        }
      },
      {
        "from": "native-input-contract",
        "to": "critic-state-assembly",
        "label": "Original-window deterministic public context",
        "kind": "features",
        "source": {
          "path": "model/network.py",
          "line": 205
        }
      },
      {
        "from": "critic-state-assembly",
        "to": "critic-player-projection",
        "label": "Four player descriptors sliced from the assembled candidate state",
        "kind": "state",
        "source": {
          "path": "model/critic.py",
          "line": 836
        }
      },
      {
        "from": "critic-refinement-5",
        "to": "critic-player-projection",
        "label": "Refined common 384-channel context broadcast across seats",
        "kind": "state",
        "source": {
          "path": "model/critic.py",
          "line": 840
        }
      },
      {
        "from": "critic-refinement-5",
        "to": "critic-event",
        "label": "Refined common event-context projection",
        "kind": "state",
        "source": {
          "path": "model/critic.py",
          "line": 875
        }
      },
      {
        "from": "critic-belief-adapter",
        "to": "critic-event",
        "label": "Winner/source/ready role pooling",
        "kind": "state",
        "source": {
          "path": "model/critic.py",
          "line": 887
        }
      },
      {
        "from": "critic-belief-adapter",
        "to": "critic-claim-state",
        "label": "Recipient and ron-payer embeddings",
        "kind": "state",
        "source": {
          "path": "model/critic.py",
          "line": 915
        }
      },
      {
        "from": "critic-claim-state",
        "to": "critic-score-head",
        "label": "Claim states with public scoring evidence",
        "kind": "state",
        "source": {
          "path": "model/critic.py",
          "line": 971
        }
      },
      {
        "from": "native-input-contract",
        "to": "critic-score-head",
        "label": "At-decision fu, visible meld bonus, dealer and legal score support",
        "kind": "constraint",
        "source": {
          "path": "model/critic.py",
          "line": 60
        }
      },
      {
        "from": "critic-event",
        "to": "critic-deposits",
        "label": "Fixed event-role masks",
        "kind": "state",
        "source": {
          "path": "model/critic.py",
          "line": 858
        }
      },
      {
        "from": "critic-belief-adapter",
        "to": "critic-deposits",
        "label": "Player embeddings pooled by deposit mask",
        "kind": "state",
        "source": {
          "path": "model/critic.py",
          "line": 1013
        }
      },
      {
        "from": "critic-result-attention",
        "to": "settlement-decoder",
        "label": "Whole-event logits",
        "kind": "logits",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        },
        "readout": "head-event"
      },
      {
        "from": "critic-deposits",
        "to": "settlement-decoder",
        "label": "Event-conditioned deposit-mask logits",
        "kind": "logits",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        },
        "readout": "head-deposit"
      },
      {
        "from": "critic-score-head",
        "to": "settlement-decoder",
        "label": "Total score probabilities",
        "kind": "logits",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 492
        }
      },
      {
        "from": "native-input-contract",
        "to": "settlement-decoder",
        "label": "Public legal-event and transfer constraints",
        "kind": "constraint",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        }
      },
      {
        "from": "settlement-decoder",
        "to": "continuation-payoffs",
        "label": "Joint settlement probabilities, scores and payoff states",
        "kind": "state",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 828
        }
      },
      {
        "from": "board-output",
        "to": "belief-refinement",
        "label": "Residual refinement input",
        "kind": "state",
        "source": {
          "path": "model/beliefs.py",
          "line": 451
        }
      },
      {
        "from": "critic-common-projection",
        "to": "critic-refinement",
        "label": "Residual refinement input",
        "kind": "state",
        "source": {
          "path": "model/critic.py",
          "line": 832
        }
      },
      {
        "from": "actor-candidate-pool",
        "to": "call-choice",
        "label": "768-channel refined actor context plus legal-set residual",
        "kind": "state",
        "source": {
          "path": "model/actor.py",
          "line": 530
        }
      },
      {
        "from": "call-choice",
        "to": "call-factorization",
        "label": "Normalized six-way branch probabilities",
        "kind": "state",
        "source": {
          "path": "model/actor.py",
          "line": 562
        }
      },
      {
        "from": "actor-final-score",
        "to": "call-factorization",
        "label": "Conditional discard probabilities on each post-call board",
        "kind": "state",
        "source": {
          "path": "model/actor.py",
          "line": 535
        }
      },
      {
        "from": "native-input-contract",
        "to": "call-factorization",
        "label": "Sparse accepted-call rows and owner/option selectors",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 443
        }
      },
      {
        "from": "native-input-contract",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "call-candidate-merge",
        "to": "critic-state-assembly",
        "label": "Merged shared neural/hand/completion states; original-window public constraints join afterward",
        "kind": "state",
        "source": {
          "path": "model/network.py",
          "line": 204
        }
      },
      {
        "from": "actor-board-output",
        "to": "actor-policy-context",
        "label": "Policy-trained actor board state",
        "kind": "state",
        "source": {
          "path": "model/network.py",
          "line": 22
        }
      },
      {
        "from": "shared-public-context",
        "to": "table-conditioning",
        "label": "Reuse 512-channel public context",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 339
        }
      },
      {
        "from": "table-conditioning",
        "to": "hand-tokenization",
        "label": "Owning row offset 128 broadcast to every hand/tile before first GELU",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 339
        }
      },
      {
        "from": "critic-state-assembly",
        "to": "critic-common-projection",
        "label": "Common-state projection",
        "kind": "state",
        "source": {
          "path": "model/critic.py",
          "line": 726
        }
      },
      {
        "from": "player-descriptors",
        "to": "critic-state-assembly",
        "label": "Original-window player descriptors",
        "kind": "state",
        "source": {
          "path": "model/critic.py",
          "line": 726
        }
      },
      {
        "from": "critic-state-assembly",
        "to": "critic-belief-uncertainty",
        "label": "Opponent probability slice",
        "kind": "state",
        "source": {
          "path": "model/critic.py",
          "line": 677
        }
      },
      {
        "from": "belief-constraints",
        "to": "shared-probabilities",
        "label": "Supported shanten and projected held-count logits",
        "kind": "state",
        "source": {
          "path": "model/network.py",
          "line": 35
        }
      },
      {
        "from": "actor-completion",
        "to": "shared-probabilities",
        "label": "Constrained completion logits",
        "kind": "state",
        "source": {
          "path": "model/network.py",
          "line": 35
        }
      },
      {
        "from": "shared-probabilities",
        "to": "actor-policy-context",
        "label": "Bounded actor evidence; shanten-weighted conditional improving slices",
        "kind": "state",
        "source": {
          "path": "model/network.py",
          "line": 35
        }
      },
      {
        "from": "shared-probabilities",
        "to": "call-candidate-merge",
        "label": "Reused opponent conditional and completion probabilities",
        "kind": "state",
        "source": {
          "path": "model/network.py",
          "line": 35
        }
      },
      {
        "from": "belief-constraints",
        "to": "structural-wait",
        "label": "Supported shanten logits",
        "kind": "state",
        "source": {
          "path": "model/beliefs.py",
          "line": 47
        }
      },
      {
        "from": "structural-wait",
        "to": "candidate-ron-prediction",
        "label": "Gather joint wait by candidate discard tile",
        "kind": "state",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 25
        }
      },
      {
        "from": "native-input-contract",
        "to": "candidate-ron-prediction",
        "label": "Discard and public safe-tile support",
        "kind": "constraint",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 25
        }
      },
      {
        "from": "native-input-contract",
        "to": "belief-readouts",
        "kind": "features",
        "label": "49 opponent-local observed channels for shared shanten head",
        "source": {
          "path": "model/beliefs.py",
          "line": 276
        }
      },
      {
        "from": "river-summaries",
        "to": "belief-readouts",
        "kind": "state",
        "label": "Existing 256-channel opponent river summaries into shared shanten head",
        "source": {
          "path": "model/beliefs.py",
          "line": 291
        }
      },
      {
        "from": "critic-belief-uncertainty",
        "to": "critic-belief-adapter",
        "label": "147 aligned belief moments per opponent",
        "kind": "state",
        "source": {
          "path": "model/critic.py",
          "line": 677
        }
      },
      {
        "from": "critic-player-projection",
        "to": "critic-belief-adapter",
        "label": "Existing opponent 96 tokens; self token unchanged",
        "kind": "state",
        "source": {
          "path": "model/critic.py",
          "line": 677
        }
      },
      {
        "from": "native-input-contract",
        "to": "completion-evidence",
        "label": "Own slot-0 hand, known supply and dora multiplicity",
        "kind": "state",
        "source": {
          "path": "model/beliefs.py",
          "line": 336
        }
      },
      {
        "from": "belief-constraints",
        "to": "completion-evidence",
        "label": "Projected five-class count marginals",
        "kind": "state",
        "source": {
          "path": "model/beliefs.py",
          "line": 336
        }
      },
      {
        "from": "river-summaries",
        "to": "completion-evidence",
        "label": "Aligned per-opponent river summary 256",
        "kind": "state",
        "source": {
          "path": "model/beliefs.py",
          "line": 336
        }
      },
      {
        "from": "completion-evidence",
        "to": "actor-completion",
        "label": "Opponent-only 46 yaku residual before support",
        "kind": "state",
        "source": {
          "path": "model/beliefs.py",
          "line": 336
        }
      },
      {
        "from": "native-input-contract",
        "to": "call-choice",
        "label": "Legal call branches on the decision board",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 546
        }
      },
      {
        "from": "native-input-contract",
        "to": "continuation-payoffs",
        "label": "Dealer, hand number and outstanding riichi deposits",
        "kind": "features",
        "source": {
          "path": "model/export.py",
          "line": 78
        }
      },
      {
        "from": "tile-correction",
        "to": "structural-wait",
        "kind": "logits",
        "label": "Refined conditional improving-tile logits",
        "source": {
          "path": "model/beliefs.py",
          "line": 52
        }
      },
      {
        "from": "tile-correction",
        "to": "shared-probabilities",
        "kind": "logits",
        "label": "Refined conditional improving-tile logits",
        "source": {
          "path": "model/beliefs.py",
          "line": 149
        }
      },
      {
        "from": "shared-public-context",
        "to": "board-input-projection",
        "label": "Reuse 512-channel public context alongside hand summaries",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 869
        }
      },
      {
        "from": "native-input-contract",
        "to": "hand-bank-output",
        "kind": "features",
        "label": "Yaku feasibility for each resulting hand",
        "source": {
          "path": "model/encoder.py",
          "line": 377
        }
      },
      {
        "from": "river-conv-2",
        "to": "river-attention",
        "kind": "state",
        "label": "Convolved tokens with observed-event mask",
        "source": {
          "path": "model/encoder.py",
          "line": 530
        }
      },
      {
        "from": "actor-policy-context",
        "to": "actor-refinement",
        "kind": "state",
        "label": "768-channel private policy context",
        "source": {
          "path": "model/network.py",
          "line": 108
        }
      },
      {
        "from": "shared-tile-projection",
        "to": "hand-tokenization",
        "kind": "state",
        "label": "Reuse the shared 8-channel base-tile identity",
        "source": {
          "path": "model/encoder.py",
          "line": 278
        }
      },
      {
        "from": "shared-tile-projection",
        "to": "river-tokenization",
        "kind": "state",
        "label": "Reuse the shared 8-channel base-tile identity",
        "source": {
          "path": "model/encoder.py",
          "line": 503
        }
      },
      {
        "from": "shared-tile-projection",
        "to": "shared-public-context",
        "kind": "state",
        "label": "Reuse the shared 8-channel base-tile identity",
        "source": {
          "path": "model/input_features.py",
          "line": 304
        }
      },
      {
        "from": "shared-tile-projection",
        "to": "candidate-projection",
        "kind": "state",
        "label": "Reuse the shared 8-channel base-tile identity",
        "source": {
          "path": "model/encoder.py",
          "line": 823
        }
      },
      {
        "from": "candidate-projection",
        "to": "actor-candidate-pool",
        "kind": "state",
        "label": "Detached legal local and call-plus-discard states",
        "source": {
          "path": "model/actor.py",
          "line": 86
        }
      },
      {
        "from": "native-input-contract",
        "to": "actor-candidate-pool",
        "kind": "features",
        "label": "Original decision owner for each after-call position",
        "source": {
          "path": "model/actor.py",
          "line": 86
        }
      },
      {
        "from": "native-input-contract",
        "to": "critic-claim-state",
        "label": "Public fu, bonus han, open-hand and riichi features",
        "kind": "state",
        "source": {
          "path": "model/critic.py",
          "line": 949
        }
      },
      {
        "from": "critic-refinement",
        "to": "critic-refinement-1",
        "kind": "state",
        "label": "Refined common context",
        "source": {
          "path": "model/critic.py",
          "line": 832
        }
      },
      {
        "from": "critic-refinement-1",
        "to": "critic-refinement-2",
        "kind": "state",
        "label": "Refined common context",
        "source": {
          "path": "model/critic.py",
          "line": 832
        }
      },
      {
        "from": "critic-refinement-2",
        "to": "critic-refinement-3",
        "kind": "state",
        "label": "Refined common context",
        "source": {
          "path": "model/critic.py",
          "line": 832
        }
      },
      {
        "from": "critic-refinement-3",
        "to": "critic-refinement-4",
        "kind": "state",
        "label": "Refined common context",
        "source": {
          "path": "model/critic.py",
          "line": 832
        }
      },
      {
        "from": "critic-refinement-4",
        "to": "critic-refinement-5",
        "kind": "state",
        "label": "Refined common context",
        "source": {
          "path": "model/critic.py",
          "line": 832
        }
      },
      {
        "from": "hand-bank-output",
        "to": "actor-board-input-projection",
        "label": "Detached shared feature input to private actor encoder",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 937
        }
      },
      {
        "from": "actor-board-input-projection",
        "to": "actor-board-block-0",
        "label": "Fused 512-channel hand-board state",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 869
        }
      },
      {
        "from": "actor-board-block-0",
        "to": "actor-board-block-1",
        "label": "Residual board state",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 890
        }
      },
      {
        "from": "actor-board-block-1",
        "to": "actor-board-block-2",
        "label": "Residual board state",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 890
        }
      },
      {
        "from": "actor-board-block-2",
        "to": "actor-board-output",
        "label": "Final residual trunk state",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 894
        }
      },
      {
        "from": "shared-public-context",
        "to": "actor-board-input-projection",
        "label": "Detached shared feature input to private actor encoder",
        "kind": "state",
        "source": {
          "path": "model/encoder.py",
          "line": 937
        }
      },
      {
        "from": "actor-refinement",
        "to": "actor-refinement-1",
        "kind": "state",
        "label": "768-channel private actor context",
        "source": {
          "path": "model/network.py",
          "line": 108
        }
      },
      {
        "from": "critic-event",
        "to": "critic-result-attention",
        "kind": "state",
        "label": "49 role-pooled event hypotheses per candidate",
        "source": {
          "path": "model/critic.py",
          "line": 855
        }
      },
      {
        "from": "critic-result-attention",
        "to": "critic-deposits",
        "kind": "state",
        "label": "Attended 32-channel event vectors",
        "source": {
          "path": "model/critic.py",
          "line": 1009
        }
      },
      {
        "from": "completion-evidence",
        "to": "candidate-ron-prediction",
        "label": "Attached opponent yaku hidden64",
        "kind": "state",
        "source": {
          "path": "model/network.py",
          "line": 50
        }
      },
      {
        "from": "actor-completion",
        "to": "candidate-ron-prediction",
        "label": "Detached opponent ron-yaku probabilities23",
        "kind": "features",
        "source": {
          "path": "model/network.py",
          "line": 50
        }
      },
      {
        "from": "critic-claim-state",
        "to": "critic-pao-allocation",
        "label": "Shared claim/player evidence for responsibility allocation",
        "kind": "state",
        "source": {
          "path": "model/critic.py",
          "line": 820
        }
      },
      {
        "from": "critic-player-projection",
        "to": "critic-pao-allocation",
        "label": "Shared claim/player evidence for responsibility allocation",
        "kind": "state",
        "source": {
          "path": "model/critic.py",
          "line": 820
        }
      },
      {
        "from": "critic-pao-allocation",
        "to": "settlement-decoder",
        "label": "Constrained true-yakuman allocation probabilities",
        "kind": "logits",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 276
        }
      },
      {
        "from": "native-input-contract",
        "to": "critic-pao-allocation",
        "label": "Known responsibility and legal claimant support",
        "kind": "constraint",
        "source": {
          "path": "model/critic.py",
          "line": 1070
        }
      },
      {
        "from": "actor-refinement-1",
        "to": "actor-candidate-pool",
        "kind": "state",
        "label": "Refined actor context supplies the attention query",
        "source": {
          "path": "model/actor.py",
          "line": 530
        }
      }
    ],
    "gradient_overlays": [
      {
        "id": "imitation",
        "title": "Expert imitation and settlement",
        "description": "Fit supported expert policy choices with detached live-Q weights, observed recorded-action settlements and seven supervised beliefs.",
        "statuses": [
          {
            "block": "native-input-contract",
            "status": "target",
            "description": "Fixed public tensors, support masks and integer selectors; no optimizer parameters and no parameter-gradient arrows into this block."
          },
          {
            "block": "hand-tokenization",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "hand-suit-0",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "hand-suit-1",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "hand-suit-2",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "hand-honors",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "hand-bank-output",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "river-tokenization",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "river-conv-0",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "river-conv-1",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "river-conv-2",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "river-summaries",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "board-input-projection",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "board-block-0",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "board-block-1",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "board-block-2",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "board-output",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "candidate-projection",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "belief-readouts",
            "status": "trainable",
            "description": "Observed shanten, improving-tile and count targets supervise their own predictions."
          },
          {
            "block": "tile-tokenization",
            "status": "trainable",
            "description": "Tile features use detached initial shanten, improving and count probabilities. Supervised tile predictions train the token projection."
          },
          {
            "block": "tile-attention-0",
            "status": "trainable",
            "description": "Held-count and conditional improving-tile supervision train the residual correction."
          },
          {
            "block": "tile-attention-1",
            "status": "trainable",
            "description": "Held-count and conditional improving-tile supervision train the residual correction."
          },
          {
            "block": "tile-correction",
            "status": "trainable",
            "description": "Held-count and conditional improving-tile supervision train the residual correction."
          },
          {
            "block": "belief-constraints",
            "status": "deterministic",
            "description": "Support masks and count projection retain derivatives for the heads’ own supervised logits."
          },
          {
            "block": "actor-candidate-aux",
            "status": "trainable",
            "description": "Observed route labels train this readout. Actor and critic read detached route probabilities."
          },
          {
            "block": "actor-completion",
            "status": "trainable",
            "description": "Completion targets train yaku and score. Score coupling reads detached yaku predictions."
          },
          {
            "block": "actor-final-score",
            "status": "trainable",
            "description": "Supported expert choices train this policy branch through weighted cross-entropy."
          },
          {
            "block": "actor-win",
            "status": "trainable",
            "description": "Supported expert choices train this policy branch through weighted cross-entropy."
          },
          {
            "block": "player-descriptors",
            "status": "deterministic",
            "description": "Fixed public descriptors join shared river representations. Settlement gradients reach the river encoder in the critic phase; actor Q evaluations are detached."
          },
          {
            "block": "critic-common-projection",
            "status": "trainable",
            "description": "Mixed observed-payment NLL/Q-MSE and critic constraints; chunked custom backward returns input-state gradients."
          },
          {
            "block": "critic-player-projection",
            "status": "trainable",
            "description": "Mixed observed-payment NLL/Q-MSE and critic constraints; chunked custom backward returns input-state gradients."
          },
          {
            "block": "critic-event",
            "status": "trainable",
            "description": "Mixed observed-payment NLL/Q-MSE and critic constraints; chunked custom backward returns input-state gradients."
          },
          {
            "block": "critic-claim-state",
            "status": "trainable",
            "description": "Mixed observed-payment NLL/Q-MSE and critic constraints; chunked custom backward returns input-state gradients."
          },
          {
            "block": "critic-score-head",
            "status": "trainable",
            "description": "Mixed observed-payment NLL/Q-MSE and critic constraints; chunked custom backward returns input-state gradients."
          },
          {
            "block": "critic-deposits",
            "status": "trainable",
            "description": "Mixed observed-payment NLL/Q-MSE and critic constraints; chunked custom backward returns input-state gradients."
          },
          {
            "block": "settlement-decoder",
            "status": "deterministic",
            "description": "Detached forecast factorization used to form Q coefficients; no reverse path in the actor objective."
          },
          {
            "block": "continuation-payoffs",
            "status": "target",
            "description": "Fixed utility and outcome expectation form stopped-gradient Q coefficients. The constants are not optimizer variables."
          },
          {
            "block": "belief-refinement",
            "status": "trainable",
            "description": "Supervised predictions train the shared belief refinement. Its zero-initialized residual starts as an identity."
          },
          {
            "block": "critic-refinement",
            "status": "trainable",
            "description": "Reachable learned gradient path; zero-initialized output starts as identity. The hidden branch receives gradients after the output kernel moves away from zero."
          },
          {
            "block": "call-choice",
            "status": "trainable",
            "description": "Supported expert choices train this policy branch through weighted cross-entropy."
          },
          {
            "block": "call-factorization",
            "status": "deterministic",
            "description": "Joint response cross-entropy reaches call choice and follow-up discard probabilities."
          },
          {
            "block": "call-candidate-merge",
            "status": "deterministic",
            "description": "Actor uses this merge for detached-Q evaluation; no Q-value gradient crosses into shared state."
          },
          {
            "block": "actor-policy-context",
            "status": "trainable",
            "description": "Supported expert choices train this policy branch through weighted cross-entropy."
          },
          {
            "block": "table-conditioning",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "critic-state-assembly",
            "status": "deterministic",
            "description": "Settlement assembles differentiable shared board, candidate and river representations with detached predictions and fixed public facts. Actor Q evaluations detach the assembled state."
          },
          {
            "block": "critic-belief-uncertainty",
            "status": "frozen",
            "description": "The critic computes moments from detached probabilities. Its adapter can train on settlement targets during the critic pass."
          },
          {
            "block": "critic-belief-adapter",
            "status": "trainable",
            "description": "Critic likelihood differentiates through the adapter and its shared input representations."
          },
          {
            "block": "candidate-ron-prediction",
            "status": "trainable",
            "description": "Observed ron legality trains board/tile eligibility using detached structural waits; no gradient enters actor candidate attention."
          },
          {
            "block": "shared-probabilities",
            "status": "deterministic",
            "description": "Policy and settlement consume detached shanten, improving, count, completion-yaku and completion-score probabilities."
          },
          {
            "block": "structural-wait",
            "status": "deterministic",
            "description": "Shanten and conditional improving probabilities determine structural wait. Candidate ron consumes the detached marginal."
          },
          {
            "block": "completion-evidence",
            "status": "trainable",
            "description": "Completion losses update the opponent residual and connected river features. Projected counts enter as detached evidence."
          },
          {
            "block": "shared-public-context",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "river-attention",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "actor-refinement",
            "status": "trainable",
            "description": "Private policy refinement trains from policy CE and MMD; it is absent from settlement and direct belief objectives."
          },
          {
            "block": "shared-tile-projection",
            "status": "trainable",
            "description": "Belief objectives train this shared projection. Settlement also trains it during critic fitting; policy gradients stop at shared encoder outputs."
          },
          {
            "block": "actor-candidate-pool",
            "status": "trainable",
            "description": "Actor-only attention; candidate inputs are detached."
          },
          {
            "block": "critic-refinement-1",
            "status": "trainable",
            "description": "Reachable learned gradient path; zero-initialized output starts as identity. The hidden branch receives gradients after the output kernel moves away from zero."
          },
          {
            "block": "critic-refinement-2",
            "status": "trainable",
            "description": "Reachable learned gradient path; zero-initialized output starts as identity. The hidden branch receives gradients after the output kernel moves away from zero."
          },
          {
            "block": "critic-refinement-3",
            "status": "trainable",
            "description": "Reachable learned gradient path; zero-initialized output starts as identity. The hidden branch receives gradients after the output kernel moves away from zero."
          },
          {
            "block": "critic-refinement-4",
            "status": "trainable",
            "description": "Reachable learned gradient path; zero-initialized output starts as identity. The hidden branch receives gradients after the output kernel moves away from zero."
          },
          {
            "block": "critic-refinement-5",
            "status": "trainable",
            "description": "Reachable learned gradient path; zero-initialized output starts as identity. The hidden branch receives gradients after the output kernel moves away from zero."
          },
          {
            "block": "actor-board-input-projection",
            "status": "trainable",
            "description": "Private actor encoder and refinement; policy gradients stop before shared lower features."
          },
          {
            "block": "actor-board-block-0",
            "status": "trainable",
            "description": "Private actor encoder and refinement; policy gradients stop before shared lower features."
          },
          {
            "block": "actor-board-block-1",
            "status": "trainable",
            "description": "Private actor encoder and refinement; policy gradients stop before shared lower features."
          },
          {
            "block": "actor-board-block-2",
            "status": "trainable",
            "description": "Private actor encoder and refinement; policy gradients stop before shared lower features."
          },
          {
            "block": "actor-board-output",
            "status": "trainable",
            "description": "Private actor encoder and refinement; policy gradients stop before shared lower features."
          },
          {
            "block": "actor-refinement-1",
            "status": "trainable",
            "description": "Private actor encoder and refinement; policy gradients stop before shared lower features."
          },
          {
            "block": "critic-result-attention",
            "status": "trainable",
            "description": "Detached in actor Q evaluation; settlement likelihood and event/deposit constraints train the result-attention and event-readout weights."
          },
          {
            "block": "critic-pao-allocation",
            "status": "trainable",
            "description": "Detached actor Q; observed settlement supervision trains allocation in critic and imitation fitting."
          }
        ],
        "edges": [
          {
            "from": "hand-suit-0",
            "to": "hand-tokenization",
            "kind": "backward",
            "label": "VJP through conditioned suit tokens",
            "source": {
              "path": "model/encoder.py",
              "line": 343
            },
            "id": "imitation-backward-hand-suit-0-hand-tokenization"
          },
          {
            "from": "hand-honors",
            "to": "hand-tokenization",
            "kind": "backward",
            "label": "VJP through conditioned honor tokens",
            "source": {
              "path": "model/encoder.py",
              "line": 368
            },
            "id": "imitation-backward-hand-honors-hand-tokenization"
          },
          {
            "from": "hand-suit-1",
            "to": "hand-suit-0",
            "kind": "backward",
            "label": "VJP through residual suit sequence",
            "source": {
              "path": "model/encoder.py",
              "line": 357
            },
            "id": "imitation-backward-hand-suit-1-hand-suit-0"
          },
          {
            "from": "hand-suit-2",
            "to": "hand-suit-1",
            "kind": "backward",
            "label": "VJP through residual suit sequence",
            "source": {
              "path": "model/encoder.py",
              "line": 357
            },
            "id": "imitation-backward-hand-suit-2-hand-suit-1"
          },
          {
            "from": "hand-bank-output",
            "to": "hand-suit-2",
            "kind": "backward",
            "label": "VJP through reconstructed 27 suit-tile tokens",
            "source": {
              "path": "model/encoder.py",
              "line": 368
            },
            "id": "imitation-backward-hand-bank-output-hand-suit-2"
          },
          {
            "from": "hand-bank-output",
            "to": "hand-honors",
            "kind": "backward",
            "label": "VJP through seven honor-tile tokens",
            "source": {
              "path": "model/encoder.py",
              "line": 368
            },
            "id": "imitation-backward-hand-bank-output-hand-honors"
          },
          {
            "from": "board-input-projection",
            "to": "hand-bank-output",
            "kind": "backward",
            "label": "VJP through current hand slot 0",
            "source": {
              "path": "model/encoder.py",
              "line": 935
            },
            "id": "imitation-backward-board-input-projection-hand-bank-output"
          },
          {
            "from": "river-conv-0",
            "to": "river-tokenization",
            "kind": "backward",
            "label": "VJP through masked 64-channel stream tokens",
            "source": {
              "path": "model/encoder.py",
              "line": 521
            },
            "id": "imitation-backward-river-conv-0-river-tokenization"
          },
          {
            "from": "river-conv-1",
            "to": "river-conv-0",
            "kind": "backward",
            "label": "VJP through masked residual stream",
            "source": {
              "path": "model/encoder.py",
              "line": 528
            },
            "id": "imitation-backward-river-conv-1-river-conv-0"
          },
          {
            "from": "river-conv-2",
            "to": "river-conv-1",
            "kind": "backward",
            "label": "VJP through masked residual stream",
            "source": {
              "path": "model/encoder.py",
              "line": 528
            },
            "id": "imitation-backward-river-conv-2-river-conv-1"
          },
          {
            "from": "river-summaries",
            "to": "river-attention",
            "kind": "backward",
            "label": "VJP through final masked stream tokens",
            "source": {
              "path": "model/encoder.py",
              "line": 539
            },
            "id": "imitation-backward-river-summaries-river-attention"
          },
          {
            "from": "shared-public-context",
            "to": "river-summaries",
            "kind": "backward",
            "label": "VJP through six ordered 64-channel summaries",
            "source": {
              "path": "model/encoder.py",
              "line": 916
            },
            "id": "imitation-backward-shared-public-context-river-summaries"
          },
          {
            "from": "board-block-0",
            "to": "board-input-projection",
            "kind": "backward",
            "label": "VJP through joint hand-board fusion",
            "source": {
              "path": "model/encoder.py",
              "line": 869
            },
            "id": "imitation-backward-board-block-0-board-input-projection"
          },
          {
            "from": "board-block-1",
            "to": "board-block-0",
            "kind": "backward",
            "label": "VJP through residual board state",
            "source": {
              "path": "model/encoder.py",
              "line": 890
            },
            "id": "imitation-backward-board-block-1-board-block-0"
          },
          {
            "from": "board-block-2",
            "to": "board-block-1",
            "kind": "backward",
            "label": "VJP through residual board state",
            "source": {
              "path": "model/encoder.py",
              "line": 890
            },
            "id": "imitation-backward-board-block-2-board-block-1"
          },
          {
            "from": "board-output",
            "to": "board-block-2",
            "kind": "backward",
            "label": "VJP through final residual trunk state",
            "source": {
              "path": "model/encoder.py",
              "line": 894
            },
            "id": "imitation-backward-board-output-board-block-2"
          },
          {
            "from": "candidate-projection",
            "to": "hand-bank-output",
            "kind": "backward",
            "label": "VJP through gathered 512-channel action hand",
            "source": {
              "path": "model/encoder.py",
              "line": 801
            },
            "id": "imitation-backward-candidate-projection-hand-bank-output"
          },
          {
            "from": "candidate-projection",
            "to": "board-output",
            "kind": "backward",
            "label": "VJP through board context projected to 192 channels",
            "source": {
              "path": "model/encoder.py",
              "line": 847
            },
            "id": "imitation-backward-candidate-projection-board-output"
          },
          {
            "from": "belief-readouts",
            "to": "belief-refinement",
            "kind": "backward",
            "label": "VJP through shared 512-channel board representation",
            "source": {
              "path": "model/beliefs.py",
              "line": 458
            },
            "id": "imitation-backward-belief-readouts-belief-refinement"
          },
          {
            "from": "tile-tokenization",
            "to": "belief-refinement",
            "kind": "backward",
            "label": "VJP through three opponent context slices",
            "source": {
              "path": "model/beliefs.py",
              "line": 241
            },
            "id": "imitation-backward-tile-tokenization-belief-refinement"
          },
          {
            "from": "tile-tokenization",
            "to": "belief-readouts",
            "kind": "stop",
            "label": "Detached initial shanten, conditional improving and count probabilities",
            "source": {
              "path": "model/beliefs.py",
              "line": 207
            },
            "id": "imitation-stop-tile-tokenization-belief-readouts"
          },
          {
            "from": "tile-attention-0",
            "to": "tile-tokenization",
            "kind": "backward",
            "label": "VJP through 34 tokens per opponent",
            "source": {
              "path": "model/beliefs.py",
              "line": 252
            },
            "id": "imitation-backward-tile-attention-0-tile-tokenization"
          },
          {
            "from": "tile-attention-1",
            "to": "tile-attention-0",
            "kind": "backward",
            "label": "VJP through refined token sequence",
            "source": {
              "path": "model/beliefs.py",
              "line": 261
            },
            "id": "imitation-backward-tile-attention-1-tile-attention-0"
          },
          {
            "from": "tile-correction",
            "to": "tile-attention-1",
            "kind": "backward",
            "label": "VJP through final 128-channel tile tokens",
            "source": {
              "path": "model/beliefs.py",
              "line": 262
            },
            "id": "imitation-backward-tile-correction-tile-attention-1"
          },
          {
            "from": "tile-correction",
            "to": "belief-readouts",
            "kind": "backward",
            "label": "VJP through initial count and ukeire logits for residual add",
            "source": {
              "path": "model/beliefs.py",
              "line": 267
            },
            "id": "imitation-backward-tile-correction-belief-readouts"
          },
          {
            "from": "belief-constraints",
            "to": "tile-correction",
            "kind": "backward",
            "label": "Gradient through the refined held-count logits",
            "source": {
              "path": "model/beliefs.py",
              "line": 473
            },
            "id": "imitation-backward-belief-constraints-tile-correction"
          },
          {
            "from": "belief-constraints",
            "to": "belief-readouts",
            "kind": "backward",
            "label": "VJP through unmodified shanten logits",
            "source": {
              "path": "model/beliefs.py",
              "line": 474
            },
            "id": "imitation-backward-belief-constraints-belief-readouts"
          },
          {
            "from": "candidate-ron-prediction",
            "to": "board-output",
            "kind": "backward",
            "label": "Ron eligibility gradients reach observed board",
            "source": {
              "path": "model/network.py",
              "line": 44
            },
            "id": "imitation-backward-candidate-ron-prediction-board-output"
          },
          {
            "from": "actor-candidate-aux",
            "to": "candidate-projection",
            "kind": "backward",
            "label": "VJP through route prediction weights and raw candidate state",
            "source": {
              "path": "model/candidate_predictions.py",
              "line": 10
            },
            "id": "imitation-backward-actor-candidate-aux-candidate-projection"
          },
          {
            "from": "actor-completion",
            "to": "belief-refinement",
            "kind": "backward",
            "label": "VJP through shared refined completion readouts",
            "source": {
              "path": "model/beliefs.py",
              "line": 458
            },
            "id": "imitation-backward-actor-completion-belief-refinement"
          },
          {
            "from": "actor-final-score",
            "to": "candidate-projection",
            "kind": "stop",
            "label": "Detached raw state; policy gradients stop before shared candidate encoding",
            "source": {
              "path": "model/network.py",
              "line": 156
            },
            "id": "imitation-stop-actor-final-score-candidate-projection"
          },
          {
            "from": "actor-final-score",
            "to": "candidate-ron-prediction",
            "kind": "stop",
            "label": "Detached candidate ron probabilities",
            "source": {
              "path": "model/actor.py",
              "line": 159
            },
            "id": "imitation-stop-actor-final-score-candidate-ron-prediction"
          },
          {
            "from": "actor-final-score",
            "to": "actor-candidate-aux",
            "kind": "stop",
            "label": "Detached candidate route probabilities",
            "source": {
              "path": "model/actor.py",
              "line": 159
            },
            "id": "imitation-stop-actor-final-score-actor-candidate-aux"
          },
          {
            "from": "actor-final-score",
            "to": "actor-candidate-pool",
            "kind": "backward",
            "label": "VJP through 768-channel gathered policy context",
            "source": {
              "path": "model/actor.py",
              "line": 530
            },
            "id": "imitation-backward-actor-final-score-actor-candidate-pool"
          },
          {
            "from": "actor-win",
            "to": "actor-candidate-pool",
            "kind": "backward",
            "label": "VJP through private actor board and predictive context",
            "source": {
              "path": "model/actor.py",
              "line": 530
            },
            "id": "imitation-backward-actor-win-actor-candidate-pool"
          },
          {
            "from": "critic-state-assembly",
            "to": "actor-candidate-aux",
            "kind": "stop",
            "label": "Detached route probabilities in the settlement state",
            "source": {
              "path": "model/network.py",
              "line": 208
            },
            "id": "imitation-stop-critic-state-assembly-actor-candidate-aux"
          },
          {
            "from": "imitation-objective",
            "to": "continuation-payoffs",
            "kind": "stop",
            "label": "Q gap and calibrated CE weight computed outside gradient recording",
            "source": {
              "path": "training/imitation.py",
              "line": 72
            },
            "id": "imitation-stop-imitation-objective-continuation-payoffs"
          },
          {
            "from": "imitation-objective",
            "to": "actor-final-score",
            "kind": "backward",
            "label": "Detached-weight expert policy CE derivative on real supported targets",
            "source": {
              "path": "training/imitation.py",
              "line": 72
            },
            "id": "imitation-backward-imitation-objective-actor-final-score"
          },
          {
            "from": "imitation-objective",
            "to": "actor-win",
            "kind": "backward",
            "label": "Detached-weight expert policy CE derivative on real supported targets",
            "source": {
              "path": "training/imitation.py",
              "line": 72
            },
            "id": "imitation-backward-imitation-objective-actor-win"
          },
          {
            "from": "belief-refinement",
            "to": "board-output",
            "kind": "backward",
            "label": "Residual identity plus refinement-branch VJP",
            "source": {
              "path": "model/beliefs.py",
              "line": 451
            },
            "id": "imitation-backward-belief-refinement-board-output"
          },
          {
            "from": "call-choice",
            "to": "actor-candidate-pool",
            "label": "VJP through private actor board and predictive context",
            "kind": "backward",
            "source": {
              "path": "model/actor.py",
              "line": 530
            },
            "id": "imitation-backward-call-choice-actor-candidate-pool"
          },
          {
            "from": "call-factorization",
            "to": "call-choice",
            "label": "Response-policy gradient through normalized six-way branch probabilities",
            "kind": "backward",
            "source": {
              "path": "model/actor.py",
              "line": 562
            },
            "id": "imitation-backward-call-factorization-call-choice"
          },
          {
            "from": "call-factorization",
            "to": "actor-final-score",
            "label": "Response-policy gradient through ordinary shared follow-up discard probabilities",
            "kind": "backward",
            "source": {
              "path": "model/actor.py",
              "line": 535
            },
            "id": "imitation-backward-call-factorization-actor-final-score"
          },
          {
            "from": "imitation-objective",
            "to": "call-factorization",
            "label": "Detached-weight expert policy CE derivative on real supported targets",
            "kind": "backward",
            "source": {
              "path": "training/imitation.py",
              "line": 72
            },
            "id": "imitation-backward-imitation-objective-call-factorization"
          },
          {
            "from": "actor-policy-context",
            "to": "actor-board-output",
            "kind": "backward",
            "label": "Policy gradients train the private actor encoder",
            "source": {
              "path": "model/network.py",
              "line": 22
            },
            "id": "imitation-backward-actor-policy-context-actor-board-output"
          },
          {
            "from": "hand-tokenization",
            "to": "table-conditioning",
            "kind": "backward",
            "label": "VJP through table offset added before first hand GELU",
            "source": {
              "path": "model/encoder.py",
              "line": 339
            },
            "id": "imitation-backward-hand-tokenization-table-conditioning"
          },
          {
            "from": "actor-policy-context",
            "to": "shared-probabilities",
            "kind": "stop",
            "label": "Detached policy belief and completion probabilities",
            "source": {
              "path": "model/network.py",
              "line": 34
            },
            "id": "imitation-stop-actor-policy-context-shared-probabilities"
          },
          {
            "from": "candidate-ron-prediction",
            "to": "structural-wait",
            "label": "Detached structural wait in candidate ron",
            "kind": "stop",
            "source": {
              "path": "model/candidate_predictions.py",
              "line": 36
            },
            "id": "imitation-stop-candidate-ron-prediction-structural-wait"
          },
          {
            "from": "belief-readouts",
            "to": "river-summaries",
            "kind": "backward",
            "label": "Shared shanten derivative into opponent-local river summaries",
            "source": {
              "path": "model/beliefs.py",
              "line": 291
            },
            "id": "imitation-backward-belief-readouts-river-summaries"
          },
          {
            "from": "completion-evidence",
            "to": "belief-constraints",
            "kind": "stop",
            "label": "Detached projected held counts",
            "source": {
              "path": "model/beliefs.py",
              "line": 529
            },
            "id": "imitation-stop-completion-evidence-belief-constraints"
          },
          {
            "from": "completion-evidence",
            "to": "river-summaries",
            "kind": "backward",
            "label": "Completion evidence VJP: Aligned per-opponent river summary 256",
            "source": {
              "path": "model/beliefs.py",
              "line": 336
            },
            "id": "imitation-backward-completion-evidence-river-summaries"
          },
          {
            "from": "actor-completion",
            "to": "completion-evidence",
            "kind": "backward",
            "label": "Completion evidence VJP: Opponent-only 46 yaku +76 score residual before support",
            "source": {
              "path": "model/beliefs.py",
              "line": 336
            },
            "id": "imitation-backward-actor-completion-completion-evidence"
          },
          {
            "from": "imitation-objective",
            "to": "belief-constraints",
            "kind": "backward",
            "label": "Direct supervised shanten and projected held-count losses",
            "source": {
              "path": "training/auxiliary.py",
              "line": 18
            },
            "id": "imitation-backward-imitation-objective-belief-constraints"
          },
          {
            "from": "imitation-objective",
            "to": "actor-completion",
            "kind": "backward",
            "label": "Observed completion yaku and score losses",
            "source": {
              "path": "training/auxiliary.py",
              "line": 18
            },
            "id": "imitation-backward-imitation-objective-actor-completion"
          },
          {
            "from": "imitation-objective",
            "to": "actor-candidate-aux",
            "kind": "backward",
            "label": "Observed candidate route loss",
            "source": {
              "path": "training/auxiliary.py",
              "line": 18
            },
            "id": "imitation-backward-imitation-objective-actor-candidate-aux"
          },
          {
            "from": "imitation-objective",
            "to": "candidate-ron-prediction",
            "kind": "backward",
            "label": "Observed candidate ron loss",
            "source": {
              "path": "training/auxiliary.py",
              "line": 18
            },
            "id": "imitation-backward-imitation-objective-candidate-ron-prediction"
          },
          {
            "from": "imitation-objective",
            "to": "tile-correction",
            "kind": "backward",
            "label": "Direct supervised conditional improving-tile loss",
            "source": {
              "path": "model/beliefs.py",
              "line": 767
            },
            "id": "imitation-backward-imitation-objective-tile-correction"
          },
          {
            "from": "table-conditioning",
            "to": "shared-public-context",
            "kind": "backward",
            "label": "VJP through shared-context hand projection",
            "source": {
              "path": "model/encoder.py",
              "line": 339
            },
            "id": "imitation-backward-table-conditioning-shared-public-context"
          },
          {
            "from": "board-input-projection",
            "to": "shared-public-context",
            "kind": "backward",
            "label": "VJP through shared context in joint fusion",
            "source": {
              "path": "model/encoder.py",
              "line": 869
            },
            "id": "imitation-backward-board-input-projection-shared-public-context"
          },
          {
            "from": "river-attention",
            "to": "river-conv-2",
            "kind": "backward",
            "label": "VJP through observed-event attention residual",
            "source": {
              "path": "model/river_attention.py",
              "line": 44
            },
            "id": "imitation-backward-river-attention-river-conv-2"
          },
          {
            "from": "actor-refinement",
            "to": "actor-policy-context",
            "kind": "backward",
            "label": "VJP through private actor refinement",
            "source": {
              "path": "model/network.py",
              "line": 108
            },
            "id": "imitation-backward-actor-refinement-actor-policy-context"
          },
          {
            "from": "hand-tokenization",
            "to": "shared-tile-projection",
            "kind": "backward",
            "label": "VJP into the shared tile-identity weights",
            "source": {
              "path": "model/encoder.py",
              "line": 278
            },
            "id": "imitation-backward-hand-tokenization-shared-tile-projection"
          },
          {
            "from": "river-tokenization",
            "to": "shared-tile-projection",
            "kind": "backward",
            "label": "VJP into the shared tile-identity weights",
            "source": {
              "path": "model/encoder.py",
              "line": 503
            },
            "id": "imitation-backward-river-tokenization-shared-tile-projection"
          },
          {
            "from": "shared-public-context",
            "to": "shared-tile-projection",
            "kind": "backward",
            "label": "VJP into the shared tile-identity weights",
            "source": {
              "path": "model/input_features.py",
              "line": 304
            },
            "id": "imitation-backward-shared-public-context-shared-tile-projection"
          },
          {
            "from": "candidate-projection",
            "to": "shared-tile-projection",
            "kind": "backward",
            "label": "VJP into the shared tile-identity weights",
            "source": {
              "path": "model/encoder.py",
              "line": 823
            },
            "id": "imitation-backward-candidate-projection-shared-tile-projection"
          },
          {
            "from": "player-descriptors",
            "to": "river-summaries",
            "kind": "backward",
            "label": "Settlement VJP: Three 256-channel opponent river summaries",
            "source": {
              "path": "model/network.py",
              "line": 214
            },
            "id": "imitation-backward-player-descriptors-river-summaries"
          },
          {
            "from": "call-candidate-merge",
            "to": "candidate-projection",
            "kind": "backward",
            "label": "Settlement VJP: Candidate states and action structure",
            "source": {
              "path": "model/actor.py",
              "line": 577
            },
            "id": "imitation-backward-call-candidate-merge-candidate-projection"
          },
          {
            "from": "call-candidate-merge",
            "to": "board-output",
            "kind": "backward",
            "label": "Settlement VJP: Shared board state",
            "source": {
              "path": "model/actor.py",
              "line": 580
            },
            "id": "imitation-backward-call-candidate-merge-board-output"
          },
          {
            "from": "critic-player-projection",
            "to": "critic-state-assembly",
            "kind": "backward",
            "label": "Gradient through player descriptors in the assembled candidate state",
            "source": {
              "path": "model/critic.py",
              "line": 836
            },
            "id": "imitation-backward-critic-player-projection-critic-state-assembly"
          },
          {
            "from": "critic-player-projection",
            "to": "critic-refinement-5",
            "kind": "backward",
            "label": "VJP through common 384-channel context broadcast across seats",
            "source": {
              "path": "model/critic.py",
              "line": 840
            },
            "id": "imitation-backward-critic-player-projection-critic-refinement-5"
          },
          {
            "from": "critic-event",
            "to": "critic-refinement-5",
            "kind": "backward",
            "label": "VJP through common event-context projection",
            "source": {
              "path": "model/critic.py",
              "line": 875
            },
            "id": "imitation-backward-critic-event-critic-refinement-5"
          },
          {
            "from": "critic-event",
            "to": "critic-belief-adapter",
            "kind": "backward",
            "label": "VJP through winner/source/ready role pooling",
            "source": {
              "path": "model/critic.py",
              "line": 887
            },
            "id": "imitation-backward-critic-event-critic-belief-adapter"
          },
          {
            "from": "critic-claim-state",
            "to": "critic-belief-adapter",
            "kind": "backward",
            "label": "VJP through recipient and ron-payer embeddings",
            "source": {
              "path": "model/critic.py",
              "line": 915
            },
            "id": "imitation-backward-critic-claim-state-critic-belief-adapter"
          },
          {
            "from": "critic-score-head",
            "to": "critic-claim-state",
            "kind": "backward",
            "label": "VJP through claim states with public scoring evidence",
            "source": {
              "path": "model/critic.py",
              "line": 971
            },
            "id": "imitation-backward-critic-score-head-critic-claim-state"
          },
          {
            "from": "critic-deposits",
            "to": "critic-result-attention",
            "kind": "backward",
            "label": "Gradient through the 32-channel event vectors used for deposit conditioning",
            "source": {
              "path": "model/critic.py",
              "line": 1009
            },
            "id": "imitation-backward-critic-deposits-critic-result-attention"
          },
          {
            "from": "critic-deposits",
            "to": "critic-belief-adapter",
            "kind": "backward",
            "label": "VJP through player embeddings pooled by deposit mask",
            "source": {
              "path": "model/critic.py",
              "line": 1013
            },
            "id": "imitation-backward-critic-deposits-critic-belief-adapter"
          },
          {
            "from": "settlement-decoder",
            "to": "critic-result-attention",
            "kind": "backward",
            "label": "VJP through whole-event logits",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 462
            },
            "id": "imitation-backward-settlement-decoder-critic-result-attention"
          },
          {
            "from": "settlement-decoder",
            "to": "critic-deposits",
            "kind": "backward",
            "label": "VJP through event-conditioned deposit-mask logits",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 462
            },
            "id": "imitation-backward-settlement-decoder-critic-deposits"
          },
          {
            "from": "settlement-decoder",
            "to": "critic-score-head",
            "kind": "backward",
            "label": "VJP through total score probabilities",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 492
            },
            "id": "imitation-backward-settlement-decoder-critic-score-head"
          },
          {
            "from": "imitation-objective",
            "to": "settlement-decoder",
            "kind": "backward",
            "label": "Supported observed-transfer NLL gradient into compatible factor probabilities",
            "source": {
              "path": "training/imitation.py",
              "line": 164
            },
            "id": "imitation-backward-imitation-objective-settlement-decoder"
          },
          {
            "from": "imitation-objective",
            "to": "critic-score-head",
            "kind": "backward",
            "label": "Raw score-support constraint gradient",
            "source": {
              "path": "training/imitation.py",
              "line": 164
            },
            "id": "imitation-backward-imitation-objective-critic-score-head"
          },
          {
            "from": "imitation-objective",
            "to": "critic-result-attention",
            "kind": "backward",
            "label": "Raw event constraint parameter gradients",
            "source": {
              "path": "training/imitation.py",
              "line": 164
            },
            "id": "imitation-backward-imitation-objective-critic-result-attention"
          },
          {
            "from": "imitation-objective",
            "to": "critic-deposits",
            "kind": "backward",
            "label": "Raw conditional-deposit constraint gradient",
            "source": {
              "path": "training/imitation.py",
              "line": 164
            },
            "id": "imitation-backward-imitation-objective-critic-deposits"
          },
          {
            "from": "critic-refinement",
            "to": "critic-common-projection",
            "kind": "backward",
            "label": "Residual identity plus refinement-branch VJP",
            "source": {
              "path": "model/critic.py",
              "line": 832
            },
            "id": "imitation-backward-critic-refinement-critic-common-projection"
          },
          {
            "from": "critic-state-assembly",
            "to": "call-candidate-merge",
            "label": "Observed-settlement gradient into shared decision and after-call candidate contexts",
            "kind": "backward",
            "source": {
              "path": "model/network.py",
              "line": 204
            },
            "id": "imitation-backward-critic-state-assembly-call-candidate-merge"
          },
          {
            "from": "critic-common-projection",
            "to": "critic-state-assembly",
            "kind": "backward",
            "label": "VJP: Common-state projection",
            "source": {
              "path": "model/critic.py",
              "line": 677
            },
            "id": "imitation-backward-critic-common-projection-critic-state-assembly"
          },
          {
            "from": "critic-state-assembly",
            "to": "player-descriptors",
            "kind": "backward",
            "label": "VJP: Original-window player descriptors",
            "source": {
              "path": "model/critic.py",
              "line": 677
            },
            "id": "imitation-backward-critic-state-assembly-player-descriptors"
          },
          {
            "from": "critic-belief-uncertainty",
            "to": "critic-state-assembly",
            "kind": "backward",
            "label": "VJP: Opponent probability slice",
            "source": {
              "path": "model/critic.py",
              "line": 677
            },
            "id": "imitation-backward-critic-belief-uncertainty-critic-state-assembly"
          },
          {
            "from": "call-candidate-merge",
            "to": "shared-probabilities",
            "kind": "stop",
            "label": "Detached parent opponent beliefs and local completion probabilities",
            "source": {
              "path": "model/network.py",
              "line": 34
            },
            "id": "imitation-stop-call-candidate-merge-shared-probabilities"
          },
          {
            "from": "critic-belief-adapter",
            "to": "critic-belief-uncertainty",
            "kind": "backward",
            "label": "Payment likelihood VJP through shared opponent residual",
            "source": {
              "path": "model/critic.py",
              "line": 677
            },
            "id": "imitation-backward-critic-belief-adapter-critic-belief-uncertainty"
          },
          {
            "from": "critic-belief-adapter",
            "to": "critic-player-projection",
            "kind": "backward",
            "label": "Payment likelihood VJP through shared opponent residual",
            "source": {
              "path": "model/critic.py",
              "line": 677
            },
            "id": "imitation-backward-critic-belief-adapter-critic-player-projection"
          },
          {
            "from": "critic-refinement-1",
            "to": "critic-refinement",
            "kind": "backward",
            "label": "Residual refinement gradient",
            "source": {
              "path": "model/critic.py",
              "line": 832
            },
            "id": "imitation-backward-critic-refinement-1-critic-refinement"
          },
          {
            "from": "critic-refinement-2",
            "to": "critic-refinement-1",
            "kind": "backward",
            "label": "Residual refinement gradient",
            "source": {
              "path": "model/critic.py",
              "line": 832
            },
            "id": "imitation-backward-critic-refinement-2-critic-refinement-1"
          },
          {
            "from": "critic-refinement-3",
            "to": "critic-refinement-2",
            "kind": "backward",
            "label": "Residual refinement gradient",
            "source": {
              "path": "model/critic.py",
              "line": 832
            },
            "id": "imitation-backward-critic-refinement-3-critic-refinement-2"
          },
          {
            "from": "critic-refinement-4",
            "to": "critic-refinement-3",
            "kind": "backward",
            "label": "Residual refinement gradient",
            "source": {
              "path": "model/critic.py",
              "line": 832
            },
            "id": "imitation-backward-critic-refinement-4-critic-refinement-3"
          },
          {
            "from": "critic-refinement-5",
            "to": "critic-refinement-4",
            "kind": "backward",
            "label": "Residual refinement gradient",
            "source": {
              "path": "model/critic.py",
              "line": 832
            },
            "id": "imitation-backward-critic-refinement-5-critic-refinement-4"
          },
          {
            "from": "actor-board-input-projection",
            "to": "shared-public-context",
            "kind": "stop",
            "label": "Policy gradients stop before shared lower encodings",
            "source": {
              "path": "model/encoder.py",
              "line": 937
            },
            "id": "imitation-stop-actor-board-input-projection-shared-public-context"
          },
          {
            "from": "actor-board-input-projection",
            "to": "hand-bank-output",
            "kind": "stop",
            "label": "Policy gradients stop before shared lower encodings",
            "source": {
              "path": "model/encoder.py",
              "line": 937
            },
            "id": "imitation-stop-actor-board-input-projection-hand-bank-output"
          },
          {
            "from": "actor-board-block-0",
            "to": "actor-board-input-projection",
            "kind": "backward",
            "label": "Private actor branch gradient",
            "source": {
              "path": "model/encoder.py",
              "line": 869
            },
            "id": "imitation-backward-actor-board-block-0-actor-board-input-projection"
          },
          {
            "from": "actor-board-block-1",
            "to": "actor-board-block-0",
            "kind": "backward",
            "label": "Private actor branch gradient",
            "source": {
              "path": "model/encoder.py",
              "line": 890
            },
            "id": "imitation-backward-actor-board-block-1-actor-board-block-0"
          },
          {
            "from": "actor-board-block-2",
            "to": "actor-board-block-1",
            "kind": "backward",
            "label": "Private actor branch gradient",
            "source": {
              "path": "model/encoder.py",
              "line": 890
            },
            "id": "imitation-backward-actor-board-block-2-actor-board-block-1"
          },
          {
            "from": "actor-board-output",
            "to": "actor-board-block-2",
            "kind": "backward",
            "label": "Private actor branch gradient",
            "source": {
              "path": "model/encoder.py",
              "line": 894
            },
            "id": "imitation-backward-actor-board-output-actor-board-block-2"
          },
          {
            "from": "actor-refinement-1",
            "to": "actor-refinement",
            "kind": "backward",
            "label": "Private actor branch gradient",
            "source": {
              "path": "model/network.py",
              "line": 108
            },
            "id": "imitation-backward-actor-refinement-1-actor-refinement"
          },
          {
            "from": "critic-result-attention",
            "to": "critic-event",
            "kind": "backward",
            "label": "Attention and identity-residual gradient into role-pooled events",
            "source": {
              "path": "model/critic.py",
              "line": 767
            },
            "id": "imitation-backward-critic-result-attention-critic-event"
          },
          {
            "from": "candidate-ron-prediction",
            "to": "completion-evidence",
            "kind": "backward",
            "label": "Ron eligibility trains opponent evidence hidden state",
            "source": {
              "path": "model/network.py",
              "line": 50
            },
            "id": "imitation-backward-candidate-ron-prediction-completion-evidence"
          },
          {
            "from": "candidate-ron-prediction",
            "to": "actor-completion",
            "kind": "stop",
            "label": "Detached opponent ron-yaku probabilities",
            "source": {
              "path": "model/network.py",
              "line": 50
            },
            "id": "imitation-stop-candidate-ron-prediction-actor-completion"
          },
          {
            "from": "critic-pao-allocation",
            "to": "critic-claim-state",
            "kind": "backward",
            "label": "Settlement likelihood through allocation evidence",
            "source": {
              "path": "model/critic.py",
              "line": 820
            },
            "id": "imitation-backward-critic-pao-allocation-critic-claim-state"
          },
          {
            "from": "critic-pao-allocation",
            "to": "critic-player-projection",
            "kind": "backward",
            "label": "Settlement likelihood through allocation evidence",
            "source": {
              "path": "model/critic.py",
              "line": 820
            },
            "id": "imitation-backward-critic-pao-allocation-critic-player-projection"
          },
          {
            "from": "settlement-decoder",
            "to": "critic-pao-allocation",
            "kind": "backward",
            "label": "Observed responsibility allocation likelihood",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 276
            },
            "id": "imitation-backward-settlement-decoder-critic-pao-allocation"
          },
          {
            "from": "actor-candidate-pool",
            "to": "candidate-projection",
            "kind": "stop",
            "label": "Detached candidate inputs; actor gradients stop",
            "source": {
              "path": "model/actor.py",
              "line": 86
            },
            "id": "imitation-stop-actor-candidate-pool-candidate-projection"
          },
          {
            "from": "actor-candidate-pool",
            "to": "actor-refinement-1",
            "kind": "backward",
            "label": "Actor residual keeps context gradient",
            "source": {
              "path": "model/actor.py",
              "line": 530
            },
            "id": "imitation-backward-actor-candidate-pool-actor-refinement-1"
          }
        ],
        "objective": {
          "id": "imitation-objective",
          "title": "Imitation + settlement objective",
          "description": "Fit supported expert policy choices with detached live-Q weights, observed recorded-action settlements and seven supervised beliefs.",
          "equations": [
            {
              "topic": "expert-weights",
              "equations": [
                0,
                1,
                2
              ]
            },
            {
              "topic": "payment-likelihood",
              "equations": [
                0
              ]
            }
          ],
          "source": {
            "path": "training/imitation.py",
            "line": 72
          }
        },
        "notes": [
          "Three expert passes each draw N_train exposures using 50% natural and 50% focused sampling; no placement-based stratum is used. Resampling can repeat or omit records.",
          "Each update fits the observed settlement of the recorded action, seven eligible belief targets and expert policy CE. Settlement and belief losses train shared representations; policy paths stop at shared outputs.",
          "Both Q values for imitation weights come from the current learner. Q gaps and 75% ESS calibration are detached; this does not freeze the critic’s separate settlement objective.",
          "Each stage starts a fresh optimizer at 1e-5. Belief and nagashi losses use unit coefficients; settlement uses fixed half-NLL/half-calibrated-Q-MSE coefficients. The next match begins the main loop without an initializer-only evaluation.",
          "The four constrained nagashi marginals receive direct unit-weight BCE from the observed qualifier set."
        ],
        "source": {
          "path": "training/imitation.py",
          "line": 72
        }
      },
      {
        "id": "critic",
        "title": "Retained path: Critic pass",
        "description": "Minimize the calibrated half-NLL/half-Q-MSE objective, direct nagashi BCE, critic constraints and seven supervised belief losses. Settlement gradients train critic layers and shared encodings; belief supervision remains active.",
        "statuses": [
          {
            "block": "native-input-contract",
            "status": "target",
            "description": "Fixed public tensors, support masks and integer selectors; no optimizer parameters and no parameter-gradient arrows into this block."
          },
          {
            "block": "hand-tokenization",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Settlement losses also update it; policy gradients stop at shared outputs."
          },
          {
            "block": "hand-suit-0",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Settlement losses also update it; policy gradients stop at shared outputs."
          },
          {
            "block": "hand-suit-1",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Settlement losses also update it; policy gradients stop at shared outputs."
          },
          {
            "block": "hand-suit-2",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Settlement losses also update it; policy gradients stop at shared outputs."
          },
          {
            "block": "hand-honors",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Settlement losses also update it; policy gradients stop at shared outputs."
          },
          {
            "block": "hand-bank-output",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Settlement losses also update it; policy gradients stop at shared outputs."
          },
          {
            "block": "river-tokenization",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Settlement losses also update it; policy gradients stop at shared outputs."
          },
          {
            "block": "river-conv-0",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Settlement losses also update it; policy gradients stop at shared outputs."
          },
          {
            "block": "river-conv-1",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Settlement losses also update it; policy gradients stop at shared outputs."
          },
          {
            "block": "river-conv-2",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Settlement losses also update it; policy gradients stop at shared outputs."
          },
          {
            "block": "river-summaries",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Settlement losses also update it; policy gradients stop at shared outputs."
          },
          {
            "block": "board-input-projection",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Settlement losses also update it; policy gradients stop at shared outputs."
          },
          {
            "block": "board-block-0",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Settlement losses also update it; policy gradients stop at shared outputs."
          },
          {
            "block": "board-block-1",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Settlement losses also update it; policy gradients stop at shared outputs."
          },
          {
            "block": "board-block-2",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Settlement losses also update it; policy gradients stop at shared outputs."
          },
          {
            "block": "board-output",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Settlement losses also update it; policy gradients stop at shared outputs."
          },
          {
            "block": "candidate-projection",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Settlement losses also update it; policy gradients stop at shared outputs."
          },
          {
            "block": "belief-readouts",
            "status": "trainable",
            "description": "Observed shanten, improving-tile and count targets supervise their own predictions."
          },
          {
            "block": "tile-tokenization",
            "status": "trainable",
            "description": "Tile features use detached initial shanten, improving and count probabilities. Supervised tile predictions train the token projection."
          },
          {
            "block": "tile-attention-0",
            "status": "trainable",
            "description": "Held-count and conditional improving-tile supervision train the residual correction."
          },
          {
            "block": "tile-attention-1",
            "status": "trainable",
            "description": "Held-count and conditional improving-tile supervision train the residual correction."
          },
          {
            "block": "tile-correction",
            "status": "trainable",
            "description": "Held-count and conditional improving-tile supervision train the residual correction."
          },
          {
            "block": "belief-constraints",
            "status": "deterministic",
            "description": "Support masks and count projection retain derivatives for the heads’ own supervised logits."
          },
          {
            "block": "actor-candidate-aux",
            "status": "trainable",
            "description": "Observed route labels train this readout. Actor and critic read detached route probabilities."
          },
          {
            "block": "actor-completion",
            "status": "trainable",
            "description": "Completion targets train yaku and score. Score coupling reads detached yaku predictions."
          },
          {
            "block": "actor-final-score",
            "status": "disconnected",
            "description": "Disconnected from the critic objective; no gradient, optimizer update or AdamW decay in this phase."
          },
          {
            "block": "actor-win",
            "status": "disconnected",
            "description": "Disconnected from the critic objective; no gradient, optimizer update or AdamW decay in this phase."
          },
          {
            "block": "player-descriptors",
            "status": "deterministic",
            "description": "Fixed public descriptors join shared river representations. Settlement gradients reach the river encoder in the critic phase; actor Q evaluations are detached."
          },
          {
            "block": "critic-common-projection",
            "status": "trainable",
            "description": "Mixed observed-payment NLL/Q-MSE and critic constraints; chunked custom backward returns input-state gradients."
          },
          {
            "block": "critic-player-projection",
            "status": "trainable",
            "description": "Mixed observed-payment NLL/Q-MSE and critic constraints; chunked custom backward returns input-state gradients."
          },
          {
            "block": "critic-event",
            "status": "trainable",
            "description": "Mixed observed-payment NLL/Q-MSE and critic constraints; chunked custom backward returns input-state gradients."
          },
          {
            "block": "critic-claim-state",
            "status": "trainable",
            "description": "Mixed observed-payment NLL/Q-MSE and critic constraints; chunked custom backward returns input-state gradients."
          },
          {
            "block": "critic-score-head",
            "status": "trainable",
            "description": "Mixed observed-payment NLL/Q-MSE and critic constraints; chunked custom backward returns input-state gradients."
          },
          {
            "block": "critic-deposits",
            "status": "trainable",
            "description": "Mixed observed-payment NLL/Q-MSE and critic constraints; chunked custom backward returns input-state gradients."
          },
          {
            "block": "settlement-decoder",
            "status": "deterministic",
            "description": "The corresponding observed-transfer likelihood factorization is differentiable into event/deposit/score factors. Training evaluates observed_terms rather than the full serving decoder; labels/support are fixed."
          },
          {
            "block": "continuation-payoffs",
            "status": "deterministic",
            "description": "Fixed continuation/J supplies payoff values and identified observed Q targets for squared-error fitting. No gradients enter continuation parameters or label/support construction; gradients pass through predicted settlement probabilities."
          },
          {
            "block": "belief-refinement",
            "status": "trainable",
            "description": "Supervised predictions train the shared belief refinement. Its zero-initialized residual starts as an identity."
          },
          {
            "block": "critic-refinement",
            "status": "trainable",
            "description": "Reachable learned gradient path; zero-initialized output starts as identity. The hidden branch receives gradients after the output kernel moves away from zero."
          },
          {
            "block": "call-choice",
            "status": "disconnected",
            "description": "Call-choice/final policy values are not critic-state inputs; no critic update."
          },
          {
            "block": "call-factorization",
            "status": "disconnected",
            "description": "Call-choice/final policy values are not critic-state inputs; no critic update."
          },
          {
            "block": "call-candidate-merge",
            "status": "deterministic",
            "description": "Settlement gradients reach shared decision and after-call candidate and board encodings. Belief probabilities and route predictions are detached."
          },
          {
            "block": "actor-policy-context",
            "status": "disconnected",
            "description": "Final-policy context projection receives actor gradients only; it is absent from the critic objective."
          },
          {
            "block": "table-conditioning",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Settlement losses also update it; policy gradients stop at shared outputs."
          },
          {
            "block": "critic-state-assembly",
            "status": "deterministic",
            "description": "Settlement assembles differentiable shared board, candidate and river representations with detached predictions and fixed public facts. Actor Q evaluations detach the assembled state."
          },
          {
            "block": "critic-belief-uncertainty",
            "status": "deterministic",
            "description": "The critic computes moments from detached probabilities. Its adapter can train on settlement targets during the critic pass."
          },
          {
            "block": "critic-belief-adapter",
            "status": "trainable",
            "description": "Critic likelihood differentiates through the adapter and its shared input representations."
          },
          {
            "block": "candidate-ron-prediction",
            "status": "trainable",
            "description": "Observed ron legality trains board/tile eligibility using detached structural waits; no gradient enters actor candidate attention."
          },
          {
            "block": "shared-probabilities",
            "status": "deterministic",
            "description": "Policy and settlement consume detached shanten, improving, count, completion-yaku and completion-score probabilities."
          },
          {
            "block": "structural-wait",
            "status": "deterministic",
            "description": "Shanten and conditional improving probabilities determine structural wait. Candidate ron consumes the detached marginal."
          },
          {
            "block": "completion-evidence",
            "status": "trainable",
            "description": "Completion losses update the opponent residual and connected river features. Projected counts enter as detached evidence."
          },
          {
            "block": "shared-public-context",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Settlement losses also update it; policy gradients stop at shared outputs."
          },
          {
            "block": "river-attention",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Settlement losses also update it; policy gradients stop at shared outputs."
          },
          {
            "block": "actor-refinement",
            "status": "frozen",
            "description": "Private policy refinement trains from policy CE and MMD; it is absent from settlement and direct belief objectives."
          },
          {
            "block": "shared-tile-projection",
            "status": "trainable",
            "description": "Belief objectives train this shared projection. Settlement also trains it during critic fitting; policy gradients stop at shared encoder outputs."
          },
          {
            "block": "actor-candidate-pool",
            "status": "frozen",
            "description": "Actor-only attention; candidate inputs are detached."
          },
          {
            "block": "critic-refinement-1",
            "status": "trainable",
            "description": "Reachable learned gradient path; zero-initialized output starts as identity. The hidden branch receives gradients after the output kernel moves away from zero."
          },
          {
            "block": "critic-refinement-2",
            "status": "trainable",
            "description": "Reachable learned gradient path; zero-initialized output starts as identity. The hidden branch receives gradients after the output kernel moves away from zero."
          },
          {
            "block": "critic-refinement-3",
            "status": "trainable",
            "description": "Reachable learned gradient path; zero-initialized output starts as identity. The hidden branch receives gradients after the output kernel moves away from zero."
          },
          {
            "block": "critic-refinement-4",
            "status": "trainable",
            "description": "Reachable learned gradient path; zero-initialized output starts as identity. The hidden branch receives gradients after the output kernel moves away from zero."
          },
          {
            "block": "critic-refinement-5",
            "status": "trainable",
            "description": "Reachable learned gradient path; zero-initialized output starts as identity. The hidden branch receives gradients after the output kernel moves away from zero."
          },
          {
            "block": "actor-board-input-projection",
            "status": "disconnected",
            "description": "Private actor encoder and refinement; policy gradients stop before shared lower features."
          },
          {
            "block": "actor-board-block-0",
            "status": "disconnected",
            "description": "Private actor encoder and refinement; policy gradients stop before shared lower features."
          },
          {
            "block": "actor-board-block-1",
            "status": "disconnected",
            "description": "Private actor encoder and refinement; policy gradients stop before shared lower features."
          },
          {
            "block": "actor-board-block-2",
            "status": "disconnected",
            "description": "Private actor encoder and refinement; policy gradients stop before shared lower features."
          },
          {
            "block": "actor-board-output",
            "status": "disconnected",
            "description": "Private actor encoder and refinement; policy gradients stop before shared lower features."
          },
          {
            "block": "actor-refinement-1",
            "status": "disconnected",
            "description": "Private actor encoder and refinement; policy gradients stop before shared lower features."
          },
          {
            "block": "critic-result-attention",
            "status": "trainable",
            "description": "Detached in actor Q evaluation; settlement likelihood and event/deposit constraints train the result-attention and event-readout weights."
          },
          {
            "block": "critic-pao-allocation",
            "status": "trainable",
            "description": "Detached actor Q; observed settlement supervision trains allocation in critic and imitation fitting."
          }
        ],
        "edges": [
          {
            "from": "hand-suit-0",
            "to": "hand-tokenization",
            "kind": "backward",
            "label": "VJP through conditioned suit tokens",
            "source": {
              "path": "model/encoder.py",
              "line": 343
            },
            "id": "critic-backward-hand-suit-0-hand-tokenization"
          },
          {
            "from": "hand-honors",
            "to": "hand-tokenization",
            "kind": "backward",
            "label": "VJP through conditioned honor tokens",
            "source": {
              "path": "model/encoder.py",
              "line": 368
            },
            "id": "critic-backward-hand-honors-hand-tokenization"
          },
          {
            "from": "hand-suit-1",
            "to": "hand-suit-0",
            "kind": "backward",
            "label": "VJP through residual suit sequence",
            "source": {
              "path": "model/encoder.py",
              "line": 357
            },
            "id": "critic-backward-hand-suit-1-hand-suit-0"
          },
          {
            "from": "hand-suit-2",
            "to": "hand-suit-1",
            "kind": "backward",
            "label": "VJP through residual suit sequence",
            "source": {
              "path": "model/encoder.py",
              "line": 357
            },
            "id": "critic-backward-hand-suit-2-hand-suit-1"
          },
          {
            "from": "hand-bank-output",
            "to": "hand-suit-2",
            "kind": "backward",
            "label": "VJP through reconstructed 27 suit-tile tokens",
            "source": {
              "path": "model/encoder.py",
              "line": 368
            },
            "id": "critic-backward-hand-bank-output-hand-suit-2"
          },
          {
            "from": "hand-bank-output",
            "to": "hand-honors",
            "kind": "backward",
            "label": "VJP through seven honor-tile tokens",
            "source": {
              "path": "model/encoder.py",
              "line": 368
            },
            "id": "critic-backward-hand-bank-output-hand-honors"
          },
          {
            "from": "board-input-projection",
            "to": "hand-bank-output",
            "kind": "backward",
            "label": "VJP through current hand slot 0",
            "source": {
              "path": "model/encoder.py",
              "line": 935
            },
            "id": "critic-backward-board-input-projection-hand-bank-output"
          },
          {
            "from": "river-conv-0",
            "to": "river-tokenization",
            "kind": "backward",
            "label": "VJP through masked 64-channel stream tokens",
            "source": {
              "path": "model/encoder.py",
              "line": 521
            },
            "id": "critic-backward-river-conv-0-river-tokenization"
          },
          {
            "from": "river-conv-1",
            "to": "river-conv-0",
            "kind": "backward",
            "label": "VJP through masked residual stream",
            "source": {
              "path": "model/encoder.py",
              "line": 528
            },
            "id": "critic-backward-river-conv-1-river-conv-0"
          },
          {
            "from": "river-conv-2",
            "to": "river-conv-1",
            "kind": "backward",
            "label": "VJP through masked residual stream",
            "source": {
              "path": "model/encoder.py",
              "line": 528
            },
            "id": "critic-backward-river-conv-2-river-conv-1"
          },
          {
            "from": "river-summaries",
            "to": "river-attention",
            "kind": "backward",
            "label": "VJP through final masked stream tokens",
            "source": {
              "path": "model/encoder.py",
              "line": 539
            },
            "id": "critic-backward-river-summaries-river-attention"
          },
          {
            "from": "shared-public-context",
            "to": "river-summaries",
            "kind": "backward",
            "label": "VJP through six ordered 64-channel summaries",
            "source": {
              "path": "model/encoder.py",
              "line": 916
            },
            "id": "critic-backward-shared-public-context-river-summaries"
          },
          {
            "from": "board-block-0",
            "to": "board-input-projection",
            "kind": "backward",
            "label": "VJP through joint hand-board fusion",
            "source": {
              "path": "model/encoder.py",
              "line": 869
            },
            "id": "critic-backward-board-block-0-board-input-projection"
          },
          {
            "from": "board-block-1",
            "to": "board-block-0",
            "kind": "backward",
            "label": "VJP through residual board state",
            "source": {
              "path": "model/encoder.py",
              "line": 890
            },
            "id": "critic-backward-board-block-1-board-block-0"
          },
          {
            "from": "board-block-2",
            "to": "board-block-1",
            "kind": "backward",
            "label": "VJP through residual board state",
            "source": {
              "path": "model/encoder.py",
              "line": 890
            },
            "id": "critic-backward-board-block-2-board-block-1"
          },
          {
            "from": "board-output",
            "to": "board-block-2",
            "kind": "backward",
            "label": "VJP through final residual trunk state",
            "source": {
              "path": "model/encoder.py",
              "line": 894
            },
            "id": "critic-backward-board-output-board-block-2"
          },
          {
            "from": "candidate-projection",
            "to": "hand-bank-output",
            "kind": "backward",
            "label": "VJP through gathered 512-channel action hand",
            "source": {
              "path": "model/encoder.py",
              "line": 801
            },
            "id": "critic-backward-candidate-projection-hand-bank-output"
          },
          {
            "from": "candidate-projection",
            "to": "board-output",
            "kind": "backward",
            "label": "VJP through board context projected to 192 channels",
            "source": {
              "path": "model/encoder.py",
              "line": 847
            },
            "id": "critic-backward-candidate-projection-board-output"
          },
          {
            "from": "belief-readouts",
            "to": "belief-refinement",
            "kind": "backward",
            "label": "VJP through shared 512-channel board representation",
            "source": {
              "path": "model/beliefs.py",
              "line": 458
            },
            "id": "critic-backward-belief-readouts-belief-refinement"
          },
          {
            "from": "tile-tokenization",
            "to": "belief-refinement",
            "kind": "backward",
            "label": "VJP through three opponent context slices",
            "source": {
              "path": "model/beliefs.py",
              "line": 241
            },
            "id": "critic-backward-tile-tokenization-belief-refinement"
          },
          {
            "from": "tile-tokenization",
            "to": "belief-readouts",
            "kind": "stop",
            "label": "Detached initial shanten, conditional improving and count probabilities",
            "source": {
              "path": "model/beliefs.py",
              "line": 207
            },
            "id": "critic-stop-tile-tokenization-belief-readouts"
          },
          {
            "from": "tile-attention-0",
            "to": "tile-tokenization",
            "kind": "backward",
            "label": "VJP through 34 tokens per opponent",
            "source": {
              "path": "model/beliefs.py",
              "line": 252
            },
            "id": "critic-backward-tile-attention-0-tile-tokenization"
          },
          {
            "from": "tile-attention-1",
            "to": "tile-attention-0",
            "kind": "backward",
            "label": "VJP through refined token sequence",
            "source": {
              "path": "model/beliefs.py",
              "line": 261
            },
            "id": "critic-backward-tile-attention-1-tile-attention-0"
          },
          {
            "from": "tile-correction",
            "to": "tile-attention-1",
            "kind": "backward",
            "label": "VJP through final 128-channel tile tokens",
            "source": {
              "path": "model/beliefs.py",
              "line": 262
            },
            "id": "critic-backward-tile-correction-tile-attention-1"
          },
          {
            "from": "tile-correction",
            "to": "belief-readouts",
            "kind": "backward",
            "label": "VJP through initial count and ukeire logits for residual add",
            "source": {
              "path": "model/beliefs.py",
              "line": 267
            },
            "id": "critic-backward-tile-correction-belief-readouts"
          },
          {
            "from": "belief-constraints",
            "to": "tile-correction",
            "kind": "backward",
            "label": "Gradient through the refined held-count logits",
            "source": {
              "path": "model/beliefs.py",
              "line": 473
            },
            "id": "critic-backward-belief-constraints-tile-correction"
          },
          {
            "from": "belief-constraints",
            "to": "belief-readouts",
            "kind": "backward",
            "label": "VJP through unmodified shanten logits",
            "source": {
              "path": "model/beliefs.py",
              "line": 474
            },
            "id": "critic-backward-belief-constraints-belief-readouts"
          },
          {
            "from": "actor-candidate-aux",
            "to": "candidate-projection",
            "kind": "backward",
            "label": "VJP through route prediction weights and raw candidate state",
            "source": {
              "path": "model/candidate_predictions.py",
              "line": 10
            },
            "id": "critic-backward-actor-candidate-aux-candidate-projection"
          },
          {
            "from": "actor-completion",
            "to": "belief-refinement",
            "kind": "backward",
            "label": "VJP through shared refined completion readouts",
            "source": {
              "path": "model/beliefs.py",
              "line": 458
            },
            "id": "critic-backward-actor-completion-belief-refinement"
          },
          {
            "from": "player-descriptors",
            "to": "river-summaries",
            "kind": "backward",
            "label": "Settlement VJP: Three 256-channel opponent river summaries",
            "source": {
              "path": "model/network.py",
              "line": 214
            },
            "id": "critic-backward-player-descriptors-river-summaries"
          },
          {
            "from": "call-candidate-merge",
            "to": "candidate-projection",
            "kind": "backward",
            "label": "Settlement VJP: Candidate states and action structure",
            "source": {
              "path": "model/actor.py",
              "line": 577
            },
            "id": "critic-backward-call-candidate-merge-candidate-projection"
          },
          {
            "from": "call-candidate-merge",
            "to": "board-output",
            "kind": "backward",
            "label": "Settlement VJP: Shared board state",
            "source": {
              "path": "model/actor.py",
              "line": 580
            },
            "id": "critic-backward-call-candidate-merge-board-output"
          },
          {
            "from": "critic-player-projection",
            "to": "critic-state-assembly",
            "kind": "backward",
            "label": "Gradient through player descriptors in the assembled candidate state",
            "source": {
              "path": "model/critic.py",
              "line": 836
            },
            "id": "critic-backward-critic-player-projection-critic-state-assembly"
          },
          {
            "from": "critic-player-projection",
            "to": "critic-refinement-5",
            "kind": "backward",
            "label": "VJP through common 384-channel context broadcast across seats",
            "source": {
              "path": "model/critic.py",
              "line": 840
            },
            "id": "critic-backward-critic-player-projection-critic-refinement-5"
          },
          {
            "from": "critic-event",
            "to": "critic-refinement-5",
            "kind": "backward",
            "label": "VJP through common event-context projection",
            "source": {
              "path": "model/critic.py",
              "line": 875
            },
            "id": "critic-backward-critic-event-critic-refinement-5"
          },
          {
            "from": "critic-event",
            "to": "critic-belief-adapter",
            "kind": "backward",
            "label": "VJP through winner/source/ready role pooling",
            "source": {
              "path": "model/critic.py",
              "line": 887
            },
            "id": "critic-backward-critic-event-critic-belief-adapter"
          },
          {
            "from": "critic-claim-state",
            "to": "critic-belief-adapter",
            "kind": "backward",
            "label": "VJP through recipient and ron-payer embeddings",
            "source": {
              "path": "model/critic.py",
              "line": 915
            },
            "id": "critic-backward-critic-claim-state-critic-belief-adapter"
          },
          {
            "from": "critic-score-head",
            "to": "critic-claim-state",
            "kind": "backward",
            "label": "VJP through claim states with public scoring evidence",
            "source": {
              "path": "model/critic.py",
              "line": 971
            },
            "id": "critic-backward-critic-score-head-critic-claim-state"
          },
          {
            "from": "critic-deposits",
            "to": "critic-result-attention",
            "kind": "backward",
            "label": "Gradient through the 32-channel event vectors used for deposit conditioning",
            "source": {
              "path": "model/critic.py",
              "line": 1009
            },
            "id": "critic-backward-critic-deposits-critic-result-attention"
          },
          {
            "from": "critic-deposits",
            "to": "critic-belief-adapter",
            "kind": "backward",
            "label": "VJP through player embeddings pooled by deposit mask",
            "source": {
              "path": "model/critic.py",
              "line": 1013
            },
            "id": "critic-backward-critic-deposits-critic-belief-adapter"
          },
          {
            "from": "settlement-decoder",
            "to": "critic-result-attention",
            "kind": "backward",
            "label": "VJP through whole-event logits",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 462
            },
            "id": "critic-backward-settlement-decoder-critic-result-attention"
          },
          {
            "from": "settlement-decoder",
            "to": "critic-deposits",
            "kind": "backward",
            "label": "VJP through event-conditioned deposit-mask logits",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 462
            },
            "id": "critic-backward-settlement-decoder-critic-deposits"
          },
          {
            "from": "settlement-decoder",
            "to": "critic-score-head",
            "kind": "backward",
            "label": "VJP through total score probabilities",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 492
            },
            "id": "critic-backward-settlement-decoder-critic-score-head"
          },
          {
            "from": "critic-state-assembly",
            "to": "actor-candidate-aux",
            "kind": "stop",
            "label": "Detached route probabilities in the settlement state",
            "source": {
              "path": "model/network.py",
              "line": 208
            },
            "id": "critic-stop-critic-state-assembly-actor-candidate-aux"
          },
          {
            "from": "critic-objective",
            "to": "settlement-decoder",
            "kind": "backward",
            "label": "Supported observed-transfer NLL gradient into compatible factor probabilities",
            "source": {
              "path": "training/trainer.py",
              "line": 97
            },
            "id": "critic-backward-critic-objective-settlement-decoder"
          },
          {
            "from": "critic-objective",
            "to": "critic-score-head",
            "kind": "backward",
            "label": "Raw score-support constraint gradient",
            "source": {
              "path": "training/trainer.py",
              "line": 97
            },
            "id": "critic-backward-critic-objective-critic-score-head"
          },
          {
            "from": "critic-objective",
            "to": "critic-result-attention",
            "kind": "backward",
            "label": "Raw event constraint parameter gradients",
            "source": {
              "path": "training/trainer.py",
              "line": 97
            },
            "id": "critic-backward-critic-objective-critic-result-attention"
          },
          {
            "from": "critic-objective",
            "to": "critic-deposits",
            "kind": "backward",
            "label": "Raw conditional-deposit constraint gradient",
            "source": {
              "path": "training/trainer.py",
              "line": 97
            },
            "id": "critic-backward-critic-objective-critic-deposits"
          },
          {
            "from": "belief-refinement",
            "to": "board-output",
            "kind": "backward",
            "label": "Residual identity plus refinement-branch VJP",
            "source": {
              "path": "model/beliefs.py",
              "line": 451
            },
            "id": "critic-backward-belief-refinement-board-output"
          },
          {
            "from": "critic-refinement",
            "to": "critic-common-projection",
            "kind": "backward",
            "label": "Residual identity plus refinement-branch VJP",
            "source": {
              "path": "model/critic.py",
              "line": 832
            },
            "id": "critic-backward-critic-refinement-critic-common-projection"
          },
          {
            "from": "critic-state-assembly",
            "to": "call-candidate-merge",
            "label": "Observed-settlement gradient into shared decision and after-call candidate contexts",
            "kind": "backward",
            "source": {
              "path": "model/network.py",
              "line": 204
            },
            "id": "critic-backward-critic-state-assembly-call-candidate-merge"
          },
          {
            "from": "hand-tokenization",
            "to": "table-conditioning",
            "kind": "backward",
            "label": "VJP through table offset added before first hand GELU",
            "source": {
              "path": "model/encoder.py",
              "line": 339
            },
            "id": "critic-backward-hand-tokenization-table-conditioning"
          },
          {
            "from": "critic-common-projection",
            "to": "critic-state-assembly",
            "kind": "backward",
            "label": "VJP: Common-state projection",
            "source": {
              "path": "model/critic.py",
              "line": 677
            },
            "id": "critic-backward-critic-common-projection-critic-state-assembly"
          },
          {
            "from": "critic-state-assembly",
            "to": "player-descriptors",
            "kind": "backward",
            "label": "VJP: Original-window player descriptors",
            "source": {
              "path": "model/critic.py",
              "line": 677
            },
            "id": "critic-backward-critic-state-assembly-player-descriptors"
          },
          {
            "from": "critic-belief-uncertainty",
            "to": "critic-state-assembly",
            "kind": "backward",
            "label": "VJP: Opponent probability slice",
            "source": {
              "path": "model/critic.py",
              "line": 677
            },
            "id": "critic-backward-critic-belief-uncertainty-critic-state-assembly"
          },
          {
            "from": "call-candidate-merge",
            "to": "shared-probabilities",
            "kind": "stop",
            "label": "Detached parent opponent beliefs and local completion probabilities",
            "source": {
              "path": "model/network.py",
              "line": 34
            },
            "id": "critic-stop-call-candidate-merge-shared-probabilities"
          },
          {
            "from": "belief-readouts",
            "to": "river-summaries",
            "kind": "backward",
            "label": "Shared shanten derivative into opponent-local river summaries",
            "source": {
              "path": "model/beliefs.py",
              "line": 291
            },
            "id": "critic-backward-belief-readouts-river-summaries"
          },
          {
            "from": "critic-belief-adapter",
            "to": "critic-belief-uncertainty",
            "kind": "backward",
            "label": "Payment likelihood VJP through shared opponent residual",
            "source": {
              "path": "model/critic.py",
              "line": 677
            },
            "id": "critic-backward-critic-belief-adapter-critic-belief-uncertainty"
          },
          {
            "from": "critic-belief-adapter",
            "to": "critic-player-projection",
            "kind": "backward",
            "label": "Payment likelihood VJP through shared opponent residual",
            "source": {
              "path": "model/critic.py",
              "line": 677
            },
            "id": "critic-backward-critic-belief-adapter-critic-player-projection"
          },
          {
            "from": "completion-evidence",
            "to": "belief-constraints",
            "kind": "stop",
            "label": "Detached projected held counts",
            "source": {
              "path": "model/beliefs.py",
              "line": 529
            },
            "id": "critic-stop-completion-evidence-belief-constraints"
          },
          {
            "from": "completion-evidence",
            "to": "river-summaries",
            "kind": "backward",
            "label": "Completion evidence VJP: Aligned per-opponent river summary 256",
            "source": {
              "path": "model/beliefs.py",
              "line": 336
            },
            "id": "critic-backward-completion-evidence-river-summaries"
          },
          {
            "from": "actor-completion",
            "to": "completion-evidence",
            "kind": "backward",
            "label": "Completion evidence VJP: Opponent-only 46 yaku +76 score residual before support",
            "source": {
              "path": "model/beliefs.py",
              "line": 336
            },
            "id": "critic-backward-actor-completion-completion-evidence"
          },
          {
            "from": "candidate-ron-prediction",
            "to": "board-output",
            "kind": "backward",
            "label": "Ron eligibility gradients reach observed board",
            "source": {
              "path": "model/network.py",
              "line": 44
            },
            "id": "critic-backward-candidate-ron-prediction-board-output"
          },
          {
            "from": "candidate-ron-prediction",
            "to": "structural-wait",
            "kind": "stop",
            "label": "Detached structural wait in candidate ron",
            "source": {
              "path": "model/candidate_predictions.py",
              "line": 36
            },
            "id": "critic-stop-candidate-ron-prediction-structural-wait"
          },
          {
            "from": "critic-objective",
            "to": "belief-constraints",
            "kind": "backward",
            "label": "Direct supervised shanten and projected held-count losses",
            "source": {
              "path": "training/auxiliary.py",
              "line": 18
            },
            "id": "critic-backward-critic-objective-belief-constraints"
          },
          {
            "from": "critic-objective",
            "to": "actor-completion",
            "kind": "backward",
            "label": "Observed completion yaku and score losses",
            "source": {
              "path": "training/auxiliary.py",
              "line": 18
            },
            "id": "critic-backward-critic-objective-actor-completion"
          },
          {
            "from": "critic-objective",
            "to": "actor-candidate-aux",
            "kind": "backward",
            "label": "Observed candidate route loss",
            "source": {
              "path": "training/auxiliary.py",
              "line": 18
            },
            "id": "critic-backward-critic-objective-actor-candidate-aux"
          },
          {
            "from": "critic-objective",
            "to": "candidate-ron-prediction",
            "kind": "backward",
            "label": "Observed candidate ron loss",
            "source": {
              "path": "training/auxiliary.py",
              "line": 18
            },
            "id": "critic-backward-critic-objective-candidate-ron-prediction"
          },
          {
            "from": "critic-objective",
            "to": "tile-correction",
            "kind": "backward",
            "label": "Direct supervised conditional improving-tile loss",
            "source": {
              "path": "model/beliefs.py",
              "line": 767
            },
            "id": "critic-backward-critic-objective-tile-correction"
          },
          {
            "from": "table-conditioning",
            "to": "shared-public-context",
            "kind": "backward",
            "label": "VJP through shared-context hand projection",
            "source": {
              "path": "model/encoder.py",
              "line": 339
            },
            "id": "critic-backward-table-conditioning-shared-public-context"
          },
          {
            "from": "board-input-projection",
            "to": "shared-public-context",
            "kind": "backward",
            "label": "VJP through shared context in joint fusion",
            "source": {
              "path": "model/encoder.py",
              "line": 869
            },
            "id": "critic-backward-board-input-projection-shared-public-context"
          },
          {
            "from": "river-attention",
            "to": "river-conv-2",
            "kind": "backward",
            "label": "VJP through observed-event attention residual",
            "source": {
              "path": "model/river_attention.py",
              "line": 44
            },
            "id": "critic-backward-river-attention-river-conv-2"
          },
          {
            "from": "actor-final-score",
            "to": "candidate-projection",
            "kind": "stop",
            "label": "Detached raw state; policy gradients stop before shared candidate encoding",
            "source": {
              "path": "model/network.py",
              "line": 156
            },
            "id": "critic-stop-actor-final-score-candidate-projection"
          },
          {
            "from": "hand-tokenization",
            "to": "shared-tile-projection",
            "kind": "backward",
            "label": "VJP into the shared tile-identity weights",
            "source": {
              "path": "model/encoder.py",
              "line": 278
            },
            "id": "critic-backward-hand-tokenization-shared-tile-projection"
          },
          {
            "from": "river-tokenization",
            "to": "shared-tile-projection",
            "kind": "backward",
            "label": "VJP into the shared tile-identity weights",
            "source": {
              "path": "model/encoder.py",
              "line": 503
            },
            "id": "critic-backward-river-tokenization-shared-tile-projection"
          },
          {
            "from": "shared-public-context",
            "to": "shared-tile-projection",
            "kind": "backward",
            "label": "VJP into the shared tile-identity weights",
            "source": {
              "path": "model/input_features.py",
              "line": 304
            },
            "id": "critic-backward-shared-public-context-shared-tile-projection"
          },
          {
            "from": "candidate-projection",
            "to": "shared-tile-projection",
            "kind": "backward",
            "label": "VJP into the shared tile-identity weights",
            "source": {
              "path": "model/encoder.py",
              "line": 823
            },
            "id": "critic-backward-candidate-projection-shared-tile-projection"
          },
          {
            "from": "critic-refinement-1",
            "to": "critic-refinement",
            "kind": "backward",
            "label": "Residual refinement gradient",
            "source": {
              "path": "model/critic.py",
              "line": 832
            },
            "id": "critic-backward-critic-refinement-1-critic-refinement"
          },
          {
            "from": "critic-refinement-2",
            "to": "critic-refinement-1",
            "kind": "backward",
            "label": "Residual refinement gradient",
            "source": {
              "path": "model/critic.py",
              "line": 832
            },
            "id": "critic-backward-critic-refinement-2-critic-refinement-1"
          },
          {
            "from": "critic-refinement-3",
            "to": "critic-refinement-2",
            "kind": "backward",
            "label": "Residual refinement gradient",
            "source": {
              "path": "model/critic.py",
              "line": 832
            },
            "id": "critic-backward-critic-refinement-3-critic-refinement-2"
          },
          {
            "from": "critic-refinement-4",
            "to": "critic-refinement-3",
            "kind": "backward",
            "label": "Residual refinement gradient",
            "source": {
              "path": "model/critic.py",
              "line": 832
            },
            "id": "critic-backward-critic-refinement-4-critic-refinement-3"
          },
          {
            "from": "critic-refinement-5",
            "to": "critic-refinement-4",
            "kind": "backward",
            "label": "Residual refinement gradient",
            "source": {
              "path": "model/critic.py",
              "line": 832
            },
            "id": "critic-backward-critic-refinement-5-critic-refinement-4"
          },
          {
            "from": "actor-board-input-projection",
            "to": "shared-public-context",
            "kind": "stop",
            "label": "Policy gradients stop before shared lower encodings",
            "source": {
              "path": "model/encoder.py",
              "line": 937
            },
            "id": "critic-stop-actor-board-input-projection-shared-public-context"
          },
          {
            "from": "actor-board-input-projection",
            "to": "hand-bank-output",
            "kind": "stop",
            "label": "Policy gradients stop before shared lower encodings",
            "source": {
              "path": "model/encoder.py",
              "line": 937
            },
            "id": "critic-stop-actor-board-input-projection-hand-bank-output"
          },
          {
            "from": "critic-result-attention",
            "to": "critic-event",
            "kind": "backward",
            "label": "Attention and identity-residual gradient into role-pooled events",
            "source": {
              "path": "model/critic.py",
              "line": 767
            },
            "id": "critic-backward-critic-result-attention-critic-event"
          },
          {
            "from": "candidate-ron-prediction",
            "to": "completion-evidence",
            "kind": "backward",
            "label": "Ron eligibility trains opponent evidence hidden state",
            "source": {
              "path": "model/network.py",
              "line": 50
            },
            "id": "critic-backward-candidate-ron-prediction-completion-evidence"
          },
          {
            "from": "candidate-ron-prediction",
            "to": "actor-completion",
            "kind": "stop",
            "label": "Detached opponent ron-yaku probabilities",
            "source": {
              "path": "model/network.py",
              "line": 50
            },
            "id": "critic-stop-candidate-ron-prediction-actor-completion"
          },
          {
            "from": "critic-pao-allocation",
            "to": "critic-claim-state",
            "kind": "backward",
            "label": "Settlement likelihood through allocation evidence",
            "source": {
              "path": "model/critic.py",
              "line": 820
            },
            "id": "critic-backward-critic-pao-allocation-critic-claim-state"
          },
          {
            "from": "critic-pao-allocation",
            "to": "critic-player-projection",
            "kind": "backward",
            "label": "Settlement likelihood through allocation evidence",
            "source": {
              "path": "model/critic.py",
              "line": 820
            },
            "id": "critic-backward-critic-pao-allocation-critic-player-projection"
          },
          {
            "from": "settlement-decoder",
            "to": "critic-pao-allocation",
            "kind": "backward",
            "label": "Observed responsibility allocation likelihood",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 276
            },
            "id": "critic-backward-settlement-decoder-critic-pao-allocation"
          },
          {
            "from": "actor-candidate-pool",
            "to": "candidate-projection",
            "kind": "stop",
            "label": "Detached candidate inputs; actor gradients stop",
            "source": {
              "path": "model/actor.py",
              "line": 86
            },
            "id": "critic-stop-actor-candidate-pool-candidate-projection"
          }
        ],
        "objective": {
          "id": "critic-objective",
          "title": "Critic pass objective",
          "description": "Minimize the calibrated half-NLL/half-Q-MSE objective, direct nagashi BCE, critic constraints and seven supervised belief losses. Settlement gradients train critic layers and shared encodings; belief supervision remains active.",
          "equations": [
            {
              "topic": "payment-likelihood",
              "equations": [
                1,
                3,
                4
              ]
            }
          ],
          "source": {
            "path": "training/trainer.py",
            "line": 97
          }
        },
        "notes": [
          "Belief supervision and belief-owned constraints train shared hand, river, board and candidate representations. Settlement also trains them during the critic phase; policy gradients stop at shared outputs.",
          "Private actor weights train from policy CE or MMD. Settlement trains private critic layers and shared representations. Prediction consumers and actor Q remain detached.",
          "Shanten, conditional improving tiles, held counts, completion yaku, completion score, candidate route and ron each have a unit-weight loss on their own known eligible targets.",
          "Mixed settlement NLL/Q-MSE and structural constraints train the critic and eligible shared representations.",
          "The custom backward of supervised_statistics recomputes bounded chunks and returns vector–Jacobian products for both input state and critic parameters.",
          "Variables with None gradients are omitted from optimizer application. Optimizer slot allocation does not imply a parameter or weight-decay update.",
          "Backward edges aggregate differentiable dependencies across likelihood and constraint operations; the graph is not an op-level TensorFlow trace.",
          "Map arrows are phase-specific structural VJPs, not measured gradient magnitudes or a claim that every row activates every branch.",
          "No backward arrows follow native masks, public tensors or selected candidate indices. Grouped blocks may contain both connected and disconnected operators; their descriptions identify partial paths.",
          "Directly supervised predictions train shared encodings. Hypothetical children inherit observed opponent predictions; their completion and route features follow the local hand. Belief-owned penalties retain gradients to their own heads and encoder.",
          "Single-choice rows and committed riichi discard rows are ineligible for every loss. An ordinary dama discard counts when the player still has a choice.",
          "The four constrained nagashi marginals receive direct unit-weight BCE from the observed qualifier set."
        ],
        "source": {
          "path": "training/trainer.py",
          "line": 97
        }
      },
      {
        "id": "actor",
        "title": "Retained path: MMD actor pass",
        "description": "Optimize detached-Q policy gain, two reference-policy KL terms at 0.3 each, belief-owned constraints at 0.01 and seven supervised belief losses.",
        "statuses": [
          {
            "block": "native-input-contract",
            "status": "target",
            "description": "Fixed public tensors, support masks and integer selectors; no optimizer parameters and no parameter-gradient arrows into this block."
          },
          {
            "block": "hand-tokenization",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "hand-suit-0",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "hand-suit-1",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "hand-suit-2",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "hand-honors",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "hand-bank-output",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "river-tokenization",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "river-conv-0",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "river-conv-1",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "river-conv-2",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "river-summaries",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "board-input-projection",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "board-block-0",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "board-block-1",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "board-block-2",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "board-output",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "candidate-projection",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "belief-readouts",
            "status": "trainable",
            "description": "Observed shanten, improving-tile and count targets supervise their own predictions. Raw logits also receive the relevant belief-owned structural constraints."
          },
          {
            "block": "tile-tokenization",
            "status": "trainable",
            "description": "Tile features use detached initial shanten, improving and count probabilities. Supervised tile predictions train the token projection."
          },
          {
            "block": "tile-attention-0",
            "status": "trainable",
            "description": "Held-count and conditional improving-tile supervision train the residual correction. The raw count logits also receive the belief-owned constraint."
          },
          {
            "block": "tile-attention-1",
            "status": "trainable",
            "description": "Held-count and conditional improving-tile supervision train the residual correction. The raw count logits also receive the belief-owned constraint."
          },
          {
            "block": "tile-correction",
            "status": "trainable",
            "description": "Held-count and conditional improving-tile supervision train the residual correction. The raw count logits also receive the belief-owned constraint."
          },
          {
            "block": "belief-constraints",
            "status": "deterministic",
            "description": "Support masks and count projection retain derivatives for the heads’ own supervised logits."
          },
          {
            "block": "actor-candidate-aux",
            "status": "trainable",
            "description": "Observed route labels train this readout. Actor and critic read detached route probabilities. Raw logits also receive the relevant belief-owned structural constraints."
          },
          {
            "block": "actor-completion",
            "status": "trainable",
            "description": "Completion targets train yaku and score. Score coupling reads detached yaku predictions. Raw logits also receive the relevant belief-owned structural constraints."
          },
          {
            "block": "actor-final-score",
            "status": "trainable",
            "description": "Updated through active-head legal-policy KL and, outside WIN, detached-Q policy gain. WIN has zero Q-gain derivative but retains head-level KL gradients."
          },
          {
            "block": "actor-win",
            "status": "trainable",
            "description": "Updated only by active WIN-head current-policy KL; the candidate-mass Q derivative is zero."
          },
          {
            "block": "player-descriptors",
            "status": "deterministic",
            "description": "Fixed public descriptors join shared river representations. Settlement gradients reach the river encoder in the critic phase; actor Q evaluations are detached."
          },
          {
            "block": "critic-common-projection",
            "status": "frozen",
            "description": "Detached critic weights and input state; no actor-phase update."
          },
          {
            "block": "critic-player-projection",
            "status": "frozen",
            "description": "Detached critic weights and input state; no actor-phase update."
          },
          {
            "block": "critic-event",
            "status": "frozen",
            "description": "Detached critic weights and input state; no actor-phase update."
          },
          {
            "block": "critic-claim-state",
            "status": "frozen",
            "description": "Detached critic weights and input state; no actor-phase update."
          },
          {
            "block": "critic-score-head",
            "status": "frozen",
            "description": "Detached critic weights and input state; no actor-phase update."
          },
          {
            "block": "critic-deposits",
            "status": "frozen",
            "description": "Detached critic weights and input state; no actor-phase update."
          },
          {
            "block": "settlement-decoder",
            "status": "deterministic",
            "description": "Detached forecast factorization used to form Q coefficients; no reverse path in the actor objective."
          },
          {
            "block": "continuation-payoffs",
            "status": "target",
            "description": "Fixed utility and outcome expectation form stopped-gradient Q coefficients. The constants are not optimizer variables."
          },
          {
            "block": "belief-refinement",
            "status": "trainable",
            "description": "Supervised predictions train the shared belief refinement. Its zero-initialized residual starts as an identity."
          },
          {
            "block": "critic-refinement",
            "status": "frozen",
            "description": "Frozen and detached in actor Q evaluation."
          },
          {
            "block": "call-choice",
            "status": "trainable",
            "description": "Actor response KL and policy-gain gradients update this branch; Q values remain detached."
          },
          {
            "block": "call-factorization",
            "status": "deterministic",
            "description": "Actor response KL and policy-gain gradients update this branch; Q values remain detached."
          },
          {
            "block": "call-candidate-merge",
            "status": "deterministic",
            "description": "Actor uses this merge for detached-Q evaluation; no Q-value gradient crosses into shared state."
          },
          {
            "block": "actor-policy-context",
            "status": "trainable",
            "description": "Final-policy context projection receives actor gradients only; it is absent from the critic objective."
          },
          {
            "block": "table-conditioning",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "critic-state-assembly",
            "status": "deterministic",
            "description": "Settlement assembles differentiable shared board, candidate and river representations with detached predictions and fixed public facts. Actor Q evaluations detach the assembled state."
          },
          {
            "block": "critic-belief-uncertainty",
            "status": "frozen",
            "description": "The critic computes moments from detached probabilities. Its adapter can train on settlement targets during the critic pass."
          },
          {
            "block": "critic-belief-adapter",
            "status": "frozen",
            "description": "Actor Q uses detached assembled state and critic weights; no actor-phase backward through this adapter."
          },
          {
            "block": "candidate-ron-prediction",
            "status": "trainable",
            "description": "Observed ron legality trains board/tile eligibility using detached structural waits; no gradient enters actor candidate attention."
          },
          {
            "block": "shared-probabilities",
            "status": "deterministic",
            "description": "Policy and settlement consume detached shanten, improving, count, completion-yaku and completion-score probabilities."
          },
          {
            "block": "structural-wait",
            "status": "deterministic",
            "description": "Shanten and conditional improving probabilities determine structural wait. Candidate ron consumes the detached marginal."
          },
          {
            "block": "completion-evidence",
            "status": "trainable",
            "description": "Completion losses update the opponent residual and connected river features. Projected counts enter as detached evidence."
          },
          {
            "block": "shared-public-context",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "river-attention",
            "status": "trainable",
            "description": "Belief losses and their own structural constraints update this shared representation. Policy gradients stop at shared outputs; critic Q is detached in this phase."
          },
          {
            "block": "actor-refinement",
            "status": "trainable",
            "description": "Private policy refinement trains from policy CE and MMD; it is absent from settlement and direct belief objectives."
          },
          {
            "block": "shared-tile-projection",
            "status": "trainable",
            "description": "Belief objectives train this shared projection. Settlement also trains it during critic fitting; policy gradients stop at shared encoder outputs."
          },
          {
            "block": "actor-candidate-pool",
            "status": "trainable",
            "description": "Actor-only attention; candidate inputs are detached."
          },
          {
            "block": "critic-refinement-1",
            "status": "frozen",
            "description": "Frozen and detached in actor Q evaluation."
          },
          {
            "block": "critic-refinement-2",
            "status": "frozen",
            "description": "Frozen and detached in actor Q evaluation."
          },
          {
            "block": "critic-refinement-3",
            "status": "frozen",
            "description": "Frozen and detached in actor Q evaluation."
          },
          {
            "block": "critic-refinement-4",
            "status": "frozen",
            "description": "Frozen and detached in actor Q evaluation."
          },
          {
            "block": "critic-refinement-5",
            "status": "frozen",
            "description": "Frozen and detached in actor Q evaluation."
          },
          {
            "block": "actor-board-input-projection",
            "status": "trainable",
            "description": "Private actor encoder and refinement; policy gradients stop before shared lower features."
          },
          {
            "block": "actor-board-block-0",
            "status": "trainable",
            "description": "Private actor encoder and refinement; policy gradients stop before shared lower features."
          },
          {
            "block": "actor-board-block-1",
            "status": "trainable",
            "description": "Private actor encoder and refinement; policy gradients stop before shared lower features."
          },
          {
            "block": "actor-board-block-2",
            "status": "trainable",
            "description": "Private actor encoder and refinement; policy gradients stop before shared lower features."
          },
          {
            "block": "actor-board-output",
            "status": "trainable",
            "description": "Private actor encoder and refinement; policy gradients stop before shared lower features."
          },
          {
            "block": "actor-refinement-1",
            "status": "trainable",
            "description": "Private actor encoder and refinement; policy gradients stop before shared lower features."
          },
          {
            "block": "critic-result-attention",
            "status": "frozen",
            "description": "Detached in actor Q evaluation; settlement likelihood and event/deposit constraints train the result-attention and event-readout weights."
          },
          {
            "block": "critic-pao-allocation",
            "status": "frozen",
            "description": "Detached actor Q; observed settlement supervision trains allocation in critic and imitation fitting."
          }
        ],
        "edges": [
          {
            "from": "hand-suit-0",
            "to": "hand-tokenization",
            "kind": "backward",
            "label": "VJP through conditioned suit tokens",
            "source": {
              "path": "model/encoder.py",
              "line": 343
            },
            "id": "actor-backward-hand-suit-0-hand-tokenization"
          },
          {
            "from": "hand-honors",
            "to": "hand-tokenization",
            "kind": "backward",
            "label": "VJP through conditioned honor tokens",
            "source": {
              "path": "model/encoder.py",
              "line": 368
            },
            "id": "actor-backward-hand-honors-hand-tokenization"
          },
          {
            "from": "hand-suit-1",
            "to": "hand-suit-0",
            "kind": "backward",
            "label": "VJP through residual suit sequence",
            "source": {
              "path": "model/encoder.py",
              "line": 357
            },
            "id": "actor-backward-hand-suit-1-hand-suit-0"
          },
          {
            "from": "hand-suit-2",
            "to": "hand-suit-1",
            "kind": "backward",
            "label": "VJP through residual suit sequence",
            "source": {
              "path": "model/encoder.py",
              "line": 357
            },
            "id": "actor-backward-hand-suit-2-hand-suit-1"
          },
          {
            "from": "hand-bank-output",
            "to": "hand-suit-2",
            "kind": "backward",
            "label": "VJP through reconstructed 27 suit-tile tokens",
            "source": {
              "path": "model/encoder.py",
              "line": 368
            },
            "id": "actor-backward-hand-bank-output-hand-suit-2"
          },
          {
            "from": "hand-bank-output",
            "to": "hand-honors",
            "kind": "backward",
            "label": "VJP through seven honor-tile tokens",
            "source": {
              "path": "model/encoder.py",
              "line": 368
            },
            "id": "actor-backward-hand-bank-output-hand-honors"
          },
          {
            "from": "board-input-projection",
            "to": "hand-bank-output",
            "kind": "backward",
            "label": "VJP through current hand slot 0",
            "source": {
              "path": "model/encoder.py",
              "line": 935
            },
            "id": "actor-backward-board-input-projection-hand-bank-output"
          },
          {
            "from": "river-conv-0",
            "to": "river-tokenization",
            "kind": "backward",
            "label": "VJP through masked 64-channel stream tokens",
            "source": {
              "path": "model/encoder.py",
              "line": 521
            },
            "id": "actor-backward-river-conv-0-river-tokenization"
          },
          {
            "from": "river-conv-1",
            "to": "river-conv-0",
            "kind": "backward",
            "label": "VJP through masked residual stream",
            "source": {
              "path": "model/encoder.py",
              "line": 528
            },
            "id": "actor-backward-river-conv-1-river-conv-0"
          },
          {
            "from": "river-conv-2",
            "to": "river-conv-1",
            "kind": "backward",
            "label": "VJP through masked residual stream",
            "source": {
              "path": "model/encoder.py",
              "line": 528
            },
            "id": "actor-backward-river-conv-2-river-conv-1"
          },
          {
            "from": "river-summaries",
            "to": "river-attention",
            "kind": "backward",
            "label": "VJP through final masked stream tokens",
            "source": {
              "path": "model/encoder.py",
              "line": 539
            },
            "id": "actor-backward-river-summaries-river-attention"
          },
          {
            "from": "shared-public-context",
            "to": "river-summaries",
            "kind": "backward",
            "label": "VJP through six ordered 64-channel summaries",
            "source": {
              "path": "model/encoder.py",
              "line": 916
            },
            "id": "actor-backward-shared-public-context-river-summaries"
          },
          {
            "from": "board-block-0",
            "to": "board-input-projection",
            "kind": "backward",
            "label": "VJP through joint hand-board fusion",
            "source": {
              "path": "model/encoder.py",
              "line": 869
            },
            "id": "actor-backward-board-block-0-board-input-projection"
          },
          {
            "from": "board-block-1",
            "to": "board-block-0",
            "kind": "backward",
            "label": "VJP through residual board state",
            "source": {
              "path": "model/encoder.py",
              "line": 890
            },
            "id": "actor-backward-board-block-1-board-block-0"
          },
          {
            "from": "board-block-2",
            "to": "board-block-1",
            "kind": "backward",
            "label": "VJP through residual board state",
            "source": {
              "path": "model/encoder.py",
              "line": 890
            },
            "id": "actor-backward-board-block-2-board-block-1"
          },
          {
            "from": "board-output",
            "to": "board-block-2",
            "kind": "backward",
            "label": "VJP through final residual trunk state",
            "source": {
              "path": "model/encoder.py",
              "line": 894
            },
            "id": "actor-backward-board-output-board-block-2"
          },
          {
            "from": "candidate-projection",
            "to": "hand-bank-output",
            "kind": "backward",
            "label": "VJP through gathered 512-channel action hand",
            "source": {
              "path": "model/encoder.py",
              "line": 801
            },
            "id": "actor-backward-candidate-projection-hand-bank-output"
          },
          {
            "from": "candidate-projection",
            "to": "board-output",
            "kind": "backward",
            "label": "VJP through board context projected to 192 channels",
            "source": {
              "path": "model/encoder.py",
              "line": 847
            },
            "id": "actor-backward-candidate-projection-board-output"
          },
          {
            "from": "belief-readouts",
            "to": "belief-refinement",
            "kind": "backward",
            "label": "VJP through shared 512-channel board representation",
            "source": {
              "path": "model/beliefs.py",
              "line": 458
            },
            "id": "actor-backward-belief-readouts-belief-refinement"
          },
          {
            "from": "tile-tokenization",
            "to": "belief-refinement",
            "kind": "backward",
            "label": "VJP through three opponent context slices",
            "source": {
              "path": "model/beliefs.py",
              "line": 241
            },
            "id": "actor-backward-tile-tokenization-belief-refinement"
          },
          {
            "from": "tile-tokenization",
            "to": "belief-readouts",
            "kind": "stop",
            "label": "Detached initial shanten, conditional improving and count probabilities",
            "source": {
              "path": "model/beliefs.py",
              "line": 207
            },
            "id": "actor-stop-tile-tokenization-belief-readouts"
          },
          {
            "from": "tile-attention-0",
            "to": "tile-tokenization",
            "kind": "backward",
            "label": "VJP through 34 tokens per opponent",
            "source": {
              "path": "model/beliefs.py",
              "line": 252
            },
            "id": "actor-backward-tile-attention-0-tile-tokenization"
          },
          {
            "from": "tile-attention-1",
            "to": "tile-attention-0",
            "kind": "backward",
            "label": "VJP through refined token sequence",
            "source": {
              "path": "model/beliefs.py",
              "line": 261
            },
            "id": "actor-backward-tile-attention-1-tile-attention-0"
          },
          {
            "from": "tile-correction",
            "to": "tile-attention-1",
            "kind": "backward",
            "label": "VJP through final 128-channel tile tokens",
            "source": {
              "path": "model/beliefs.py",
              "line": 262
            },
            "id": "actor-backward-tile-correction-tile-attention-1"
          },
          {
            "from": "tile-correction",
            "to": "belief-readouts",
            "kind": "backward",
            "label": "VJP through initial count and ukeire logits for residual add",
            "source": {
              "path": "model/beliefs.py",
              "line": 267
            },
            "id": "actor-backward-tile-correction-belief-readouts"
          },
          {
            "from": "belief-constraints",
            "to": "tile-correction",
            "kind": "backward",
            "label": "Gradient through the refined held-count logits",
            "source": {
              "path": "model/beliefs.py",
              "line": 473
            },
            "id": "actor-backward-belief-constraints-tile-correction"
          },
          {
            "from": "belief-constraints",
            "to": "belief-readouts",
            "kind": "backward",
            "label": "VJP through unmodified shanten logits",
            "source": {
              "path": "model/beliefs.py",
              "line": 474
            },
            "id": "actor-backward-belief-constraints-belief-readouts"
          },
          {
            "from": "candidate-ron-prediction",
            "to": "board-output",
            "kind": "backward",
            "label": "Ron eligibility gradients reach observed board",
            "source": {
              "path": "model/network.py",
              "line": 44
            },
            "id": "actor-backward-candidate-ron-prediction-board-output"
          },
          {
            "from": "actor-candidate-aux",
            "to": "candidate-projection",
            "kind": "backward",
            "label": "VJP through route prediction weights and raw candidate state",
            "source": {
              "path": "model/candidate_predictions.py",
              "line": 10
            },
            "id": "actor-backward-actor-candidate-aux-candidate-projection"
          },
          {
            "from": "actor-completion",
            "to": "belief-refinement",
            "kind": "backward",
            "label": "VJP through shared refined completion readouts",
            "source": {
              "path": "model/beliefs.py",
              "line": 458
            },
            "id": "actor-backward-actor-completion-belief-refinement"
          },
          {
            "from": "actor-final-score",
            "to": "candidate-projection",
            "kind": "stop",
            "label": "Detached raw state; policy gradients stop before shared candidate encoding",
            "source": {
              "path": "model/network.py",
              "line": 156
            },
            "id": "actor-stop-actor-final-score-candidate-projection"
          },
          {
            "from": "actor-final-score",
            "to": "candidate-ron-prediction",
            "kind": "stop",
            "label": "Detached candidate ron probabilities",
            "source": {
              "path": "model/actor.py",
              "line": 159
            },
            "id": "actor-stop-actor-final-score-candidate-ron-prediction"
          },
          {
            "from": "actor-final-score",
            "to": "actor-candidate-aux",
            "kind": "stop",
            "label": "Detached candidate route probabilities",
            "source": {
              "path": "model/actor.py",
              "line": 159
            },
            "id": "actor-stop-actor-final-score-actor-candidate-aux"
          },
          {
            "from": "actor-final-score",
            "to": "actor-candidate-pool",
            "kind": "backward",
            "label": "VJP through 768-channel gathered policy context",
            "source": {
              "path": "model/actor.py",
              "line": 530
            },
            "id": "actor-backward-actor-final-score-actor-candidate-pool"
          },
          {
            "from": "actor-win",
            "to": "actor-candidate-pool",
            "kind": "backward",
            "label": "VJP through private actor board and predictive context",
            "source": {
              "path": "model/actor.py",
              "line": 530
            },
            "id": "actor-backward-actor-win-actor-candidate-pool"
          },
          {
            "from": "critic-state-assembly",
            "to": "actor-candidate-aux",
            "kind": "stop",
            "label": "Detached route probabilities in the settlement state",
            "source": {
              "path": "model/network.py",
              "line": 208
            },
            "id": "actor-stop-critic-state-assembly-actor-candidate-aux"
          },
          {
            "from": "actor-objective",
            "to": "continuation-payoffs",
            "kind": "stop",
            "label": "Q is a detached coefficient; only current policy mass differentiates",
            "source": {
              "path": "training/corrections/trainer.py",
              "line": 13
            },
            "id": "actor-stop-actor-objective-continuation-payoffs"
          },
          {
            "from": "actor-objective",
            "to": "actor-final-score",
            "kind": "backward",
            "label": "Policy gain and current-policy KL derivatives",
            "source": {
              "path": "training/corrections/trainer.py",
              "line": 52
            },
            "id": "actor-backward-actor-objective-actor-final-score"
          },
          {
            "from": "actor-objective",
            "to": "actor-win",
            "kind": "backward",
            "label": "Current-policy KL only; WIN candidate-mass Q gain cancels",
            "source": {
              "path": "training/corrections/trainer.py",
              "line": 52
            },
            "id": "actor-backward-actor-objective-actor-win"
          },
          {
            "from": "actor-objective",
            "to": "tile-correction",
            "kind": "backward",
            "label": "Direct supervised improving-tile loss and weighted raw count-constraint gradient",
            "source": {
              "path": "training/corrections/trainer.py",
              "line": 52
            },
            "id": "actor-backward-actor-objective-tile-correction"
          },
          {
            "from": "actor-objective",
            "to": "belief-readouts",
            "kind": "backward",
            "label": "0.01 raw shanten/count constraint gradients",
            "source": {
              "path": "training/corrections/trainer.py",
              "line": 52
            },
            "id": "actor-backward-actor-objective-belief-readouts"
          },
          {
            "from": "belief-refinement",
            "to": "board-output",
            "kind": "backward",
            "label": "Residual identity plus refinement-branch VJP",
            "source": {
              "path": "model/beliefs.py",
              "line": 451
            },
            "id": "actor-backward-belief-refinement-board-output"
          },
          {
            "from": "critic-common-projection",
            "to": "critic-state-assembly",
            "label": "Q evaluation detaches the assembled candidate state.",
            "kind": "stop",
            "source": {
              "path": "training/trainer.py",
              "line": 47
            },
            "id": "actor-stop-critic-common-projection-critic-state-assembly"
          },
          {
            "from": "critic-player-projection",
            "to": "critic-state-assembly",
            "label": "Q evaluation detaches the assembled candidate state.",
            "kind": "stop",
            "source": {
              "path": "training/trainer.py",
              "line": 47
            },
            "id": "actor-stop-critic-player-projection-critic-state-assembly"
          },
          {
            "from": "critic-belief-uncertainty",
            "to": "critic-state-assembly",
            "label": "Q evaluation detaches the assembled candidate state.",
            "kind": "stop",
            "source": {
              "path": "training/trainer.py",
              "line": 47
            },
            "id": "actor-stop-critic-belief-uncertainty-critic-state-assembly"
          },
          {
            "from": "call-choice",
            "to": "actor-candidate-pool",
            "label": "VJP through private actor board and predictive context",
            "kind": "backward",
            "source": {
              "path": "model/actor.py",
              "line": 530
            },
            "id": "actor-backward-call-choice-actor-candidate-pool"
          },
          {
            "from": "call-factorization",
            "to": "call-choice",
            "label": "Response-policy gradient through normalized six-way branch probabilities",
            "kind": "backward",
            "source": {
              "path": "model/actor.py",
              "line": 562
            },
            "id": "actor-backward-call-factorization-call-choice"
          },
          {
            "from": "call-factorization",
            "to": "actor-final-score",
            "label": "Response-policy gradient through ordinary shared follow-up discard probabilities",
            "kind": "backward",
            "source": {
              "path": "model/actor.py",
              "line": 535
            },
            "id": "actor-backward-call-factorization-actor-final-score"
          },
          {
            "from": "actor-objective",
            "to": "call-factorization",
            "label": "Response-phase full joint-policy KL and detached-Q policy gain",
            "kind": "backward",
            "source": {
              "path": "training/corrections/trainer.py",
              "line": 52
            },
            "id": "actor-backward-actor-objective-call-factorization"
          },
          {
            "from": "actor-policy-context",
            "to": "actor-board-output",
            "kind": "backward",
            "label": "Policy gradients train the private actor encoder",
            "source": {
              "path": "model/network.py",
              "line": 22
            },
            "id": "actor-backward-actor-policy-context-actor-board-output"
          },
          {
            "from": "hand-tokenization",
            "to": "table-conditioning",
            "kind": "backward",
            "label": "VJP through table offset added before first hand GELU",
            "source": {
              "path": "model/encoder.py",
              "line": 339
            },
            "id": "actor-backward-hand-tokenization-table-conditioning"
          },
          {
            "from": "actor-policy-context",
            "to": "shared-probabilities",
            "kind": "stop",
            "label": "Detached policy belief and completion probabilities",
            "source": {
              "path": "model/network.py",
              "line": 34
            },
            "id": "actor-stop-actor-policy-context-shared-probabilities"
          },
          {
            "from": "candidate-ron-prediction",
            "to": "structural-wait",
            "label": "Detached structural wait in candidate ron",
            "kind": "stop",
            "source": {
              "path": "model/candidate_predictions.py",
              "line": 36
            },
            "id": "actor-stop-candidate-ron-prediction-structural-wait"
          },
          {
            "from": "belief-readouts",
            "to": "river-summaries",
            "kind": "backward",
            "label": "Shared shanten derivative into opponent-local river summaries",
            "source": {
              "path": "model/beliefs.py",
              "line": 291
            },
            "id": "actor-backward-belief-readouts-river-summaries"
          },
          {
            "from": "completion-evidence",
            "to": "belief-constraints",
            "kind": "stop",
            "label": "Detached projected held counts",
            "source": {
              "path": "model/beliefs.py",
              "line": 529
            },
            "id": "actor-stop-completion-evidence-belief-constraints"
          },
          {
            "from": "completion-evidence",
            "to": "river-summaries",
            "kind": "backward",
            "label": "Completion evidence VJP: Aligned per-opponent river summary 256",
            "source": {
              "path": "model/beliefs.py",
              "line": 336
            },
            "id": "actor-backward-completion-evidence-river-summaries"
          },
          {
            "from": "actor-completion",
            "to": "completion-evidence",
            "kind": "backward",
            "label": "Completion evidence VJP: Opponent-only 46 yaku +76 score residual before support",
            "source": {
              "path": "model/beliefs.py",
              "line": 336
            },
            "id": "actor-backward-actor-completion-completion-evidence"
          },
          {
            "from": "actor-objective",
            "to": "belief-constraints",
            "kind": "backward",
            "label": "Direct supervised shanten and projected held-count losses",
            "source": {
              "path": "training/auxiliary.py",
              "line": 18
            },
            "id": "actor-backward-actor-objective-belief-constraints"
          },
          {
            "from": "actor-objective",
            "to": "actor-completion",
            "kind": "backward",
            "label": "Observed completion yaku and score losses and belief-owned structural constraint",
            "source": {
              "path": "training/auxiliary.py",
              "line": 18
            },
            "id": "actor-backward-actor-objective-actor-completion"
          },
          {
            "from": "actor-objective",
            "to": "actor-candidate-aux",
            "kind": "backward",
            "label": "Observed candidate route loss and belief-owned structural constraint",
            "source": {
              "path": "training/auxiliary.py",
              "line": 18
            },
            "id": "actor-backward-actor-objective-actor-candidate-aux"
          },
          {
            "from": "actor-objective",
            "to": "candidate-ron-prediction",
            "kind": "backward",
            "label": "Observed candidate ron loss",
            "source": {
              "path": "training/auxiliary.py",
              "line": 18
            },
            "id": "actor-backward-actor-objective-candidate-ron-prediction"
          },
          {
            "from": "table-conditioning",
            "to": "shared-public-context",
            "kind": "backward",
            "label": "VJP through shared-context hand projection",
            "source": {
              "path": "model/encoder.py",
              "line": 339
            },
            "id": "actor-backward-table-conditioning-shared-public-context"
          },
          {
            "from": "board-input-projection",
            "to": "shared-public-context",
            "kind": "backward",
            "label": "VJP through shared context in joint fusion",
            "source": {
              "path": "model/encoder.py",
              "line": 869
            },
            "id": "actor-backward-board-input-projection-shared-public-context"
          },
          {
            "from": "river-attention",
            "to": "river-conv-2",
            "kind": "backward",
            "label": "VJP through observed-event attention residual",
            "source": {
              "path": "model/river_attention.py",
              "line": 44
            },
            "id": "actor-backward-river-attention-river-conv-2"
          },
          {
            "from": "actor-refinement",
            "to": "actor-policy-context",
            "kind": "backward",
            "label": "VJP through private actor refinement",
            "source": {
              "path": "model/network.py",
              "line": 108
            },
            "id": "actor-backward-actor-refinement-actor-policy-context"
          },
          {
            "from": "hand-tokenization",
            "to": "shared-tile-projection",
            "kind": "backward",
            "label": "VJP into the shared tile-identity weights",
            "source": {
              "path": "model/encoder.py",
              "line": 278
            },
            "id": "actor-backward-hand-tokenization-shared-tile-projection"
          },
          {
            "from": "river-tokenization",
            "to": "shared-tile-projection",
            "kind": "backward",
            "label": "VJP into the shared tile-identity weights",
            "source": {
              "path": "model/encoder.py",
              "line": 503
            },
            "id": "actor-backward-river-tokenization-shared-tile-projection"
          },
          {
            "from": "shared-public-context",
            "to": "shared-tile-projection",
            "kind": "backward",
            "label": "VJP into the shared tile-identity weights",
            "source": {
              "path": "model/input_features.py",
              "line": 304
            },
            "id": "actor-backward-shared-public-context-shared-tile-projection"
          },
          {
            "from": "candidate-projection",
            "to": "shared-tile-projection",
            "kind": "backward",
            "label": "VJP into the shared tile-identity weights",
            "source": {
              "path": "model/encoder.py",
              "line": 823
            },
            "id": "actor-backward-candidate-projection-shared-tile-projection"
          },
          {
            "from": "actor-board-input-projection",
            "to": "shared-public-context",
            "kind": "stop",
            "label": "Policy gradients stop before shared lower encodings",
            "source": {
              "path": "model/encoder.py",
              "line": 937
            },
            "id": "actor-stop-actor-board-input-projection-shared-public-context"
          },
          {
            "from": "actor-board-input-projection",
            "to": "hand-bank-output",
            "kind": "stop",
            "label": "Policy gradients stop before shared lower encodings",
            "source": {
              "path": "model/encoder.py",
              "line": 937
            },
            "id": "actor-stop-actor-board-input-projection-hand-bank-output"
          },
          {
            "from": "actor-board-block-0",
            "to": "actor-board-input-projection",
            "kind": "backward",
            "label": "Private actor branch gradient",
            "source": {
              "path": "model/encoder.py",
              "line": 869
            },
            "id": "actor-backward-actor-board-block-0-actor-board-input-projection"
          },
          {
            "from": "actor-board-block-1",
            "to": "actor-board-block-0",
            "kind": "backward",
            "label": "Private actor branch gradient",
            "source": {
              "path": "model/encoder.py",
              "line": 890
            },
            "id": "actor-backward-actor-board-block-1-actor-board-block-0"
          },
          {
            "from": "actor-board-block-2",
            "to": "actor-board-block-1",
            "kind": "backward",
            "label": "Private actor branch gradient",
            "source": {
              "path": "model/encoder.py",
              "line": 890
            },
            "id": "actor-backward-actor-board-block-2-actor-board-block-1"
          },
          {
            "from": "actor-board-output",
            "to": "actor-board-block-2",
            "kind": "backward",
            "label": "Private actor branch gradient",
            "source": {
              "path": "model/encoder.py",
              "line": 894
            },
            "id": "actor-backward-actor-board-output-actor-board-block-2"
          },
          {
            "from": "actor-refinement-1",
            "to": "actor-refinement",
            "kind": "backward",
            "label": "Private actor branch gradient",
            "source": {
              "path": "model/network.py",
              "line": 108
            },
            "id": "actor-backward-actor-refinement-1-actor-refinement"
          },
          {
            "from": "candidate-ron-prediction",
            "to": "completion-evidence",
            "kind": "backward",
            "label": "Ron eligibility trains opponent evidence hidden state",
            "source": {
              "path": "model/network.py",
              "line": 50
            },
            "id": "actor-backward-candidate-ron-prediction-completion-evidence"
          },
          {
            "from": "candidate-ron-prediction",
            "to": "actor-completion",
            "kind": "stop",
            "label": "Detached opponent ron-yaku probabilities",
            "source": {
              "path": "model/network.py",
              "line": 50
            },
            "id": "actor-stop-candidate-ron-prediction-actor-completion"
          },
          {
            "from": "actor-candidate-pool",
            "to": "candidate-projection",
            "kind": "stop",
            "label": "Detached candidate inputs; actor gradients stop",
            "source": {
              "path": "model/actor.py",
              "line": 86
            },
            "id": "actor-stop-actor-candidate-pool-candidate-projection"
          },
          {
            "from": "actor-candidate-pool",
            "to": "actor-refinement-1",
            "kind": "backward",
            "label": "Actor residual keeps context gradient",
            "source": {
              "path": "model/actor.py",
              "line": 530
            },
            "id": "actor-backward-actor-candidate-pool-actor-refinement-1"
          }
        ],
        "objective": {
          "id": "actor-objective",
          "title": "MMD actor pass objective",
          "description": "Optimize detached-Q policy gain, two reference-policy KL terms at 0.3 each, belief-owned constraints at 0.01 and seven supervised belief losses.",
          "equations": [
            {
              "topic": "mmd",
              "equations": [
                0,
                1,
                2,
                4,
                5
              ]
            }
          ],
          "source": {
            "path": "training/corrections/trainer.py",
            "line": 52
          }
        },
        "notes": [
          "Belief supervision and belief-owned constraints train shared hand, river, board and candidate representations. Settlement also trains them during the critic phase; policy gradients stop at shared outputs.",
          "Private actor weights train from policy CE or MMD. Settlement trains private critic layers and shared representations. Prediction consumers and actor Q remain detached.",
          "Detached Q is a coefficient in ∇θρ: the expected-value gradient is −Σc stop_gradient(Qc)∇θρc.",
          "Critic-private parameters receive no actor update. Shared representation updates can alter subsequent critic predictions despite the detached evaluation path.",
          "The previous-policy expected-Q contribution is constant with respect to current parameters. Both KL terms differentiate only the current distribution.",
          "WIN maps current and previous policies to the same Dirac mass at candidate 260; the Q-gain gradient vanishes for that phase, while head-level KL gradients remain.",
          "Shanten, conditional improving tiles, held counts, completion yaku, completion score, candidate route and ron each have a unit-weight loss on their own known eligible targets.",
          "The fixed continuation constants and production SavedModel parameters are excluded from both improvement optimizers.",
          "Mirror and production policies consume the same public inputs. Their input edges are omitted; their detached output dependencies are explicit.",
          "Map arrows are phase-specific structural VJPs, not measured gradient magnitudes or a claim that every row activates every branch.",
          "No backward arrows follow native masks, public tensors or selected candidate indices. Grouped blocks may contain both connected and disconnected operators; their descriptions identify partial paths.",
          "Directly supervised predictions train shared encodings. Hypothetical children inherit observed opponent predictions; their completion and route features follow the local hand. Belief-owned penalties retain gradients to their own heads and encoder.",
          "Single-choice rows and committed riichi discard rows are ineligible for every loss. An ordinary dama discard counts when the player still has a choice."
        ],
        "source": {
          "path": "training/corrections/trainer.py",
          "line": 52
        }
      }
    ],
    "heads": [
      {
        "id": "head-shanten",
        "tensor": "opponent_shanten_logits",
        "title": "Opponent shanten",
        "parent": "belief-constraints",
        "head": true,
        "kind": "learned head",
        "input_shape": "512 board + 305 opponent channels, then public support",
        "shape": "3 × 4",
        "description": "Shared four-class shanten prediction conditioned on opponent-local public evidence and existing river summaries.",
        "sharing": "Same board/observation/readout weights across all three opponents; local inputs differ.",
        "supervision": "Observed opponent shanten targets on eligible labeled decisions in weighted imitation, critic fitting and MMD.",
        "gradients": {
          "actor": {
            "status": "trainable",
            "description": "Direct opponent shanten loss. Downstream consumers read detached predictions. Raw logits also receive structural constraints."
          },
          "critic": {
            "status": "trainable",
            "description": "Direct opponent shanten loss. Downstream consumers read detached predictions."
          },
          "imitation": {
            "status": "trainable",
            "description": "Direct opponent shanten loss. Downstream consumers read detached predictions."
          }
        },
        "source": {
          "path": "model/beliefs.py",
          "line": 276
        },
        "equations": [
          {
            "topic": "shared-opponent-shanten",
            "equations": [
              0
            ]
          }
        ],
        "notes": [
          "Opponent axes have size 3. Shanten has 4 classes; improving-tile predictions have 34 tile types per shanten class; held-count predictions use 37 tile/red channels and 5 count classes, 0 through 4."
        ],
        "inputs": [
          {
            "nodes": [
              "belief-refinement"
            ],
            "title": "Refined board state",
            "detail": "A 512-channel board vector supplies a shared 48-channel prior for all three opponents.",
            "source": {
              "path": "model/beliefs.py",
              "line": 332
            }
          },
          {
            "nodes": [
              "river-summaries"
            ],
            "title": "Opponent river summary",
            "detail": "Each opponent contributes their own 256-channel river vector to the observation projection.",
            "source": {
              "path": "model/beliefs.py",
              "line": 291
            }
          },
          {
            "fields": [
              "meld_tiles",
              "dealer_relative_seat",
              "riichi_state",
              "opponent_discard_count",
              "live_wall_count",
              "last_tedashi_tile_id"
            ],
            "title": "Public shanten evidence",
            "detail": "The readout uses meld count, dealer flag, riichi, discard count, live wall and last tedashi. Declared riichi or four melds also forces tenpai.",
            "source": {
              "path": "model/beliefs.py",
              "line": 289
            },
            "decision_only": true,
            "nodes": [
              "inputs-parent-table",
              "inputs-parent-opponents"
            ]
          }
        ],
        "forward_uses": {
          "belief": [
            {
              "title": "Candidate ron risk",
              "node": "candidate_ron_logits",
              "via": [
                "structural wait"
              ]
            }
          ],
          "actor": [
            {
              "title": "Policy context",
              "node": "policy_context",
              "via": []
            },
            {
              "title": "Policy context",
              "node": "policy_context",
              "via": [
                "shanten-weighted ukeire"
              ]
            }
          ],
          "critic": [
            {
              "title": "Settlement state",
              "node": "critic_state",
              "via": []
            }
          ]
        },
        "output_name": "opponent_shanten_logits",
        "consumers": [
          {
            "title": "Structural wait",
            "link": "#architecture/head-structural-wait"
          },
          {
            "title": "Shanten-weighted ukeire",
            "link": "#architecture/actor-policy-context"
          },
          {
            "title": "Policy context",
            "link": "#architecture/actor-policy-context"
          },
          {
            "title": "Settlement state",
            "link": "#architecture/critic-state-assembly"
          }
        ]
      },
      {
        "id": "head-ukeire",
        "tensor": "opponent_ukeire_by_shanten_logits",
        "title": "Conditional ukeire",
        "parent": "tile-correction",
        "head": true,
        "kind": "learned head",
        "input_shape": "512 board readout + per-tile attention correction",
        "shape": "3 × 4 × 34",
        "description": "The base readout and the tile-attention residual together predict improving tiles conditional on each shanten class.",
        "sharing": "Independent opponent/class/tile coefficients; actor/critic share predictions.",
        "supervision": "Observed conditional improving tiles targets on eligible labeled decisions in weighted imitation, critic fitting and MMD.",
        "gradients": {
          "actor": {
            "status": "trainable",
            "description": "Direct conditional improving tiles loss. Downstream consumers read detached predictions."
          },
          "critic": {
            "status": "trainable",
            "description": "Direct conditional improving tiles loss. Downstream consumers read detached predictions."
          },
          "imitation": {
            "status": "trainable",
            "description": "Direct conditional improving tiles loss. Downstream consumers read detached predictions."
          }
        },
        "source": {
          "path": "model/beliefs.py",
          "line": 424
        },
        "equations": [
          {
            "topic": "policy-readouts",
            "equations": [
              0
            ]
          }
        ],
        "notes": [
          "Opponent axes have size 3. Shanten has 4 classes; improving-tile predictions have 34 tile types per shanten class; held-count predictions use 37 tile/red channels and 5 count classes, 0 through 4."
        ],
        "inputs": [
          {
            "nodes": [
              "belief-readouts"
            ],
            "title": "Initial improving-tile logits",
            "detail": "A Dense readout of the refined board supplies a trainable base for each opponent, shanten class and tile.",
            "source": {
              "path": "model/beliefs.py",
              "line": 272
            }
          },
          {
            "nodes": [
              "tile-attention-1"
            ],
            "title": "Tile-attention correction",
            "detail": "The final tile tokens combine board context, tile identity and public copy bounds with detached initial shanten, improving-tile and count estimates. A learned residual corrects each base logit.",
            "source": {
              "path": "model/beliefs.py",
              "line": 262
            }
          }
        ],
        "forward_uses": {
          "belief": [
            {
              "title": "Candidate ron risk",
              "node": "candidate_ron_logits",
              "via": [
                "structural wait"
              ]
            }
          ],
          "actor": [
            {
              "title": "Policy context",
              "node": "policy_context",
              "via": [
                "shanten-weighted ukeire"
              ]
            }
          ],
          "critic": [
            {
              "title": "Settlement state",
              "node": "critic_state",
              "via": []
            }
          ]
        },
        "output_name": "opponent_ukeire_by_shanten_logits",
        "consumers": [
          {
            "title": "Structural wait",
            "link": "#architecture/head-structural-wait"
          },
          {
            "title": "Shanten-weighted ukeire",
            "link": "#architecture/actor-policy-context"
          },
          {
            "title": "Settlement state",
            "link": "#architecture/critic-state-assembly"
          }
        ]
      },
      {
        "id": "head-counts",
        "tensor": "opponent_hand_count_logits",
        "title": "Opponent tile counts",
        "parent": "belief-constraints",
        "head": true,
        "kind": "learned head",
        "input_shape": "512 board readout + per-tile correction, then public count projection",
        "shape": "3 × 37 × 5",
        "description": "Categorical held-count logits constrained by public tile support.",
        "sharing": "Independent opponent/tile/count coefficients; actor/critic share predictions.",
        "supervision": "Observed opponent held counts targets on eligible labeled decisions in weighted imitation, critic fitting and MMD.",
        "gradients": {
          "actor": {
            "status": "trainable",
            "description": "Direct opponent held counts loss. Downstream consumers read detached predictions. Raw logits also receive structural constraints."
          },
          "critic": {
            "status": "trainable",
            "description": "Direct opponent held counts loss. Downstream consumers read detached predictions."
          },
          "imitation": {
            "status": "trainable",
            "description": "Direct opponent held counts loss. Downstream consumers read detached predictions."
          }
        },
        "source": {
          "path": "model/beliefs.py",
          "line": 424
        },
        "equations": [
          {
            "topic": "policy-readouts",
            "equations": [
              0
            ]
          }
        ],
        "notes": [
          "Opponent axes have size 3. Shanten has 4 classes; improving-tile predictions have 34 tile types per shanten class; held-count predictions use 37 tile/red channels and 5 count classes, 0 through 4."
        ],
        "inputs": [
          {
            "nodes": [
              "belief-readouts"
            ],
            "title": "Initial tile-count logits",
            "detail": "A Dense readout of the refined board supplies trainable count logits for ordinary and red tiles.",
            "source": {
              "path": "model/beliefs.py",
              "line": 468
            }
          },
          {
            "nodes": [
              "tile-attention-1"
            ],
            "title": "Tile-attention correction",
            "detail": "The final tile tokens combine board context, tile identity and public copy bounds with detached initial shanten, improving-tile and count estimates. A learned residual corrects each base logit.",
            "source": {
              "path": "model/beliefs.py",
              "line": 262
            }
          },
          {
            "fields": [
              "meld_tiles",
              "known_unavailable_counts",
              "candidate_hand_red",
              "public_visible_red_counts"
            ],
            "title": "Public tile supply and hand sizes",
            "detail": "Exposed melds bound each count. Remaining ordinary and red copies and concealed hand sizes constrain the joint projection across opponents.",
            "source": {
              "path": "model/beliefs.py",
              "line": 595
            },
            "decision_only": true,
            "nodes": [
              "inputs-parent-hand",
              "inputs-parent-table"
            ]
          },
          {
            "fields": [
              "dora_multiplicity",
              "seat_wind",
              "prevailing_wind"
            ],
            "title": "Projection weights",
            "detail": "Dora, red fives and value honors determine the relative cost of moving each count marginal.",
            "source": {
              "path": "model/beliefs.py",
              "line": 597
            },
            "decision_only": true,
            "nodes": [
              "inputs-parent-table"
            ]
          }
        ],
        "forward_uses": {
          "belief": [
            {
              "title": "Completion yaku",
              "node": "round_completion_yaku_logits",
              "via": []
            },
            {
              "title": "Ron eligibility",
              "node": "ron_eligibility_logits",
              "via": []
            }
          ],
          "actor": [
            {
              "title": "Policy context",
              "node": "policy_context",
              "via": []
            }
          ],
          "critic": [
            {
              "title": "Settlement state",
              "node": "critic_state",
              "via": []
            }
          ]
        },
        "output_name": "opponent_hand_count_logits",
        "consumers": [
          {
            "title": "Completion yaku",
            "link": "#architecture/head-completion-yaku"
          },
          {
            "title": "Ron eligibility",
            "link": "#architecture/head-ron-eligibility"
          },
          {
            "title": "Policy context",
            "link": "#architecture/actor-policy-context"
          },
          {
            "title": "Settlement state",
            "link": "#architecture/critic-state-assembly"
          }
        ]
      },
      {
        "id": "head-completion-yaku",
        "tensor": "round_completion_yaku_logits",
        "title": "Completion yaku",
        "parent": "actor-completion",
        "head": true,
        "kind": "learned head",
        "input_shape": "Base readout: refined latent 512; opponent-only residual: evidence 33 + river 256",
        "shape": "4 × 2 × 23",
        "description": "Independent binary logits per player, win kind and 23 yaku categories. Opponent logits add the shared completion-evidence residual before constraints; self uses its base logits.",
        "sharing": "Same prediction used by actor and critic; independent output coefficients per player and win kind. One additional residual map is shared across opponents.",
        "supervision": "Observed next-tenpai completion yaku targets on eligible labeled decisions in weighted imitation, critic fitting and MMD.",
        "gradients": {
          "actor": {
            "status": "trainable",
            "description": "Direct next-tenpai completion yaku loss. Downstream consumers read detached predictions. Raw logits also receive structural constraints."
          },
          "critic": {
            "status": "trainable",
            "description": "Direct next-tenpai completion yaku loss. Downstream consumers read detached predictions."
          },
          "imitation": {
            "status": "trainable",
            "description": "Direct next-tenpai completion yaku loss. Downstream consumers read detached predictions."
          }
        },
        "source": {
          "path": "model/beliefs.py",
          "line": 458
        },
        "equations": [
          {
            "topic": "policy-readouts",
            "equations": [
              0
            ]
          },
          {
            "topic": "completion-evidence",
            "equations": [
              1
            ]
          }
        ],
        "inputs": [
          {
            "nodes": [
              "belief-refinement"
            ],
            "title": "Refined board state",
            "detail": "The 512-channel board vector supplies the base logits for self and all three opponents, for ron and tsumo.",
            "source": {
              "path": "model/beliefs.py",
              "line": 518
            }
          },
          {
            "nodes": [
              "head-counts"
            ],
            "via": [
              "completion-evidence"
            ],
            "title": "Opponent tile counts",
            "detail": "Expected physical tile counts supply suit, dora and red-five summaries to the opponent-only residual.",
            "detached": true,
            "source": {
              "path": "model/beliefs.py",
              "line": 529
            }
          },
          {
            "nodes": [
              "river-summaries"
            ],
            "via": [
              "completion-evidence"
            ],
            "title": "Opponent river summary",
            "detail": "Each 256-channel river vector joins the 33 tile-summary channels for that opponent.",
            "source": {
              "path": "model/beliefs.py",
              "line": 401
            }
          },
          {
            "fields": [
              "candidate_hand_counts",
              "candidate_hand_red",
              "known_unavailable_counts",
              "public_visible_red_counts",
              "dora_multiplicity"
            ],
            "via": [
              "completion-evidence"
            ],
            "title": "Own hand and unseen tiles",
            "detail": "The current hand in slot 0, remaining tile supply and dora multiplicities contribute to the opponent-only residual.",
            "source": {
              "path": "model/beliefs.py",
              "line": 367
            },
            "nodes": [
              "inputs-parent-hand",
              "inputs-parent-table",
              "inputs-child-hand",
              "inputs-child-table"
            ]
          },
          {
            "fields": [
              "meld_tiles",
              "meld_type",
              "known_unavailable_counts",
              "candidate_hand_counts",
              "trigger_tile_id",
              "trigger_valid",
              "trigger_source",
              "seat_wind",
              "prevailing_wind"
            ],
            "title": "Public yaku support",
            "detail": "Fixed melds restrict compatible yaku. Claimable copies, the offered discard and player and round winds determine which value-honor triplets are possible.",
            "source": {
              "path": "model/payment_scoring.py",
              "line": 245
            },
            "nodes": [
              "inputs-parent-hand",
              "inputs-parent-table",
              "inputs-parent-actions",
              "inputs-child-hand",
              "inputs-child-table",
              "inputs-child-actions"
            ]
          }
        ],
        "forward_uses": {
          "belief": [
            {
              "title": "Completion potential (han/fu)",
              "node": "round_completion_score_logits",
              "via": []
            },
            {
              "title": "Ron eligibility",
              "node": "ron_eligibility_logits",
              "via": []
            }
          ],
          "actor": [
            {
              "title": "Policy context",
              "node": "policy_context",
              "via": []
            }
          ],
          "critic": [
            {
              "title": "Settlement state",
              "node": "critic_state",
              "via": []
            }
          ]
        },
        "output_name": "round_completion_yaku_logits",
        "consumers": [
          {
            "title": "Completion potential (han/fu)",
            "link": "#architecture/head-completion-score"
          },
          {
            "title": "Ron eligibility",
            "link": "#architecture/head-ron-eligibility"
          },
          {
            "title": "Policy context",
            "link": "#architecture/actor-policy-context"
          },
          {
            "title": "Settlement state",
            "link": "#architecture/critic-state-assembly"
          }
        ]
      },
      {
        "id": "head-completion-score",
        "tensor": "round_completion_score_logits",
        "title": "Completion potential (han/fu)",
        "parent": "actor-completion",
        "head": true,
        "kind": "learned head",
        "input_shape": "Refined latent 512",
        "shape": "1 × 2 × 38",
        "description": "Own-hand best ordinary finish of the next observed tenpai shape, separately for ron and tsumo. Includes actual riichi, visible dora/red and applicable menzen tsumo; excludes hypothetical ura, ippatsu and special-event bonuses. Detached probabilities feed actor and critic.",
        "sharing": "Own-seat readout, independent output coefficients per win kind.",
        "supervision": "Highest-point ordinary completion of the next observed tenpai shape; direct scorer labels in each training phase.",
        "gradients": {
          "actor": {
            "status": "trainable",
            "description": "Direct next-tenpai completion score loss. Downstream consumers read detached predictions. Raw logits also receive structural constraints."
          },
          "critic": {
            "status": "trainable",
            "description": "Direct next-tenpai completion score loss. Downstream consumers read detached predictions."
          },
          "imitation": {
            "status": "trainable",
            "description": "Direct next-tenpai completion score loss. Downstream consumers read detached predictions."
          }
        },
        "source": {
          "path": "model/beliefs.py",
          "line": 458
        },
        "equations": [
          {
            "topic": "policy-readouts",
            "equations": [
              0
            ]
          }
        ],
        "inputs": [
          {
            "nodes": [
              "belief-refinement"
            ],
            "title": "Refined board state",
            "detail": "The 512-channel board vector supplies the base logits for self and all three opponents, for ron and tsumo.",
            "source": {
              "path": "model/beliefs.py",
              "line": 518
            }
          },
          {
            "nodes": [
              "head-completion-yaku"
            ],
            "title": "Completion yaku probabilities",
            "detail": "Own-seat ron and tsumo yaku probabilities constrain the score distribution through minimum han.",
            "detached": true,
            "source": {
              "path": "model/beliefs.py",
              "line": 549
            }
          },
          {
            "fields": [
              "candidate_fu",
              "meld_tiles",
              "meld_type",
              "riichi_state",
              "public_bonus"
            ],
            "title": "Public score support",
            "detail": "Own candidate-zero fu, public melds, riichi and visible bonus han restrict the own-hand score support.",
            "source": {
              "path": "model/payment_scoring.py",
              "line": 454
            },
            "nodes": [
              "inputs-parent-table",
              "inputs-parent-hand",
              "inputs-child-table",
              "inputs-child-hand"
            ]
          }
        ],
        "forward_uses": {
          "belief": [],
          "actor": [
            {
              "title": "Policy context",
              "node": "policy_context",
              "via": []
            }
          ],
          "critic": [
            {
              "title": "Settlement state",
              "node": "critic_state",
              "via": []
            }
          ]
        },
        "output_name": "round_completion_score_logits",
        "consumers": [
          {
            "title": "Policy context",
            "link": "#architecture/actor-policy-context"
          },
          {
            "title": "Settlement state",
            "link": "#architecture/critic-state-assembly"
          }
        ]
      },
      {
        "id": "head-win",
        "output_name": "win_decision_logits",
        "consumers": [
          {
            "title": "Serving output",
            "link": "#outputs/win_decision_logits"
          }
        ],
        "title": "Win / pass",
        "parent": "actor-win",
        "head": true,
        "kind": "learned head",
        "input_shape": "768 actor board + predicted-evidence context",
        "shape": "2",
        "description": "Binary WIN/pass readout conditioned on the same predictive context as other policy branches.",
        "sharing": "One actor-only Dense 2 readout.",
        "supervision": "Supported win/pass choices train the expert policy. The MMD WIN head receives reference-policy KL.",
        "gradients": {
          "actor": {
            "status": "trainable",
            "description": "The WIN distribution receives current-policy KL. A fixed WIN candidate gives zero Q-gain derivative."
          },
          "critic": {
            "status": "disconnected",
            "description": "This head is disconnected from the critic objective and receives no update or weight decay."
          },
          "imitation": {
            "status": "trainable",
            "description": "Supported expert choices train the active policy through weighted cross-entropy."
          }
        },
        "source": {
          "path": "model/actor.py",
          "line": 204
        },
        "equations": [
          {
            "topic": "policy-readouts",
            "equations": [
              0
            ]
          }
        ],
        "inputs": [
          {
            "title": "Board and belief context",
            "detail": "The 768-channel policy context enters the two-logit win/pass readout.",
            "nodes": [
              "actor-policy-context"
            ],
            "source": {
              "path": "model/actor.py",
              "line": 204
            }
          },
          {
            "title": "Win eligibility",
            "detail": "The public win kind determines whether the win slot is legal.",
            "nodes": [
              "inputs-parent-actions"
            ],
            "source": {
              "path": "model/actions.py",
              "line": 314
            },
            "fields": [
              "win_kind"
            ]
          }
        ]
      },
      {
        "id": "head-route",
        "tensor": "route_affinity_logits",
        "title": "Candidate route affinity",
        "parent": "actor-candidate-aux",
        "head": true,
        "kind": "learned head",
        "input_shape": "384",
        "shape": "3 per selected candidate",
        "description": "Three Bernoulli route-affinity logits per candidate.",
        "sharing": "Dense 384→3 shared across candidate rows; actor/critic consume predictions.",
        "supervision": "Observed candidate route affinity targets on eligible labeled decisions in weighted imitation, critic fitting and MMD.",
        "gradients": {
          "actor": {
            "status": "trainable",
            "description": "Direct candidate route affinity loss. Downstream consumers read detached predictions. Raw logits also receive structural constraints."
          },
          "critic": {
            "status": "trainable",
            "description": "Direct candidate route affinity loss. Downstream consumers read detached predictions."
          },
          "imitation": {
            "status": "trainable",
            "description": "Direct candidate route affinity loss. Downstream consumers read detached predictions."
          }
        },
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 10
        },
        "equations": [
          {
            "topic": "policy-readouts",
            "equations": [
              0
            ]
          }
        ],
        "inputs": [
          {
            "nodes": [
              "candidate-projection"
            ],
            "title": "Raw candidate state",
            "detail": "The 384-channel candidate vector before actor-only attention supplies three learned logits. Its board and action indices select the hand for the route mask.",
            "source": {
              "path": "model/candidate_predictions.py",
              "line": 10
            }
          },
          {
            "fields": [
              "candidate_meld_tiles",
              "candidate_meld_types",
              "discard_candidate_hand",
              "kan_candidate_hand"
            ],
            "title": "Candidate melds and hand indices",
            "detail": "The discard or kan hand index selects the meld tiles and types that permit tanyao, flush and outside-hand routes.",
            "source": {
              "path": "model/candidate_predictions.py",
              "line": 69
            },
            "nodes": [
              "inputs-parent-hand",
              "inputs-parent-actions",
              "inputs-child-hand",
              "inputs-child-actions"
            ]
          }
        ],
        "forward_uses": {
          "belief": [],
          "actor": [
            {
              "title": "Discard",
              "node": "discard_policy_logits",
              "via": []
            },
            {
              "title": "Riichi",
              "node": "riichi_policy_logits",
              "via": []
            },
            {
              "title": "Kan",
              "node": "kan_action_logits",
              "via": []
            }
          ],
          "critic": [
            {
              "title": "Settlement state",
              "node": "critic_state",
              "via": []
            }
          ]
        },
        "output_name": "route_affinity_logits",
        "consumers": [
          {
            "title": "Discard",
            "link": "#architecture/head-discard"
          },
          {
            "title": "Riichi",
            "link": "#architecture/head-riichi"
          },
          {
            "title": "Kan",
            "link": "#architecture/head-kan"
          },
          {
            "title": "Settlement state",
            "link": "#architecture/critic-state-assembly"
          }
        ]
      },
      {
        "id": "head-ron-eligibility",
        "tensor": "ron_eligibility_logits",
        "title": "Ron eligibility",
        "parent": "candidate-ron-prediction",
        "head": true,
        "kind": "learned head",
        "input_shape": "3 × (board512 + yaku hidden64 + ron-yaku probabilities23)",
        "shape": "3 × 34",
        "description": "Shared opponent eligibility inferred once per observed board; hidden yaku evidence remains attached while yaku probabilities are detached. Tables are reused across ordinary, riichi and call-discard alternatives.",
        "sharing": "Shared Dense599→128 + GELU → Dense34 across the three opponents.",
        "supervision": "Observed candidate ron legality trains gathered eligibility through the supported ron product.",
        "gradients": {
          "actor": {
            "status": "trainable",
            "description": "Direct candidate ron legality loss. Downstream consumers read detached predictions."
          },
          "critic": {
            "status": "trainable",
            "description": "Direct candidate ron legality loss. Downstream consumers read detached predictions."
          },
          "imitation": {
            "status": "trainable",
            "description": "Direct candidate ron legality loss. Downstream consumers read detached predictions."
          }
        },
        "source": {
          "path": "model/network.py",
          "line": 44
        },
        "equations": [
          {
            "topic": "policy-readouts",
            "equations": [
              0
            ]
          }
        ],
        "inputs": [
          {
            "nodes": [
              "board-output"
            ],
            "title": "Observed board",
            "detail": "Current hand and observed table produce one shared opponent/tile eligibility table.",
            "source": {
              "path": "model/network.py",
              "line": 44
            }
          },
          {
            "nodes": [
              "completion-evidence"
            ],
            "title": "Opponent yaku hidden state",
            "detail": "Attached 64-channel evidence state per opponent. Ron supervision trains the hidden projection and river features directly.",
            "source": {
              "path": "model/network.py",
              "line": 50
            }
          },
          {
            "nodes": [
              "head-completion-yaku"
            ],
            "title": "Opponent ron-yaku probabilities",
            "detail": "Detached 23-category ron probabilities per opponent from the supported completion-yaku head.",
            "source": {
              "path": "model/network.py",
              "line": 50
            },
            "detached": true
          },
          {
            "nodes": [
              "head-counts"
            ],
            "via": [
              "completion-evidence"
            ],
            "title": "Detached opponent counts",
            "detail": "Count probabilities supply suit/dora/red evidence for the attached yaku hidden state; ron gradients stop at the count predictions.",
            "detached": true,
            "source": {
              "path": "model/beliefs.py",
              "line": 529
            }
          }
        ],
        "forward_uses": {
          "belief": [
            {
              "title": "Candidate ron risk",
              "node": "candidate_ron_logits",
              "via": []
            }
          ],
          "actor": [],
          "critic": []
        },
        "output_name": "ron_eligibility_logits",
        "consumers": [
          {
            "title": "Candidate ron risk",
            "link": "#architecture/head-ron"
          }
        ]
      },
      {
        "id": "head-ron",
        "tensor": "candidate_ron_logits",
        "fixed_inputs": {
          "kan_action_logits": "fixed at zero"
        },
        "actor_support": "Ordinary, dama, declaration and post-chi/pon cuts. Guaranteed-safe tiles have zero risk.",
        "title": "Candidate ron risk",
        "parent": "candidate-ron-prediction",
        "head": true,
        "kind": "derived prediction",
        "input_shape": "3 gathered eligibility + 3 detached structural-wait logits",
        "shape": "3 per selected candidate",
        "description": "Ron probability combines the shared board/tile eligibility and structural wait with deterministic safe/discard support.",
        "sharing": "No independent weights; candidates offering the same base tile share immediate risk.",
        "supervision": "Observed candidate ron legality targets on eligible labeled decisions in weighted imitation, critic fitting and MMD.",
        "gradients": {
          "actor": {
            "status": "trainable",
            "description": "Observed ron loss differentiates through the product into eligibility and the observed board. Structural wait is detached; this product has no independent weights."
          },
          "critic": {
            "status": "trainable",
            "description": "Observed ron loss differentiates through the product into eligibility and the observed board. Structural wait is detached; this product has no independent weights."
          },
          "imitation": {
            "status": "trainable",
            "description": "Observed ron loss differentiates through the product into eligibility and the observed board. Structural wait is detached; this product has no independent weights."
          }
        },
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 25
        },
        "equations": [
          {
            "topic": "candidate-ron-factorization",
            "equations": [
              1,
              2
            ]
          }
        ],
        "inputs": [
          {
            "nodes": [
              "head-structural-wait"
            ],
            "title": "Structural wait on the offered tile",
            "detail": "The base-tile wait probability multiplies each opponent’s learned eligibility. Red and ordinary fives use the same wait.",
            "detached": true,
            "source": {
              "path": "model/candidate_predictions.py",
              "line": 36
            }
          },
          {
            "nodes": [
              "head-ron-eligibility"
            ],
            "title": "Shared tile eligibility",
            "detail": "Gather the observed-board eligibility at the discarded base tile, including across call alternatives.",
            "source": {
              "path": "model/candidate_predictions.py",
              "line": 34
            }
          },
          {
            "fields": [
              "decision_phase",
              "genbutsu_to_seat",
              "known_unavailable_counts",
              "meld_tiles"
            ],
            "title": "Discard and safe-tile masks",
            "detail": "The decision phase gates discard, dama and riichi candidates, including local post-call discards. Genbutsu and provably safe exhausted honors suppress ron.",
            "source": {
              "path": "model/candidate_predictions.py",
              "line": 47
            },
            "nodes": [
              "inputs-parent-table",
              "inputs-parent-opponents",
              "inputs-parent-actions",
              "inputs-child-table",
              "inputs-child-opponents",
              "inputs-child-actions"
            ]
          }
        ],
        "forward_uses": {
          "belief": [],
          "actor": [
            {
              "title": "Discard",
              "node": "discard_policy_logits",
              "via": []
            },
            {
              "title": "Riichi",
              "node": "riichi_policy_logits",
              "via": []
            },
            {
              "title": "Kan",
              "node": "kan_action_logits",
              "via": []
            }
          ],
          "critic": []
        },
        "output_name": "candidate_ron_logits",
        "consumers": [
          {
            "title": "Discard",
            "link": "#architecture/head-discard"
          },
          {
            "title": "Riichi",
            "link": "#architecture/head-riichi"
          },
          {
            "title": "Kan (fixed at zero)",
            "link": "#architecture/head-kan"
          }
        ]
      },
      {
        "id": "head-event",
        "output_name": "event_logits",
        "consumers": [
          {
            "title": "Joint event probability",
            "link": "#architecture/settlement-decoder"
          }
        ],
        "title": "Events + 4 nagashi",
        "parent": "critic-result-attention",
        "head": true,
        "kind": "learned readout with fixed subset expansion",
        "input_shape": "49 attended event vectors × 32 channels",
        "shape": "60 derived · 49 learned",
        "description": "The shared scalar readout produces 45 ordinary event logits and four nagashi logits. Their qualifier masks derive 15 additional combinations, giving 60 event probabilities.",
        "sharing": "Dense 32→1 shared across events after result attention.",
        "supervision": "Mixed observed settlement NLL/Q-MSE, direct per-player nagashi BCE and public support constraints.",
        "gradients": {
          "actor": {
            "status": "frozen",
            "description": "Critic parameters and Q are detached in actor updates."
          },
          "critic": {
            "status": "trainable",
            "description": "Critic likelihood/constraint gradient path."
          },
          "imitation": {
            "status": "trainable",
            "description": "Critic likelihood/constraint gradient path."
          }
        },
        "source": {
          "path": "model/critic.py",
          "line": 815
        },
        "equations": [
          {
            "topic": "result-attention",
            "equations": [
              1
            ]
          }
        ],
        "inputs": [
          {
            "title": "49 attended readout vectors",
            "detail": "The shared readout produces 45 ordinary logits and four constrained nagashi signals. Qualifier masks derive 15 nagashi event logits.",
            "nodes": [
              "critic-result-attention"
            ],
            "source": {
              "path": "model/critic.py",
              "line": 895
            }
          }
        ]
      },
      {
        "id": "head-deposit",
        "output_name": "deposit_logits",
        "consumers": [
          {
            "title": "Event-conditioned deposit probability",
            "link": "#architecture/settlement-decoder"
          }
        ],
        "title": "Deposit mask",
        "parent": "critic-deposits",
        "head": true,
        "kind": "learned head",
        "input_shape": "60 events × 16 depositor subsets × 8 channels",
        "shape": "60 × 16",
        "description": "The same 8 → 1 affine readout scores each of the 16 depositor subsets for each terminal event.",
        "sharing": "Dense 8→1 shared across event/mask pairs.",
        "supervision": "Observed compatible settlement likelihood and deposit-support constraints.",
        "gradients": {
          "actor": {
            "status": "frozen",
            "description": "Critic parameters and Q are detached in actor updates."
          },
          "critic": {
            "status": "trainable",
            "description": "Critic likelihood/constraint gradient path."
          },
          "imitation": {
            "status": "trainable",
            "description": "Critic likelihood/constraint gradient path."
          }
        },
        "source": {
          "path": "model/critic.py",
          "line": 819
        },
        "equations": [
          {
            "topic": "critic-factor-heads",
            "equations": [
              3
            ]
          }
        ],
        "inputs": [
          {
            "title": "Event-conditioned deposit vectors",
            "detail": "One shared linear readout takes eight features for each of the 60 events and 16 deposit masks. These features combine the event vector, pooled player states and fixed role counts.",
            "nodes": [
              "critic-deposits"
            ],
            "source": {
              "path": "model/critic.py",
              "line": 1092
            }
          }
        ]
      },
      {
        "id": "head-score",
        "output_name": "score_logits",
        "consumers": [
          {
            "title": "Total-score probabilities",
            "link": "#architecture/settlement-decoder"
          }
        ],
        "title": "Settlement value (han/fu)",
        "parent": "critic-score-head",
        "head": true,
        "kind": "learned head",
        "input_shape": "96 claim channels including public scoring evidence",
        "shape": "24 × 38",
        "description": "Single total han/fu distribution for each winning claim, conditioned on action, claimant, win method and public scoring evidence. Trained through observed settlement likelihood.",
        "sharing": "Dense 96→38 shared across claims.",
        "supervision": "Observed settlement likelihood marginalizes compatible score bins; support constraints.",
        "gradients": {
          "actor": {
            "status": "frozen",
            "description": "Critic parameters and Q are detached in actor updates."
          },
          "critic": {
            "status": "trainable",
            "description": "Critic likelihood/constraint gradient path."
          },
          "imitation": {
            "status": "trainable",
            "description": "Critic likelihood/constraint gradient path."
          }
        },
        "source": {
          "path": "model/critic.py",
          "line": 824
        },
        "equations": [
          {
            "topic": "critic-factor-heads",
            "equations": [
              2
            ]
          },
          {
            "topic": "payment-likelihood",
            "equations": [
              2
            ]
          }
        ],
        "inputs": [
          {
            "title": "Claim state with public scoring evidence",
            "detail": "Sixteen 96-channel claim states include public fu, bonus han, open-hand and riichi evidence.",
            "nodes": [
              "critic-claim-state"
            ],
            "source": {
              "path": "model/critic.py",
              "line": 971
            }
          },
          {
            "title": "Public fu, bonus and score support",
            "detail": "The readout also gets known meld fu. Dealer, open hand, riichi, bonus and yakuman feasibility constrain its 38 total-han/fu outcomes.",
            "nodes": [
              "inputs-parent-table",
              "inputs-parent-hand",
              "inputs-parent-actions"
            ],
            "source": {
              "path": "model/critic.py",
              "line": 972
            }
          }
        ]
      },
      {
        "id": "head-discard",
        "output_name": "discard_policy_logits",
        "consumers": [
          {
            "title": "Post-call discard distribution",
            "link": "#architecture/head-response"
          },
          {
            "title": "Active policy weights on critic candidates",
            "link": "#math/candidate-mass"
          },
          {
            "title": "Serving output",
            "link": "#outputs/discard_policy_logits"
          }
        ],
        "title": "Discard policy",
        "parent": "actor-final-score",
        "head": true,
        "kind": "shared policy branch",
        "input_shape": "295 shared candidate scores",
        "shape": "37",
        "description": "Gather and legal-mask the shared final scorer for this decision phase. No independent learned readout is added.",
        "sharing": "Discard, riichi and kan branches share the 1158→512→1 candidate scorer, also reused for follow-up discards.",
        "supervision": "Supported expert choices train the active policy with detached-Q-weighted cross-entropy. MMD uses detached-Q gain and current-policy KL.",
        "gradients": {
          "actor": {
            "status": "shared",
            "description": "Differentiates through the shared scorer when this phase is active."
          },
          "critic": {
            "status": "disconnected",
            "description": "Final policy branches are disconnected from the critic objective."
          },
          "imitation": {
            "status": "shared",
            "description": "Differentiates through the shared scorer when this phase is active."
          }
        },
        "source": {
          "path": "model/actor.py",
          "line": 192
        },
        "equations": [
          {
            "topic": "legal-policy",
            "equations": [
              0,
              1
            ]
          }
        ],
        "inputs": [
          {
            "title": "Raw candidate state",
            "detail": "The scorer reads detached 384-channel local candidate states. Legal-set pooling separately conditions actor context.",
            "nodes": [
              "candidate-projection"
            ],
            "source": {
              "path": "model/network.py",
              "line": 156
            }
          },
          {
            "title": "Policy context",
            "detail": "The 768-channel actor context queries detached legal candidates through 128-channel attention and receives the projected weighted-value residual.",
            "nodes": [
              "actor-policy-context",
              "actor-candidate-pool"
            ],
            "source": {
              "path": "model/actor.py",
              "line": 320
            }
          },
          {
            "title": "Route affinity",
            "detail": "Three detached route probabilities attach to the local candidate.",
            "nodes": [
              "head-route"
            ],
            "source": {
              "path": "model/actor.py",
              "line": 160
            },
            "detached": true
          },
          {
            "title": "Ron risk",
            "detail": "Three detached probabilities describe ron liability for the cut.",
            "nodes": [
              "head-ron"
            ],
            "source": {
              "path": "model/actor.py",
              "line": 160
            },
            "detached": true
          },
          {
            "title": "Discard support and tile evidence",
            "detail": "The local board supplies legal cuts, opening-discard symmetry and final-wall safe-cut support.",
            "nodes": [
              "inputs-parent-actions",
              "inputs-parent-hand",
              "inputs-parent-table",
              "inputs-parent-opponents",
              "inputs-child-actions",
              "inputs-child-hand",
              "inputs-child-table",
              "inputs-child-opponents"
            ],
            "source": {
              "path": "model/actor.py",
              "line": 33
            }
          }
        ]
      },
      {
        "id": "head-riichi",
        "output_name": "riichi_policy_logits",
        "consumers": [
          {
            "title": "Riichi decision marginal",
            "link": "#architecture/head-riichi_action"
          },
          {
            "title": "Active policy weights on critic candidates",
            "link": "#math/candidate-mass"
          },
          {
            "title": "Serving output",
            "link": "#outputs/riichi_policy_logits"
          }
        ],
        "title": "Riichi policy",
        "parent": "actor-final-score",
        "head": true,
        "kind": "shared policy branch",
        "input_shape": "295 shared candidate scores",
        "shape": "74",
        "description": "Gather and legal-mask the shared final scorer for this decision phase. No independent learned readout is added.",
        "sharing": "Discard, riichi and kan branches share the 1158→512→1 candidate scorer, also reused for follow-up discards.",
        "supervision": "Supported expert choices train the active policy with detached-Q-weighted cross-entropy. MMD uses detached-Q gain and current-policy KL.",
        "gradients": {
          "actor": {
            "status": "shared",
            "description": "Differentiates through the shared scorer when this phase is active."
          },
          "critic": {
            "status": "disconnected",
            "description": "Final policy branches are disconnected from the critic objective."
          },
          "imitation": {
            "status": "shared",
            "description": "Differentiates through the shared scorer when this phase is active."
          }
        },
        "source": {
          "path": "model/actor.py",
          "line": 192
        },
        "equations": [
          {
            "topic": "legal-policy",
            "equations": [
              0,
              1
            ]
          }
        ],
        "inputs": [
          {
            "title": "Raw candidate state",
            "detail": "The scorer reads detached 384-channel local candidate states. Legal-set pooling separately conditions actor context.",
            "nodes": [
              "candidate-projection"
            ],
            "source": {
              "path": "model/network.py",
              "line": 156
            }
          },
          {
            "title": "Policy context",
            "detail": "The 768-channel actor context queries detached legal candidates through 128-channel attention and receives the projected weighted-value residual.",
            "nodes": [
              "actor-policy-context",
              "actor-candidate-pool"
            ],
            "source": {
              "path": "model/actor.py",
              "line": 320
            }
          },
          {
            "title": "Route affinity",
            "detail": "Three detached route probabilities attach to the local candidate.",
            "nodes": [
              "head-route"
            ],
            "source": {
              "path": "model/actor.py",
              "line": 160
            },
            "detached": true
          },
          {
            "title": "Ron risk",
            "detail": "Three detached probabilities describe ron liability for the cut.",
            "nodes": [
              "head-ron"
            ],
            "source": {
              "path": "model/actor.py",
              "line": 160
            },
            "detached": true
          },
          {
            "title": "Riichi and discard support",
            "detail": "The decision position’s legal discards and declaration mask select the two 37-tile branches. The discard scorer also applies opening symmetry and the dama branch’s final-wall support.",
            "nodes": [
              "inputs-parent-actions",
              "inputs-parent-table",
              "inputs-parent-hand",
              "inputs-parent-opponents"
            ],
            "source": {
              "path": "model/actor.py",
              "line": 27
            }
          }
        ]
      },
      {
        "id": "head-response",
        "output_name": "response_policy_logits",
        "consumers": [
          {
            "title": "Call-kind marginal",
            "link": "#architecture/head-response_action"
          },
          {
            "title": "Chi-pattern marginal",
            "link": "#architecture/head-chi_pattern"
          },
          {
            "title": "Active policy weights on critic candidates",
            "link": "#math/candidate-mass"
          },
          {
            "title": "Serving output",
            "link": "#outputs/response_policy_logits"
          }
        ],
        "title": "Response policy",
        "parent": "call-factorization",
        "head": true,
        "kind": "factorized policy branch",
        "input_shape": "Original board call logits + shared follow-up discard logits",
        "shape": "150",
        "description": "Joint 150-action response distribution from a learned 6-way call choice and the ordinary discard network on accepted-call states.",
        "sharing": "Independent call-choice Dense 6; follow-up discard parameters shared with the ordinary policy.",
        "supervision": "Supported expert choices train the active policy with detached-Q-weighted cross-entropy. MMD uses detached-Q gain and current-policy KL.",
        "gradients": {
          "actor": {
            "status": "shared",
            "description": "Differentiates through the shared scorer when this phase is active."
          },
          "critic": {
            "status": "disconnected",
            "description": "Final policy branches are disconnected from the critic objective."
          },
          "imitation": {
            "status": "shared",
            "description": "Differentiates through the shared scorer when this phase is active."
          }
        },
        "source": {
          "path": "model/actor.py",
          "line": 559
        },
        "equations": [
          {
            "topic": "call-factorization",
            "equations": [
              0
            ]
          }
        ],
        "inputs": [
          {
            "title": "Call choice at the decision",
            "detail": "The original decision supplies the six branch logits, normalized over legal choices.",
            "nodes": [
              "head-call-choice"
            ],
            "source": {
              "path": "model/actor.py",
              "line": 553
            }
          },
          {
            "title": "After-call discard distribution",
            "detail": "The same discard scorer runs in each after-call position. Its 37 log probabilities describe the follow-up discard.",
            "nodes": [
              "head-discard"
            ],
            "source": {
              "path": "model/actor.py",
              "line": 535
            }
          },
          {
            "title": "Decision and call indices",
            "detail": "Owner and option scatter each follow-up discard distribution into the matching chi or pon slot for its decision.",
            "nodes": [
              "inputs-call-routing"
            ],
            "source": {
              "path": "model/actor.py",
              "line": 540
            }
          },
          {
            "title": "Response legality",
            "detail": "Pass and daiminkan support plus one 4 × 37 call-discard mask define admissible response slots. Kuikae exclusions remain specific to each call option.",
            "nodes": [
              "inputs-parent-actions"
            ],
            "source": {
              "path": "model/actor.py",
              "line": 545
            },
            "fields": [
              "response_legal_mask",
              "call_discard_legal"
            ]
          }
        ]
      },
      {
        "id": "head-kan",
        "output_name": "kan_action_logits",
        "consumers": [
          {
            "title": "Active policy weights on critic candidates",
            "link": "#math/candidate-mass"
          },
          {
            "title": "Serving output",
            "link": "#outputs/kan_action_logits"
          }
        ],
        "title": "Kan policy",
        "parent": "actor-final-score",
        "head": true,
        "kind": "shared policy branch",
        "input_shape": "295 shared candidate scores",
        "shape": "35",
        "description": "Gather and legal-mask the shared final scorer for this decision phase. No independent learned readout is added.",
        "sharing": "Discard, riichi and kan branches share the 1158→512→1 candidate scorer, also reused for follow-up discards.",
        "supervision": "Supported expert choices train the active policy with detached-Q-weighted cross-entropy. MMD uses detached-Q gain and current-policy KL.",
        "gradients": {
          "actor": {
            "status": "shared",
            "description": "Differentiates through the shared scorer when this phase is active."
          },
          "critic": {
            "status": "disconnected",
            "description": "Final policy branches are disconnected from the critic objective."
          },
          "imitation": {
            "status": "shared",
            "description": "Differentiates through the shared scorer when this phase is active."
          }
        },
        "source": {
          "path": "model/actor.py",
          "line": 192
        },
        "equations": [
          {
            "topic": "legal-policy",
            "equations": [
              0,
              1
            ]
          }
        ],
        "inputs": [
          {
            "title": "Raw candidate state",
            "detail": "The scorer reads detached 384-channel local candidate states. Legal-set pooling separately conditions actor context.",
            "nodes": [
              "candidate-projection"
            ],
            "source": {
              "path": "model/network.py",
              "line": 156
            }
          },
          {
            "title": "Policy context",
            "detail": "The 768-channel actor context queries detached legal candidates through 128-channel attention and receives the projected weighted-value residual.",
            "nodes": [
              "actor-policy-context",
              "actor-candidate-pool"
            ],
            "source": {
              "path": "model/actor.py",
              "line": 320
            }
          },
          {
            "title": "Route affinity",
            "detail": "Three detached route probabilities attach to the local candidate.",
            "nodes": [
              "head-route"
            ],
            "source": {
              "path": "model/actor.py",
              "line": 160
            },
            "detached": true
          },
          {
            "title": "Ron risk (fixed at zero)",
            "detail": "The shared scorer receives this input on kan candidates. The discard eligibility mask fixes its probability at zero.",
            "nodes": [
              "head-ron"
            ],
            "source": {
              "path": "model/candidate_predictions.py",
              "line": 47
            },
            "detached": true
          },
          {
            "title": "Legal kan options",
            "detail": "One pass slot and 34 tile types are masked by the decision position’s kan legality vector.",
            "nodes": [
              "inputs-parent-actions"
            ],
            "source": {
              "path": "model/actions.py",
              "line": 330
            }
          }
        ]
      },
      {
        "id": "head-riichi_action",
        "output_name": "riichi_action_logits",
        "consumers": [
          {
            "title": "Serving output",
            "link": "#outputs/riichi_action_logits"
          }
        ],
        "title": "Riichi decision marginal",
        "parent": "actor-final-score",
        "head": true,
        "kind": "derived marginal",
        "input_shape": "Legal policy branch log masses",
        "shape": "2",
        "description": "Deterministic log-sum-exp marginal of the normalized policy branch.",
        "sharing": "No parameters; uses the shared policy scorer through its source branch.",
        "supervision": "No separate current MMD loss; review consumers use these derived probabilities.",
        "gradients": {
          "actor": {
            "status": "deterministic",
            "description": "No separate objective originates at this serving summary; source policy branches retain their own gradients."
          },
          "critic": {
            "status": "disconnected",
            "description": "No critic objective path through serving policy marginals."
          },
          "imitation": {
            "status": "deterministic",
            "description": "No separate objective originates at this serving summary; source policy branches retain their own gradients."
          }
        },
        "source": {
          "path": "model/actor.py",
          "line": 71
        },
        "equations": [
          {
            "topic": "policy-readouts",
            "equations": [
              3
            ]
          }
        ],
        "inputs": [
          {
            "title": "Joint riichi policy",
            "detail": "Log-sum-exp across 37 cuts gives each of the two declaration choices.",
            "nodes": [
              "head-riichi"
            ],
            "source": {
              "path": "model/actor.py",
              "line": 66
            }
          }
        ]
      },
      {
        "id": "head-response_action",
        "output_name": "response_action_logits",
        "consumers": [
          {
            "title": "Serving output",
            "link": "#outputs/response_action_logits"
          }
        ],
        "title": "Call-kind marginal",
        "parent": "call-factorization",
        "head": true,
        "kind": "derived marginal",
        "input_shape": "Legal policy branch log masses",
        "shape": "4",
        "description": "Deterministic log-sum-exp marginal of the normalized policy branch.",
        "sharing": "No parameters; uses the shared policy scorer through its source branch.",
        "supervision": "No separate current MMD loss; review consumers use these derived probabilities.",
        "gradients": {
          "actor": {
            "status": "deterministic",
            "description": "No separate objective originates at this serving summary; source policy branches retain their own gradients."
          },
          "critic": {
            "status": "disconnected",
            "description": "No critic objective path through serving policy marginals."
          },
          "imitation": {
            "status": "deterministic",
            "description": "No separate objective originates at this serving summary; source policy branches retain their own gradients."
          }
        },
        "source": {
          "path": "model/actor.py",
          "line": 72
        },
        "equations": [
          {
            "topic": "policy-readouts",
            "equations": [
              3
            ]
          }
        ],
        "inputs": [
          {
            "title": "Joint response policy",
            "detail": "The pass slot, all chi cuts, all pon cuts and daiminkan slot yield four action-type logits.",
            "nodes": [
              "head-response"
            ],
            "source": {
              "path": "model/actor.py",
              "line": 72
            }
          }
        ]
      },
      {
        "id": "head-chi_pattern",
        "output_name": "chi_pattern_logits",
        "consumers": [
          {
            "title": "Serving output",
            "link": "#outputs/chi_pattern_logits"
          }
        ],
        "title": "Chi-pattern marginal",
        "parent": "call-factorization",
        "head": true,
        "kind": "derived marginal",
        "input_shape": "Legal policy branch log masses",
        "shape": "3",
        "description": "Deterministic log-sum-exp marginal of the normalized policy branch.",
        "sharing": "No parameters; uses the shared policy scorer through its source branch.",
        "supervision": "No separate current MMD loss; review consumers use these derived probabilities.",
        "gradients": {
          "actor": {
            "status": "deterministic",
            "description": "No separate objective originates at this serving summary; source policy branches retain their own gradients."
          },
          "critic": {
            "status": "disconnected",
            "description": "No critic objective path through serving policy marginals."
          },
          "imitation": {
            "status": "deterministic",
            "description": "No separate objective originates at this serving summary; source policy branches retain their own gradients."
          }
        },
        "source": {
          "path": "model/actor.py",
          "line": 81
        },
        "equations": [
          {
            "topic": "policy-readouts",
            "equations": [
              3
            ]
          }
        ],
        "inputs": [
          {
            "title": "Chi branches of the response policy",
            "detail": "Each of three chi-pattern logits sums over the 37 following discard choices.",
            "nodes": [
              "head-response"
            ],
            "source": {
              "path": "model/actor.py",
              "line": 81
            }
          }
        ]
      },
      {
        "id": "head-call-choice",
        "output_name": "call_choice",
        "consumers": [
          {
            "title": "Six-way call normalization and response composition",
            "link": "#architecture/head-response"
          }
        ],
        "title": "Call choice",
        "parent": "call-choice",
        "head": true,
        "kind": "learned head",
        "input_shape": "768 original-window actor board board + predicted-evidence context",
        "shape": "6",
        "description": "Independent learned readout for pass, three chi patterns, pon and daiminkan. Zero-initialized kernel and bias precede legal branch normalization.",
        "sharing": "One six-way readout shared across original call windows; distinct from the shared follow-up discard scorer.",
        "supervision": "Supported expert responses train the joint call policy. MMD uses joint response KL and detached-Q policy gain.",
        "gradients": {
          "actor": {
            "status": "trainable",
            "description": "The joint response policy receives MMD gain and KL gradients."
          },
          "critic": {
            "status": "disconnected",
            "description": "This head is disconnected from the critic objective and receives no update or weight decay."
          },
          "imitation": {
            "status": "trainable",
            "description": "Supported expert choices train the active policy through weighted cross-entropy."
          }
        },
        "source": {
          "path": "model/actor.py",
          "line": 423
        },
        "equations": [
          {
            "topic": "policy-readouts",
            "equations": [
              0
            ]
          }
        ],
        "inputs": [
          {
            "title": "Policy context at the decision",
            "detail": "One Dense layer on the decision position’s 768-channel policy context produces six raw branch logits. The decision phase mask is applied when building the response policy.",
            "nodes": [
              "actor-policy-context"
            ],
            "source": {
              "path": "model/actor.py",
              "line": 555
            }
          }
        ]
      },
      {
        "id": "head-structural-wait",
        "output_name": "opponent_wait_logits",
        "title": "Structural wait",
        "parent": "structural-wait",
        "head": true,
        "kind": "derived prediction",
        "input_shape": "Shanten logits +conditional improving logits",
        "shape": "3 ×34",
        "description": "Joint tenpai/improving marginal used by candidate RonRisk.",
        "sharing": "No independent weights; inherits shanten/improving heads",
        "supervision": "Derived from supervised shanten and improving-tile predictions. Candidate ron reads a detached wait.",
        "gradients": {
          "actor": {
            "status": "deterministic",
            "description": "The derived wait has no separate loss or parameters."
          },
          "critic": {
            "status": "deterministic",
            "description": "The derived wait has no separate loss or parameters."
          },
          "imitation": {
            "status": "deterministic",
            "description": "The derived wait has no separate loss or parameters."
          }
        },
        "source": {
          "path": "model/beliefs.py",
          "line": 47
        },
        "equations": [
          {
            "topic": "candidate-ron-factorization",
            "equations": [
              0
            ]
          }
        ],
        "inputs": [
          {
            "nodes": [
              "head-shanten"
            ],
            "title": "Tenpai probability",
            "detail": "The constrained shanten distribution supplies the probability of class 0 for each opponent.",
            "source": {
              "path": "model/beliefs.py",
              "line": 51
            }
          },
          {
            "nodes": [
              "head-ukeire"
            ],
            "title": "Improving tiles at tenpai",
            "detail": "The shanten-zero slice supplies the conditional probability for each of 34 tile types. Multiplying by tenpai probability gives the joint wait.",
            "source": {
              "path": "model/beliefs.py",
              "line": 52
            }
          }
        ],
        "consumers": [
          {
            "title": "Candidate ron risk",
            "link": "#architecture/head-ron"
          }
        ]
      },
      {
        "id": "head-pao",
        "output_name": "pao_logits",
        "consumers": [
          {
            "title": "Exact responsibility payments",
            "link": "#architecture/settlement-decoder"
          }
        ],
        "title": "Pao allocation",
        "parent": "critic-pao-allocation",
        "head": true,
        "kind": "learned head",
        "input_shape": "Claim96, player96 and three role flags",
        "shape": "16 × 4",
        "description": "Predict four payer allocations per claim, constrained by known responsibility and true-yakuman support.",
        "sharing": "Shared claimant, player and role projections; scalar readout tied across claims and seats.",
        "supervision": "Observed settlement likelihood through constrained true-yakuman allocation.",
        "gradients": {
          "actor": {
            "status": "frozen",
            "description": "Critic parameters and Q are detached in actor updates."
          },
          "critic": {
            "status": "trainable",
            "description": "Critic likelihood/constraint gradient path."
          },
          "imitation": {
            "status": "trainable",
            "description": "Critic likelihood/constraint gradient path."
          }
        },
        "source": {
          "path": "model/critic.py",
          "line": 820
        },
        "equations": [
          {
            "topic": "exceptional-settlement",
            "equations": [
              0
            ]
          }
        ],
        "inputs": [
          {
            "title": "Claim and responsible-player evidence",
            "detail": "Sixteen claim vectors combine with four player vectors and role flags for shared responsibility allocation.",
            "nodes": [
              "critic-claim-state",
              "critic-player-projection"
            ],
            "source": {
              "path": "model/critic.py",
              "line": 1034
            }
          },
          {
            "title": "Known responsibility and true-yakuman support",
            "detail": "Public payer, riichi and score support mask invalid responsibility allocations.",
            "nodes": [
              "inputs-parent-table",
              "inputs-parent-actions"
            ],
            "source": {
              "path": "model/critic.py",
              "line": 1070
            }
          }
        ]
      }
    ],
    "unused_inputs": [
      "riichi_legal_mask",
      "call_discard_shanten",
      "call_discard_ukeire_count",
      "call_efficiency",
      "discard_tedashi_legal",
      "post_call_riichi_legal_mask",
      "post_call_call_discard_legal",
      "post_call_call_discard_shanten",
      "post_call_call_discard_ukeire_count",
      "post_call_call_efficiency",
      "post_call_discard_tedashi_legal",
      "post_call_pao_payer"
    ],
    "parameters": 18929944,
    "actor_parameters": 6091273,
    "critic_parameters": 3357361,
    "edges": [
      {
        "from": "inputs",
        "to": "hand-bank",
        "label": "Local hand contents and tile-aligned public evidence · Yaku feasibility for each resulting hand"
      },
      {
        "from": "inputs",
        "to": "rivers",
        "label": "Pre/post-riichi tile streams and validity"
      },
      {
        "from": "inputs",
        "to": "board",
        "label": "Public fields encoded once, excluding tile-local arrays"
      },
      {
        "from": "hand-bank",
        "to": "board",
        "label": "Current hand slot 0 only: 512 channels"
      },
      {
        "from": "rivers",
        "to": "board",
        "label": "Six learned river summaries, 384 channels"
      },
      {
        "from": "inputs",
        "to": "candidates",
        "label": "Action support, gathers and structural features · Public route-support mask · Board-specific hand facts and post-call ownership indices"
      },
      {
        "from": "hand-bank",
        "to": "candidates",
        "label": "H[n,hand_index(a)]; multiple legal actions may reuse one hand"
      },
      {
        "from": "board",
        "to": "candidates",
        "label": "Same local board 512 → 192 for all local action queries · Shared board state · Reuse the shared 8-channel base-tile identity"
      },
      {
        "from": "beliefs",
        "to": "tile-attention",
        "label": "Refined three opponent context slices · Initial count, ukeire and shanten marginals · Initial count and ukeire logits for residual add"
      },
      {
        "from": "inputs",
        "to": "tile-attention",
        "label": "Known meld copies and available tile counts"
      },
      {
        "from": "tile-attention",
        "to": "beliefs",
        "label": "Refined held-count logits for public support and projection · Refined conditional improving-tile logits · Refined conditional improving-tile logits"
      },
      {
        "from": "inputs",
        "to": "beliefs",
        "label": "Meld, riichi and tile-capacity support · Public completion support · Discard and public safe-tile support · 49 opponent-local observed channels for shared shanten head · Own slot-0 hand, known supply and dora multiplicity"
      },
      {
        "from": "board",
        "to": "beliefs",
        "label": "Observed-board eligibility for each opponent/tile · Residual refinement input"
      },
      {
        "from": "candidates",
        "to": "actor",
        "label": "Detached raw candidate; policy gradients stop here · Bounded route probabilities · Detached legal local and call-plus-discard states"
      },
      {
        "from": "beliefs",
        "to": "actor",
        "label": "Bounded candidate ron probabilities · Bounded actor evidence; shanten-weighted conditional improving slices"
      },
      {
        "from": "inputs",
        "to": "actor",
        "label": "Phase legality and deterministic policy transforms · Native win/pass support · Sparse accepted-call rows and owner/option selectors · Legal call branches on the decision board · Original decision owner for each after-call position"
      },
      {
        "from": "rivers",
        "to": "player-context",
        "label": "Three 256-channel opponent river summaries"
      },
      {
        "from": "inputs",
        "to": "player-context",
        "label": "Public seat facts and action-relative roles"
      },
      {
        "from": "candidates",
        "to": "player-context",
        "label": "Original decision row and joint action after matching post-call discards"
      },
      {
        "from": "candidates",
        "to": "critic",
        "label": "Detached route probabilities for the matched action · Merged shared neural/hand/completion states; original-window public constraints join afterward"
      },
      {
        "from": "inputs",
        "to": "critic",
        "label": "Original-window deterministic public context · At-decision fu, visible meld bonus, dealer and legal score support · Public fu, bonus han, open-hand and riichi features · Known responsibility and legal claimant support"
      },
      {
        "from": "critic",
        "to": "settlement",
        "label": "Whole-event logits · Event-conditioned deposit-mask logits · Total score probabilities · Constrained true-yakuman allocation probabilities"
      },
      {
        "from": "inputs",
        "to": "settlement",
        "label": "Public legal-event and transfer constraints"
      },
      {
        "from": "settlement",
        "to": "continuation",
        "label": "Joint settlement probabilities, scores and payoff states"
      },
      {
        "from": "board",
        "to": "hand-bank",
        "label": "Reuse 512-channel public context · Reuse the shared 8-channel base-tile identity"
      },
      {
        "from": "player-context",
        "to": "critic",
        "label": "Original-window player descriptors"
      },
      {
        "from": "beliefs",
        "to": "candidates",
        "label": "Reused opponent conditional and completion probabilities"
      },
      {
        "from": "rivers",
        "to": "beliefs",
        "label": "Existing 256-channel opponent river summaries into shared shanten head · Aligned per-opponent river summary 256"
      },
      {
        "from": "inputs",
        "to": "continuation",
        "label": "Dealer, hand number and outstanding riichi deposits"
      },
      {
        "from": "board",
        "to": "rivers",
        "label": "Reuse the shared 8-channel base-tile identity"
      },
      {
        "from": "hand-bank",
        "to": "actor",
        "label": "Detached shared feature input to private actor encoder"
      },
      {
        "from": "board",
        "to": "actor",
        "label": "Detached shared feature input to private actor encoder"
      }
    ],
    "input_tensors": [
      {
        "id": "input-candidate-hand-counts",
        "name": "candidate_hand_counts",
        "title": "Candidate hand counts",
        "shape": [
          null,
          16,
          34
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-hand",
        "group": "hand-bank",
        "feature": "candidate_hand_counts",
        "description": "Integer occupancy tensor over deduplicated candidate hands and 34 ordinary tile types; red fives contribute to their ordinary type counts.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 65
        },
        "reader_areas": [
          "board",
          "belief",
          "actor",
          "critic"
        ]
      },
      {
        "id": "input-candidate-hand-red",
        "name": "candidate_hand_red",
        "title": "Candidate hand red",
        "shape": [
          null,
          16,
          3
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-hand",
        "group": "hand-bank",
        "feature": "candidate_hand_red",
        "description": "Per-candidate red-five occupancy by suit, represented separately from ordinary type counts.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 66
        },
        "reader_areas": [
          "board",
          "belief",
          "critic"
        ]
      },
      {
        "id": "input-candidate-hand-yaku-possibility",
        "name": "candidate_hand_yaku_possibility",
        "title": "Candidate hand yaku possibility",
        "shape": [
          null,
          16,
          19
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-hand",
        "group": "hand-bank",
        "feature": "candidate_hand_yaku_possibility",
        "description": "Nineteen coarse yaku-feasibility flags for each resulting hand-bank slot, combining its fixed-meld compatibility and public tile availability. They enter that hand’s readout; they are not completed-hand yaku labels.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 67
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-candidate-meld-tiles",
        "name": "candidate_meld_tiles",
        "title": "Candidate meld tiles",
        "shape": [
          null,
          16,
          4
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-hand",
        "group": "hand-bank",
        "feature": "candidate_meld_tiles",
        "description": "Compact lowest-tile code per fixed meld in each local hand.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 68
        },
        "reader_areas": [
          "board",
          "belief",
          "critic"
        ]
      },
      {
        "id": "input-candidate-meld-types",
        "name": "candidate_meld_types",
        "title": "Candidate meld types",
        "shape": [
          null,
          16,
          4
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-hand",
        "group": "hand-bank",
        "feature": "candidate_meld_types",
        "description": "Fixed-meld type aligned with candidate_meld_tiles.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 69
        },
        "reader_areas": [
          "board",
          "belief",
          "critic"
        ]
      },
      {
        "id": "input-candidate-meld-red",
        "name": "candidate_meld_red",
        "title": "Candidate meld red",
        "shape": [
          null,
          16,
          3
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-hand",
        "group": "hand-bank",
        "feature": "candidate_meld_red",
        "description": "Red-five counts by suit across each local hand’s fixed melds.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 70
        },
        "reader_areas": [
          "board",
          "critic"
        ]
      },
      {
        "id": "input-candidate-hand-valid",
        "name": "candidate_hand_valid",
        "title": "Candidate hand valid",
        "shape": [
          null,
          16
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-hand",
        "group": "hand-bank",
        "feature": "candidate_hand_valid",
        "description": "Binary occupancy mask for the 16-entry candidate-hand axis.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 71
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-discard-candidate-hand",
        "name": "discard_candidate_hand",
        "title": "Discard candidate hand",
        "shape": [
          null,
          37
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "hand-bank",
        "feature": "discard_candidate_hand",
        "description": "Gather indices from 37 discard actions into the deduplicated candidate-hand bank. Routing only; excluded from the learned board projection.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 72
        },
        "reader_areas": [
          "board",
          "belief",
          "critic"
        ]
      },
      {
        "id": "input-kan-candidate-hand",
        "name": "kan_candidate_hand",
        "title": "Kan candidate hand",
        "shape": [
          null,
          34
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "hand-bank",
        "feature": "kan_candidate_hand",
        "description": "Gather indices from tile-specific kan candidates into the candidate-hand bank. Routing only; excluded from the learned board projection.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 73
        },
        "reader_areas": [
          "board",
          "belief",
          "critic"
        ]
      },
      {
        "id": "input-river-pre-tile-id",
        "name": "river_pre_tile_id",
        "title": "River pre tile id",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_pre_tile_id",
        "description": "Pre-riichi opponent-sequence channel: ordinary tile-type IDs.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 74
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-pre-is-red",
        "name": "river_pre_is_red",
        "title": "River pre is red",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_pre_is_red",
        "description": "Pre-riichi opponent-sequence channel: binary red-five attributes.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 75
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-pre-tsumogiri",
        "name": "river_pre_tsumogiri",
        "title": "River pre tsumogiri",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_pre_tsumogiri",
        "description": "Pre-riichi opponent-sequence channel: binary draw-discard attributes.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 76
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-pre-origin",
        "name": "river_pre_origin",
        "title": "River pre origin",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_pre_origin",
        "description": "Pre-riichi opponent-sequence channel: categorical discard-origin codes.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 77
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-pre-riichi",
        "name": "river_pre_riichi",
        "title": "River pre riichi",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_pre_riichi",
        "description": "Pre-riichi opponent-sequence channel: binary declaration-discard attributes.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 78
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-pre-call-resolution",
        "name": "river_pre_call_resolution",
        "title": "River pre call resolution",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_pre_call_resolution",
        "description": "Pre-riichi opponent-sequence channel: offset categorical response-resolution codes.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 79
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-pre-caller",
        "name": "river_pre_caller",
        "title": "River pre caller",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_pre_caller",
        "description": "Pre-riichi opponent-sequence channel: offset actor-relative caller codes with separate unresolved/no-caller categories.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 80
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-pre-event-age",
        "name": "river_pre_event_age",
        "title": "River pre event age",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "float16",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_pre_event_age",
        "description": "Pre-riichi opponent-sequence channel: event-distance scalars normalized by 100 and clipped at 1.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 81
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-pre-own-gap",
        "name": "river_pre_own_gap",
        "title": "River pre own gap",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "float16",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_pre_own_gap",
        "description": "Pre-riichi opponent-sequence channel: self-discard-count differences normalized by 24 and clipped at 1.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 82
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-pre-live-wall",
        "name": "river_pre_live_wall",
        "title": "River pre live wall",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "float16",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_pre_live_wall",
        "description": "Pre-riichi opponent-sequence channel: discard-time live-wall counts normalized by 70.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 83
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-pre-current-dora-multiplicity",
        "name": "river_pre_current_dora_multiplicity",
        "title": "River pre current dora multiplicity",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_pre_current_dora_multiplicity",
        "description": "Pre-riichi opponent-sequence channel: current integer dora multiplicities.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 84
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-pre-dora-multiplicity-at-discard",
        "name": "river_pre_dora_multiplicity_at_discard",
        "title": "River pre dora multiplicity at discard",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_pre_dora_multiplicity_at_discard",
        "description": "Pre-riichi opponent-sequence channel: discard-time integer dora multiplicities.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 85
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-pre-valid",
        "name": "river_pre_valid",
        "title": "River pre valid",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_pre_valid",
        "description": "Pre-riichi opponent-sequence channel: binary sequence occupancy masks.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 86
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-post-tile-id",
        "name": "river_post_tile_id",
        "title": "River post tile id",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_post_tile_id",
        "description": "Post-riichi opponent-sequence channel: ordinary tile-type IDs.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 87
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-post-is-red",
        "name": "river_post_is_red",
        "title": "River post is red",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_post_is_red",
        "description": "Post-riichi opponent-sequence channel: binary red-five attributes.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 88
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-post-tsumogiri",
        "name": "river_post_tsumogiri",
        "title": "River post tsumogiri",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_post_tsumogiri",
        "description": "Post-riichi opponent-sequence channel: binary draw-discard attributes.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 89
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-post-origin",
        "name": "river_post_origin",
        "title": "River post origin",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_post_origin",
        "description": "Post-riichi opponent-sequence channel: categorical discard-origin codes.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 90
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-post-call-resolution",
        "name": "river_post_call_resolution",
        "title": "River post call resolution",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_post_call_resolution",
        "description": "Post-riichi opponent-sequence channel: offset categorical response-resolution codes.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 91
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-post-caller",
        "name": "river_post_caller",
        "title": "River post caller",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_post_caller",
        "description": "Post-riichi opponent-sequence channel: offset actor-relative caller codes with separate unresolved/no-caller categories.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 92
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-post-event-age",
        "name": "river_post_event_age",
        "title": "River post event age",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "float16",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_post_event_age",
        "description": "Post-riichi opponent-sequence channel: event-distance scalars normalized by 100 and clipped at 1.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 93
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-post-own-gap",
        "name": "river_post_own_gap",
        "title": "River post own gap",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "float16",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_post_own_gap",
        "description": "Post-riichi opponent-sequence channel: self-discard-count differences normalized by 24 and clipped at 1.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 94
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-post-live-wall",
        "name": "river_post_live_wall",
        "title": "River post live wall",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "float16",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_post_live_wall",
        "description": "Post-riichi opponent-sequence channel: discard-time live-wall counts normalized by 70.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 95
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-post-current-dora-multiplicity",
        "name": "river_post_current_dora_multiplicity",
        "title": "River post current dora multiplicity",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_post_current_dora_multiplicity",
        "description": "Post-riichi opponent-sequence channel: current integer dora multiplicities.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 96
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-post-dora-multiplicity-at-discard",
        "name": "river_post_dora_multiplicity_at_discard",
        "title": "River post dora multiplicity at discard",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_post_dora_multiplicity_at_discard",
        "description": "Post-riichi opponent-sequence channel: discard-time integer dora multiplicities.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 97
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-river-post-valid",
        "name": "river_post_valid",
        "title": "River post valid",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "rivers",
        "feature": "river_post_valid",
        "description": "Post-riichi opponent-sequence channel: binary sequence occupancy masks.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 98
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-meld-type",
        "name": "meld_type",
        "title": "Meld type",
        "shape": [
          null,
          4,
          4
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "melds",
        "feature": "meld_type",
        "description": "Categorical observed-meld kind with zero padding, indexed by relative player and meld slot.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 99
        },
        "reader_areas": [
          "board",
          "belief",
          "critic"
        ]
      },
      {
        "id": "input-meld-tiles",
        "name": "meld_tiles",
        "title": "Meld tiles",
        "shape": [
          null,
          4,
          4,
          4
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "melds",
        "feature": "meld_tiles",
        "description": "Public meld constituent codes; reconstruct ordinary IDs, red flags and valid flags.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 68
        },
        "reader_areas": [
          "board",
          "belief",
          "actor",
          "critic"
        ]
      },
      {
        "id": "input-meld-source",
        "name": "meld_source",
        "title": "Meld source",
        "shape": [
          null,
          4,
          4
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "melds",
        "feature": "meld_source",
        "description": "Categorical actor-relative source-seat index for each public call, with zero for closed/no-source entries.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 101
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-meld-call-age",
        "name": "meld_call_age",
        "title": "Meld call age",
        "shape": [
          null,
          4,
          4
        ],
        "dtype": "float16",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "melds",
        "feature": "meld_call_age",
        "description": "Clipped event-distance scalar from the original meld event, normalized by 100.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 102
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-meld-upgrade-age",
        "name": "meld_upgrade_age",
        "title": "Meld upgrade age",
        "shape": [
          null,
          4,
          4
        ],
        "dtype": "float16",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "melds",
        "feature": "meld_upgrade_age",
        "description": "Clipped event-distance scalar from an added-kan upgrade, normalized by 100.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 103
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-current-draw-tile-id",
        "name": "current_draw_tile_id",
        "title": "Current draw tile id",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-hand",
        "group": "self",
        "feature": "current_draw_tile_id",
        "description": "Ordinary tile-type ID of the current self draw, interpreted under current_draw_valid.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 104
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-current-draw-is-red",
        "name": "current_draw_is_red",
        "title": "Current draw is red",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-hand",
        "group": "self",
        "feature": "current_draw_is_red",
        "description": "Binary red-five indicator for the current self draw.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 105
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-current-draw-valid",
        "name": "current_draw_valid",
        "title": "Current draw valid",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-hand",
        "group": "self",
        "feature": "current_draw_valid",
        "description": "Binary validity mask for current-draw identity channels.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 106
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-normal-self-shanten",
        "name": "normal_self_shanten",
        "title": "Normal self shanten",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-hand",
        "group": "self",
        "feature": "normal_self_shanten",
        "description": "Clipped categorical standard-hand shanten encoding; category equals actual shanten + 1 until saturation.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 107
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-chiitoitsu-self-shanten",
        "name": "chiitoitsu_self_shanten",
        "title": "Chiitoitsu self shanten",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-hand",
        "group": "self",
        "feature": "chiitoitsu_self_shanten",
        "description": "Clipped categorical seven-pairs shanten encoding with a distinct infeasible-family sentinel when fixed melds exist.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 108
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-kokushi-self-shanten",
        "name": "kokushi_self_shanten",
        "title": "Kokushi self shanten",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-hand",
        "group": "self",
        "feature": "kokushi_self_shanten",
        "description": "Clipped categorical thirteen-orphans shanten encoding with a distinct infeasible-family sentinel when fixed melds exist.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 109
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-closed-hand",
        "name": "closed_hand",
        "title": "Closed hand",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-hand",
        "group": "self",
        "feature": "closed_hand",
        "description": "Binary closed-hand predicate used by structural/scoring constraints.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 110
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-self-efficiency",
        "name": "self_efficiency",
        "title": "Self efficiency",
        "shape": [
          null,
          3
        ],
        "dtype": "float32",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-hand",
        "group": "self",
        "feature": "self_efficiency",
        "description": "Three normalized self-hand statistics: actual shanten, improving-type cardinality and available improving-copy count.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 111
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-dora-multiplicity",
        "name": "dora_multiplicity",
        "title": "Dora multiplicity",
        "shape": [
          null,
          34
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "table",
        "feature": "dora_multiplicity",
        "description": "Per-ordinary-tile integer multiplicity induced by visible dora indicators.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 84
        },
        "reader_areas": [
          "board",
          "belief",
          "actor",
          "critic"
        ]
      },
      {
        "id": "input-public-visible-red-counts",
        "name": "public_visible_red_counts",
        "title": "Public visible red counts",
        "shape": [
          null,
          3
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "table",
        "feature": "public_visible_red_counts",
        "description": "Public red-five occupancy by suit, excluding concealed self occupancy.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 113
        },
        "reader_areas": [
          "board",
          "belief"
        ]
      },
      {
        "id": "input-known-unavailable-counts",
        "name": "known_unavailable_counts",
        "title": "Known unavailable counts",
        "shape": [
          null,
          34
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "table",
        "feature": "known_unavailable_counts",
        "description": "Per-ordinary-tile unavailable-copy count combining public exposures and the self hand.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 114
        },
        "reader_areas": [
          "board",
          "belief",
          "actor",
          "critic"
        ]
      },
      {
        "id": "input-prevailing-wind",
        "name": "prevailing_wind",
        "title": "Prevailing wind",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "table",
        "feature": "prevailing_wind",
        "description": "Categorical current-round wind ID.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 115
        },
        "reader_areas": [
          "board",
          "belief",
          "actor",
          "critic"
        ]
      },
      {
        "id": "input-hands-remaining",
        "name": "hands_remaining",
        "title": "Hands remaining",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "table",
        "feature": "hands_remaining",
        "description": "Signed scheduled hands remaining after this hand in a South game.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 116
        },
        "reader_areas": [
          "board",
          "critic"
        ]
      },
      {
        "id": "input-dealer-relative-seat",
        "name": "dealer_relative_seat",
        "title": "Dealer relative seat",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "table",
        "feature": "dealer_relative_seat",
        "description": "Categorical dealer index in actor-relative seat coordinates.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 117
        },
        "reader_areas": [
          "board",
          "belief",
          "actor",
          "critic"
        ]
      },
      {
        "id": "input-honba",
        "name": "honba",
        "title": "Honba",
        "shape": [
          null
        ],
        "dtype": "int16",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "table",
        "feature": "honba",
        "description": "Integer repeat-counter scalar conditioning settlement transfers.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 118
        },
        "reader_areas": [
          "board",
          "critic"
        ]
      },
      {
        "id": "input-riichi-sticks",
        "name": "riichi_sticks",
        "title": "Riichi sticks",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "table",
        "feature": "riichi_sticks",
        "description": "Integer count of accepted riichi deposits in the current table pot.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 119
        },
        "reader_areas": [
          "board",
          "critic"
        ]
      },
      {
        "id": "input-live-wall-count",
        "name": "live_wall_count",
        "title": "Live wall count",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "table",
        "feature": "live_wall_count",
        "description": "Integer remaining ordinary-draw count; excludes replacement draws.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 120
        },
        "reader_areas": [
          "board",
          "belief",
          "actor",
          "critic"
        ]
      },
      {
        "id": "input-total-kan-count",
        "name": "total_kan_count",
        "title": "Total kan count",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "table",
        "feature": "total_kan_count",
        "description": "Integer kan count in the current hand.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 121
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-scores",
        "name": "scores",
        "title": "Scores",
        "shape": [
          null,
          4
        ],
        "dtype": "int32",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "table",
        "feature": "scores",
        "description": "Current points in wind-seat order: East, South, West, North.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 122
        },
        "reader_areas": [
          "board",
          "critic"
        ]
      },
      {
        "id": "input-ranks",
        "name": "ranks",
        "title": "Ranks",
        "shape": [
          null,
          4
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "table",
        "feature": "ranks",
        "description": "Current ranks in wind-seat order: East, South, West, North.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 123
        },
        "reader_areas": [
          "board",
          "critic"
        ]
      },
      {
        "id": "input-seat-wind",
        "name": "seat_wind",
        "title": "Seat wind",
        "shape": [
          null,
          4
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "table",
        "feature": "seat_wind",
        "description": "Categorical player-wind IDs in actor-relative player order.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 124
        },
        "reader_areas": [
          "board",
          "belief",
          "actor",
          "critic"
        ]
      },
      {
        "id": "input-open-opponent-yaku-possibility",
        "name": "open_opponent_yaku_possibility",
        "title": "Open opponent yaku possibility",
        "shape": [
          null,
          4,
          13
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "opponents",
        "feature": "open_opponent_yaku_possibility",
        "description": "Thirteen-channel fixed-meld/public-supply feasibility subset, populated for opponents with observed open calls.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 125
        },
        "reader_areas": [
          "board",
          "critic"
        ]
      },
      {
        "id": "input-opponent-called-tile-count",
        "name": "opponent_called_tile_count",
        "title": "Opponent called tile count",
        "shape": [
          null,
          4
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "opponents",
        "feature": "opponent_called_tile_count",
        "description": "Observed open-meld tile cardinality per opponent; self slot remains zero.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 126
        },
        "reader_areas": [
          "board",
          "critic"
        ]
      },
      {
        "id": "input-opponent-discard-count",
        "name": "opponent_discard_count",
        "title": "Opponent discard count",
        "shape": [
          null,
          4
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "opponents",
        "feature": "opponent_discard_count",
        "description": "Integer public discard-sequence length per relative player.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 127
        },
        "reader_areas": [
          "board",
          "belief",
          "actor",
          "critic"
        ]
      },
      {
        "id": "input-nagashi-possible",
        "name": "nagashi_possible",
        "title": "Nagashi possible",
        "shape": [
          null,
          4
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "table",
        "feature": "nagashi_possible",
        "description": "Exact per-player public nagashi eligibility from full discard history: every discard is terminal/honor and none has been called.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 128
        },
        "reader_areas": [
          "actor",
          "critic"
        ]
      },
      {
        "id": "input-pao-payer",
        "name": "pao_payer",
        "title": "Pao payer",
        "shape": [
          null,
          4
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "table",
        "feature": "pao_payer",
        "description": "Known public responsibility payer for each player after the completing dragon or wind call.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 129
        },
        "reader_areas": [
          "critic"
        ]
      },
      {
        "id": "input-last-tedashi-tile-id",
        "name": "last_tedashi_tile_id",
        "title": "Last tedashi tile id",
        "shape": [
          null,
          4
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "opponents",
        "feature": "last_tedashi_tile_id",
        "description": "Compact latest non-tsumogiri discard code per player.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 130
        },
        "reader_areas": [
          "board",
          "belief",
          "critic"
        ]
      },
      {
        "id": "input-riichi-push-count",
        "name": "riichi_push_count",
        "title": "Riichi push count",
        "shape": [
          null,
          4,
          4
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "opponents",
        "feature": "riichi_push_count",
        "description": "Player×riichi-target count of non-tsumogiri discards lacking established safe-tile evidence.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 131
        },
        "reader_areas": [
          "board",
          "critic"
        ]
      },
      {
        "id": "input-genbutsu-to-seat",
        "name": "genbutsu_to_seat",
        "title": "Genbutsu to seat",
        "shape": [
          null,
          4,
          34
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "opponents",
        "feature": "genbutsu_to_seat",
        "description": "Binary player×tile public safe-tile relation derived from observed discard and riichi history.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 132
        },
        "reader_areas": [
          "board",
          "belief",
          "actor",
          "critic"
        ]
      },
      {
        "id": "input-passed-unchanged-to-seat",
        "name": "passed_unchanged_to_seat",
        "title": "Passed unchanged to seat",
        "shape": [
          null,
          4,
          34
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "opponents",
        "feature": "passed_unchanged_to_seat",
        "description": "Binary player×tile passed-discard relation retained across intervals without relevant hand changes.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 133
        },
        "reader_areas": [
          "board",
          "critic"
        ]
      },
      {
        "id": "input-sotogawa-earliest-turn-to-seat",
        "name": "sotogawa_earliest_turn_to_seat",
        "title": "Sotogawa earliest turn to seat",
        "shape": [
          null,
          4,
          34
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-opponents",
        "group": "opponents",
        "feature": "sotogawa_earliest_turn_to_seat",
        "description": "Earliest qualifying opening-discard index for each player×outside-tile relation; zero encodes absence.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 134
        },
        "reader_areas": [
          "board",
          "critic"
        ]
      },
      {
        "id": "input-win-kind",
        "name": "win_kind",
        "title": "Win kind",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "decision",
        "feature": "win_kind",
        "description": "Categorical optional-win context: none, ron or tsumo.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 135
        },
        "reader_areas": [
          "board",
          "actor"
        ]
      },
      {
        "id": "input-decision-phase",
        "name": "decision_phase",
        "title": "Decision phase",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "decision",
        "feature": "decision_phase",
        "description": "Categorical phase selecting the native action contract; numeric phase IDs differ from TRAIN_POLICY_HEADS indices.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 136
        },
        "reader_areas": [
          "board",
          "belief",
          "critic"
        ]
      },
      {
        "id": "input-trigger-tile-id",
        "name": "trigger_tile_id",
        "title": "Trigger tile id",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "decision",
        "feature": "trigger_tile_id",
        "description": "Ordinary tile-type ID of the event-conditioned trigger.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 137
        },
        "reader_areas": [
          "board",
          "belief"
        ]
      },
      {
        "id": "input-trigger-is-red",
        "name": "trigger_is_red",
        "title": "Trigger is red",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "decision",
        "feature": "trigger_is_red",
        "description": "Binary red-five attribute of the trigger tile.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 138
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-trigger-valid",
        "name": "trigger_valid",
        "title": "Trigger valid",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "decision",
        "feature": "trigger_valid",
        "description": "Binary validity mask for trigger identity channels.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 139
        },
        "reader_areas": [
          "board",
          "belief"
        ]
      },
      {
        "id": "input-trigger-source",
        "name": "trigger_source",
        "title": "Trigger source",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "decision",
        "feature": "trigger_source",
        "description": "Actor-relative source-seat ID of the triggering event.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 140
        },
        "reader_areas": [
          "board",
          "belief",
          "critic"
        ]
      },
      {
        "id": "input-riichi-state",
        "name": "riichi_state",
        "title": "Riichi state",
        "shape": [
          null,
          4
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "decision",
        "feature": "riichi_state",
        "description": "Per-player categorical state encoded as declared + accepted flags.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 141
        },
        "reader_areas": [
          "board",
          "belief",
          "critic"
        ]
      },
      {
        "id": "input-ippatsu-alive",
        "name": "ippatsu_alive",
        "title": "Ippatsu alive",
        "shape": [
          null,
          4
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "decision",
        "feature": "ippatsu_alive",
        "description": "Binary per-player ippatsu eligibility under observed intervening events.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 142
        },
        "reader_areas": [
          "board",
          "critic"
        ]
      },
      {
        "id": "input-rinshan-state",
        "name": "rinshan_state",
        "title": "Rinshan state",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-hand",
        "group": "decision",
        "feature": "rinshan_state",
        "description": "Binary predicate that the current replacement draw belongs to self.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 143
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-riichi-legal-mask",
        "name": "riichi_legal_mask",
        "title": "Riichi legal mask",
        "shape": [
          null,
          2
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "decision",
        "feature": "riichi_legal_mask",
        "description": "Binary support mask for decline/declaration branches.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 144
        },
        "reader_areas": []
      },
      {
        "id": "input-riichi-discard-legal-mask",
        "name": "riichi_discard_legal_mask",
        "title": "Riichi discard legal mask",
        "shape": [
          null,
          37
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "decision",
        "feature": "riichi_discard_legal_mask",
        "description": "Binary support mask over declaration-compatible discard classes.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 145
        },
        "reader_areas": [
          "board",
          "actor"
        ]
      },
      {
        "id": "input-response-legal-mask",
        "name": "response_legal_mask",
        "title": "Response legal mask",
        "shape": [
          null,
          4
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "decision",
        "feature": "response_legal_mask",
        "description": "Binary support mask over pass/chi/pon/open-kan branches.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 146
        },
        "reader_areas": [
          "board",
          "actor"
        ]
      },
      {
        "id": "input-call-discard-legal",
        "name": "call_discard_legal",
        "title": "Call discard legal",
        "shape": [
          null,
          4,
          37
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "calls",
        "feature": "call_discard_legal",
        "description": "Legal follow-up discards for each call option, including its kuikae exclusions.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 147
        },
        "reader_areas": [
          "actor"
        ]
      },
      {
        "id": "input-call-discard-shanten",
        "name": "call_discard_shanten",
        "title": "Call discard shanten",
        "shape": [
          null,
          4,
          37
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "calls",
        "feature": "call_discard_shanten",
        "description": "Call-option × follow-up-discard shanten categories, actual shanten + 1.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 148
        },
        "reader_areas": []
      },
      {
        "id": "input-call-discard-ukeire-count",
        "name": "call_discard_ukeire_count",
        "title": "Call discard ukeire count",
        "shape": [
          null,
          4,
          37
        ],
        "dtype": "int16",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "calls",
        "feature": "call_discard_ukeire_count",
        "description": "Call-option × follow-up-discard available improving-copy counts.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 149
        },
        "reader_areas": []
      },
      {
        "id": "input-kan-legal-mask",
        "name": "kan_legal_mask",
        "title": "Kan legal mask",
        "shape": [
          null,
          35
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "calls",
        "feature": "kan_legal_mask",
        "description": "Binary support mask over decline and 34 tile-specific kan actions.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 150
        },
        "reader_areas": [
          "board",
          "actor"
        ]
      },
      {
        "id": "input-call-efficiency",
        "name": "call_efficiency",
        "title": "Call efficiency",
        "shape": [
          null,
          4,
          3
        ],
        "dtype": "float32",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "calls",
        "feature": "call_efficiency",
        "description": "Normalized shanten/improving-type/improving-copy statistics after each call option.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 151
        },
        "reader_areas": []
      },
      {
        "id": "input-kan-efficiency",
        "name": "kan_efficiency",
        "title": "Kan efficiency",
        "shape": [
          null,
          34,
          3
        ],
        "dtype": "float32",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "calls",
        "feature": "kan_efficiency",
        "description": "Per-tile kan-candidate normalized shanten/improving-type/improving-copy statistics before the replacement draw.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 152
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-discard-abort",
        "name": "discard_abort",
        "title": "Discard abort",
        "shape": [
          null,
          2,
          37
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "discards",
        "feature": "discard_abort",
        "description": "Binary discard-conditioned abort indicators for ordinary and declaration branches.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 153
        },
        "reader_areas": [
          "board",
          "critic"
        ]
      },
      {
        "id": "input-discard-action-legal",
        "name": "discard_action_legal",
        "title": "Discard action legal",
        "shape": [
          null,
          37
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "discards",
        "feature": "discard_action_legal",
        "description": "Binary support mask over 37 ordinary/red discard classes.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 154
        },
        "reader_areas": [
          "board",
          "actor"
        ]
      },
      {
        "id": "input-discard-tedashi-legal",
        "name": "discard_tedashi_legal",
        "title": "Discard tedashi legal",
        "shape": [
          null,
          37
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "discards",
        "feature": "discard_tedashi_legal",
        "description": "Binary predicate that a discard class admits a held-tile physical realization.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 155
        },
        "reader_areas": []
      },
      {
        "id": "input-discard-action-normal-shanten",
        "name": "discard_action_normal_shanten",
        "title": "Discard action normal shanten",
        "shape": [
          null,
          37
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "discards",
        "feature": "discard_action_normal_shanten",
        "description": "Standard-hand post-discard shanten category.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 156
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-discard-action-normal-ukeire-count",
        "name": "discard_action_normal_ukeire_count",
        "title": "Discard action normal ukeire count",
        "shape": [
          null,
          37
        ],
        "dtype": "int16",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "discards",
        "feature": "discard_action_normal_ukeire_count",
        "description": "Standard-hand post-discard available improving-copy count.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 157
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-discard-action-all-shanten",
        "name": "discard_action_all_shanten",
        "title": "Discard action all shanten",
        "shape": [
          null,
          37
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "discards",
        "feature": "discard_action_all_shanten",
        "description": "Minimum-shanten hand-family post-discard shanten category.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 158
        },
        "reader_areas": [
          "board",
          "actor",
          "critic"
        ]
      },
      {
        "id": "input-discard-action-all-ukeire-count",
        "name": "discard_action_all_ukeire_count",
        "title": "Discard action all ukeire count",
        "shape": [
          null,
          37
        ],
        "dtype": "int16",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "discards",
        "feature": "discard_action_all_ukeire_count",
        "description": "Minimum-shanten hand-family post-discard available improving-copy count.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 159
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-discard-retained-genbutsu",
        "name": "discard_retained_genbutsu",
        "title": "Discard retained genbutsu",
        "shape": [
          null,
          37,
          4
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "discards",
        "feature": "discard_retained_genbutsu",
        "description": "Discard×player statistic for safe-tile occupancy retained after the candidate discard.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 160
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-action-win-value-range",
        "name": "action_win_value_range",
        "title": "Action win value range",
        "shape": [
          null,
          110,
          2,
          2
        ],
        "dtype": "float32",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "scoring",
        "feature": "action_win_value_range",
        "description": "Action-conditioned completion min/max points. Reconstruct the closed/open neural axis from resulting-meld openness; used only in the corresponding local action query.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 161
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-action-win-value-valid",
        "name": "action_win_value_valid",
        "title": "Action win value valid",
        "shape": [
          null,
          110,
          2
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "scoring",
        "feature": "action_win_value_valid",
        "description": "Binary support for action-conditioned completion bounds. Reconstruct the closed/open neural axis from resulting-meld openness.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 162
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-action-value-eligible",
        "name": "action_value_eligible",
        "title": "Action value eligible",
        "shape": [
          null,
          110
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "scoring",
        "feature": "action_value_eligible",
        "description": "Native action-conditioned completion-search eligibility, gathered by the compact-to-local scoring row map.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 163
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-action-open-yaku-restricted",
        "name": "action_open_yaku_restricted",
        "title": "Action open yaku restricted",
        "shape": [
          null,
          110,
          2
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-actions",
        "group": "scoring",
        "feature": "action_open_yaku_restricted",
        "description": "Native action-conditioned open-yaku restriction channels, gathered into the corresponding local action descriptor.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 164
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-candidate-yaku-shanten",
        "name": "candidate_yaku_shanten",
        "title": "Candidate yaku shanten",
        "shape": [
          null,
          16,
          3
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-hand",
        "group": "scoring",
        "feature": "candidate_yaku_shanten",
        "description": "Candidate×route-family integer distances for tanyao, flush and outside-hand routes.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 165
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-public-bonus",
        "name": "public_bonus",
        "title": "Public bonus",
        "shape": [
          null,
          4
        ],
        "dtype": "int8",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-table",
        "group": "scoring",
        "feature": "public_bonus",
        "description": "Per-player deterministic bonus-han contribution from observed fixed melds and visible dora.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 166
        },
        "reader_areas": [
          "belief",
          "critic"
        ]
      },
      {
        "id": "input-candidate-fu",
        "name": "candidate_fu",
        "title": "Candidate fu",
        "shape": [
          null,
          16
        ],
        "dtype": "int16",
        "row_axis": "Decision positions",
        "owner": "inputs-parent-hand",
        "group": "scoring",
        "feature": "candidate_fu",
        "description": "Candidate-dependent fixed-meld fu contribution for each resulting hand; not the final winning-hand fu total.",
        "source": {
          "path": "log_dataset/native_collection/src/schema.rs",
          "line": 167
        },
        "reader_areas": [
          "belief",
          "critic"
        ]
      },
      {
        "id": "input-post-call-candidate-hand-counts",
        "name": "post_call_candidate_hand_counts",
        "title": "Candidate hand counts",
        "shape": [
          null,
          16,
          34
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-hand",
        "group": "hand-bank",
        "feature": "candidate_hand_counts",
        "description": "Integer occupancy tensor over deduplicated candidate hands and 34 ordinary tile types; red fives contribute to their ordinary type counts.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "belief",
          "actor",
          "critic"
        ]
      },
      {
        "id": "input-post-call-candidate-hand-red",
        "name": "post_call_candidate_hand_red",
        "title": "Candidate hand red",
        "shape": [
          null,
          16,
          3
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-hand",
        "group": "hand-bank",
        "feature": "candidate_hand_red",
        "description": "Per-candidate red-five occupancy by suit, represented separately from ordinary type counts.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "belief",
          "critic"
        ]
      },
      {
        "id": "input-post-call-candidate-hand-yaku-possibility",
        "name": "post_call_candidate_hand_yaku_possibility",
        "title": "Candidate hand yaku possibility",
        "shape": [
          null,
          16,
          19
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-hand",
        "group": "hand-bank",
        "feature": "candidate_hand_yaku_possibility",
        "description": "Nineteen coarse yaku-feasibility flags for each resulting hand-bank slot, combining its fixed-meld compatibility and public tile availability. They enter that hand’s readout; they are not completed-hand yaku labels.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-candidate-meld-tiles",
        "name": "post_call_candidate_meld_tiles",
        "title": "Candidate meld tiles",
        "shape": [
          null,
          16,
          4
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-hand",
        "group": "hand-bank",
        "feature": "candidate_meld_tiles",
        "description": "Compact lowest-tile code per fixed meld in each local hand.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "belief",
          "critic"
        ]
      },
      {
        "id": "input-post-call-candidate-meld-types",
        "name": "post_call_candidate_meld_types",
        "title": "Candidate meld types",
        "shape": [
          null,
          16,
          4
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-hand",
        "group": "hand-bank",
        "feature": "candidate_meld_types",
        "description": "Fixed-meld type aligned with candidate_meld_tiles.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "belief",
          "critic"
        ]
      },
      {
        "id": "input-post-call-candidate-meld-red",
        "name": "post_call_candidate_meld_red",
        "title": "Candidate meld red",
        "shape": [
          null,
          16,
          3
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-hand",
        "group": "hand-bank",
        "feature": "candidate_meld_red",
        "description": "Red-five counts by suit across each local hand’s fixed melds.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "critic"
        ]
      },
      {
        "id": "input-post-call-candidate-hand-valid",
        "name": "post_call_candidate_hand_valid",
        "title": "Candidate hand valid",
        "shape": [
          null,
          16
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-hand",
        "group": "hand-bank",
        "feature": "candidate_hand_valid",
        "description": "Binary occupancy mask for the 16-entry candidate-hand axis.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-discard-candidate-hand",
        "name": "post_call_discard_candidate_hand",
        "title": "Discard candidate hand",
        "shape": [
          null,
          37
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "hand-bank",
        "feature": "discard_candidate_hand",
        "description": "Gather indices from 37 discard actions into the deduplicated candidate-hand bank. Routing only; excluded from the learned board projection.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "belief",
          "critic"
        ]
      },
      {
        "id": "input-post-call-kan-candidate-hand",
        "name": "post_call_kan_candidate_hand",
        "title": "Kan candidate hand",
        "shape": [
          null,
          34
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "hand-bank",
        "feature": "kan_candidate_hand",
        "description": "Gather indices from tile-specific kan candidates into the candidate-hand bank. Routing only; excluded from the learned board projection.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "belief",
          "critic"
        ]
      },
      {
        "id": "input-post-call-river-pre-tile-id",
        "name": "post_call_river_pre_tile_id",
        "title": "River pre tile id",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_pre_tile_id",
        "description": "Pre-riichi opponent-sequence channel: ordinary tile-type IDs.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-pre-is-red",
        "name": "post_call_river_pre_is_red",
        "title": "River pre is red",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_pre_is_red",
        "description": "Pre-riichi opponent-sequence channel: binary red-five attributes.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-pre-tsumogiri",
        "name": "post_call_river_pre_tsumogiri",
        "title": "River pre tsumogiri",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_pre_tsumogiri",
        "description": "Pre-riichi opponent-sequence channel: binary draw-discard attributes.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-pre-origin",
        "name": "post_call_river_pre_origin",
        "title": "River pre origin",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_pre_origin",
        "description": "Pre-riichi opponent-sequence channel: categorical discard-origin codes.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-pre-riichi",
        "name": "post_call_river_pre_riichi",
        "title": "River pre riichi",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_pre_riichi",
        "description": "Pre-riichi opponent-sequence channel: binary declaration-discard attributes.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-pre-call-resolution",
        "name": "post_call_river_pre_call_resolution",
        "title": "River pre call resolution",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_pre_call_resolution",
        "description": "Pre-riichi opponent-sequence channel: offset categorical response-resolution codes.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-pre-caller",
        "name": "post_call_river_pre_caller",
        "title": "River pre caller",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_pre_caller",
        "description": "Pre-riichi opponent-sequence channel: offset actor-relative caller codes with separate unresolved/no-caller categories.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-pre-event-age",
        "name": "post_call_river_pre_event_age",
        "title": "River pre event age",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "float16",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_pre_event_age",
        "description": "Pre-riichi opponent-sequence channel: event-distance scalars normalized by 100 and clipped at 1.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-pre-own-gap",
        "name": "post_call_river_pre_own_gap",
        "title": "River pre own gap",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "float16",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_pre_own_gap",
        "description": "Pre-riichi opponent-sequence channel: self-discard-count differences normalized by 24 and clipped at 1.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-pre-live-wall",
        "name": "post_call_river_pre_live_wall",
        "title": "River pre live wall",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "float16",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_pre_live_wall",
        "description": "Pre-riichi opponent-sequence channel: discard-time live-wall counts normalized by 70.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-pre-current-dora-multiplicity",
        "name": "post_call_river_pre_current_dora_multiplicity",
        "title": "River pre current dora multiplicity",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_pre_current_dora_multiplicity",
        "description": "Pre-riichi opponent-sequence channel: current integer dora multiplicities.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-pre-dora-multiplicity-at-discard",
        "name": "post_call_river_pre_dora_multiplicity_at_discard",
        "title": "River pre dora multiplicity at discard",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_pre_dora_multiplicity_at_discard",
        "description": "Pre-riichi opponent-sequence channel: discard-time integer dora multiplicities.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-pre-valid",
        "name": "post_call_river_pre_valid",
        "title": "River pre valid",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_pre_valid",
        "description": "Pre-riichi opponent-sequence channel: binary sequence occupancy masks.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-post-tile-id",
        "name": "post_call_river_post_tile_id",
        "title": "River post tile id",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_post_tile_id",
        "description": "Post-riichi opponent-sequence channel: ordinary tile-type IDs.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-post-is-red",
        "name": "post_call_river_post_is_red",
        "title": "River post is red",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_post_is_red",
        "description": "Post-riichi opponent-sequence channel: binary red-five attributes.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-post-tsumogiri",
        "name": "post_call_river_post_tsumogiri",
        "title": "River post tsumogiri",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_post_tsumogiri",
        "description": "Post-riichi opponent-sequence channel: binary draw-discard attributes.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-post-origin",
        "name": "post_call_river_post_origin",
        "title": "River post origin",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_post_origin",
        "description": "Post-riichi opponent-sequence channel: categorical discard-origin codes.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-post-call-resolution",
        "name": "post_call_river_post_call_resolution",
        "title": "River post call resolution",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_post_call_resolution",
        "description": "Post-riichi opponent-sequence channel: offset categorical response-resolution codes.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-post-caller",
        "name": "post_call_river_post_caller",
        "title": "River post caller",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_post_caller",
        "description": "Post-riichi opponent-sequence channel: offset actor-relative caller codes with separate unresolved/no-caller categories.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-post-event-age",
        "name": "post_call_river_post_event_age",
        "title": "River post event age",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "float16",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_post_event_age",
        "description": "Post-riichi opponent-sequence channel: event-distance scalars normalized by 100 and clipped at 1.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-post-own-gap",
        "name": "post_call_river_post_own_gap",
        "title": "River post own gap",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "float16",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_post_own_gap",
        "description": "Post-riichi opponent-sequence channel: self-discard-count differences normalized by 24 and clipped at 1.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-post-live-wall",
        "name": "post_call_river_post_live_wall",
        "title": "River post live wall",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "float16",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_post_live_wall",
        "description": "Post-riichi opponent-sequence channel: discard-time live-wall counts normalized by 70.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-post-current-dora-multiplicity",
        "name": "post_call_river_post_current_dora_multiplicity",
        "title": "River post current dora multiplicity",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_post_current_dora_multiplicity",
        "description": "Post-riichi opponent-sequence channel: current integer dora multiplicities.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-post-dora-multiplicity-at-discard",
        "name": "post_call_river_post_dora_multiplicity_at_discard",
        "title": "River post dora multiplicity at discard",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_post_dora_multiplicity_at_discard",
        "description": "Post-riichi opponent-sequence channel: discard-time integer dora multiplicities.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-river-post-valid",
        "name": "post_call_river_post_valid",
        "title": "River post valid",
        "shape": [
          null,
          3,
          32
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "rivers",
        "feature": "river_post_valid",
        "description": "Post-riichi opponent-sequence channel: binary sequence occupancy masks.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-meld-type",
        "name": "post_call_meld_type",
        "title": "Meld type",
        "shape": [
          null,
          4,
          4
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "melds",
        "feature": "meld_type",
        "description": "Categorical observed-meld kind with zero padding, indexed by relative player and meld slot.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "belief"
        ]
      },
      {
        "id": "input-post-call-meld-tiles",
        "name": "post_call_meld_tiles",
        "title": "Meld tiles",
        "shape": [
          null,
          4,
          4,
          4
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "melds",
        "feature": "meld_tiles",
        "description": "Public meld constituent codes; reconstruct ordinary IDs, red flags and valid flags.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "belief",
          "actor"
        ]
      },
      {
        "id": "input-post-call-meld-source",
        "name": "post_call_meld_source",
        "title": "Meld source",
        "shape": [
          null,
          4,
          4
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "melds",
        "feature": "meld_source",
        "description": "Categorical actor-relative source-seat index for each public call, with zero for closed/no-source entries.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-meld-call-age",
        "name": "post_call_meld_call_age",
        "title": "Meld call age",
        "shape": [
          null,
          4,
          4
        ],
        "dtype": "float16",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "melds",
        "feature": "meld_call_age",
        "description": "Clipped event-distance scalar from the original meld event, normalized by 100.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-meld-upgrade-age",
        "name": "post_call_meld_upgrade_age",
        "title": "Meld upgrade age",
        "shape": [
          null,
          4,
          4
        ],
        "dtype": "float16",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "melds",
        "feature": "meld_upgrade_age",
        "description": "Clipped event-distance scalar from an added-kan upgrade, normalized by 100.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-current-draw-tile-id",
        "name": "post_call_current_draw_tile_id",
        "title": "Current draw tile id",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-hand",
        "group": "self",
        "feature": "current_draw_tile_id",
        "description": "Ordinary tile-type ID of the current self draw, interpreted under current_draw_valid.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-current-draw-is-red",
        "name": "post_call_current_draw_is_red",
        "title": "Current draw is red",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-hand",
        "group": "self",
        "feature": "current_draw_is_red",
        "description": "Binary red-five indicator for the current self draw.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-current-draw-valid",
        "name": "post_call_current_draw_valid",
        "title": "Current draw valid",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-hand",
        "group": "self",
        "feature": "current_draw_valid",
        "description": "Binary validity mask for current-draw identity channels.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-normal-self-shanten",
        "name": "post_call_normal_self_shanten",
        "title": "Normal self shanten",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-hand",
        "group": "self",
        "feature": "normal_self_shanten",
        "description": "Clipped categorical standard-hand shanten encoding; category equals actual shanten + 1 until saturation.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-chiitoitsu-self-shanten",
        "name": "post_call_chiitoitsu_self_shanten",
        "title": "Chiitoitsu self shanten",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-hand",
        "group": "self",
        "feature": "chiitoitsu_self_shanten",
        "description": "Clipped categorical seven-pairs shanten encoding with a distinct infeasible-family sentinel when fixed melds exist.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-kokushi-self-shanten",
        "name": "post_call_kokushi_self_shanten",
        "title": "Kokushi self shanten",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-hand",
        "group": "self",
        "feature": "kokushi_self_shanten",
        "description": "Clipped categorical thirteen-orphans shanten encoding with a distinct infeasible-family sentinel when fixed melds exist.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-closed-hand",
        "name": "post_call_closed_hand",
        "title": "Closed hand",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-hand",
        "group": "self",
        "feature": "closed_hand",
        "description": "Binary closed-hand predicate used by structural/scoring constraints.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-self-efficiency",
        "name": "post_call_self_efficiency",
        "title": "Self efficiency",
        "shape": [
          null,
          3
        ],
        "dtype": "float32",
        "row_axis": "After-call positions",
        "owner": "inputs-child-hand",
        "group": "self",
        "feature": "self_efficiency",
        "description": "Three normalized self-hand statistics: actual shanten, improving-type cardinality and available improving-copy count.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-dora-multiplicity",
        "name": "post_call_dora_multiplicity",
        "title": "Dora multiplicity",
        "shape": [
          null,
          34
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "table",
        "feature": "dora_multiplicity",
        "description": "Per-ordinary-tile integer multiplicity induced by visible dora indicators.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "belief",
          "actor",
          "critic"
        ]
      },
      {
        "id": "input-post-call-public-visible-red-counts",
        "name": "post_call_public_visible_red_counts",
        "title": "Public visible red counts",
        "shape": [
          null,
          3
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "table",
        "feature": "public_visible_red_counts",
        "description": "Public red-five occupancy by suit, excluding concealed self occupancy.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "belief"
        ]
      },
      {
        "id": "input-post-call-known-unavailable-counts",
        "name": "post_call_known_unavailable_counts",
        "title": "Known unavailable counts",
        "shape": [
          null,
          34
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "table",
        "feature": "known_unavailable_counts",
        "description": "Per-ordinary-tile unavailable-copy count combining public exposures and the self hand.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "belief",
          "actor",
          "critic"
        ]
      },
      {
        "id": "input-post-call-prevailing-wind",
        "name": "post_call_prevailing_wind",
        "title": "Prevailing wind",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "table",
        "feature": "prevailing_wind",
        "description": "Categorical current-round wind ID.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "belief",
          "actor"
        ]
      },
      {
        "id": "input-post-call-hands-remaining",
        "name": "post_call_hands_remaining",
        "title": "Hands remaining",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "table",
        "feature": "hands_remaining",
        "description": "Signed scheduled hands remaining after this hand in a South game.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-dealer-relative-seat",
        "name": "post_call_dealer_relative_seat",
        "title": "Dealer relative seat",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "table",
        "feature": "dealer_relative_seat",
        "description": "Categorical dealer index in actor-relative seat coordinates.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "actor"
        ]
      },
      {
        "id": "input-post-call-honba",
        "name": "post_call_honba",
        "title": "Honba",
        "shape": [
          null
        ],
        "dtype": "int16",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "table",
        "feature": "honba",
        "description": "Integer repeat-counter scalar conditioning settlement transfers.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-riichi-sticks",
        "name": "post_call_riichi_sticks",
        "title": "Riichi sticks",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "table",
        "feature": "riichi_sticks",
        "description": "Integer count of accepted riichi deposits in the current table pot.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-live-wall-count",
        "name": "post_call_live_wall_count",
        "title": "Live wall count",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "table",
        "feature": "live_wall_count",
        "description": "Integer remaining ordinary-draw count; excludes replacement draws.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "actor",
          "critic"
        ]
      },
      {
        "id": "input-post-call-total-kan-count",
        "name": "post_call_total_kan_count",
        "title": "Total kan count",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "table",
        "feature": "total_kan_count",
        "description": "Integer kan count in the current hand.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-scores",
        "name": "post_call_scores",
        "title": "Scores",
        "shape": [
          null,
          4
        ],
        "dtype": "int32",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "table",
        "feature": "scores",
        "description": "Current points in wind-seat order: East, South, West, North.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-ranks",
        "name": "post_call_ranks",
        "title": "Ranks",
        "shape": [
          null,
          4
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "table",
        "feature": "ranks",
        "description": "Current ranks in wind-seat order: East, South, West, North.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-seat-wind",
        "name": "post_call_seat_wind",
        "title": "Seat wind",
        "shape": [
          null,
          4
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "table",
        "feature": "seat_wind",
        "description": "Categorical player-wind IDs in actor-relative player order.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "belief",
          "actor"
        ]
      },
      {
        "id": "input-post-call-open-opponent-yaku-possibility",
        "name": "post_call_open_opponent_yaku_possibility",
        "title": "Open opponent yaku possibility",
        "shape": [
          null,
          4,
          13
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "opponents",
        "feature": "open_opponent_yaku_possibility",
        "description": "Thirteen-channel fixed-meld/public-supply feasibility subset, populated for opponents with observed open calls.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-opponent-called-tile-count",
        "name": "post_call_opponent_called_tile_count",
        "title": "Opponent called tile count",
        "shape": [
          null,
          4
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "opponents",
        "feature": "opponent_called_tile_count",
        "description": "Observed open-meld tile cardinality per opponent; self slot remains zero.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-opponent-discard-count",
        "name": "post_call_opponent_discard_count",
        "title": "Opponent discard count",
        "shape": [
          null,
          4
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "opponents",
        "feature": "opponent_discard_count",
        "description": "Integer public discard-sequence length per relative player.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "actor"
        ]
      },
      {
        "id": "input-post-call-nagashi-possible",
        "name": "post_call_nagashi_possible",
        "title": "Nagashi possible",
        "shape": [
          null,
          4
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "table",
        "feature": "nagashi_possible",
        "description": "Exact per-player public nagashi eligibility from full discard history: every discard is terminal/honor and none has been called.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "actor"
        ]
      },
      {
        "id": "input-post-call-pao-payer",
        "name": "post_call_pao_payer",
        "title": "Pao payer",
        "shape": [
          null,
          4
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "table",
        "feature": "pao_payer",
        "description": "Known public responsibility payer for each player after the completing dragon or wind call.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": []
      },
      {
        "id": "input-post-call-last-tedashi-tile-id",
        "name": "post_call_last_tedashi_tile_id",
        "title": "Last tedashi tile id",
        "shape": [
          null,
          4
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "opponents",
        "feature": "last_tedashi_tile_id",
        "description": "Compact latest non-tsumogiri discard code per player.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-riichi-push-count",
        "name": "post_call_riichi_push_count",
        "title": "Riichi push count",
        "shape": [
          null,
          4,
          4
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "opponents",
        "feature": "riichi_push_count",
        "description": "Player×riichi-target count of non-tsumogiri discards lacking established safe-tile evidence.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-genbutsu-to-seat",
        "name": "post_call_genbutsu_to_seat",
        "title": "Genbutsu to seat",
        "shape": [
          null,
          4,
          34
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "opponents",
        "feature": "genbutsu_to_seat",
        "description": "Binary player×tile public safe-tile relation derived from observed discard and riichi history.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "belief",
          "actor"
        ]
      },
      {
        "id": "input-post-call-passed-unchanged-to-seat",
        "name": "post_call_passed_unchanged_to_seat",
        "title": "Passed unchanged to seat",
        "shape": [
          null,
          4,
          34
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "opponents",
        "feature": "passed_unchanged_to_seat",
        "description": "Binary player×tile passed-discard relation retained across intervals without relevant hand changes.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-sotogawa-earliest-turn-to-seat",
        "name": "post_call_sotogawa_earliest_turn_to_seat",
        "title": "Sotogawa earliest turn to seat",
        "shape": [
          null,
          4,
          34
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-opponents",
        "group": "opponents",
        "feature": "sotogawa_earliest_turn_to_seat",
        "description": "Earliest qualifying opening-discard index for each player×outside-tile relation; zero encodes absence.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-win-kind",
        "name": "post_call_win_kind",
        "title": "Win kind",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "decision",
        "feature": "win_kind",
        "description": "Categorical optional-win context: none, ron or tsumo.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-decision-phase",
        "name": "post_call_decision_phase",
        "title": "Decision phase",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "decision",
        "feature": "decision_phase",
        "description": "Categorical phase selecting the native action contract; numeric phase IDs differ from TRAIN_POLICY_HEADS indices.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "belief"
        ]
      },
      {
        "id": "input-post-call-trigger-tile-id",
        "name": "post_call_trigger_tile_id",
        "title": "Trigger tile id",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "decision",
        "feature": "trigger_tile_id",
        "description": "Ordinary tile-type ID of the event-conditioned trigger.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "belief"
        ]
      },
      {
        "id": "input-post-call-trigger-is-red",
        "name": "post_call_trigger_is_red",
        "title": "Trigger is red",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "decision",
        "feature": "trigger_is_red",
        "description": "Binary red-five attribute of the trigger tile.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-trigger-valid",
        "name": "post_call_trigger_valid",
        "title": "Trigger valid",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "decision",
        "feature": "trigger_valid",
        "description": "Binary validity mask for trigger identity channels.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "belief"
        ]
      },
      {
        "id": "input-post-call-trigger-source",
        "name": "post_call_trigger_source",
        "title": "Trigger source",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "decision",
        "feature": "trigger_source",
        "description": "Actor-relative source-seat ID of the triggering event.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "belief"
        ]
      },
      {
        "id": "input-post-call-riichi-state",
        "name": "post_call_riichi_state",
        "title": "Riichi state",
        "shape": [
          null,
          4
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "decision",
        "feature": "riichi_state",
        "description": "Per-player categorical state encoded as declared + accepted flags.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "belief"
        ]
      },
      {
        "id": "input-post-call-ippatsu-alive",
        "name": "post_call_ippatsu_alive",
        "title": "Ippatsu alive",
        "shape": [
          null,
          4
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "decision",
        "feature": "ippatsu_alive",
        "description": "Binary per-player ippatsu eligibility under observed intervening events.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-rinshan-state",
        "name": "post_call_rinshan_state",
        "title": "Rinshan state",
        "shape": [
          null
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-hand",
        "group": "decision",
        "feature": "rinshan_state",
        "description": "Binary predicate that the current replacement draw belongs to self.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-riichi-legal-mask",
        "name": "post_call_riichi_legal_mask",
        "title": "Riichi legal mask",
        "shape": [
          null,
          2
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "decision",
        "feature": "riichi_legal_mask",
        "description": "Binary support mask for decline/declaration branches.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": []
      },
      {
        "id": "input-post-call-riichi-discard-legal-mask",
        "name": "post_call_riichi_discard_legal_mask",
        "title": "Riichi discard legal mask",
        "shape": [
          null,
          37
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "decision",
        "feature": "riichi_discard_legal_mask",
        "description": "Binary support mask over declaration-compatible discard classes.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-response-legal-mask",
        "name": "post_call_response_legal_mask",
        "title": "Response legal mask",
        "shape": [
          null,
          4
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "decision",
        "feature": "response_legal_mask",
        "description": "Binary support mask over pass/chi/pon/open-kan branches.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-call-discard-legal",
        "name": "post_call_call_discard_legal",
        "title": "Call discard legal",
        "shape": [
          null,
          4,
          37
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "calls",
        "feature": "call_discard_legal",
        "description": "Legal follow-up discards for each call option, including its kuikae exclusions.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": []
      },
      {
        "id": "input-post-call-call-discard-shanten",
        "name": "post_call_call_discard_shanten",
        "title": "Call discard shanten",
        "shape": [
          null,
          4,
          37
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "calls",
        "feature": "call_discard_shanten",
        "description": "Call-option × follow-up-discard shanten categories, actual shanten + 1.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": []
      },
      {
        "id": "input-post-call-call-discard-ukeire-count",
        "name": "post_call_call_discard_ukeire_count",
        "title": "Call discard ukeire count",
        "shape": [
          null,
          4,
          37
        ],
        "dtype": "int16",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "calls",
        "feature": "call_discard_ukeire_count",
        "description": "Call-option × follow-up-discard available improving-copy counts.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": []
      },
      {
        "id": "input-post-call-kan-legal-mask",
        "name": "post_call_kan_legal_mask",
        "title": "Kan legal mask",
        "shape": [
          null,
          35
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "calls",
        "feature": "kan_legal_mask",
        "description": "Binary support mask over decline and 34 tile-specific kan actions.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-call-efficiency",
        "name": "post_call_call_efficiency",
        "title": "Call efficiency",
        "shape": [
          null,
          4,
          3
        ],
        "dtype": "float32",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "calls",
        "feature": "call_efficiency",
        "description": "Normalized shanten/improving-type/improving-copy statistics after each call option.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": []
      },
      {
        "id": "input-post-call-kan-efficiency",
        "name": "post_call_kan_efficiency",
        "title": "Kan efficiency",
        "shape": [
          null,
          34,
          3
        ],
        "dtype": "float32",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "calls",
        "feature": "kan_efficiency",
        "description": "Per-tile kan-candidate normalized shanten/improving-type/improving-copy statistics before the replacement draw.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-discard-abort",
        "name": "post_call_discard_abort",
        "title": "Discard abort",
        "shape": [
          null,
          2,
          37
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "discards",
        "feature": "discard_abort",
        "description": "Binary discard-conditioned abort indicators for ordinary and declaration branches.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-discard-action-legal",
        "name": "post_call_discard_action_legal",
        "title": "Discard action legal",
        "shape": [
          null,
          37
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "discards",
        "feature": "discard_action_legal",
        "description": "Binary support mask over 37 ordinary/red discard classes.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "actor"
        ]
      },
      {
        "id": "input-post-call-discard-tedashi-legal",
        "name": "post_call_discard_tedashi_legal",
        "title": "Discard tedashi legal",
        "shape": [
          null,
          37
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "discards",
        "feature": "discard_tedashi_legal",
        "description": "Binary predicate that a discard class admits a held-tile physical realization.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": []
      },
      {
        "id": "input-post-call-discard-action-normal-shanten",
        "name": "post_call_discard_action_normal_shanten",
        "title": "Discard action normal shanten",
        "shape": [
          null,
          37
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "discards",
        "feature": "discard_action_normal_shanten",
        "description": "Standard-hand post-discard shanten category.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-discard-action-normal-ukeire-count",
        "name": "post_call_discard_action_normal_ukeire_count",
        "title": "Discard action normal ukeire count",
        "shape": [
          null,
          37
        ],
        "dtype": "int16",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "discards",
        "feature": "discard_action_normal_ukeire_count",
        "description": "Standard-hand post-discard available improving-copy count.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-discard-action-all-shanten",
        "name": "post_call_discard_action_all_shanten",
        "title": "Discard action all shanten",
        "shape": [
          null,
          37
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "discards",
        "feature": "discard_action_all_shanten",
        "description": "Minimum-shanten hand-family post-discard shanten category.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board",
          "actor"
        ]
      },
      {
        "id": "input-post-call-discard-action-all-ukeire-count",
        "name": "post_call_discard_action_all_ukeire_count",
        "title": "Discard action all ukeire count",
        "shape": [
          null,
          37
        ],
        "dtype": "int16",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "discards",
        "feature": "discard_action_all_ukeire_count",
        "description": "Minimum-shanten hand-family post-discard available improving-copy count.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-discard-retained-genbutsu",
        "name": "post_call_discard_retained_genbutsu",
        "title": "Discard retained genbutsu",
        "shape": [
          null,
          37,
          4
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "discards",
        "feature": "discard_retained_genbutsu",
        "description": "Discard×player statistic for safe-tile occupancy retained after the candidate discard.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-action-win-value-range",
        "name": "post_call_action_win_value_range",
        "title": "Action win value range",
        "shape": [
          null,
          110,
          2,
          2
        ],
        "dtype": "float32",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "scoring",
        "feature": "action_win_value_range",
        "description": "Action-conditioned completion min/max points. Reconstruct the closed/open neural axis from resulting-meld openness; used only in the corresponding local action query.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-action-win-value-valid",
        "name": "post_call_action_win_value_valid",
        "title": "Action win value valid",
        "shape": [
          null,
          110,
          2
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "scoring",
        "feature": "action_win_value_valid",
        "description": "Binary support for action-conditioned completion bounds. Reconstruct the closed/open neural axis from resulting-meld openness.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-action-value-eligible",
        "name": "post_call_action_value_eligible",
        "title": "Action value eligible",
        "shape": [
          null,
          110
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "scoring",
        "feature": "action_value_eligible",
        "description": "Native action-conditioned completion-search eligibility, gathered by the compact-to-local scoring row map.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-action-open-yaku-restricted",
        "name": "post_call_action_open_yaku_restricted",
        "title": "Action open yaku restricted",
        "shape": [
          null,
          110,
          2
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-actions",
        "group": "scoring",
        "feature": "action_open_yaku_restricted",
        "description": "Native action-conditioned open-yaku restriction channels, gathered into the corresponding local action descriptor.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-candidate-yaku-shanten",
        "name": "post_call_candidate_yaku_shanten",
        "title": "Candidate yaku shanten",
        "shape": [
          null,
          16,
          3
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-hand",
        "group": "scoring",
        "feature": "candidate_yaku_shanten",
        "description": "Candidate×route-family integer distances for tanyao, flush and outside-hand routes.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "board"
        ]
      },
      {
        "id": "input-post-call-public-bonus",
        "name": "post_call_public_bonus",
        "title": "Public bonus",
        "shape": [
          null,
          4
        ],
        "dtype": "int8",
        "row_axis": "After-call positions",
        "owner": "inputs-child-table",
        "group": "scoring",
        "feature": "public_bonus",
        "description": "Per-player deterministic bonus-han contribution from observed fixed melds and visible dora.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "belief"
        ]
      },
      {
        "id": "input-post-call-candidate-fu",
        "name": "post_call_candidate_fu",
        "title": "Candidate fu",
        "shape": [
          null,
          16
        ],
        "dtype": "int16",
        "row_axis": "After-call positions",
        "owner": "inputs-child-hand",
        "group": "scoring",
        "feature": "candidate_fu",
        "description": "Candidate-dependent fixed-meld fu contribution for each resulting hand; not the final winning-hand fu total.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 17
        },
        "reader_areas": [
          "belief"
        ]
      },
      {
        "id": "input-post-call-owner",
        "name": "post_call_owner",
        "title": "Post call owner",
        "shape": [
          null
        ],
        "dtype": "int32",
        "row_axis": "After-call positions",
        "owner": "inputs-call-routing",
        "group": "calls",
        "feature": null,
        "description": "Index of the original decision for this after-call position.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 20
        },
        "reader_areas": [
          "actor",
          "critic"
        ]
      },
      {
        "id": "input-post-call-option",
        "name": "post_call_option",
        "title": "Post call option",
        "shape": [
          null
        ],
        "dtype": "int32",
        "row_axis": "After-call positions",
        "owner": "inputs-call-routing",
        "group": "calls",
        "feature": null,
        "description": "Call option, with 0–2 for chi patterns and 3 for pon.",
        "source": {
          "path": "log_dataset/call_states.py",
          "line": 21
        },
        "reader_areas": [
          "actor",
          "critic"
        ]
      }
    ],
    "input_edges": [
      {
        "from": "input-candidate-hand-counts",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "input-candidate-hand-red",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "input-candidate-meld-tiles",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "input-candidate-meld-types",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "input-candidate-meld-red",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "input-candidate-hand-valid",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "input-dora-multiplicity",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "input-known-unavailable-counts",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "input-genbutsu-to-seat",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "input-passed-unchanged-to-seat",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "input-sotogawa-earliest-turn-to-seat",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "input-post-call-candidate-hand-counts",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "input-post-call-candidate-hand-red",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "input-post-call-candidate-meld-tiles",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "input-post-call-candidate-meld-types",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "input-post-call-candidate-meld-red",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "input-post-call-candidate-hand-valid",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "input-post-call-dora-multiplicity",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "input-post-call-known-unavailable-counts",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "input-post-call-genbutsu-to-seat",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "input-post-call-passed-unchanged-to-seat",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "input-post-call-sotogawa-earliest-turn-to-seat",
        "to": "hand-tokenization",
        "label": "Local hand contents and tile-aligned public evidence",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 933
        }
      },
      {
        "from": "input-river-pre-tile-id",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-pre-is-red",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-pre-tsumogiri",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-pre-origin",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-pre-riichi",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-pre-call-resolution",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-pre-caller",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-pre-event-age",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-pre-own-gap",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-pre-live-wall",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-pre-current-dora-multiplicity",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-pre-dora-multiplicity-at-discard",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-pre-valid",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-post-tile-id",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-post-is-red",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-post-tsumogiri",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-post-origin",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-post-call-resolution",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-post-caller",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-post-event-age",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-post-own-gap",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-post-live-wall",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-post-current-dora-multiplicity",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-post-dora-multiplicity-at-discard",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-river-post-valid",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-pre-tile-id",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-pre-is-red",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-pre-tsumogiri",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-pre-origin",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-pre-riichi",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-pre-call-resolution",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-pre-caller",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-pre-event-age",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-pre-own-gap",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-pre-live-wall",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-pre-current-dora-multiplicity",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-pre-dora-multiplicity-at-discard",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-pre-valid",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-post-tile-id",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-post-is-red",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-post-tsumogiri",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-post-origin",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-post-call-resolution",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-post-caller",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-post-event-age",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-post-own-gap",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-post-live-wall",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-post-current-dora-multiplicity",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-post-dora-multiplicity-at-discard",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-post-call-river-post-valid",
        "to": "river-tokenization",
        "label": "Pre/post-riichi tile streams and validity",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        }
      },
      {
        "from": "input-meld-type",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-meld-tiles",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-meld-source",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-meld-call-age",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-meld-upgrade-age",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-current-draw-tile-id",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-current-draw-is-red",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-current-draw-valid",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-normal-self-shanten",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-chiitoitsu-self-shanten",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-kokushi-self-shanten",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-closed-hand",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-self-efficiency",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-public-visible-red-counts",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-prevailing-wind",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-hands-remaining",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-dealer-relative-seat",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-honba",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-riichi-sticks",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-live-wall-count",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-total-kan-count",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-scores",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-ranks",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-seat-wind",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-open-opponent-yaku-possibility",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-opponent-called-tile-count",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-opponent-discard-count",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-last-tedashi-tile-id",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-riichi-push-count",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-win-kind",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-decision-phase",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-trigger-tile-id",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-trigger-is-red",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-trigger-valid",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-trigger-source",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-riichi-state",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-ippatsu-alive",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-rinshan-state",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-meld-type",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-meld-tiles",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-meld-source",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-meld-call-age",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-meld-upgrade-age",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-current-draw-tile-id",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-current-draw-is-red",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-current-draw-valid",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-normal-self-shanten",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-chiitoitsu-self-shanten",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-kokushi-self-shanten",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-closed-hand",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-self-efficiency",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-public-visible-red-counts",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-prevailing-wind",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-hands-remaining",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-dealer-relative-seat",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-honba",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-riichi-sticks",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-live-wall-count",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-total-kan-count",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-scores",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-ranks",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-seat-wind",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-open-opponent-yaku-possibility",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-opponent-called-tile-count",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-opponent-discard-count",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-last-tedashi-tile-id",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-riichi-push-count",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-win-kind",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-decision-phase",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-trigger-tile-id",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-trigger-is-red",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-trigger-valid",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-trigger-source",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-riichi-state",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-ippatsu-alive",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-post-call-rinshan-state",
        "to": "shared-public-context",
        "label": "Public fields encoded once, excluding tile-local arrays",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 923
        }
      },
      {
        "from": "input-candidate-meld-tiles",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-candidate-meld-types",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-discard-candidate-hand",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-kan-candidate-hand",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-current-draw-valid",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-live-wall-count",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-decision-phase",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-trigger-source",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-rinshan-state",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-riichi-discard-legal-mask",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-response-legal-mask",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-kan-legal-mask",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-kan-efficiency",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-discard-abort",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-discard-action-legal",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-discard-action-normal-shanten",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-discard-action-normal-ukeire-count",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-discard-action-all-shanten",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-discard-action-all-ukeire-count",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-discard-retained-genbutsu",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-action-win-value-range",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-action-win-value-valid",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-action-value-eligible",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-action-open-yaku-restricted",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-candidate-yaku-shanten",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-candidate-meld-tiles",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-candidate-meld-types",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-discard-candidate-hand",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-kan-candidate-hand",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-current-draw-valid",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-live-wall-count",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-decision-phase",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-trigger-source",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-rinshan-state",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-riichi-discard-legal-mask",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-response-legal-mask",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-kan-legal-mask",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-kan-efficiency",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-discard-abort",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-discard-action-legal",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-discard-action-normal-shanten",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-discard-action-normal-ukeire-count",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-discard-action-all-shanten",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-discard-action-all-ukeire-count",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-discard-retained-genbutsu",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-action-win-value-range",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-action-win-value-valid",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-action-value-eligible",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-action-open-yaku-restricted",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-post-call-candidate-yaku-shanten",
        "to": "candidate-projection",
        "label": "Action support, gathers and structural features",
        "kind": "features",
        "source": {
          "path": "model/encoder.py",
          "line": 656
        }
      },
      {
        "from": "input-candidate-hand-red",
        "to": "tile-tokenization",
        "label": "Known meld copies and available tile counts",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 203
        }
      },
      {
        "from": "input-meld-tiles",
        "to": "tile-tokenization",
        "label": "Known meld copies and available tile counts",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 203
        }
      },
      {
        "from": "input-public-visible-red-counts",
        "to": "tile-tokenization",
        "label": "Known meld copies and available tile counts",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 203
        }
      },
      {
        "from": "input-known-unavailable-counts",
        "to": "tile-tokenization",
        "label": "Known meld copies and available tile counts",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 203
        }
      },
      {
        "from": "input-candidate-hand-red",
        "to": "belief-constraints",
        "label": "Meld, riichi and tile-capacity support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 496
        }
      },
      {
        "from": "input-meld-tiles",
        "to": "belief-constraints",
        "label": "Meld, riichi and tile-capacity support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 496
        }
      },
      {
        "from": "input-dora-multiplicity",
        "to": "belief-constraints",
        "label": "Meld, riichi and tile-capacity support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 496
        }
      },
      {
        "from": "input-public-visible-red-counts",
        "to": "belief-constraints",
        "label": "Meld, riichi and tile-capacity support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 496
        }
      },
      {
        "from": "input-known-unavailable-counts",
        "to": "belief-constraints",
        "label": "Meld, riichi and tile-capacity support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 496
        }
      },
      {
        "from": "input-prevailing-wind",
        "to": "belief-constraints",
        "label": "Meld, riichi and tile-capacity support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 496
        }
      },
      {
        "from": "input-seat-wind",
        "to": "belief-constraints",
        "label": "Meld, riichi and tile-capacity support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 496
        }
      },
      {
        "from": "input-riichi-state",
        "to": "belief-constraints",
        "label": "Meld, riichi and tile-capacity support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 496
        }
      },
      {
        "from": "input-candidate-meld-tiles",
        "to": "actor-candidate-aux",
        "label": "Public route-support mask",
        "kind": "features",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 13
        }
      },
      {
        "from": "input-candidate-meld-types",
        "to": "actor-candidate-aux",
        "label": "Public route-support mask",
        "kind": "features",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 13
        }
      },
      {
        "from": "input-discard-candidate-hand",
        "to": "actor-candidate-aux",
        "label": "Public route-support mask",
        "kind": "features",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 13
        }
      },
      {
        "from": "input-kan-candidate-hand",
        "to": "actor-candidate-aux",
        "label": "Public route-support mask",
        "kind": "features",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 13
        }
      },
      {
        "from": "input-post-call-candidate-meld-tiles",
        "to": "actor-candidate-aux",
        "label": "Public route-support mask",
        "kind": "features",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 13
        }
      },
      {
        "from": "input-post-call-candidate-meld-types",
        "to": "actor-candidate-aux",
        "label": "Public route-support mask",
        "kind": "features",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 13
        }
      },
      {
        "from": "input-post-call-discard-candidate-hand",
        "to": "actor-candidate-aux",
        "label": "Public route-support mask",
        "kind": "features",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 13
        }
      },
      {
        "from": "input-post-call-kan-candidate-hand",
        "to": "actor-candidate-aux",
        "label": "Public route-support mask",
        "kind": "features",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 13
        }
      },
      {
        "from": "input-candidate-hand-counts",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-meld-type",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-meld-tiles",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-known-unavailable-counts",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-prevailing-wind",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-seat-wind",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-trigger-tile-id",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-trigger-valid",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-trigger-source",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-riichi-state",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-public-bonus",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-candidate-fu",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-post-call-candidate-hand-counts",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-post-call-meld-type",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-post-call-meld-tiles",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-post-call-known-unavailable-counts",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-post-call-prevailing-wind",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-post-call-seat-wind",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-post-call-trigger-tile-id",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-post-call-trigger-valid",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-post-call-trigger-source",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-post-call-riichi-state",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-post-call-public-bonus",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-post-call-candidate-fu",
        "to": "actor-completion",
        "label": "Public completion support",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 544
        }
      },
      {
        "from": "input-candidate-hand-counts",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-meld-tiles",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-dora-multiplicity",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-known-unavailable-counts",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-prevailing-wind",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-dealer-relative-seat",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-live-wall-count",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-seat-wind",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-opponent-discard-count",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-nagashi-possible",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-genbutsu-to-seat",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-riichi-discard-legal-mask",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-kan-legal-mask",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-discard-action-legal",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-discard-action-all-shanten",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-post-call-candidate-hand-counts",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-post-call-meld-tiles",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-post-call-dora-multiplicity",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-post-call-known-unavailable-counts",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-post-call-prevailing-wind",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-post-call-dealer-relative-seat",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-post-call-live-wall-count",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-post-call-seat-wind",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-post-call-opponent-discard-count",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-post-call-nagashi-possible",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-post-call-genbutsu-to-seat",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-post-call-discard-action-legal",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-post-call-discard-action-all-shanten",
        "to": "actor-final-score",
        "label": "Phase legality and deterministic policy transforms",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 197
        }
      },
      {
        "from": "input-win-kind",
        "to": "actor-win",
        "label": "Native win/pass support",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 208
        }
      },
      {
        "from": "input-meld-type",
        "to": "player-descriptors",
        "label": "Public seat facts and action-relative roles",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 546
        }
      },
      {
        "from": "input-meld-tiles",
        "to": "player-descriptors",
        "label": "Public seat facts and action-relative roles",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 546
        }
      },
      {
        "from": "input-dora-multiplicity",
        "to": "player-descriptors",
        "label": "Public seat facts and action-relative roles",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 546
        }
      },
      {
        "from": "input-known-unavailable-counts",
        "to": "player-descriptors",
        "label": "Public seat facts and action-relative roles",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 546
        }
      },
      {
        "from": "input-prevailing-wind",
        "to": "player-descriptors",
        "label": "Public seat facts and action-relative roles",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 546
        }
      },
      {
        "from": "input-live-wall-count",
        "to": "player-descriptors",
        "label": "Public seat facts and action-relative roles",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 546
        }
      },
      {
        "from": "input-scores",
        "to": "player-descriptors",
        "label": "Public seat facts and action-relative roles",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 546
        }
      },
      {
        "from": "input-ranks",
        "to": "player-descriptors",
        "label": "Public seat facts and action-relative roles",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 546
        }
      },
      {
        "from": "input-seat-wind",
        "to": "player-descriptors",
        "label": "Public seat facts and action-relative roles",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 546
        }
      },
      {
        "from": "input-open-opponent-yaku-possibility",
        "to": "player-descriptors",
        "label": "Public seat facts and action-relative roles",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 546
        }
      },
      {
        "from": "input-opponent-called-tile-count",
        "to": "player-descriptors",
        "label": "Public seat facts and action-relative roles",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 546
        }
      },
      {
        "from": "input-opponent-discard-count",
        "to": "player-descriptors",
        "label": "Public seat facts and action-relative roles",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 546
        }
      },
      {
        "from": "input-last-tedashi-tile-id",
        "to": "player-descriptors",
        "label": "Public seat facts and action-relative roles",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 546
        }
      },
      {
        "from": "input-genbutsu-to-seat",
        "to": "player-descriptors",
        "label": "Public seat facts and action-relative roles",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 546
        }
      },
      {
        "from": "input-passed-unchanged-to-seat",
        "to": "player-descriptors",
        "label": "Public seat facts and action-relative roles",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 546
        }
      },
      {
        "from": "input-sotogawa-earliest-turn-to-seat",
        "to": "player-descriptors",
        "label": "Public seat facts and action-relative roles",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 546
        }
      },
      {
        "from": "input-decision-phase",
        "to": "player-descriptors",
        "label": "Public seat facts and action-relative roles",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 546
        }
      },
      {
        "from": "input-trigger-source",
        "to": "player-descriptors",
        "label": "Public seat facts and action-relative roles",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 546
        }
      },
      {
        "from": "input-riichi-state",
        "to": "player-descriptors",
        "label": "Public seat facts and action-relative roles",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 546
        }
      },
      {
        "from": "input-ippatsu-alive",
        "to": "player-descriptors",
        "label": "Public seat facts and action-relative roles",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 546
        }
      },
      {
        "from": "input-dora-multiplicity",
        "to": "critic-state-assembly",
        "label": "Original-window deterministic public context",
        "kind": "features",
        "source": {
          "path": "model/network.py",
          "line": 205
        }
      },
      {
        "from": "input-known-unavailable-counts",
        "to": "critic-state-assembly",
        "label": "Original-window deterministic public context",
        "kind": "features",
        "source": {
          "path": "model/network.py",
          "line": 205
        }
      },
      {
        "from": "input-dealer-relative-seat",
        "to": "critic-state-assembly",
        "label": "Original-window deterministic public context",
        "kind": "features",
        "source": {
          "path": "model/network.py",
          "line": 205
        }
      },
      {
        "from": "input-opponent-called-tile-count",
        "to": "critic-state-assembly",
        "label": "Original-window deterministic public context",
        "kind": "features",
        "source": {
          "path": "model/network.py",
          "line": 205
        }
      },
      {
        "from": "input-opponent-discard-count",
        "to": "critic-state-assembly",
        "label": "Original-window deterministic public context",
        "kind": "features",
        "source": {
          "path": "model/network.py",
          "line": 205
        }
      },
      {
        "from": "input-riichi-push-count",
        "to": "critic-state-assembly",
        "label": "Original-window deterministic public context",
        "kind": "features",
        "source": {
          "path": "model/network.py",
          "line": 205
        }
      },
      {
        "from": "input-genbutsu-to-seat",
        "to": "critic-state-assembly",
        "label": "Original-window deterministic public context",
        "kind": "features",
        "source": {
          "path": "model/network.py",
          "line": 205
        }
      },
      {
        "from": "input-passed-unchanged-to-seat",
        "to": "critic-state-assembly",
        "label": "Original-window deterministic public context",
        "kind": "features",
        "source": {
          "path": "model/network.py",
          "line": 205
        }
      },
      {
        "from": "input-sotogawa-earliest-turn-to-seat",
        "to": "critic-state-assembly",
        "label": "Original-window deterministic public context",
        "kind": "features",
        "source": {
          "path": "model/network.py",
          "line": 205
        }
      },
      {
        "from": "input-riichi-state",
        "to": "critic-state-assembly",
        "label": "Original-window deterministic public context",
        "kind": "features",
        "source": {
          "path": "model/network.py",
          "line": 205
        }
      },
      {
        "from": "input-ippatsu-alive",
        "to": "critic-state-assembly",
        "label": "Original-window deterministic public context",
        "kind": "features",
        "source": {
          "path": "model/network.py",
          "line": 205
        }
      },
      {
        "from": "input-candidate-meld-tiles",
        "to": "critic-score-head",
        "label": "At-decision fu, visible meld bonus, dealer and legal score support",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 60
        }
      },
      {
        "from": "input-candidate-meld-types",
        "to": "critic-score-head",
        "label": "At-decision fu, visible meld bonus, dealer and legal score support",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 60
        }
      },
      {
        "from": "input-candidate-meld-red",
        "to": "critic-score-head",
        "label": "At-decision fu, visible meld bonus, dealer and legal score support",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 60
        }
      },
      {
        "from": "input-discard-candidate-hand",
        "to": "critic-score-head",
        "label": "At-decision fu, visible meld bonus, dealer and legal score support",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 60
        }
      },
      {
        "from": "input-kan-candidate-hand",
        "to": "critic-score-head",
        "label": "At-decision fu, visible meld bonus, dealer and legal score support",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 60
        }
      },
      {
        "from": "input-meld-type",
        "to": "critic-score-head",
        "label": "At-decision fu, visible meld bonus, dealer and legal score support",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 60
        }
      },
      {
        "from": "input-meld-tiles",
        "to": "critic-score-head",
        "label": "At-decision fu, visible meld bonus, dealer and legal score support",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 60
        }
      },
      {
        "from": "input-dora-multiplicity",
        "to": "critic-score-head",
        "label": "At-decision fu, visible meld bonus, dealer and legal score support",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 60
        }
      },
      {
        "from": "input-dealer-relative-seat",
        "to": "critic-score-head",
        "label": "At-decision fu, visible meld bonus, dealer and legal score support",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 60
        }
      },
      {
        "from": "input-decision-phase",
        "to": "critic-score-head",
        "label": "At-decision fu, visible meld bonus, dealer and legal score support",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 60
        }
      },
      {
        "from": "input-riichi-state",
        "to": "critic-score-head",
        "label": "At-decision fu, visible meld bonus, dealer and legal score support",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 60
        }
      },
      {
        "from": "input-public-bonus",
        "to": "critic-score-head",
        "label": "At-decision fu, visible meld bonus, dealer and legal score support",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 60
        }
      },
      {
        "from": "input-candidate-fu",
        "to": "critic-score-head",
        "label": "At-decision fu, visible meld bonus, dealer and legal score support",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 60
        }
      },
      {
        "from": "input-candidate-meld-tiles",
        "to": "settlement-decoder",
        "label": "Public legal-event and transfer constraints",
        "kind": "features",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        }
      },
      {
        "from": "input-candidate-meld-types",
        "to": "settlement-decoder",
        "label": "Public legal-event and transfer constraints",
        "kind": "features",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        }
      },
      {
        "from": "input-discard-candidate-hand",
        "to": "settlement-decoder",
        "label": "Public legal-event and transfer constraints",
        "kind": "features",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        }
      },
      {
        "from": "input-kan-candidate-hand",
        "to": "settlement-decoder",
        "label": "Public legal-event and transfer constraints",
        "kind": "features",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        }
      },
      {
        "from": "input-meld-type",
        "to": "settlement-decoder",
        "label": "Public legal-event and transfer constraints",
        "kind": "features",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        }
      },
      {
        "from": "input-meld-tiles",
        "to": "settlement-decoder",
        "label": "Public legal-event and transfer constraints",
        "kind": "features",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        }
      },
      {
        "from": "input-known-unavailable-counts",
        "to": "settlement-decoder",
        "label": "Public legal-event and transfer constraints",
        "kind": "features",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        }
      },
      {
        "from": "input-hands-remaining",
        "to": "settlement-decoder",
        "label": "Public legal-event and transfer constraints",
        "kind": "features",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        }
      },
      {
        "from": "input-dealer-relative-seat",
        "to": "settlement-decoder",
        "label": "Public legal-event and transfer constraints",
        "kind": "features",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        }
      },
      {
        "from": "input-honba",
        "to": "settlement-decoder",
        "label": "Public legal-event and transfer constraints",
        "kind": "features",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        }
      },
      {
        "from": "input-riichi-sticks",
        "to": "settlement-decoder",
        "label": "Public legal-event and transfer constraints",
        "kind": "features",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        }
      },
      {
        "from": "input-live-wall-count",
        "to": "settlement-decoder",
        "label": "Public legal-event and transfer constraints",
        "kind": "features",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        }
      },
      {
        "from": "input-scores",
        "to": "settlement-decoder",
        "label": "Public legal-event and transfer constraints",
        "kind": "features",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        }
      },
      {
        "from": "input-seat-wind",
        "to": "settlement-decoder",
        "label": "Public legal-event and transfer constraints",
        "kind": "features",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        }
      },
      {
        "from": "input-nagashi-possible",
        "to": "settlement-decoder",
        "label": "Public legal-event and transfer constraints",
        "kind": "features",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        }
      },
      {
        "from": "input-pao-payer",
        "to": "settlement-decoder",
        "label": "Public legal-event and transfer constraints",
        "kind": "features",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        }
      },
      {
        "from": "input-genbutsu-to-seat",
        "to": "settlement-decoder",
        "label": "Public legal-event and transfer constraints",
        "kind": "features",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        }
      },
      {
        "from": "input-decision-phase",
        "to": "settlement-decoder",
        "label": "Public legal-event and transfer constraints",
        "kind": "features",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        }
      },
      {
        "from": "input-riichi-state",
        "to": "settlement-decoder",
        "label": "Public legal-event and transfer constraints",
        "kind": "features",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        }
      },
      {
        "from": "input-discard-abort",
        "to": "settlement-decoder",
        "label": "Public legal-event and transfer constraints",
        "kind": "features",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        }
      },
      {
        "from": "input-discard-action-all-shanten",
        "to": "settlement-decoder",
        "label": "Public legal-event and transfer constraints",
        "kind": "features",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        }
      },
      {
        "from": "input-response-legal-mask",
        "to": "call-factorization",
        "label": "Sparse accepted-call rows and owner/option selectors",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 443
        }
      },
      {
        "from": "input-call-discard-legal",
        "to": "call-factorization",
        "label": "Sparse accepted-call rows and owner/option selectors",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 443
        }
      },
      {
        "from": "input-post-call-owner",
        "to": "call-factorization",
        "label": "Sparse accepted-call rows and owner/option selectors",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 443
        }
      },
      {
        "from": "input-post-call-option",
        "to": "call-factorization",
        "label": "Sparse accepted-call rows and owner/option selectors",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 443
        }
      },
      {
        "from": "input-candidate-hand-counts",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "input-candidate-hand-red",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "input-candidate-meld-tiles",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "input-candidate-meld-types",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "input-candidate-meld-red",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "input-discard-candidate-hand",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "input-kan-candidate-hand",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "input-dora-multiplicity",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "input-known-unavailable-counts",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "input-live-wall-count",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "input-post-call-candidate-hand-counts",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "input-post-call-candidate-hand-red",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "input-post-call-candidate-meld-tiles",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "input-post-call-candidate-meld-types",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "input-post-call-candidate-meld-red",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "input-post-call-discard-candidate-hand",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "input-post-call-kan-candidate-hand",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "input-post-call-dora-multiplicity",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "input-post-call-known-unavailable-counts",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "input-post-call-live-wall-count",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "input-post-call-owner",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "input-post-call-option",
        "to": "call-candidate-merge",
        "label": "Board-specific hand facts and post-call ownership indices",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 508
        }
      },
      {
        "from": "input-meld-tiles",
        "to": "candidate-ron-prediction",
        "label": "Discard and public safe-tile support",
        "kind": "features",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 25
        }
      },
      {
        "from": "input-known-unavailable-counts",
        "to": "candidate-ron-prediction",
        "label": "Discard and public safe-tile support",
        "kind": "features",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 25
        }
      },
      {
        "from": "input-genbutsu-to-seat",
        "to": "candidate-ron-prediction",
        "label": "Discard and public safe-tile support",
        "kind": "features",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 25
        }
      },
      {
        "from": "input-decision-phase",
        "to": "candidate-ron-prediction",
        "label": "Discard and public safe-tile support",
        "kind": "features",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 25
        }
      },
      {
        "from": "input-post-call-meld-tiles",
        "to": "candidate-ron-prediction",
        "label": "Discard and public safe-tile support",
        "kind": "features",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 25
        }
      },
      {
        "from": "input-post-call-known-unavailable-counts",
        "to": "candidate-ron-prediction",
        "label": "Discard and public safe-tile support",
        "kind": "features",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 25
        }
      },
      {
        "from": "input-post-call-genbutsu-to-seat",
        "to": "candidate-ron-prediction",
        "label": "Discard and public safe-tile support",
        "kind": "features",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 25
        }
      },
      {
        "from": "input-post-call-decision-phase",
        "to": "candidate-ron-prediction",
        "label": "Discard and public safe-tile support",
        "kind": "features",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 25
        }
      },
      {
        "from": "input-meld-tiles",
        "to": "belief-readouts",
        "kind": "features",
        "label": "49 opponent-local observed channels for shared shanten head",
        "source": {
          "path": "model/beliefs.py",
          "line": 276
        }
      },
      {
        "from": "input-dealer-relative-seat",
        "to": "belief-readouts",
        "kind": "features",
        "label": "49 opponent-local observed channels for shared shanten head",
        "source": {
          "path": "model/beliefs.py",
          "line": 276
        }
      },
      {
        "from": "input-live-wall-count",
        "to": "belief-readouts",
        "kind": "features",
        "label": "49 opponent-local observed channels for shared shanten head",
        "source": {
          "path": "model/beliefs.py",
          "line": 276
        }
      },
      {
        "from": "input-opponent-discard-count",
        "to": "belief-readouts",
        "kind": "features",
        "label": "49 opponent-local observed channels for shared shanten head",
        "source": {
          "path": "model/beliefs.py",
          "line": 276
        }
      },
      {
        "from": "input-last-tedashi-tile-id",
        "to": "belief-readouts",
        "kind": "features",
        "label": "49 opponent-local observed channels for shared shanten head",
        "source": {
          "path": "model/beliefs.py",
          "line": 276
        }
      },
      {
        "from": "input-riichi-state",
        "to": "belief-readouts",
        "kind": "features",
        "label": "49 opponent-local observed channels for shared shanten head",
        "source": {
          "path": "model/beliefs.py",
          "line": 276
        }
      },
      {
        "from": "input-candidate-hand-counts",
        "to": "completion-evidence",
        "label": "Own slot-0 hand, known supply and dora multiplicity",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 336
        }
      },
      {
        "from": "input-candidate-hand-red",
        "to": "completion-evidence",
        "label": "Own slot-0 hand, known supply and dora multiplicity",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 336
        }
      },
      {
        "from": "input-dora-multiplicity",
        "to": "completion-evidence",
        "label": "Own slot-0 hand, known supply and dora multiplicity",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 336
        }
      },
      {
        "from": "input-public-visible-red-counts",
        "to": "completion-evidence",
        "label": "Own slot-0 hand, known supply and dora multiplicity",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 336
        }
      },
      {
        "from": "input-known-unavailable-counts",
        "to": "completion-evidence",
        "label": "Own slot-0 hand, known supply and dora multiplicity",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 336
        }
      },
      {
        "from": "input-post-call-candidate-hand-counts",
        "to": "completion-evidence",
        "label": "Own slot-0 hand, known supply and dora multiplicity",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 336
        }
      },
      {
        "from": "input-post-call-candidate-hand-red",
        "to": "completion-evidence",
        "label": "Own slot-0 hand, known supply and dora multiplicity",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 336
        }
      },
      {
        "from": "input-post-call-dora-multiplicity",
        "to": "completion-evidence",
        "label": "Own slot-0 hand, known supply and dora multiplicity",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 336
        }
      },
      {
        "from": "input-post-call-public-visible-red-counts",
        "to": "completion-evidence",
        "label": "Own slot-0 hand, known supply and dora multiplicity",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 336
        }
      },
      {
        "from": "input-post-call-known-unavailable-counts",
        "to": "completion-evidence",
        "label": "Own slot-0 hand, known supply and dora multiplicity",
        "kind": "features",
        "source": {
          "path": "model/beliefs.py",
          "line": 336
        }
      },
      {
        "from": "input-response-legal-mask",
        "to": "call-choice",
        "label": "Legal call branches on the decision board",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 546
        }
      },
      {
        "from": "input-call-discard-legal",
        "to": "call-choice",
        "label": "Legal call branches on the decision board",
        "kind": "features",
        "source": {
          "path": "model/actor.py",
          "line": 546
        }
      },
      {
        "from": "input-prevailing-wind",
        "to": "continuation-payoffs",
        "label": "Dealer, hand number and outstanding riichi deposits",
        "kind": "features",
        "source": {
          "path": "model/export.py",
          "line": 78
        }
      },
      {
        "from": "input-hands-remaining",
        "to": "continuation-payoffs",
        "label": "Dealer, hand number and outstanding riichi deposits",
        "kind": "features",
        "source": {
          "path": "model/export.py",
          "line": 78
        }
      },
      {
        "from": "input-dealer-relative-seat",
        "to": "continuation-payoffs",
        "label": "Dealer, hand number and outstanding riichi deposits",
        "kind": "features",
        "source": {
          "path": "model/export.py",
          "line": 78
        }
      },
      {
        "from": "input-riichi-sticks",
        "to": "continuation-payoffs",
        "label": "Dealer, hand number and outstanding riichi deposits",
        "kind": "features",
        "source": {
          "path": "model/export.py",
          "line": 78
        }
      },
      {
        "from": "input-candidate-hand-yaku-possibility",
        "to": "hand-bank-output",
        "kind": "features",
        "label": "Yaku feasibility for each resulting hand",
        "source": {
          "path": "model/encoder.py",
          "line": 377
        }
      },
      {
        "from": "input-post-call-candidate-hand-yaku-possibility",
        "to": "hand-bank-output",
        "kind": "features",
        "label": "Yaku feasibility for each resulting hand",
        "source": {
          "path": "model/encoder.py",
          "line": 377
        }
      },
      {
        "from": "input-post-call-owner",
        "to": "actor-candidate-pool",
        "kind": "features",
        "label": "Original decision owner for each after-call position",
        "source": {
          "path": "model/actor.py",
          "line": 86
        }
      },
      {
        "from": "input-candidate-meld-tiles",
        "to": "critic-claim-state",
        "label": "Public fu, bonus han, open-hand and riichi features",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 949
        }
      },
      {
        "from": "input-candidate-meld-types",
        "to": "critic-claim-state",
        "label": "Public fu, bonus han, open-hand and riichi features",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 949
        }
      },
      {
        "from": "input-candidate-meld-red",
        "to": "critic-claim-state",
        "label": "Public fu, bonus han, open-hand and riichi features",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 949
        }
      },
      {
        "from": "input-discard-candidate-hand",
        "to": "critic-claim-state",
        "label": "Public fu, bonus han, open-hand and riichi features",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 949
        }
      },
      {
        "from": "input-kan-candidate-hand",
        "to": "critic-claim-state",
        "label": "Public fu, bonus han, open-hand and riichi features",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 949
        }
      },
      {
        "from": "input-meld-type",
        "to": "critic-claim-state",
        "label": "Public fu, bonus han, open-hand and riichi features",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 949
        }
      },
      {
        "from": "input-meld-tiles",
        "to": "critic-claim-state",
        "label": "Public fu, bonus han, open-hand and riichi features",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 949
        }
      },
      {
        "from": "input-dora-multiplicity",
        "to": "critic-claim-state",
        "label": "Public fu, bonus han, open-hand and riichi features",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 949
        }
      },
      {
        "from": "input-decision-phase",
        "to": "critic-claim-state",
        "label": "Public fu, bonus han, open-hand and riichi features",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 949
        }
      },
      {
        "from": "input-riichi-state",
        "to": "critic-claim-state",
        "label": "Public fu, bonus han, open-hand and riichi features",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 949
        }
      },
      {
        "from": "input-public-bonus",
        "to": "critic-claim-state",
        "label": "Public fu, bonus han, open-hand and riichi features",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 949
        }
      },
      {
        "from": "input-candidate-fu",
        "to": "critic-claim-state",
        "label": "Public fu, bonus han, open-hand and riichi features",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 949
        }
      },
      {
        "from": "input-pao-payer",
        "to": "critic-pao-allocation",
        "label": "Known responsibility and legal claimant support",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 1070
        }
      },
      {
        "from": "input-riichi-state",
        "to": "critic-pao-allocation",
        "label": "Known responsibility and legal claimant support",
        "kind": "features",
        "source": {
          "path": "model/critic.py",
          "line": 1070
        }
      }
    ],
    "input_blocks": [
      {
        "id": "inputs-parent-table",
        "board": "parent",
        "subject": "table",
        "title": "At decision · Public table",
        "kind": "Input block",
        "members": [
          "input-meld-type",
          "input-meld-tiles",
          "input-meld-source",
          "input-meld-call-age",
          "input-meld-upgrade-age",
          "input-dora-multiplicity",
          "input-public-visible-red-counts",
          "input-known-unavailable-counts",
          "input-prevailing-wind",
          "input-hands-remaining",
          "input-dealer-relative-seat",
          "input-honba",
          "input-riichi-sticks",
          "input-live-wall-count",
          "input-total-kan-count",
          "input-scores",
          "input-ranks",
          "input-seat-wind",
          "input-nagashi-possible",
          "input-pao-payer",
          "input-riichi-state",
          "input-ippatsu-alive",
          "input-public-bonus"
        ]
      },
      {
        "id": "inputs-parent-hand",
        "board": "parent",
        "subject": "hand",
        "title": "At decision · Own hand",
        "kind": "Input block",
        "members": [
          "input-candidate-hand-counts",
          "input-candidate-hand-red",
          "input-candidate-hand-yaku-possibility",
          "input-candidate-meld-tiles",
          "input-candidate-meld-types",
          "input-candidate-meld-red",
          "input-candidate-hand-valid",
          "input-current-draw-tile-id",
          "input-current-draw-is-red",
          "input-current-draw-valid",
          "input-normal-self-shanten",
          "input-chiitoitsu-self-shanten",
          "input-kokushi-self-shanten",
          "input-closed-hand",
          "input-self-efficiency",
          "input-rinshan-state",
          "input-candidate-yaku-shanten",
          "input-candidate-fu"
        ]
      },
      {
        "id": "inputs-parent-opponents",
        "board": "parent",
        "subject": "opponents",
        "title": "At decision · Opponent evidence",
        "kind": "Input block",
        "members": [
          "input-river-pre-tile-id",
          "input-river-pre-is-red",
          "input-river-pre-tsumogiri",
          "input-river-pre-origin",
          "input-river-pre-riichi",
          "input-river-pre-call-resolution",
          "input-river-pre-caller",
          "input-river-pre-event-age",
          "input-river-pre-own-gap",
          "input-river-pre-live-wall",
          "input-river-pre-current-dora-multiplicity",
          "input-river-pre-dora-multiplicity-at-discard",
          "input-river-pre-valid",
          "input-river-post-tile-id",
          "input-river-post-is-red",
          "input-river-post-tsumogiri",
          "input-river-post-origin",
          "input-river-post-call-resolution",
          "input-river-post-caller",
          "input-river-post-event-age",
          "input-river-post-own-gap",
          "input-river-post-live-wall",
          "input-river-post-current-dora-multiplicity",
          "input-river-post-dora-multiplicity-at-discard",
          "input-river-post-valid",
          "input-open-opponent-yaku-possibility",
          "input-opponent-called-tile-count",
          "input-opponent-discard-count",
          "input-last-tedashi-tile-id",
          "input-riichi-push-count",
          "input-genbutsu-to-seat",
          "input-passed-unchanged-to-seat",
          "input-sotogawa-earliest-turn-to-seat"
        ]
      },
      {
        "id": "inputs-parent-actions",
        "board": "parent",
        "subject": "actions",
        "title": "At decision · Action choices",
        "kind": "Input block",
        "members": [
          "input-discard-candidate-hand",
          "input-kan-candidate-hand",
          "input-win-kind",
          "input-decision-phase",
          "input-trigger-tile-id",
          "input-trigger-is-red",
          "input-trigger-valid",
          "input-trigger-source",
          "input-riichi-legal-mask",
          "input-riichi-discard-legal-mask",
          "input-response-legal-mask",
          "input-call-discard-legal",
          "input-call-discard-shanten",
          "input-call-discard-ukeire-count",
          "input-kan-legal-mask",
          "input-call-efficiency",
          "input-kan-efficiency",
          "input-discard-abort",
          "input-discard-action-legal",
          "input-discard-tedashi-legal",
          "input-discard-action-normal-shanten",
          "input-discard-action-normal-ukeire-count",
          "input-discard-action-all-shanten",
          "input-discard-action-all-ukeire-count",
          "input-discard-retained-genbutsu",
          "input-action-win-value-range",
          "input-action-win-value-valid",
          "input-action-value-eligible",
          "input-action-open-yaku-restricted"
        ]
      },
      {
        "id": "inputs-child-table",
        "board": "child",
        "subject": "table",
        "title": "After call · Public table",
        "kind": "Input block",
        "members": [
          "input-post-call-meld-type",
          "input-post-call-meld-tiles",
          "input-post-call-meld-source",
          "input-post-call-meld-call-age",
          "input-post-call-meld-upgrade-age",
          "input-post-call-dora-multiplicity",
          "input-post-call-public-visible-red-counts",
          "input-post-call-known-unavailable-counts",
          "input-post-call-prevailing-wind",
          "input-post-call-hands-remaining",
          "input-post-call-dealer-relative-seat",
          "input-post-call-honba",
          "input-post-call-riichi-sticks",
          "input-post-call-live-wall-count",
          "input-post-call-total-kan-count",
          "input-post-call-scores",
          "input-post-call-ranks",
          "input-post-call-seat-wind",
          "input-post-call-nagashi-possible",
          "input-post-call-pao-payer",
          "input-post-call-riichi-state",
          "input-post-call-ippatsu-alive",
          "input-post-call-public-bonus"
        ]
      },
      {
        "id": "inputs-child-hand",
        "board": "child",
        "subject": "hand",
        "title": "After call · Own hand",
        "kind": "Input block",
        "members": [
          "input-post-call-candidate-hand-counts",
          "input-post-call-candidate-hand-red",
          "input-post-call-candidate-hand-yaku-possibility",
          "input-post-call-candidate-meld-tiles",
          "input-post-call-candidate-meld-types",
          "input-post-call-candidate-meld-red",
          "input-post-call-candidate-hand-valid",
          "input-post-call-current-draw-tile-id",
          "input-post-call-current-draw-is-red",
          "input-post-call-current-draw-valid",
          "input-post-call-normal-self-shanten",
          "input-post-call-chiitoitsu-self-shanten",
          "input-post-call-kokushi-self-shanten",
          "input-post-call-closed-hand",
          "input-post-call-self-efficiency",
          "input-post-call-rinshan-state",
          "input-post-call-candidate-yaku-shanten",
          "input-post-call-candidate-fu"
        ]
      },
      {
        "id": "inputs-child-opponents",
        "board": "child",
        "subject": "opponents",
        "title": "After call · Opponent evidence",
        "kind": "Input block",
        "members": [
          "input-post-call-river-pre-tile-id",
          "input-post-call-river-pre-is-red",
          "input-post-call-river-pre-tsumogiri",
          "input-post-call-river-pre-origin",
          "input-post-call-river-pre-riichi",
          "input-post-call-river-pre-call-resolution",
          "input-post-call-river-pre-caller",
          "input-post-call-river-pre-event-age",
          "input-post-call-river-pre-own-gap",
          "input-post-call-river-pre-live-wall",
          "input-post-call-river-pre-current-dora-multiplicity",
          "input-post-call-river-pre-dora-multiplicity-at-discard",
          "input-post-call-river-pre-valid",
          "input-post-call-river-post-tile-id",
          "input-post-call-river-post-is-red",
          "input-post-call-river-post-tsumogiri",
          "input-post-call-river-post-origin",
          "input-post-call-river-post-call-resolution",
          "input-post-call-river-post-caller",
          "input-post-call-river-post-event-age",
          "input-post-call-river-post-own-gap",
          "input-post-call-river-post-live-wall",
          "input-post-call-river-post-current-dora-multiplicity",
          "input-post-call-river-post-dora-multiplicity-at-discard",
          "input-post-call-river-post-valid",
          "input-post-call-open-opponent-yaku-possibility",
          "input-post-call-opponent-called-tile-count",
          "input-post-call-opponent-discard-count",
          "input-post-call-last-tedashi-tile-id",
          "input-post-call-riichi-push-count",
          "input-post-call-genbutsu-to-seat",
          "input-post-call-passed-unchanged-to-seat",
          "input-post-call-sotogawa-earliest-turn-to-seat"
        ]
      },
      {
        "id": "inputs-child-actions",
        "board": "child",
        "subject": "actions",
        "title": "After call · Action choices",
        "kind": "Input block",
        "members": [
          "input-post-call-discard-candidate-hand",
          "input-post-call-kan-candidate-hand",
          "input-post-call-win-kind",
          "input-post-call-decision-phase",
          "input-post-call-trigger-tile-id",
          "input-post-call-trigger-is-red",
          "input-post-call-trigger-valid",
          "input-post-call-trigger-source",
          "input-post-call-riichi-legal-mask",
          "input-post-call-riichi-discard-legal-mask",
          "input-post-call-response-legal-mask",
          "input-post-call-call-discard-legal",
          "input-post-call-call-discard-shanten",
          "input-post-call-call-discard-ukeire-count",
          "input-post-call-kan-legal-mask",
          "input-post-call-call-efficiency",
          "input-post-call-kan-efficiency",
          "input-post-call-discard-abort",
          "input-post-call-discard-action-legal",
          "input-post-call-discard-tedashi-legal",
          "input-post-call-discard-action-normal-shanten",
          "input-post-call-discard-action-normal-ukeire-count",
          "input-post-call-discard-action-all-shanten",
          "input-post-call-discard-action-all-ukeire-count",
          "input-post-call-discard-retained-genbutsu",
          "input-post-call-action-win-value-range",
          "input-post-call-action-win-value-valid",
          "input-post-call-action-value-eligible",
          "input-post-call-action-open-yaku-restricted"
        ]
      },
      {
        "id": "inputs-call-routing",
        "board": "routing",
        "subject": "routing",
        "title": "Decision and call indices",
        "kind": "Input block",
        "members": [
          "input-post-call-owner",
          "input-post-call-option"
        ]
      }
    ],
    "belief_source": {
      "path": "model/beliefs.py",
      "line": 91
    },
    "modules": [
      {
        "id": "model/__init__.py",
        "path": "model/__init__.py",
        "description": "Mahjong network components, scoring, export and inference.",
        "symbols": []
      },
      {
        "id": "model/actions.py",
        "path": "model/actions.py",
        "description": "Legal actions, physical-copy selection and model action indexing.",
        "symbols": [
          {
            "name": "phase_for_actions",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/actions.py",
              "line": 53
            },
            "layers": []
          },
          {
            "name": "forced_policy_action",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/actions.py",
              "line": 66
            },
            "layers": []
          },
          {
            "name": "policy_request",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/actions.py",
              "line": 88
            },
            "layers": []
          },
          {
            "name": "continue_request",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/actions.py",
              "line": 101
            },
            "layers": []
          },
          {
            "name": "select_discard",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/actions.py",
              "line": 121
            },
            "layers": []
          },
          {
            "name": "policy_candidates",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/actions.py",
              "line": 144
            },
            "layers": []
          },
          {
            "name": "opening_temperature",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/actions.py",
              "line": 248
            },
            "layers": []
          },
          {
            "name": "select_policy_action",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/actions.py",
              "line": 252
            },
            "layers": []
          },
          {
            "name": "legal_choices",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/actions.py",
              "line": 305
            },
            "layers": []
          },
          {
            "name": "guaranteed_safe_tiles",
            "kind": "function",
            "description": "Publicly proven ron safety, by opponent and base tile.",
            "source": {
              "path": "model/actions.py",
              "line": 334
            },
            "layers": []
          },
          {
            "name": "candidate_hand_indices",
            "kind": "function",
            "description": "Local hand indices in the joint 295-action address space.\n\nCall-window slots retain the original hand here; their accepted-call\nrepresentations are encoded from sparse child states separately.",
            "source": {
              "path": "model/actions.py",
              "line": 366
            },
            "layers": []
          },
          {
            "name": "discard_decisions",
            "kind": "function",
            "description": "Actions ending in a discard, including chii/pon then discard.",
            "source": {
              "path": "model/actions.py",
              "line": 389
            },
            "layers": []
          }
        ]
      },
      {
        "id": "model/actor.py",
        "path": "model/actor.py",
        "description": "Policy heads, legal masks and final candidate scoring.",
        "symbols": [
          {
            "name": "PolicyMask",
            "kind": "class",
            "description": "",
            "source": {
              "path": "model/actor.py",
              "line": 10
            },
            "layers": []
          },
          {
            "name": "PolicySummaries",
            "kind": "class",
            "description": "",
            "source": {
              "path": "model/actor.py",
              "line": 64
            },
            "layers": []
          },
          {
            "name": "CandidatePool",
            "kind": "class",
            "description": "Attend to legal candidates using the private actor context.",
            "source": {
              "path": "model/actor.py",
              "line": 86
            },
            "layers": [
              "tf.keras.layers.LayerNormalization()",
              "tf.keras.layers.LayerNormalization()",
              "tf.keras.layers.Dense(width)",
              "tf.keras.layers.Dense(width)",
              "tf.keras.layers.Dense(width)",
              "tf.keras.layers.Dense(\n            output_width, kernel_initializer=\"zeros\", bias_initializer=\"zeros\"\n        )"
            ]
          },
          {
            "name": "build_policy_heads",
            "kind": "function",
            "description": "Condition each local action on decision and candidate predictions.",
            "source": {
              "path": "model/actor.py",
              "line": 155
            },
            "layers": [
              "tf.keras.layers.Dense(\n        512, activation=\"gelu\", dtype=\"float32\", name=\"final_pass\"\n    )",
              "tf.keras.layers.LayerNormalization(\n        center=False,\n        scale=False,\n        epsilon=1e-5,\n        dtype=\"float32\",\n        name=\"final_pass_normalized\",\n    )",
              "tf.keras.layers.Dense(1, dtype=\"float32\", name=\"final_scores\")"
            ]
          },
          {
            "name": "build_board_heads",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/actor.py",
              "line": 203
            },
            "layers": [
              "tf.keras.layers.Dense(2, dtype=\"float32\", name=\"win_decision_logits\")"
            ]
          },
          {
            "name": "final_wall_safe_cuts",
            "kind": "function",
            "description": "Return the forced uniform support, or an empty mask on free choices.",
            "source": {
              "path": "model/actor.py",
              "line": 215
            },
            "layers": []
          },
          {
            "name": "opening_discard_symmetry",
            "kind": "function",
            "description": "Pool equivalent legal cuts on the dealer’s first discard.",
            "source": {
              "path": "model/actor.py",
              "line": 239
            },
            "layers": []
          },
          {
            "name": "FinalCandidates",
            "kind": "class",
            "description": "",
            "source": {
              "path": "model/actor.py",
              "line": 316
            },
            "layers": []
          },
          {
            "name": "distribution",
            "kind": "function",
            "description": "Normalize over the exact native candidates used by the collector.",
            "source": {
              "path": "model/actor.py",
              "line": 325
            },
            "layers": []
          },
          {
            "name": "CallPolicy",
            "kind": "class",
            "description": "A call choice followed by the ordinary policy on accepted-call states.",
            "source": {
              "path": "model/actor.py",
              "line": 338
            },
            "layers": [
              "tf.keras.layers.Dense(\n            6,\n            kernel_initializer=\"zeros\",\n            bias_initializer=\"zeros\",\n            dtype=\"float32\",\n            name=\"call_choice\",\n        )"
            ]
          },
          {
            "name": "greedy_choices",
            "kind": "function",
            "description": "Marginal branch selection on device, with lowest-index tie breaks.",
            "source": {
              "path": "model/actor.py",
              "line": 611
            },
            "layers": []
          },
          {
            "name": "UnpackCandidates",
            "kind": "class",
            "description": "",
            "source": {
              "path": "model/actor.py",
              "line": 644
            },
            "layers": []
          }
        ]
      },
      {
        "id": "model/beliefs.py",
        "path": "model/beliefs.py",
        "description": "Opponent belief heads, constraints and supervision.",
        "symbols": [
          {
            "name": "held_count_context",
            "kind": "function",
            "description": "Known meld copies, unseen physical copies and concealed hand sizes.",
            "source": {
              "path": "model/beliefs.py",
              "line": 12
            },
            "layers": []
          },
          {
            "name": "HeldCountMask",
            "kind": "class",
            "description": "",
            "source": {
              "path": "model/beliefs.py",
              "line": 37
            },
            "layers": []
          },
          {
            "name": "StructuralWait",
            "kind": "class",
            "description": "Joint tenpai-and-improving probability as stable tile-wise logits.",
            "source": {
              "path": "model/beliefs.py",
              "line": 47
            },
            "layers": []
          },
          {
            "name": "Probabilities",
            "kind": "class",
            "description": "",
            "source": {
              "path": "model/beliefs.py",
              "line": 145
            },
            "layers": []
          },
          {
            "name": "TileAttention",
            "kind": "class",
            "description": "Refine count and wait marginals jointly across all 34 tile types.",
            "source": {
              "path": "model/beliefs.py",
              "line": 157
            },
            "layers": [
              "tf.keras.layers.Embedding(34, 8, dtype=\"float32\")",
              "tf.keras.layers.Dense(3 * 64, dtype=\"float32\")",
              "tf.keras.layers.Dense(128, dtype=\"mixed_bfloat16\")",
              "tf.keras.layers.Dense(\n            14,\n            kernel_initializer=\"zeros\",\n            bias_initializer=\"zeros\",\n            dtype=\"float32\",\n        )",
              "tf.keras.layers.MultiHeadAttention(\n                num_heads=4, key_dim=32, dtype=\"mixed_bfloat16\"\n            )",
              "tf.keras.layers.LayerNormalization(dtype=\"float32\")",
              "tf.keras.layers.LayerNormalization(dtype=\"float32\")",
              "tf.keras.layers.Dense(\n                        256, activation=\"gelu\", dtype=\"mixed_bfloat16\"\n                    )",
              "tf.keras.layers.Dense(128, dtype=\"mixed_bfloat16\")"
            ]
          },
          {
            "name": "OpponentShanten",
            "kind": "class",
            "description": "One shared four-class readout conditioned on each opponent's evidence.",
            "source": {
              "path": "model/beliefs.py",
              "line": 276
            },
            "layers": [
              "tf.keras.layers.Dense(48, use_bias=False, dtype=\"float32\")",
              "tf.keras.layers.Dense(48, dtype=\"float32\")",
              "tf.keras.layers.Dense(\n            4, kernel_initializer=\"zeros\", dtype=\"float32\"\n        )"
            ]
          },
          {
            "name": "CompletionEvidence",
            "kind": "class",
            "description": "Shared opponent yaku residual from observed and inferred tiles.",
            "source": {
              "path": "model/beliefs.py",
              "line": 336
            },
            "layers": [
              "tf.keras.layers.Dense(\n            64, activation=\"gelu\", dtype=\"float32\"\n        )",
              "tf.keras.layers.Dense(\n            math.prod(actions.ACTOR_OUTPUTS[COMPLETION_HEADS[0]][1:]),\n            kernel_initializer=\"zeros\",\n            dtype=\"float32\",\n        )"
            ]
          },
          {
            "name": "Beliefs",
            "kind": "class",
            "description": "Shared opponent and hand-completion beliefs from the board encoder.",
            "source": {
              "path": "model/beliefs.py",
              "line": 408
            },
            "layers": [
              "tf.keras.layers.LayerNormalization(dtype=\"float32\")",
              "tf.keras.layers.Dense(1152, activation=\"gelu\", dtype=\"float32\")",
              "tf.keras.layers.Dense(\n                    512, kernel_initializer=\"zeros\", dtype=\"float32\"\n                )",
              "tf.keras.layers.Dense(\n                    math.prod(actions.ACTOR_OUTPUTS[name]),\n                    dtype=\"float32\",\n                    name=name.removesuffix(\"_logits\") + \"_scores\",\n                )"
            ]
          },
          {
            "name": "count_weights",
            "kind": "function",
            "description": "Shared strategic weights for count supervision and projection.",
            "source": {
              "path": "model/beliefs.py",
              "line": 563
            },
            "layers": []
          },
          {
            "name": "CountProjection",
            "kind": "class",
            "description": "Weighted minimum-KL marginal projection using public constraints.\n\nInput logits must already have HeldCountMask applied. This enforces\nexpected concealed sizes and shared physical copy limits, not a joint\ndistribution over legal hands. No hidden labels enter the projection.",
            "source": {
              "path": "model/beliefs.py",
              "line": 585
            },
            "layers": []
          },
          {
            "name": "belief_loss_terms",
            "kind": "function",
            "description": "Opponent supervision for joint training.",
            "source": {
              "path": "model/beliefs.py",
              "line": 750
            },
            "layers": []
          },
          {
            "name": "ukeire_loss",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/beliefs.py",
              "line": 767
            },
            "layers": []
          },
          {
            "name": "completion_loss_terms",
            "kind": "function",
            "description": "Masked supervised yaku and score completion likelihoods.",
            "source": {
              "path": "model/beliefs.py",
              "line": 791
            },
            "layers": []
          }
        ]
      },
      {
        "id": "model/candidate_predictions.py",
        "path": "model/candidate_predictions.py",
        "description": "Candidate route support and opponent ron liability predictions.",
        "symbols": [
          {
            "name": "predict",
            "kind": "function",
            "description": "Predict candidate targets once for each selected local action.",
            "source": {
              "path": "model/candidate_predictions.py",
              "line": 8
            },
            "layers": [
              "tf.keras.layers.Dense(\n        3, dtype=\"float32\", name=\"route_affinity\"\n    )"
            ]
          },
          {
            "name": "RonRisk",
            "kind": "class",
            "description": "Ron requires a structural wait on the discarded tile and eligibility.",
            "source": {
              "path": "model/candidate_predictions.py",
              "line": 25
            },
            "layers": []
          },
          {
            "name": "RouteMask",
            "kind": "class",
            "description": "",
            "source": {
              "path": "model/candidate_predictions.py",
              "line": 53
            },
            "layers": []
          },
          {
            "name": "ron_risk_labels",
            "kind": "function",
            "description": "Legal discard ron, including unknown amounts but excluding triple ron.",
            "source": {
              "path": "model/candidate_predictions.py",
              "line": 90
            },
            "layers": []
          },
          {
            "name": "loss_terms",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/candidate_predictions.py",
              "line": 106
            },
            "layers": []
          }
        ]
      },
      {
        "id": "model/critic.py",
        "path": "model/critic.py",
        "description": "Action-conditioned settlements and policy values.",
        "symbols": [
          {
            "name": "meld_tile_counts",
            "kind": "function",
            "description": "Expand chi starts, triplets and kans to their physical tile counts.",
            "source": {
              "path": "model/critic.py",
              "line": 48
            },
            "layers": []
          },
          {
            "name": "public_inputs",
            "kind": "function",
            "description": "Guaranteed scoring constraints given an attempted action.\n\nScores and the existing pot remain pre-action: settlement deposits account\nfor a declaration only after its discard survives ron.",
            "source": {
              "path": "model/critic.py",
              "line": 60
            },
            "layers": []
          },
          {
            "name": "PublicContext",
            "kind": "class",
            "description": "",
            "source": {
              "path": "model/critic.py",
              "line": 334
            },
            "layers": []
          },
          {
            "name": "HandContext",
            "kind": "class",
            "description": "",
            "source": {
              "path": "model/critic.py",
              "line": 468
            },
            "layers": []
          },
          {
            "name": "PlayerContext",
            "kind": "class",
            "description": "Public player descriptors, without learned opponent-slot predictions.",
            "source": {
              "path": "model/critic.py",
              "line": 542
            },
            "layers": []
          },
          {
            "name": "BeliefContext",
            "kind": "class",
            "description": "Small shared residual from an opponent token and belief moments.",
            "source": {
              "path": "model/critic.py",
              "line": 677
            },
            "layers": [
              "tf.keras.layers.Dense(\n            128, activation=\"gelu\", dtype=\"float32\"\n        )",
              "tf.keras.layers.Dense(\n            96, kernel_initializer=\"zeros\", dtype=\"float32\"\n        )"
            ]
          },
          {
            "name": "ResultAttention",
            "kind": "class",
            "description": "Refine whole-event hypotheses within each candidate independently.",
            "source": {
              "path": "model/critic.py",
              "line": 741
            },
            "layers": [
              "tf.keras.layers.LayerNormalization(\n            dtype=self.dtype_policy\n        )",
              "tf.keras.layers.MultiHeadAttention(\n            num_heads=4, key_dim=16, dtype=self.dtype_policy\n        )",
              "tf.keras.layers.Dense(\n            32,\n            use_bias=False,\n            kernel_initializer=\"zeros\",\n            dtype=self.dtype_policy,\n        )"
            ]
          },
          {
            "name": "PaymentCritic",
            "kind": "class",
            "description": "Predict action-conditioned hand events, scores and deposits.",
            "source": {
              "path": "model/critic.py",
              "line": 770
            },
            "layers": [
              "tf.keras.layers.Dense(\n            384, activation=\"gelu\", dtype=\"float32\"\n        )",
              "tf.keras.layers.Dense(\n            96, activation=\"gelu\", dtype=\"float32\"\n        )",
              "tf.keras.layers.Dense(\n            96, activation=\"gelu\", dtype=\"float32\"\n        )",
              "tf.keras.layers.Dense(\n            96, activation=\"gelu\", dtype=\"float32\"\n        )",
              "tf.keras.layers.Dense(32, dtype=\"float32\")",
              "tf.keras.layers.Embedding(5, 32, dtype=\"float32\")",
              "tf.keras.layers.Dense(1, dtype=\"float32\")",
              "tf.keras.layers.Dense(8, dtype=\"float32\")",
              "tf.keras.layers.Dense(8, dtype=\"float32\")",
              "tf.keras.layers.Dense(8, dtype=\"float32\")",
              "tf.keras.layers.Dense(1, dtype=\"float32\")",
              "tf.keras.layers.Dense(16, dtype=\"float32\")",
              "tf.keras.layers.Dense(16, dtype=\"float32\")",
              "tf.keras.layers.Dense(16, dtype=\"float32\")",
              "tf.keras.layers.Dense(1, dtype=\"float32\")",
              "tf.keras.layers.Dense(\n            len(payment_scoring.SCORES), dtype=\"float32\", name=\"total_score\"\n        )",
              "tf.keras.layers.Dense(32, dtype=\"float32\")",
              "tf.keras.layers.LayerNormalization(dtype=\"float32\")",
              "tf.keras.layers.Dense(\n                        480, activation=\"gelu\", dtype=\"float32\"\n                    )",
              "tf.keras.layers.Dense(\n                        384, kernel_initializer=\"zeros\", dtype=\"float32\"\n                    )"
            ]
          },
          {
            "name": "metrics_from_statistics",
            "kind": "function",
            "description": "Reduce globally before deriving RMSE in the original J units.",
            "source": {
              "path": "model/critic.py",
              "line": 1335
            },
            "layers": []
          },
          {
            "name": "settlement_objective",
            "kind": "function",
            "description": "Equal calibrated likelihood/value fit, plus direct constraints.",
            "source": {
              "path": "model/critic.py",
              "line": 1348
            },
            "layers": []
          },
          {
            "name": "chosen_actions",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/critic.py",
              "line": 1358
            },
            "layers": []
          },
          {
            "name": "active_candidates",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/critic.py",
              "line": 1383
            },
            "layers": []
          },
          {
            "name": "candidate_probabilities",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/critic.py",
              "line": 1408
            },
            "layers": []
          }
        ]
      },
      {
        "id": "model/encoder.py",
        "path": "model/encoder.py",
        "description": "Shared board, hand and river representations.",
        "symbols": [
          {
            "name": "TableContext",
            "kind": "class",
            "description": "Encode shared fields and river summaries once before hand fusion.",
            "source": {
              "path": "model/encoder.py",
              "line": 52
            },
            "layers": [
              "tf.keras.layers.Dense(\n                max(4, width // 2), use_bias=False, dtype=self.dtype_policy\n            )",
              "tf.keras.layers.Dense(\n                    384, use_bias=False, dtype=self.dtype_policy\n                )",
              "tf.keras.layers.Dense(\n                    512, activation=\"gelu\", dtype=self.dtype_policy\n                )"
            ]
          },
          {
            "name": "semantic_features",
            "kind": "function",
            "description": "Flatten already encoded field coordinates in schema order.",
            "source": {
              "path": "model/encoder.py",
              "line": 125
            },
            "layers": []
          },
          {
            "name": "SuitResidual",
            "kind": "class",
            "description": "",
            "source": {
              "path": "model/encoder.py",
              "line": 137
            },
            "layers": [
              "tf.keras.layers.Conv1D(\n            filters=128,\n            kernel_size=3,\n            padding=\"same\",\n            dilation_rate=dilation,\n            dtype=self.dtype_policy,\n            activation=\"gelu\",\n        )",
              "tf.keras.layers.Conv1D(\n            filters=128,\n            kernel_size=3,\n            padding=\"same\",\n            dilation_rate=dilation,\n            dtype=self.dtype_policy,\n        )",
              "tf.keras.layers.LayerNormalization(\n            dtype=self.dtype_policy\n        )"
            ]
          },
          {
            "name": "HandBank",
            "kind": "class",
            "description": "Encode occupied candidate hands with shared, suit-local convolutions.",
            "source": {
              "path": "model/encoder.py",
              "line": 176
            },
            "layers": [
              "tf.keras.layers.Dense(\n            128, use_bias=False, dtype=self.dtype_policy\n        )",
              "tf.keras.layers.Dense(\n            128,\n            activation=None,\n            dtype=self.dtype_policy,\n        )",
              "tf.keras.layers.Dense(\n            128, activation=\"gelu\", dtype=self.dtype_policy\n        )",
              "tf.keras.layers.LayerNormalization(\n            dtype=self.dtype_policy\n        )",
              "tf.keras.layers.Dense(\n                    384, use_bias=False, dtype=self.dtype_policy\n                )",
              "tf.keras.layers.Dense(\n                    512, activation=\"gelu\", dtype=self.dtype_policy\n                )"
            ]
          },
          {
            "name": "RiverEncoding",
            "kind": "class",
            "description": "Encode separately padded pre/post-riichi rivers with shared weights.",
            "source": {
              "path": "model/encoder.py",
              "line": 399
            },
            "layers": [
              "tf.keras.layers.Dense(\n            64, activation=\"gelu\", dtype=self.dtype_policy\n        )",
              "tf.keras.layers.Dense(\n            64, activation=\"gelu\", dtype=self.dtype_policy\n        )",
              "tf.keras.layers.Conv1D(\n                filters=64,\n                kernel_size=3,\n                padding=\"same\",\n                dilation_rate=dilation,\n                dtype=self.dtype_policy,\n            )",
              "tf.keras.layers.LayerNormalization(dtype=self.dtype_policy)"
            ]
          },
          {
            "name": "projected_draws",
            "kind": "function",
            "description": "Ordinary draw counts and last drawer if this action takes effect.",
            "source": {
              "path": "model/encoder.py",
              "line": 558
            },
            "layers": []
          },
          {
            "name": "last_draw_context",
            "kind": "function",
            "description": "Current last-tile flags and projected seats without further calls.\n\nSeat projections describe ordinary live-wall draws, excluding rinshan.\nA kan consumes one live-wall tile for its replacement draw. A response\npass continues after the discarder; our chii/pon continues after us.",
            "source": {
              "path": "model/encoder.py",
              "line": 587
            },
            "layers": []
          },
          {
            "name": "DecisionCandidates",
            "kind": "class",
            "description": "Local discard/riichi, pass and kan candidates in joint action IDs.",
            "source": {
              "path": "model/encoder.py",
              "line": 632
            },
            "layers": [
              "tf.keras.layers.Dense(\n            192, activation=\"gelu\", dtype=self.dtype_policy\n        )",
              "tf.keras.layers.Dense(\n            384, activation=\"gelu\", dtype=self.dtype_policy\n        )"
            ]
          },
          {
            "name": "board_stack",
            "kind": "function",
            "description": "Independent upper board representation over shared lower encodings.",
            "source": {
              "path": "model/encoder.py",
              "line": 866
            },
            "layers": [
              "tf.keras.layers.Dense(\n        512, activation=\"gelu\", name=f\"{prefix}_fusion\", dtype=\"mixed_bfloat16\"\n    )",
              "tf.keras.layers.Dense(\n        512, activation=\"gelu\", name=f\"{prefix}_state\", dtype=\"mixed_bfloat16\"\n    )",
              "tf.keras.layers.LayerNormalization(\n        center=False,\n        scale=False,\n        epsilon=1e-5,\n        dtype=\"float32\",\n        name=f\"{prefix}_state_normalized\",\n    )",
              "tf.keras.layers.LayerNormalization(\n            name=f\"{prefix}_block_{block}_norm\", dtype=\"mixed_bfloat16\"\n        )",
              "tf.keras.layers.Dense(\n            576,\n            activation=\"gelu\",\n            name=f\"{prefix}_block_{block}_expand\",\n            dtype=\"mixed_bfloat16\",\n        )",
              "tf.keras.layers.Dense(\n            576,\n            activation=\"gelu\",\n            name=f\"{prefix}_block_{block}_hidden\",\n            dtype=\"mixed_bfloat16\",\n        )",
              "tf.keras.layers.Dense(\n            512, name=f\"{prefix}_block_{block}_contract\", dtype=\"mixed_bfloat16\"\n        )"
            ]
          },
          {
            "name": "encode_inputs",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/encoder.py",
              "line": 906
            },
            "layers": [
              "tf.keras.layers.LayerNormalization(\n        center=False,\n        scale=False,\n        epsilon=1e-5,\n        dtype=\"float32\",\n        name=\"candidate_state_normalized\",\n    )"
            ]
          }
        ]
      },
      {
        "id": "model/export.py",
        "path": "model/export.py",
        "description": "Export the joint actor, board heads and action payment critic.",
        "symbols": [
          {
            "name": "ServingModel",
            "kind": "class",
            "description": "",
            "source": {
              "path": "model/export.py",
              "line": 18
            },
            "layers": []
          },
          {
            "name": "build_network",
            "kind": "function",
            "description": "Build every actor and critic variable before strict weight loading.",
            "source": {
              "path": "model/export.py",
              "line": 197
            },
            "layers": []
          },
          {
            "name": "load_network",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/export.py",
              "line": 218
            },
            "layers": []
          },
          {
            "name": "run",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/export.py",
              "line": 225
            },
            "layers": []
          },
          {
            "name": "main",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/export.py",
              "line": 318
            },
            "layers": []
          }
        ]
      },
      {
        "id": "model/inference.py",
        "path": "model/inference.py",
        "description": "Strict SavedModel loading and batched inference.",
        "symbols": [
          {
            "name": "Inference",
            "kind": "class",
            "description": "",
            "source": {
              "path": "model/inference.py",
              "line": 16
            },
            "layers": []
          },
          {
            "name": "Predictor",
            "kind": "class",
            "description": "",
            "source": {
              "path": "model/inference.py",
              "line": 30
            },
            "layers": []
          }
        ]
      },
      {
        "id": "model/input_features.py",
        "path": "model/input_features.py",
        "description": "Lossless semantic expansion of compact model inputs.",
        "symbols": [
          {
            "name": "candidate_melds",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/input_features.py",
              "line": 36
            },
            "layers": []
          },
          {
            "name": "meld_tile_ids",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/input_features.py",
              "line": 53
            },
            "layers": []
          },
          {
            "name": "meld_tile_red",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/input_features.py",
              "line": 63
            },
            "layers": []
          },
          {
            "name": "meld_tile_valid",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/input_features.py",
              "line": 69
            },
            "layers": []
          },
          {
            "name": "last_tedashi_tile",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/input_features.py",
              "line": 73
            },
            "layers": []
          },
          {
            "name": "blocker_counts",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/input_features.py",
              "line": 80
            },
            "layers": []
          },
          {
            "name": "neural_features",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/input_features.py",
              "line": 106
            },
            "layers": []
          },
          {
            "name": "NeuralFeatures",
            "kind": "class",
            "description": "Expand compact fields and project one shared one-hot tile vocabulary.",
            "source": {
              "path": "model/input_features.py",
              "line": 123
            },
            "layers": [
              "tf.keras.layers.Dense(\n            TILE_WIDTH, use_bias=False, dtype=\"float32\", name=\"tile_projection\"\n        )"
            ]
          },
          {
            "name": "tile_features",
            "kind": "function",
            "description": "Project base-34 one-hot identity; red codes share their five's row.",
            "source": {
              "path": "model/input_features.py",
              "line": 143
            },
            "layers": []
          },
          {
            "name": "field_width",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/input_features.py",
              "line": 233
            },
            "layers": []
          },
          {
            "name": "field_features",
            "kind": "function",
            "description": "Encode learned evidence; deterministic consumers retain native values.",
            "source": {
              "path": "model/input_features.py",
              "line": 241
            },
            "layers": []
          },
          {
            "name": "SemanticFields",
            "kind": "class",
            "description": "Shared categorical embeddings, masks, and compressed numeric evidence.",
            "source": {
              "path": "model/input_features.py",
              "line": 276
            },
            "layers": [
              "tf.keras.layers.Embedding(width, 2, dtype=self.dtype_policy)"
            ]
          }
        ]
      },
      {
        "id": "model/joint_settlement.py",
        "path": "model/joint_settlement.py",
        "description": "Scored hand endings and bank transitions, with coexisting ron claims.\n\nThe learned tensor describes events and hand scores. Monetary transfers are\ncomputed by rules, including double ron, dealer repeats and deposit priority.",
        "symbols": [
          {
            "name": "claim_transfers",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 120
            },
            "layers": []
          },
          {
            "name": "settlement_support",
            "kind": "function",
            "description": "Enumerate score/allocation atoms, with deposits on a separate axis.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 158
            },
            "layers": []
          },
          {
            "name": "dealer_indices",
            "kind": "function",
            "description": "Select the contiguous settlement block for each position's dealer.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 255
            },
            "layers": []
          },
          {
            "name": "bank_transfers",
            "kind": "function",
            "description": "Bank movement for every position, settlement and deposit mask.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 263
            },
            "layers": []
          },
          {
            "name": "claim_probabilities",
            "kind": "function",
            "description": "Only true yakuman can redirect a claim through responsibility.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 276
            },
            "layers": []
          },
          {
            "name": "public_inputs",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 313
            },
            "layers": []
          },
          {
            "name": "settlement_states",
            "kind": "function",
            "description": "Rule-derived outcomes depend only on the position, not its actions.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 331
            },
            "layers": []
          },
          {
            "name": "event_legal",
            "kind": "function",
            "description": "Shared event/bank support, including deterministic last-discard facts.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 368
            },
            "layers": []
          },
          {
            "name": "event_probabilities",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 462
            },
            "layers": []
          },
          {
            "name": "dealer_repeat_probability",
            "kind": "function",
            "description": "Nagashi repeat law from legal exhaustive readiness and deposits.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 473
            },
            "layers": []
          },
          {
            "name": "probabilities",
            "kind": "function",
            "description": "Exact categorical law, without ranks or payment marginals.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 492
            },
            "layers": []
          },
          {
            "name": "decode",
            "kind": "function",
            "description": "Rule-derived transfers, ranks and diagnostics for serving.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 523
            },
            "layers": []
          },
          {
            "name": "observed_support",
            "kind": "function",
            "description": "Label-compatible score atoms and public event/deposit support.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 532
            },
            "layers": []
          },
          {
            "name": "observed_terms",
            "kind": "function",
            "description": "Observed categorical likelihood without a score Cartesian product.\n\nRecorded ending kind and readiness distinguish zero-payment draws and\naborts. Responsibility and joint nagashi use the same law as action Q.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 624
            },
            "layers": []
          },
          {
            "name": "observed_payoff",
            "kind": "function",
            "description": "Exact J only when every label-compatible settlement agrees.\n\nRecorded ending labels resolve continuation ambiguity. Unknown payment\namounts retain NLL supervision without an invented squared-error target.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 687
            },
            "layers": []
          },
          {
            "name": "expectation",
            "kind": "function",
            "description": "Sum deposits before scored events to avoid long FP32 channel sums.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 729
            },
            "layers": []
          },
          {
            "name": "position_payoffs",
            "kind": "function",
            "description": "Project settlement states to normalized J once per position.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 737
            },
            "layers": []
          },
          {
            "name": "supervision_chunk",
            "kind": "function",
            "description": "Fuse fixed support, payoff projection and target matching once.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 752
            },
            "layers": []
          },
          {
            "name": "prepare_supervision",
            "kind": "function",
            "description": "Cache fixed supervision in bounded, fused 32-row chunks.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 771
            },
            "layers": []
          },
          {
            "name": "gather_position_payoffs",
            "kind": "function",
            "description": "Project each requested position once in bounded, fixed-size chunks.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 802
            },
            "layers": []
          },
          {
            "name": "continuation_forecast",
            "kind": "function",
            "description": "Public-state payoff of each settlement, shared by every action.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 828
            },
            "layers": []
          },
          {
            "name": "policy_objective",
            "kind": "function",
            "description": "Normalized ST3 plus first-place reward and fourth-place penalty.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 879
            },
            "layers": []
          },
          {
            "name": "post_hand_forecast",
            "kind": "function",
            "description": "Forecast match outcomes from a post-hand state.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 888
            },
            "layers": []
          },
          {
            "name": "continuation_values",
            "kind": "function",
            "description": "Fixed Gumbel continuation with time-dependent score variance.\n\nScores use 10,000-point units. Positive dealership drift and a positive\nquadratic variance in remaining hands preserve directional consistency.\nThe calibrated coefficients are fixed during policy and critic training.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 914
            },
            "layers": []
          },
          {
            "name": "marginals",
            "kind": "function",
            "description": "Class marginals; four state-dependent atoms encode the bank exactly.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 948
            },
            "layers": []
          },
          {
            "name": "payment_values",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 1020
            },
            "layers": []
          },
          {
            "name": "payment_labels",
            "kind": "function",
            "description": "Map transfers; -1 denotes a known win with unknown payment amount.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 1033
            },
            "layers": []
          },
          {
            "name": "settlement_moments",
            "kind": "function",
            "description": "Exact honba-free player/bank moments, retaining transfer covariance.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 1066
            },
            "layers": []
          },
          {
            "name": "placement_prior",
            "kind": "function",
            "description": "Coherent actor rank probabilities from a Gumbel future-score prior.\n\nScores and scale must share units; leading batch dimensions broadcast.\nEnumerate only opponent orders, avoiding the 24-permutation score tensor.",
            "source": {
              "path": "model/joint_settlement.py",
              "line": 1084
            },
            "layers": []
          }
        ]
      },
      {
        "id": "model/losses.py",
        "path": "model/losses.py",
        "description": "Masked loss reductions shared across components and replicas.",
        "symbols": [
          {
            "name": "constraint_divergence",
            "kind": "function",
            "description": "Teach raw predictions the projection, without moving its target.",
            "source": {
              "path": "model/losses.py",
              "line": 6
            },
            "layers": []
          },
          {
            "name": "ConstraintLoss",
            "kind": "class",
            "description": "",
            "source": {
              "path": "model/losses.py",
              "line": 23
            },
            "layers": []
          },
          {
            "name": "masked_totals",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/losses.py",
              "line": 45
            },
            "layers": []
          },
          {
            "name": "mean_valid",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/losses.py",
              "line": 54
            },
            "layers": []
          },
          {
            "name": "candidate_mean",
            "kind": "function",
            "description": "Equal decision mass over valid candidate/head entries.\n\nRows are the sorted decision IDs returned by DecisionCandidates. Unknown\ncandidates contribute neither loss nor normalization mass.",
            "source": {
              "path": "model/losses.py",
              "line": 65
            },
            "layers": []
          },
          {
            "name": "packed_means",
            "kind": "function",
            "description": "Reduce masked statistics using TensorFlow's distributed autodiff.",
            "source": {
              "path": "model/losses.py",
              "line": 87
            },
            "layers": []
          },
          {
            "name": "MaskedMeans",
            "kind": "class",
            "description": "Collect independent masked means into one replica reduction.",
            "source": {
              "path": "model/losses.py",
              "line": 95
            },
            "layers": []
          },
          {
            "name": "classification",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/losses.py",
              "line": 112
            },
            "layers": []
          }
        ]
      },
      {
        "id": "model/network.py",
        "path": "model/network.py",
        "description": "Assembly of the shared actor, beliefs and payment critic.",
        "symbols": [
          {
            "name": "JointPolicyPayment",
            "kind": "class",
            "description": "Shared policy, beliefs, auxiliaries and payment critic.",
            "source": {
              "path": "model/network.py",
              "line": 15
            },
            "layers": [
              "tf.keras.layers.Dense(\n            34, dtype=\"float32\", name=\"candidate_ron\"\n        )",
              "tf.keras.layers.Dense(\n            256, activation=\"gelu\", dtype=\"float32\", name=\"policy_evidence\"\n        )",
              "tf.keras.layers.Dense(\n                128,\n                activation=\"gelu\",\n                dtype=\"float32\",\n                name=\"ron_eligibility_hidden\",\n            )",
              "tf.keras.layers.LayerNormalization(dtype=\"float32\")",
              "tf.keras.layers.Dense(\n                                384, activation=\"gelu\", dtype=\"float32\"\n                            )",
              "tf.keras.layers.Dense(\n                                768, kernel_initializer=\"zeros\", dtype=\"float32\"\n                            )"
            ]
          }
        ]
      },
      {
        "id": "model/outcomes.py",
        "path": "model/outcomes.py",
        "description": "Stable hand payments, score conservation and initial-dealer tie priority.",
        "symbols": [
          {
            "name": "basic_points",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/outcomes.py",
              "line": 40
            },
            "layers": []
          },
          {
            "name": "saint3_jade_south",
            "kind": "function",
            "description": "Final ST3 return, with one-based ranks and scores in table points.",
            "source": {
              "path": "model/outcomes.py",
              "line": 81
            },
            "layers": []
          },
          {
            "name": "normalize_draw_payments",
            "kind": "function",
            "description": "Remove native draw deltas' already-paid riichi deposits.\n\nNagashi and zero-transfer exhaustive draws can retain the per-seat\ndeposit delta. MJAI reach_accepted already accounts for that payment.\nAccept only the observed, conservation-checked native defect.",
            "source": {
              "path": "model/outcomes.py",
              "line": 89
            },
            "layers": []
          },
          {
            "name": "normalize_recorded_endings",
            "kind": "function",
            "description": "Recover omitted fourth-riichi acceptance from next-round accounting.\n\nAnnotate the existing terminal event, preserving every decision index.\nA triple ron on the fourth declaration retains its unpaid deposit.",
            "source": {
              "path": "model/outcomes.py",
              "line": 117
            },
            "layers": []
          },
          {
            "name": "terminal_payments",
            "kind": "function",
            "description": "Typed ron/tsumo/draw/bank transfers, without honba, including pao.",
            "source": {
              "path": "model/outcomes.py",
              "line": 166
            },
            "layers": []
          },
          {
            "name": "terminal_ending",
            "kind": "function",
            "description": "Observed ending kind, ron source and draw readiness for one hand.\n\nKinds are ron, tsumo, exhaustive draw, abort and nagashi (0 through 4).\nInput draw deltas must already be normalized by normalize_draw_payments.\nOnly final concealed tile counts are reconstructed; no decisions replay.",
            "source": {
              "path": "model/outcomes.py",
              "line": 258
            },
            "layers": []
          },
          {
            "name": "settlement",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/outcomes.py",
              "line": 339
            },
            "layers": []
          },
          {
            "name": "relative_payments",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/outcomes.py",
              "line": 347
            },
            "layers": []
          },
          {
            "name": "payment_classes",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/outcomes.py",
              "line": 354
            },
            "layers": []
          }
        ]
      },
      {
        "id": "model/payment_scoring.py",
        "path": "model/payment_scoring.py",
        "description": "Public yaku constraints and joint han/fu payment scoring.",
        "symbols": [
          {
            "name": "exclusive_cliques",
            "kind": "function",
            "description": "Maximal exclusive sets, built once from the scored-yaku graph.",
            "source": {
              "path": "model/payment_scoring.py",
              "line": 51
            },
            "layers": []
          },
          {
            "name": "support",
            "kind": "function",
            "description": "Twenty-three named-yaku masks; concealed future tiles stay unknown.",
            "source": {
              "path": "model/payment_scoring.py",
              "line": 78
            },
            "layers": []
          },
          {
            "name": "public_melds",
            "kind": "function",
            "description": "Public groups in the same start-tile encoding as candidate melds.",
            "source": {
              "path": "model/payment_scoring.py",
              "line": 204
            },
            "layers": []
          },
          {
            "name": "fixed_meld_fu",
            "kind": "function",
            "description": "Self candidate-zero fu and opponent fu from fixed public melds.",
            "source": {
              "path": "model/payment_scoring.py",
              "line": 223
            },
            "layers": []
          },
          {
            "name": "CompletionMask",
            "kind": "class",
            "description": "",
            "source": {
              "path": "model/payment_scoring.py",
              "line": 242
            },
            "layers": []
          },
          {
            "name": "score_class",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/payment_scoring.py",
              "line": 310
            },
            "layers": []
          },
          {
            "name": "payment_amounts",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/payment_scoring.py",
              "line": 395
            },
            "layers": []
          },
          {
            "name": "minimum_han_mask",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/payment_scoring.py",
              "line": 399
            },
            "layers": []
          },
          {
            "name": "masked_score_logits",
            "kind": "function",
            "description": "",
            "source": {
              "path": "model/payment_scoring.py",
              "line": 414
            },
            "layers": []
          },
          {
            "name": "CompletionScoreMask",
            "kind": "class",
            "description": "",
            "source": {
              "path": "model/payment_scoring.py",
              "line": 451
            },
            "layers": []
          },
          {
            "name": "CompletionScoreCoupling",
            "kind": "class",
            "description": "Lift score tails to the lower bounds implied by the same completion.\n\nCompatible yaku marginals are never added as if independent. Exclusive\nalternatives can be summed; the strongest exclusive-set bound wins.",
            "source": {
              "path": "model/payment_scoring.py",
              "line": 497
            },
            "layers": []
          }
        ]
      },
      {
        "id": "model/river_attention.py",
        "path": "model/river_attention.py",
        "description": "Observed-event attention across opponent seats and riichi segments.",
        "symbols": [
          {
            "name": "RiverAttention",
            "kind": "class",
            "description": "",
            "source": {
              "path": "model/river_attention.py",
              "line": 7
            },
            "layers": [
              "tf.keras.layers.Embedding(\n            64, 64, dtype=self.dtype_policy\n        )",
              "tf.keras.layers.Embedding(3, 64, dtype=self.dtype_policy)",
              "tf.keras.layers.MultiHeadAttention(\n            num_heads=4, key_dim=16, dtype=self.dtype_policy\n        )",
              "tf.keras.layers.Dense(\n            64,\n            use_bias=False,\n            kernel_initializer=\"zeros\",\n            dtype=self.dtype_policy,\n        )"
            ]
          }
        ]
      }
    ],
    "gradient_items": [
      {
        "from": "hand-suit-0",
        "to": "hand-tokenization",
        "kind": "backward",
        "label": "VJP through conditioned suit tokens",
        "source": {
          "path": "model/encoder.py",
          "line": 343
        },
        "id": "imitation-backward-hand-suit-0-hand-tokenization",
        "phase": "imitation",
        "title": "Suit residual block 1 → Context-conditioned hand tokens",
        "description": "VJP through conditioned suit tokens",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "hand-honors",
        "to": "hand-tokenization",
        "kind": "backward",
        "label": "VJP through conditioned honor tokens",
        "source": {
          "path": "model/encoder.py",
          "line": 368
        },
        "id": "imitation-backward-hand-honors-hand-tokenization",
        "phase": "imitation",
        "title": "Honor tile projection → Context-conditioned hand tokens",
        "description": "VJP through conditioned honor tokens",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "hand-suit-1",
        "to": "hand-suit-0",
        "kind": "backward",
        "label": "VJP through residual suit sequence",
        "source": {
          "path": "model/encoder.py",
          "line": 357
        },
        "id": "imitation-backward-hand-suit-1-hand-suit-0",
        "phase": "imitation",
        "title": "Suit residual block 2 → Suit residual block 1",
        "description": "VJP through residual suit sequence",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "hand-suit-2",
        "to": "hand-suit-1",
        "kind": "backward",
        "label": "VJP through residual suit sequence",
        "source": {
          "path": "model/encoder.py",
          "line": 357
        },
        "id": "imitation-backward-hand-suit-2-hand-suit-1",
        "phase": "imitation",
        "title": "Suit residual block 3 → Suit residual block 2",
        "description": "VJP through residual suit sequence",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "hand-bank-output",
        "to": "hand-suit-2",
        "kind": "backward",
        "label": "VJP through reconstructed 27 suit-tile tokens",
        "source": {
          "path": "model/encoder.py",
          "line": 368
        },
        "id": "imitation-backward-hand-bank-output-hand-suit-2",
        "phase": "imitation",
        "title": "Conditioned local hand bank → Suit residual block 3",
        "description": "VJP through reconstructed 27 suit-tile tokens",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "hand-bank-output",
        "to": "hand-honors",
        "kind": "backward",
        "label": "VJP through seven honor-tile tokens",
        "source": {
          "path": "model/encoder.py",
          "line": 368
        },
        "id": "imitation-backward-hand-bank-output-hand-honors",
        "phase": "imitation",
        "title": "Conditioned local hand bank → Honor tile projection",
        "description": "VJP through seven honor-tile tokens",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "board-input-projection",
        "to": "hand-bank-output",
        "kind": "backward",
        "label": "VJP through current hand slot 0",
        "source": {
          "path": "model/encoder.py",
          "line": 935
        },
        "id": "imitation-backward-board-input-projection-hand-bank-output",
        "phase": "imitation",
        "title": "Joint hand-board fusion → Conditioned local hand bank",
        "description": "VJP through current hand slot 0",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "river-conv-0",
        "to": "river-tokenization",
        "kind": "backward",
        "label": "VJP through masked 64-channel stream tokens",
        "source": {
          "path": "model/encoder.py",
          "line": 521
        },
        "id": "imitation-backward-river-conv-0-river-tokenization",
        "phase": "imitation",
        "title": "River residual block 1 → River token projection",
        "description": "VJP through masked 64-channel stream tokens",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "river-conv-1",
        "to": "river-conv-0",
        "kind": "backward",
        "label": "VJP through masked residual stream",
        "source": {
          "path": "model/encoder.py",
          "line": 528
        },
        "id": "imitation-backward-river-conv-1-river-conv-0",
        "phase": "imitation",
        "title": "River residual block 2 → River residual block 1",
        "description": "VJP through masked residual stream",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "river-conv-2",
        "to": "river-conv-1",
        "kind": "backward",
        "label": "VJP through masked residual stream",
        "source": {
          "path": "model/encoder.py",
          "line": 528
        },
        "id": "imitation-backward-river-conv-2-river-conv-1",
        "phase": "imitation",
        "title": "River residual block 3 → River residual block 2",
        "description": "VJP through masked residual stream",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "river-summaries",
        "to": "river-attention",
        "kind": "backward",
        "label": "VJP through final masked stream tokens",
        "source": {
          "path": "model/encoder.py",
          "line": 539
        },
        "id": "imitation-backward-river-summaries-river-attention",
        "phase": "imitation",
        "title": "River board and player summaries → Cross-river event attention",
        "description": "VJP through final masked stream tokens",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "shared-public-context",
        "to": "river-summaries",
        "kind": "backward",
        "label": "VJP through six ordered 64-channel summaries",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        },
        "id": "imitation-backward-shared-public-context-river-summaries",
        "phase": "imitation",
        "title": "Shared public context → River board and player summaries",
        "description": "VJP through six ordered 64-channel summaries",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "board-block-0",
        "to": "board-input-projection",
        "kind": "backward",
        "label": "VJP through joint hand-board fusion",
        "source": {
          "path": "model/encoder.py",
          "line": 869
        },
        "id": "imitation-backward-board-block-0-board-input-projection",
        "phase": "imitation",
        "title": "Board residual block 1 → Joint hand-board fusion",
        "description": "VJP through joint hand-board fusion",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "board-block-1",
        "to": "board-block-0",
        "kind": "backward",
        "label": "VJP through residual board state",
        "source": {
          "path": "model/encoder.py",
          "line": 890
        },
        "id": "imitation-backward-board-block-1-board-block-0",
        "phase": "imitation",
        "title": "Board residual block 2 → Board residual block 1",
        "description": "VJP through residual board state",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "board-block-2",
        "to": "board-block-1",
        "kind": "backward",
        "label": "VJP through residual board state",
        "source": {
          "path": "model/encoder.py",
          "line": 890
        },
        "id": "imitation-backward-board-block-2-board-block-1",
        "phase": "imitation",
        "title": "Board residual block 3 → Board residual block 2",
        "description": "VJP through residual board state",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "board-output",
        "to": "board-block-2",
        "kind": "backward",
        "label": "VJP through final residual trunk state",
        "source": {
          "path": "model/encoder.py",
          "line": 894
        },
        "id": "imitation-backward-board-output-board-block-2",
        "phase": "imitation",
        "title": "Shared decision state → Board residual block 3",
        "description": "VJP through final residual trunk state",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "candidate-projection",
        "to": "hand-bank-output",
        "kind": "backward",
        "label": "VJP through gathered 512-channel action hand",
        "source": {
          "path": "model/encoder.py",
          "line": 801
        },
        "id": "imitation-backward-candidate-projection-hand-bank-output",
        "phase": "imitation",
        "title": "Local action queries → Conditioned local hand bank",
        "description": "VJP through gathered 512-channel action hand",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "candidate-projection",
        "to": "board-output",
        "kind": "backward",
        "label": "VJP through board context projected to 192 channels",
        "source": {
          "path": "model/encoder.py",
          "line": 847
        },
        "id": "imitation-backward-candidate-projection-board-output",
        "phase": "imitation",
        "title": "Local action queries → Shared decision state",
        "description": "VJP through board context projected to 192 channels",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "belief-readouts",
        "to": "belief-refinement",
        "kind": "backward",
        "label": "VJP through shared 512-channel board representation",
        "source": {
          "path": "model/beliefs.py",
          "line": 458
        },
        "id": "imitation-backward-belief-readouts-belief-refinement",
        "phase": "imitation",
        "title": "Initial belief readouts → Belief residual refinement",
        "description": "VJP through shared 512-channel board representation",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "tile-tokenization",
        "to": "belief-refinement",
        "kind": "backward",
        "label": "VJP through three opponent context slices",
        "source": {
          "path": "model/beliefs.py",
          "line": 241
        },
        "id": "imitation-backward-tile-tokenization-belief-refinement",
        "phase": "imitation",
        "title": "Tile attention tokenization → Belief residual refinement",
        "description": "VJP through three opponent context slices",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "tile-tokenization",
        "to": "belief-readouts",
        "kind": "stop",
        "label": "Detached initial shanten, conditional improving and count probabilities",
        "source": {
          "path": "model/beliefs.py",
          "line": 207
        },
        "id": "imitation-stop-tile-tokenization-belief-readouts",
        "phase": "imitation",
        "title": "Tile attention tokenization ⊣ Initial belief readouts",
        "description": "Detached initial shanten, conditional improving and count probabilities",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "tile-attention-0",
        "to": "tile-tokenization",
        "kind": "backward",
        "label": "VJP through 34 tokens per opponent",
        "source": {
          "path": "model/beliefs.py",
          "line": 252
        },
        "id": "imitation-backward-tile-attention-0-tile-tokenization",
        "phase": "imitation",
        "title": "Tile attention block 1 → Tile attention tokenization",
        "description": "VJP through 34 tokens per opponent",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "tile-attention-1",
        "to": "tile-attention-0",
        "kind": "backward",
        "label": "VJP through refined token sequence",
        "source": {
          "path": "model/beliefs.py",
          "line": 261
        },
        "id": "imitation-backward-tile-attention-1-tile-attention-0",
        "phase": "imitation",
        "title": "Tile attention block 2 → Tile attention block 1",
        "description": "VJP through refined token sequence",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "tile-correction",
        "to": "tile-attention-1",
        "kind": "backward",
        "label": "VJP through final 128-channel tile tokens",
        "source": {
          "path": "model/beliefs.py",
          "line": 262
        },
        "id": "imitation-backward-tile-correction-tile-attention-1",
        "phase": "imitation",
        "title": "Residual belief correction → Tile attention block 2",
        "description": "VJP through final 128-channel tile tokens",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "tile-correction",
        "to": "belief-readouts",
        "kind": "backward",
        "label": "VJP through initial count and ukeire logits for residual add",
        "source": {
          "path": "model/beliefs.py",
          "line": 267
        },
        "id": "imitation-backward-tile-correction-belief-readouts",
        "phase": "imitation",
        "title": "Residual belief correction → Initial belief readouts",
        "description": "VJP through initial count and ukeire logits for residual add",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "belief-constraints",
        "to": "tile-correction",
        "kind": "backward",
        "label": "Gradient through the refined held-count logits",
        "source": {
          "path": "model/beliefs.py",
          "line": 473
        },
        "id": "imitation-backward-belief-constraints-tile-correction",
        "phase": "imitation",
        "title": "Belief support and count projection → Residual belief correction",
        "description": "Gradient through the refined held-count logits",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "belief-constraints",
        "to": "belief-readouts",
        "kind": "backward",
        "label": "VJP through unmodified shanten logits",
        "source": {
          "path": "model/beliefs.py",
          "line": 474
        },
        "id": "imitation-backward-belief-constraints-belief-readouts",
        "phase": "imitation",
        "title": "Belief support and count projection → Initial belief readouts",
        "description": "VJP through unmodified shanten logits",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "candidate-ron-prediction",
        "to": "board-output",
        "kind": "backward",
        "label": "Ron eligibility gradients reach observed board",
        "source": {
          "path": "model/network.py",
          "line": 44
        },
        "id": "imitation-backward-candidate-ron-prediction-board-output",
        "phase": "imitation",
        "title": "Ron-risk prediction → Shared decision state",
        "description": "Ron eligibility gradients reach observed board",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-candidate-aux",
        "to": "candidate-projection",
        "kind": "backward",
        "label": "VJP through route prediction weights and raw candidate state",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 10
        },
        "id": "imitation-backward-actor-candidate-aux-candidate-projection",
        "phase": "imitation",
        "title": "Shared route prediction → Local action queries",
        "description": "VJP through route prediction weights and raw candidate state",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-completion",
        "to": "belief-refinement",
        "kind": "backward",
        "label": "VJP through shared refined completion readouts",
        "source": {
          "path": "model/beliefs.py",
          "line": 458
        },
        "id": "imitation-backward-actor-completion-belief-refinement",
        "phase": "imitation",
        "title": "Shared completion potential → Belief residual refinement",
        "description": "VJP through shared refined completion readouts",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-final-score",
        "to": "candidate-projection",
        "kind": "stop",
        "label": "Detached raw state; policy gradients stop before shared candidate encoding",
        "source": {
          "path": "model/network.py",
          "line": 156
        },
        "id": "imitation-stop-actor-final-score-candidate-projection",
        "phase": "imitation",
        "title": "Final candidate scorer ⊣ Local action queries",
        "description": "Detached raw state; policy gradients stop before shared candidate encoding",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "actor-final-score",
        "to": "candidate-ron-prediction",
        "kind": "stop",
        "label": "Detached candidate ron probabilities",
        "source": {
          "path": "model/actor.py",
          "line": 159
        },
        "id": "imitation-stop-actor-final-score-candidate-ron-prediction",
        "phase": "imitation",
        "title": "Final candidate scorer ⊣ Ron-risk prediction",
        "description": "Detached candidate ron probabilities",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "actor-final-score",
        "to": "actor-candidate-aux",
        "kind": "stop",
        "label": "Detached candidate route probabilities",
        "source": {
          "path": "model/actor.py",
          "line": 159
        },
        "id": "imitation-stop-actor-final-score-actor-candidate-aux",
        "phase": "imitation",
        "title": "Final candidate scorer ⊣ Shared route prediction",
        "description": "Detached candidate route probabilities",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "actor-final-score",
        "to": "actor-candidate-pool",
        "kind": "backward",
        "label": "VJP through 768-channel gathered policy context",
        "source": {
          "path": "model/actor.py",
          "line": 530
        },
        "id": "imitation-backward-actor-final-score-actor-candidate-pool",
        "phase": "imitation",
        "title": "Final candidate scorer → Legal candidate attention",
        "description": "VJP through 768-channel gathered policy context",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-win",
        "to": "actor-candidate-pool",
        "kind": "backward",
        "label": "VJP through private actor board and predictive context",
        "source": {
          "path": "model/actor.py",
          "line": 530
        },
        "id": "imitation-backward-actor-win-actor-candidate-pool",
        "phase": "imitation",
        "title": "Win/pass head → Legal candidate attention",
        "description": "VJP through private actor board and predictive context",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-state-assembly",
        "to": "actor-candidate-aux",
        "kind": "stop",
        "label": "Detached route probabilities in the settlement state",
        "source": {
          "path": "model/network.py",
          "line": 208
        },
        "id": "imitation-stop-critic-state-assembly-actor-candidate-aux",
        "phase": "imitation",
        "title": "Critic state assembly ⊣ Shared route prediction",
        "description": "Detached route probabilities in the settlement state",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "imitation-objective",
        "to": "continuation-payoffs",
        "kind": "stop",
        "label": "Q gap and calibrated CE weight computed outside gradient recording",
        "source": {
          "path": "training/imitation.py",
          "line": 72
        },
        "id": "imitation-stop-imitation-objective-continuation-payoffs",
        "phase": "imitation",
        "title": "Imitation + settlement objective ⊣ Fixed continuation and expected value",
        "description": "Q gap and calibrated CE weight computed outside gradient recording",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "imitation-objective",
        "to": "actor-final-score",
        "kind": "backward",
        "label": "Detached-weight expert policy CE derivative on real supported targets",
        "source": {
          "path": "training/imitation.py",
          "line": 72
        },
        "id": "imitation-backward-imitation-objective-actor-final-score",
        "phase": "imitation",
        "title": "Imitation + settlement objective → Final candidate scorer",
        "description": "Detached-weight expert policy CE derivative on real supported targets",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "imitation-objective",
        "to": "actor-win",
        "kind": "backward",
        "label": "Detached-weight expert policy CE derivative on real supported targets",
        "source": {
          "path": "training/imitation.py",
          "line": 72
        },
        "id": "imitation-backward-imitation-objective-actor-win",
        "phase": "imitation",
        "title": "Imitation + settlement objective → Win/pass head",
        "description": "Detached-weight expert policy CE derivative on real supported targets",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "belief-refinement",
        "to": "board-output",
        "kind": "backward",
        "label": "Residual identity plus refinement-branch VJP",
        "source": {
          "path": "model/beliefs.py",
          "line": 451
        },
        "id": "imitation-backward-belief-refinement-board-output",
        "phase": "imitation",
        "title": "Belief residual refinement → Shared decision state",
        "description": "Residual identity plus refinement-branch VJP",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "call-choice",
        "to": "actor-candidate-pool",
        "label": "VJP through private actor board and predictive context",
        "kind": "backward",
        "source": {
          "path": "model/actor.py",
          "line": 530
        },
        "id": "imitation-backward-call-choice-actor-candidate-pool",
        "phase": "imitation",
        "title": "Call choice on decision board → Legal candidate attention",
        "description": "VJP through private actor board and predictive context",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "call-factorization",
        "to": "call-choice",
        "label": "Response-policy gradient through normalized six-way branch probabilities",
        "kind": "backward",
        "source": {
          "path": "model/actor.py",
          "line": 562
        },
        "id": "imitation-backward-call-factorization-call-choice",
        "phase": "imitation",
        "title": "Post-call discard policy → Call choice on decision board",
        "description": "Response-policy gradient through normalized six-way branch probabilities",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "call-factorization",
        "to": "actor-final-score",
        "label": "Response-policy gradient through ordinary shared follow-up discard probabilities",
        "kind": "backward",
        "source": {
          "path": "model/actor.py",
          "line": 535
        },
        "id": "imitation-backward-call-factorization-actor-final-score",
        "phase": "imitation",
        "title": "Post-call discard policy → Final candidate scorer",
        "description": "Response-policy gradient through ordinary shared follow-up discard probabilities",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "imitation-objective",
        "to": "call-factorization",
        "label": "Detached-weight expert policy CE derivative on real supported targets",
        "kind": "backward",
        "source": {
          "path": "training/imitation.py",
          "line": 72
        },
        "id": "imitation-backward-imitation-objective-call-factorization",
        "phase": "imitation",
        "title": "Imitation + settlement objective → Post-call discard policy",
        "description": "Detached-weight expert policy CE derivative on real supported targets",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-policy-context",
        "to": "actor-board-output",
        "kind": "backward",
        "label": "Policy gradients train the private actor encoder",
        "source": {
          "path": "model/network.py",
          "line": 22
        },
        "id": "imitation-backward-actor-policy-context-actor-board-output",
        "phase": "imitation",
        "title": "Policy context projection → Actor Shared decision state",
        "description": "Policy gradients train the private actor encoder",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "hand-tokenization",
        "to": "table-conditioning",
        "kind": "backward",
        "label": "VJP through table offset added before first hand GELU",
        "source": {
          "path": "model/encoder.py",
          "line": 339
        },
        "id": "imitation-backward-hand-tokenization-table-conditioning",
        "phase": "imitation",
        "title": "Context-conditioned hand tokens → Shared-context hand conditioning",
        "description": "VJP through table offset added before first hand GELU",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-policy-context",
        "to": "shared-probabilities",
        "kind": "stop",
        "label": "Detached policy belief and completion probabilities",
        "source": {
          "path": "model/network.py",
          "line": 34
        },
        "id": "imitation-stop-actor-policy-context-shared-probabilities",
        "phase": "imitation",
        "title": "Policy context projection ⊣ Shared FP32 probabilities",
        "description": "Detached policy belief and completion probabilities",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "candidate-ron-prediction",
        "to": "structural-wait",
        "label": "Detached structural wait in candidate ron",
        "kind": "stop",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 36
        },
        "id": "imitation-stop-candidate-ron-prediction-structural-wait",
        "phase": "imitation",
        "title": "Ron-risk prediction ⊣ Structural wait prediction",
        "description": "Detached structural wait in candidate ron",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "belief-readouts",
        "to": "river-summaries",
        "kind": "backward",
        "label": "Shared shanten derivative into opponent-local river summaries",
        "source": {
          "path": "model/beliefs.py",
          "line": 291
        },
        "id": "imitation-backward-belief-readouts-river-summaries",
        "phase": "imitation",
        "title": "Initial belief readouts → River board and player summaries",
        "description": "Shared shanten derivative into opponent-local river summaries",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "completion-evidence",
        "to": "belief-constraints",
        "kind": "stop",
        "label": "Detached projected held counts",
        "source": {
          "path": "model/beliefs.py",
          "line": 529
        },
        "id": "imitation-stop-completion-evidence-belief-constraints",
        "phase": "imitation",
        "title": "Opponent completion evidence ⊣ Belief support and count projection",
        "description": "Detached projected held counts",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "completion-evidence",
        "to": "river-summaries",
        "kind": "backward",
        "label": "Completion evidence VJP: Aligned per-opponent river summary 256",
        "source": {
          "path": "model/beliefs.py",
          "line": 336
        },
        "id": "imitation-backward-completion-evidence-river-summaries",
        "phase": "imitation",
        "title": "Opponent completion evidence → River board and player summaries",
        "description": "Completion evidence VJP: Aligned per-opponent river summary 256",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-completion",
        "to": "completion-evidence",
        "kind": "backward",
        "label": "Completion evidence VJP: Opponent-only 46 yaku +76 score residual before support",
        "source": {
          "path": "model/beliefs.py",
          "line": 336
        },
        "id": "imitation-backward-actor-completion-completion-evidence",
        "phase": "imitation",
        "title": "Shared completion potential → Opponent completion evidence",
        "description": "Completion evidence VJP: Opponent-only 46 yaku +76 score residual before support",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "imitation-objective",
        "to": "belief-constraints",
        "kind": "backward",
        "label": "Direct supervised shanten and projected held-count losses",
        "source": {
          "path": "training/auxiliary.py",
          "line": 18
        },
        "id": "imitation-backward-imitation-objective-belief-constraints",
        "phase": "imitation",
        "title": "Imitation + settlement objective → Belief support and count projection",
        "description": "Direct supervised shanten and projected held-count losses",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "imitation-objective",
        "to": "actor-completion",
        "kind": "backward",
        "label": "Observed completion yaku and score losses",
        "source": {
          "path": "training/auxiliary.py",
          "line": 18
        },
        "id": "imitation-backward-imitation-objective-actor-completion",
        "phase": "imitation",
        "title": "Imitation + settlement objective → Shared completion potential",
        "description": "Observed completion yaku and score losses",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "imitation-objective",
        "to": "actor-candidate-aux",
        "kind": "backward",
        "label": "Observed candidate route loss",
        "source": {
          "path": "training/auxiliary.py",
          "line": 18
        },
        "id": "imitation-backward-imitation-objective-actor-candidate-aux",
        "phase": "imitation",
        "title": "Imitation + settlement objective → Shared route prediction",
        "description": "Observed candidate route loss",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "imitation-objective",
        "to": "candidate-ron-prediction",
        "kind": "backward",
        "label": "Observed candidate ron loss",
        "source": {
          "path": "training/auxiliary.py",
          "line": 18
        },
        "id": "imitation-backward-imitation-objective-candidate-ron-prediction",
        "phase": "imitation",
        "title": "Imitation + settlement objective → Ron-risk prediction",
        "description": "Observed candidate ron loss",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "imitation-objective",
        "to": "tile-correction",
        "kind": "backward",
        "label": "Direct supervised conditional improving-tile loss",
        "source": {
          "path": "model/beliefs.py",
          "line": 767
        },
        "id": "imitation-backward-imitation-objective-tile-correction",
        "phase": "imitation",
        "title": "Imitation + settlement objective → Residual belief correction",
        "description": "Direct supervised conditional improving-tile loss",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "table-conditioning",
        "to": "shared-public-context",
        "kind": "backward",
        "label": "VJP through shared-context hand projection",
        "source": {
          "path": "model/encoder.py",
          "line": 339
        },
        "id": "imitation-backward-table-conditioning-shared-public-context",
        "phase": "imitation",
        "title": "Shared-context hand conditioning → Shared public context",
        "description": "VJP through shared-context hand projection",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "board-input-projection",
        "to": "shared-public-context",
        "kind": "backward",
        "label": "VJP through shared context in joint fusion",
        "source": {
          "path": "model/encoder.py",
          "line": 869
        },
        "id": "imitation-backward-board-input-projection-shared-public-context",
        "phase": "imitation",
        "title": "Joint hand-board fusion → Shared public context",
        "description": "VJP through shared context in joint fusion",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "river-attention",
        "to": "river-conv-2",
        "kind": "backward",
        "label": "VJP through observed-event attention residual",
        "source": {
          "path": "model/river_attention.py",
          "line": 44
        },
        "id": "imitation-backward-river-attention-river-conv-2",
        "phase": "imitation",
        "title": "Cross-river event attention → River residual block 3",
        "description": "VJP through observed-event attention residual",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-refinement",
        "to": "actor-policy-context",
        "kind": "backward",
        "label": "VJP through private actor refinement",
        "source": {
          "path": "model/network.py",
          "line": 108
        },
        "id": "imitation-backward-actor-refinement-actor-policy-context",
        "phase": "imitation",
        "title": "Actor refinement block 1 → Policy context projection",
        "description": "VJP through private actor refinement",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "hand-tokenization",
        "to": "shared-tile-projection",
        "kind": "backward",
        "label": "VJP into the shared tile-identity weights",
        "source": {
          "path": "model/encoder.py",
          "line": 278
        },
        "id": "imitation-backward-hand-tokenization-shared-tile-projection",
        "phase": "imitation",
        "title": "Context-conditioned hand tokens → Shared tile identity projection",
        "description": "VJP into the shared tile-identity weights",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "river-tokenization",
        "to": "shared-tile-projection",
        "kind": "backward",
        "label": "VJP into the shared tile-identity weights",
        "source": {
          "path": "model/encoder.py",
          "line": 503
        },
        "id": "imitation-backward-river-tokenization-shared-tile-projection",
        "phase": "imitation",
        "title": "River token projection → Shared tile identity projection",
        "description": "VJP into the shared tile-identity weights",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "shared-public-context",
        "to": "shared-tile-projection",
        "kind": "backward",
        "label": "VJP into the shared tile-identity weights",
        "source": {
          "path": "model/input_features.py",
          "line": 304
        },
        "id": "imitation-backward-shared-public-context-shared-tile-projection",
        "phase": "imitation",
        "title": "Shared public context → Shared tile identity projection",
        "description": "VJP into the shared tile-identity weights",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "candidate-projection",
        "to": "shared-tile-projection",
        "kind": "backward",
        "label": "VJP into the shared tile-identity weights",
        "source": {
          "path": "model/encoder.py",
          "line": 823
        },
        "id": "imitation-backward-candidate-projection-shared-tile-projection",
        "phase": "imitation",
        "title": "Local action queries → Shared tile identity projection",
        "description": "VJP into the shared tile-identity weights",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "player-descriptors",
        "to": "river-summaries",
        "kind": "backward",
        "label": "Settlement VJP: Three 256-channel opponent river summaries",
        "source": {
          "path": "model/network.py",
          "line": 214
        },
        "id": "imitation-backward-player-descriptors-river-summaries",
        "phase": "imitation",
        "title": "Deterministic player descriptors → River board and player summaries",
        "description": "Settlement VJP: Three 256-channel opponent river summaries",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "call-candidate-merge",
        "to": "candidate-projection",
        "kind": "backward",
        "label": "Settlement VJP: Candidate states and action structure",
        "source": {
          "path": "model/actor.py",
          "line": 577
        },
        "id": "imitation-backward-call-candidate-merge-candidate-projection",
        "phase": "imitation",
        "title": "Map post-call discards to actions → Local action queries",
        "description": "Settlement VJP: Candidate states and action structure",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "call-candidate-merge",
        "to": "board-output",
        "kind": "backward",
        "label": "Settlement VJP: Shared board state",
        "source": {
          "path": "model/actor.py",
          "line": 580
        },
        "id": "imitation-backward-call-candidate-merge-board-output",
        "phase": "imitation",
        "title": "Map post-call discards to actions → Shared decision state",
        "description": "Settlement VJP: Shared board state",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-player-projection",
        "to": "critic-state-assembly",
        "kind": "backward",
        "label": "Gradient through player descriptors in the assembled candidate state",
        "source": {
          "path": "model/critic.py",
          "line": 836
        },
        "id": "imitation-backward-critic-player-projection-critic-state-assembly",
        "phase": "imitation",
        "title": "Self and opponent player projections → Critic state assembly",
        "description": "Gradient through player descriptors in the assembled candidate state",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-player-projection",
        "to": "critic-refinement-5",
        "kind": "backward",
        "label": "VJP through common 384-channel context broadcast across seats",
        "source": {
          "path": "model/critic.py",
          "line": 840
        },
        "id": "imitation-backward-critic-player-projection-critic-refinement-5",
        "phase": "imitation",
        "title": "Self and opponent player projections → Critic residual block 6",
        "description": "VJP through common 384-channel context broadcast across seats",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-event",
        "to": "critic-refinement-5",
        "kind": "backward",
        "label": "VJP through common event-context projection",
        "source": {
          "path": "model/critic.py",
          "line": 875
        },
        "id": "imitation-backward-critic-event-critic-refinement-5",
        "phase": "imitation",
        "title": "Joint-event role pooling → Critic residual block 6",
        "description": "VJP through common event-context projection",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-event",
        "to": "critic-belief-adapter",
        "kind": "backward",
        "label": "VJP through winner/source/ready role pooling",
        "source": {
          "path": "model/critic.py",
          "line": 887
        },
        "id": "imitation-backward-critic-event-critic-belief-adapter",
        "phase": "imitation",
        "title": "Joint-event role pooling → Shared opponent moment residual",
        "description": "VJP through winner/source/ready role pooling",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-claim-state",
        "to": "critic-belief-adapter",
        "kind": "backward",
        "label": "VJP through recipient and ron-payer embeddings",
        "source": {
          "path": "model/critic.py",
          "line": 915
        },
        "id": "imitation-backward-critic-claim-state-critic-belief-adapter",
        "phase": "imitation",
        "title": "Claim-state projection → Shared opponent moment residual",
        "description": "VJP through recipient and ron-payer embeddings",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-score-head",
        "to": "critic-claim-state",
        "kind": "backward",
        "label": "VJP through claim states with public scoring evidence",
        "source": {
          "path": "model/critic.py",
          "line": 971
        },
        "id": "imitation-backward-critic-score-head-critic-claim-state",
        "phase": "imitation",
        "title": "Settlement value decoder → Claim-state projection",
        "description": "VJP through claim states with public scoring evidence",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-deposits",
        "to": "critic-result-attention",
        "kind": "backward",
        "label": "Gradient through the 32-channel event vectors used for deposit conditioning",
        "source": {
          "path": "model/critic.py",
          "line": 1009
        },
        "id": "imitation-backward-critic-deposits-critic-result-attention",
        "phase": "imitation",
        "title": "Deposit-mask conditioning → Result attention and event readout",
        "description": "Gradient through the 32-channel event vectors used for deposit conditioning",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-deposits",
        "to": "critic-belief-adapter",
        "kind": "backward",
        "label": "VJP through player embeddings pooled by deposit mask",
        "source": {
          "path": "model/critic.py",
          "line": 1013
        },
        "id": "imitation-backward-critic-deposits-critic-belief-adapter",
        "phase": "imitation",
        "title": "Deposit-mask conditioning → Shared opponent moment residual",
        "description": "VJP through player embeddings pooled by deposit mask",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "settlement-decoder",
        "to": "critic-result-attention",
        "kind": "backward",
        "label": "VJP through whole-event logits",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        },
        "id": "imitation-backward-settlement-decoder-critic-result-attention",
        "phase": "imitation",
        "title": "Deterministic settlement decoder → Result attention and event readout",
        "description": "VJP through whole-event logits",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "settlement-decoder",
        "to": "critic-deposits",
        "kind": "backward",
        "label": "VJP through event-conditioned deposit-mask logits",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        },
        "id": "imitation-backward-settlement-decoder-critic-deposits",
        "phase": "imitation",
        "title": "Deterministic settlement decoder → Deposit-mask conditioning",
        "description": "VJP through event-conditioned deposit-mask logits",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "settlement-decoder",
        "to": "critic-score-head",
        "kind": "backward",
        "label": "VJP through total score probabilities",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 492
        },
        "id": "imitation-backward-settlement-decoder-critic-score-head",
        "phase": "imitation",
        "title": "Deterministic settlement decoder → Settlement value decoder",
        "description": "VJP through total score probabilities",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "imitation-objective",
        "to": "settlement-decoder",
        "kind": "backward",
        "label": "Supported observed-transfer NLL gradient into compatible factor probabilities",
        "source": {
          "path": "training/imitation.py",
          "line": 164
        },
        "id": "imitation-backward-imitation-objective-settlement-decoder",
        "phase": "imitation",
        "title": "Imitation + settlement objective → Deterministic settlement decoder",
        "description": "Supported observed-transfer NLL gradient into compatible factor probabilities",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "imitation-objective",
        "to": "critic-score-head",
        "kind": "backward",
        "label": "Raw score-support constraint gradient",
        "source": {
          "path": "training/imitation.py",
          "line": 164
        },
        "id": "imitation-backward-imitation-objective-critic-score-head",
        "phase": "imitation",
        "title": "Imitation + settlement objective → Settlement value decoder",
        "description": "Raw score-support constraint gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "imitation-objective",
        "to": "critic-result-attention",
        "kind": "backward",
        "label": "Raw event constraint parameter gradients",
        "source": {
          "path": "training/imitation.py",
          "line": 164
        },
        "id": "imitation-backward-imitation-objective-critic-result-attention",
        "phase": "imitation",
        "title": "Imitation + settlement objective → Result attention and event readout",
        "description": "Raw event constraint parameter gradients",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "imitation-objective",
        "to": "critic-deposits",
        "kind": "backward",
        "label": "Raw conditional-deposit constraint gradient",
        "source": {
          "path": "training/imitation.py",
          "line": 164
        },
        "id": "imitation-backward-imitation-objective-critic-deposits",
        "phase": "imitation",
        "title": "Imitation + settlement objective → Deposit-mask conditioning",
        "description": "Raw conditional-deposit constraint gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-refinement",
        "to": "critic-common-projection",
        "kind": "backward",
        "label": "Residual identity plus refinement-branch VJP",
        "source": {
          "path": "model/critic.py",
          "line": 832
        },
        "id": "imitation-backward-critic-refinement-critic-common-projection",
        "phase": "imitation",
        "title": "Critic residual block 1 → Critic candidate projection",
        "description": "Residual identity plus refinement-branch VJP",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-state-assembly",
        "to": "call-candidate-merge",
        "label": "Observed-settlement gradient into shared decision and after-call candidate contexts",
        "kind": "backward",
        "source": {
          "path": "model/network.py",
          "line": 204
        },
        "id": "imitation-backward-critic-state-assembly-call-candidate-merge",
        "phase": "imitation",
        "title": "Critic state assembly → Map post-call discards to actions",
        "description": "Observed-settlement gradient into shared decision and after-call candidate contexts",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-common-projection",
        "to": "critic-state-assembly",
        "kind": "backward",
        "label": "VJP: Common-state projection",
        "source": {
          "path": "model/critic.py",
          "line": 677
        },
        "id": "imitation-backward-critic-common-projection-critic-state-assembly",
        "phase": "imitation",
        "title": "Critic candidate projection → Critic state assembly",
        "description": "VJP: Common-state projection",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-state-assembly",
        "to": "player-descriptors",
        "kind": "backward",
        "label": "VJP: Original-window player descriptors",
        "source": {
          "path": "model/critic.py",
          "line": 677
        },
        "id": "imitation-backward-critic-state-assembly-player-descriptors",
        "phase": "imitation",
        "title": "Critic state assembly → Deterministic player descriptors",
        "description": "VJP: Original-window player descriptors",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-belief-uncertainty",
        "to": "critic-state-assembly",
        "kind": "backward",
        "label": "VJP: Opponent probability slice",
        "source": {
          "path": "model/critic.py",
          "line": 677
        },
        "id": "imitation-backward-critic-belief-uncertainty-critic-state-assembly",
        "phase": "imitation",
        "title": "Per-opponent belief moments → Critic state assembly",
        "description": "VJP: Opponent probability slice",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "call-candidate-merge",
        "to": "shared-probabilities",
        "kind": "stop",
        "label": "Detached parent opponent beliefs and local completion probabilities",
        "source": {
          "path": "model/network.py",
          "line": 34
        },
        "id": "imitation-stop-call-candidate-merge-shared-probabilities",
        "phase": "imitation",
        "title": "Map post-call discards to actions ⊣ Shared FP32 probabilities",
        "description": "Detached parent opponent beliefs and local completion probabilities",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "critic-belief-adapter",
        "to": "critic-belief-uncertainty",
        "kind": "backward",
        "label": "Payment likelihood VJP through shared opponent residual",
        "source": {
          "path": "model/critic.py",
          "line": 677
        },
        "id": "imitation-backward-critic-belief-adapter-critic-belief-uncertainty",
        "phase": "imitation",
        "title": "Shared opponent moment residual → Per-opponent belief moments",
        "description": "Payment likelihood VJP through shared opponent residual",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-belief-adapter",
        "to": "critic-player-projection",
        "kind": "backward",
        "label": "Payment likelihood VJP through shared opponent residual",
        "source": {
          "path": "model/critic.py",
          "line": 677
        },
        "id": "imitation-backward-critic-belief-adapter-critic-player-projection",
        "phase": "imitation",
        "title": "Shared opponent moment residual → Self and opponent player projections",
        "description": "Payment likelihood VJP through shared opponent residual",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-refinement-1",
        "to": "critic-refinement",
        "kind": "backward",
        "label": "Residual refinement gradient",
        "source": {
          "path": "model/critic.py",
          "line": 832
        },
        "id": "imitation-backward-critic-refinement-1-critic-refinement",
        "phase": "imitation",
        "title": "Critic residual block 2 → Critic residual block 1",
        "description": "Residual refinement gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-refinement-2",
        "to": "critic-refinement-1",
        "kind": "backward",
        "label": "Residual refinement gradient",
        "source": {
          "path": "model/critic.py",
          "line": 832
        },
        "id": "imitation-backward-critic-refinement-2-critic-refinement-1",
        "phase": "imitation",
        "title": "Critic residual block 3 → Critic residual block 2",
        "description": "Residual refinement gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-refinement-3",
        "to": "critic-refinement-2",
        "kind": "backward",
        "label": "Residual refinement gradient",
        "source": {
          "path": "model/critic.py",
          "line": 832
        },
        "id": "imitation-backward-critic-refinement-3-critic-refinement-2",
        "phase": "imitation",
        "title": "Critic residual block 4 → Critic residual block 3",
        "description": "Residual refinement gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-refinement-4",
        "to": "critic-refinement-3",
        "kind": "backward",
        "label": "Residual refinement gradient",
        "source": {
          "path": "model/critic.py",
          "line": 832
        },
        "id": "imitation-backward-critic-refinement-4-critic-refinement-3",
        "phase": "imitation",
        "title": "Critic residual block 5 → Critic residual block 4",
        "description": "Residual refinement gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-refinement-5",
        "to": "critic-refinement-4",
        "kind": "backward",
        "label": "Residual refinement gradient",
        "source": {
          "path": "model/critic.py",
          "line": 832
        },
        "id": "imitation-backward-critic-refinement-5-critic-refinement-4",
        "phase": "imitation",
        "title": "Critic residual block 6 → Critic residual block 5",
        "description": "Residual refinement gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-board-input-projection",
        "to": "shared-public-context",
        "kind": "stop",
        "label": "Policy gradients stop before shared lower encodings",
        "source": {
          "path": "model/encoder.py",
          "line": 937
        },
        "id": "imitation-stop-actor-board-input-projection-shared-public-context",
        "phase": "imitation",
        "title": "Actor hand-board fusion ⊣ Shared public context",
        "description": "Policy gradients stop before shared lower encodings",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "actor-board-input-projection",
        "to": "hand-bank-output",
        "kind": "stop",
        "label": "Policy gradients stop before shared lower encodings",
        "source": {
          "path": "model/encoder.py",
          "line": 937
        },
        "id": "imitation-stop-actor-board-input-projection-hand-bank-output",
        "phase": "imitation",
        "title": "Actor hand-board fusion ⊣ Conditioned local hand bank",
        "description": "Policy gradients stop before shared lower encodings",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "actor-board-block-0",
        "to": "actor-board-input-projection",
        "kind": "backward",
        "label": "Private actor branch gradient",
        "source": {
          "path": "model/encoder.py",
          "line": 869
        },
        "id": "imitation-backward-actor-board-block-0-actor-board-input-projection",
        "phase": "imitation",
        "title": "Actor residual block 1 → Actor hand-board fusion",
        "description": "Private actor branch gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-board-block-1",
        "to": "actor-board-block-0",
        "kind": "backward",
        "label": "Private actor branch gradient",
        "source": {
          "path": "model/encoder.py",
          "line": 890
        },
        "id": "imitation-backward-actor-board-block-1-actor-board-block-0",
        "phase": "imitation",
        "title": "Actor residual block 2 → Actor residual block 1",
        "description": "Private actor branch gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-board-block-2",
        "to": "actor-board-block-1",
        "kind": "backward",
        "label": "Private actor branch gradient",
        "source": {
          "path": "model/encoder.py",
          "line": 890
        },
        "id": "imitation-backward-actor-board-block-2-actor-board-block-1",
        "phase": "imitation",
        "title": "Actor residual block 3 → Actor residual block 2",
        "description": "Private actor branch gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-board-output",
        "to": "actor-board-block-2",
        "kind": "backward",
        "label": "Private actor branch gradient",
        "source": {
          "path": "model/encoder.py",
          "line": 894
        },
        "id": "imitation-backward-actor-board-output-actor-board-block-2",
        "phase": "imitation",
        "title": "Actor Shared decision state → Actor residual block 3",
        "description": "Private actor branch gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-refinement-1",
        "to": "actor-refinement",
        "kind": "backward",
        "label": "Private actor branch gradient",
        "source": {
          "path": "model/network.py",
          "line": 108
        },
        "id": "imitation-backward-actor-refinement-1-actor-refinement",
        "phase": "imitation",
        "title": "Actor refinement block 2 → Actor refinement block 1",
        "description": "Private actor branch gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-result-attention",
        "to": "critic-event",
        "kind": "backward",
        "label": "Attention and identity-residual gradient into role-pooled events",
        "source": {
          "path": "model/critic.py",
          "line": 767
        },
        "id": "imitation-backward-critic-result-attention-critic-event",
        "phase": "imitation",
        "title": "Result attention and event readout → Joint-event role pooling",
        "description": "Attention and identity-residual gradient into role-pooled events",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "candidate-ron-prediction",
        "to": "completion-evidence",
        "kind": "backward",
        "label": "Ron eligibility trains opponent evidence hidden state",
        "source": {
          "path": "model/network.py",
          "line": 50
        },
        "id": "imitation-backward-candidate-ron-prediction-completion-evidence",
        "phase": "imitation",
        "title": "Ron-risk prediction → Opponent completion evidence",
        "description": "Ron eligibility trains opponent evidence hidden state",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "candidate-ron-prediction",
        "to": "actor-completion",
        "kind": "stop",
        "label": "Detached opponent ron-yaku probabilities",
        "source": {
          "path": "model/network.py",
          "line": 50
        },
        "id": "imitation-stop-candidate-ron-prediction-actor-completion",
        "phase": "imitation",
        "title": "Ron-risk prediction ⊣ Shared completion potential",
        "description": "Detached opponent ron-yaku probabilities",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "critic-pao-allocation",
        "to": "critic-claim-state",
        "kind": "backward",
        "label": "Settlement likelihood through allocation evidence",
        "source": {
          "path": "model/critic.py",
          "line": 820
        },
        "id": "imitation-backward-critic-pao-allocation-critic-claim-state",
        "phase": "imitation",
        "title": "Pao allocation → Claim-state projection",
        "description": "Settlement likelihood through allocation evidence",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-pao-allocation",
        "to": "critic-player-projection",
        "kind": "backward",
        "label": "Settlement likelihood through allocation evidence",
        "source": {
          "path": "model/critic.py",
          "line": 820
        },
        "id": "imitation-backward-critic-pao-allocation-critic-player-projection",
        "phase": "imitation",
        "title": "Pao allocation → Self and opponent player projections",
        "description": "Settlement likelihood through allocation evidence",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "settlement-decoder",
        "to": "critic-pao-allocation",
        "kind": "backward",
        "label": "Observed responsibility allocation likelihood",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 276
        },
        "id": "imitation-backward-settlement-decoder-critic-pao-allocation",
        "phase": "imitation",
        "title": "Deterministic settlement decoder → Pao allocation",
        "description": "Observed responsibility allocation likelihood",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-candidate-pool",
        "to": "candidate-projection",
        "kind": "stop",
        "label": "Detached candidate inputs; actor gradients stop",
        "source": {
          "path": "model/actor.py",
          "line": 86
        },
        "id": "imitation-stop-actor-candidate-pool-candidate-projection",
        "phase": "imitation",
        "title": "Legal candidate attention ⊣ Local action queries",
        "description": "Detached candidate inputs; actor gradients stop",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "actor-candidate-pool",
        "to": "actor-refinement-1",
        "kind": "backward",
        "label": "Actor residual keeps context gradient",
        "source": {
          "path": "model/actor.py",
          "line": 530
        },
        "id": "imitation-backward-actor-candidate-pool-actor-refinement-1",
        "phase": "imitation",
        "title": "Legal candidate attention → Actor refinement block 2",
        "description": "Actor residual keeps context gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "hand-suit-0",
        "to": "hand-tokenization",
        "kind": "backward",
        "label": "VJP through conditioned suit tokens",
        "source": {
          "path": "model/encoder.py",
          "line": 343
        },
        "id": "critic-backward-hand-suit-0-hand-tokenization",
        "phase": "critic",
        "title": "Suit residual block 1 → Context-conditioned hand tokens",
        "description": "VJP through conditioned suit tokens",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "hand-honors",
        "to": "hand-tokenization",
        "kind": "backward",
        "label": "VJP through conditioned honor tokens",
        "source": {
          "path": "model/encoder.py",
          "line": 368
        },
        "id": "critic-backward-hand-honors-hand-tokenization",
        "phase": "critic",
        "title": "Honor tile projection → Context-conditioned hand tokens",
        "description": "VJP through conditioned honor tokens",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "hand-suit-1",
        "to": "hand-suit-0",
        "kind": "backward",
        "label": "VJP through residual suit sequence",
        "source": {
          "path": "model/encoder.py",
          "line": 357
        },
        "id": "critic-backward-hand-suit-1-hand-suit-0",
        "phase": "critic",
        "title": "Suit residual block 2 → Suit residual block 1",
        "description": "VJP through residual suit sequence",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "hand-suit-2",
        "to": "hand-suit-1",
        "kind": "backward",
        "label": "VJP through residual suit sequence",
        "source": {
          "path": "model/encoder.py",
          "line": 357
        },
        "id": "critic-backward-hand-suit-2-hand-suit-1",
        "phase": "critic",
        "title": "Suit residual block 3 → Suit residual block 2",
        "description": "VJP through residual suit sequence",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "hand-bank-output",
        "to": "hand-suit-2",
        "kind": "backward",
        "label": "VJP through reconstructed 27 suit-tile tokens",
        "source": {
          "path": "model/encoder.py",
          "line": 368
        },
        "id": "critic-backward-hand-bank-output-hand-suit-2",
        "phase": "critic",
        "title": "Conditioned local hand bank → Suit residual block 3",
        "description": "VJP through reconstructed 27 suit-tile tokens",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "hand-bank-output",
        "to": "hand-honors",
        "kind": "backward",
        "label": "VJP through seven honor-tile tokens",
        "source": {
          "path": "model/encoder.py",
          "line": 368
        },
        "id": "critic-backward-hand-bank-output-hand-honors",
        "phase": "critic",
        "title": "Conditioned local hand bank → Honor tile projection",
        "description": "VJP through seven honor-tile tokens",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "board-input-projection",
        "to": "hand-bank-output",
        "kind": "backward",
        "label": "VJP through current hand slot 0",
        "source": {
          "path": "model/encoder.py",
          "line": 935
        },
        "id": "critic-backward-board-input-projection-hand-bank-output",
        "phase": "critic",
        "title": "Joint hand-board fusion → Conditioned local hand bank",
        "description": "VJP through current hand slot 0",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "river-conv-0",
        "to": "river-tokenization",
        "kind": "backward",
        "label": "VJP through masked 64-channel stream tokens",
        "source": {
          "path": "model/encoder.py",
          "line": 521
        },
        "id": "critic-backward-river-conv-0-river-tokenization",
        "phase": "critic",
        "title": "River residual block 1 → River token projection",
        "description": "VJP through masked 64-channel stream tokens",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "river-conv-1",
        "to": "river-conv-0",
        "kind": "backward",
        "label": "VJP through masked residual stream",
        "source": {
          "path": "model/encoder.py",
          "line": 528
        },
        "id": "critic-backward-river-conv-1-river-conv-0",
        "phase": "critic",
        "title": "River residual block 2 → River residual block 1",
        "description": "VJP through masked residual stream",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "river-conv-2",
        "to": "river-conv-1",
        "kind": "backward",
        "label": "VJP through masked residual stream",
        "source": {
          "path": "model/encoder.py",
          "line": 528
        },
        "id": "critic-backward-river-conv-2-river-conv-1",
        "phase": "critic",
        "title": "River residual block 3 → River residual block 2",
        "description": "VJP through masked residual stream",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "river-summaries",
        "to": "river-attention",
        "kind": "backward",
        "label": "VJP through final masked stream tokens",
        "source": {
          "path": "model/encoder.py",
          "line": 539
        },
        "id": "critic-backward-river-summaries-river-attention",
        "phase": "critic",
        "title": "River board and player summaries → Cross-river event attention",
        "description": "VJP through final masked stream tokens",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "shared-public-context",
        "to": "river-summaries",
        "kind": "backward",
        "label": "VJP through six ordered 64-channel summaries",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        },
        "id": "critic-backward-shared-public-context-river-summaries",
        "phase": "critic",
        "title": "Shared public context → River board and player summaries",
        "description": "VJP through six ordered 64-channel summaries",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "board-block-0",
        "to": "board-input-projection",
        "kind": "backward",
        "label": "VJP through joint hand-board fusion",
        "source": {
          "path": "model/encoder.py",
          "line": 869
        },
        "id": "critic-backward-board-block-0-board-input-projection",
        "phase": "critic",
        "title": "Board residual block 1 → Joint hand-board fusion",
        "description": "VJP through joint hand-board fusion",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "board-block-1",
        "to": "board-block-0",
        "kind": "backward",
        "label": "VJP through residual board state",
        "source": {
          "path": "model/encoder.py",
          "line": 890
        },
        "id": "critic-backward-board-block-1-board-block-0",
        "phase": "critic",
        "title": "Board residual block 2 → Board residual block 1",
        "description": "VJP through residual board state",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "board-block-2",
        "to": "board-block-1",
        "kind": "backward",
        "label": "VJP through residual board state",
        "source": {
          "path": "model/encoder.py",
          "line": 890
        },
        "id": "critic-backward-board-block-2-board-block-1",
        "phase": "critic",
        "title": "Board residual block 3 → Board residual block 2",
        "description": "VJP through residual board state",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "board-output",
        "to": "board-block-2",
        "kind": "backward",
        "label": "VJP through final residual trunk state",
        "source": {
          "path": "model/encoder.py",
          "line": 894
        },
        "id": "critic-backward-board-output-board-block-2",
        "phase": "critic",
        "title": "Shared decision state → Board residual block 3",
        "description": "VJP through final residual trunk state",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "candidate-projection",
        "to": "hand-bank-output",
        "kind": "backward",
        "label": "VJP through gathered 512-channel action hand",
        "source": {
          "path": "model/encoder.py",
          "line": 801
        },
        "id": "critic-backward-candidate-projection-hand-bank-output",
        "phase": "critic",
        "title": "Local action queries → Conditioned local hand bank",
        "description": "VJP through gathered 512-channel action hand",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "candidate-projection",
        "to": "board-output",
        "kind": "backward",
        "label": "VJP through board context projected to 192 channels",
        "source": {
          "path": "model/encoder.py",
          "line": 847
        },
        "id": "critic-backward-candidate-projection-board-output",
        "phase": "critic",
        "title": "Local action queries → Shared decision state",
        "description": "VJP through board context projected to 192 channels",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "belief-readouts",
        "to": "belief-refinement",
        "kind": "backward",
        "label": "VJP through shared 512-channel board representation",
        "source": {
          "path": "model/beliefs.py",
          "line": 458
        },
        "id": "critic-backward-belief-readouts-belief-refinement",
        "phase": "critic",
        "title": "Initial belief readouts → Belief residual refinement",
        "description": "VJP through shared 512-channel board representation",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "tile-tokenization",
        "to": "belief-refinement",
        "kind": "backward",
        "label": "VJP through three opponent context slices",
        "source": {
          "path": "model/beliefs.py",
          "line": 241
        },
        "id": "critic-backward-tile-tokenization-belief-refinement",
        "phase": "critic",
        "title": "Tile attention tokenization → Belief residual refinement",
        "description": "VJP through three opponent context slices",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "tile-tokenization",
        "to": "belief-readouts",
        "kind": "stop",
        "label": "Detached initial shanten, conditional improving and count probabilities",
        "source": {
          "path": "model/beliefs.py",
          "line": 207
        },
        "id": "critic-stop-tile-tokenization-belief-readouts",
        "phase": "critic",
        "title": "Tile attention tokenization ⊣ Initial belief readouts",
        "description": "Detached initial shanten, conditional improving and count probabilities",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "tile-attention-0",
        "to": "tile-tokenization",
        "kind": "backward",
        "label": "VJP through 34 tokens per opponent",
        "source": {
          "path": "model/beliefs.py",
          "line": 252
        },
        "id": "critic-backward-tile-attention-0-tile-tokenization",
        "phase": "critic",
        "title": "Tile attention block 1 → Tile attention tokenization",
        "description": "VJP through 34 tokens per opponent",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "tile-attention-1",
        "to": "tile-attention-0",
        "kind": "backward",
        "label": "VJP through refined token sequence",
        "source": {
          "path": "model/beliefs.py",
          "line": 261
        },
        "id": "critic-backward-tile-attention-1-tile-attention-0",
        "phase": "critic",
        "title": "Tile attention block 2 → Tile attention block 1",
        "description": "VJP through refined token sequence",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "tile-correction",
        "to": "tile-attention-1",
        "kind": "backward",
        "label": "VJP through final 128-channel tile tokens",
        "source": {
          "path": "model/beliefs.py",
          "line": 262
        },
        "id": "critic-backward-tile-correction-tile-attention-1",
        "phase": "critic",
        "title": "Residual belief correction → Tile attention block 2",
        "description": "VJP through final 128-channel tile tokens",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "tile-correction",
        "to": "belief-readouts",
        "kind": "backward",
        "label": "VJP through initial count and ukeire logits for residual add",
        "source": {
          "path": "model/beliefs.py",
          "line": 267
        },
        "id": "critic-backward-tile-correction-belief-readouts",
        "phase": "critic",
        "title": "Residual belief correction → Initial belief readouts",
        "description": "VJP through initial count and ukeire logits for residual add",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "belief-constraints",
        "to": "tile-correction",
        "kind": "backward",
        "label": "Gradient through the refined held-count logits",
        "source": {
          "path": "model/beliefs.py",
          "line": 473
        },
        "id": "critic-backward-belief-constraints-tile-correction",
        "phase": "critic",
        "title": "Belief support and count projection → Residual belief correction",
        "description": "Gradient through the refined held-count logits",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "belief-constraints",
        "to": "belief-readouts",
        "kind": "backward",
        "label": "VJP through unmodified shanten logits",
        "source": {
          "path": "model/beliefs.py",
          "line": 474
        },
        "id": "critic-backward-belief-constraints-belief-readouts",
        "phase": "critic",
        "title": "Belief support and count projection → Initial belief readouts",
        "description": "VJP through unmodified shanten logits",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-candidate-aux",
        "to": "candidate-projection",
        "kind": "backward",
        "label": "VJP through route prediction weights and raw candidate state",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 10
        },
        "id": "critic-backward-actor-candidate-aux-candidate-projection",
        "phase": "critic",
        "title": "Shared route prediction → Local action queries",
        "description": "VJP through route prediction weights and raw candidate state",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-completion",
        "to": "belief-refinement",
        "kind": "backward",
        "label": "VJP through shared refined completion readouts",
        "source": {
          "path": "model/beliefs.py",
          "line": 458
        },
        "id": "critic-backward-actor-completion-belief-refinement",
        "phase": "critic",
        "title": "Shared completion potential → Belief residual refinement",
        "description": "VJP through shared refined completion readouts",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "player-descriptors",
        "to": "river-summaries",
        "kind": "backward",
        "label": "Settlement VJP: Three 256-channel opponent river summaries",
        "source": {
          "path": "model/network.py",
          "line": 214
        },
        "id": "critic-backward-player-descriptors-river-summaries",
        "phase": "critic",
        "title": "Deterministic player descriptors → River board and player summaries",
        "description": "Settlement VJP: Three 256-channel opponent river summaries",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "call-candidate-merge",
        "to": "candidate-projection",
        "kind": "backward",
        "label": "Settlement VJP: Candidate states and action structure",
        "source": {
          "path": "model/actor.py",
          "line": 577
        },
        "id": "critic-backward-call-candidate-merge-candidate-projection",
        "phase": "critic",
        "title": "Map post-call discards to actions → Local action queries",
        "description": "Settlement VJP: Candidate states and action structure",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "call-candidate-merge",
        "to": "board-output",
        "kind": "backward",
        "label": "Settlement VJP: Shared board state",
        "source": {
          "path": "model/actor.py",
          "line": 580
        },
        "id": "critic-backward-call-candidate-merge-board-output",
        "phase": "critic",
        "title": "Map post-call discards to actions → Shared decision state",
        "description": "Settlement VJP: Shared board state",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-player-projection",
        "to": "critic-state-assembly",
        "kind": "backward",
        "label": "Gradient through player descriptors in the assembled candidate state",
        "source": {
          "path": "model/critic.py",
          "line": 836
        },
        "id": "critic-backward-critic-player-projection-critic-state-assembly",
        "phase": "critic",
        "title": "Self and opponent player projections → Critic state assembly",
        "description": "Gradient through player descriptors in the assembled candidate state",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-player-projection",
        "to": "critic-refinement-5",
        "kind": "backward",
        "label": "VJP through common 384-channel context broadcast across seats",
        "source": {
          "path": "model/critic.py",
          "line": 840
        },
        "id": "critic-backward-critic-player-projection-critic-refinement-5",
        "phase": "critic",
        "title": "Self and opponent player projections → Critic residual block 6",
        "description": "VJP through common 384-channel context broadcast across seats",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-event",
        "to": "critic-refinement-5",
        "kind": "backward",
        "label": "VJP through common event-context projection",
        "source": {
          "path": "model/critic.py",
          "line": 875
        },
        "id": "critic-backward-critic-event-critic-refinement-5",
        "phase": "critic",
        "title": "Joint-event role pooling → Critic residual block 6",
        "description": "VJP through common event-context projection",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-event",
        "to": "critic-belief-adapter",
        "kind": "backward",
        "label": "VJP through winner/source/ready role pooling",
        "source": {
          "path": "model/critic.py",
          "line": 887
        },
        "id": "critic-backward-critic-event-critic-belief-adapter",
        "phase": "critic",
        "title": "Joint-event role pooling → Shared opponent moment residual",
        "description": "VJP through winner/source/ready role pooling",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-claim-state",
        "to": "critic-belief-adapter",
        "kind": "backward",
        "label": "VJP through recipient and ron-payer embeddings",
        "source": {
          "path": "model/critic.py",
          "line": 915
        },
        "id": "critic-backward-critic-claim-state-critic-belief-adapter",
        "phase": "critic",
        "title": "Claim-state projection → Shared opponent moment residual",
        "description": "VJP through recipient and ron-payer embeddings",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-score-head",
        "to": "critic-claim-state",
        "kind": "backward",
        "label": "VJP through claim states with public scoring evidence",
        "source": {
          "path": "model/critic.py",
          "line": 971
        },
        "id": "critic-backward-critic-score-head-critic-claim-state",
        "phase": "critic",
        "title": "Settlement value decoder → Claim-state projection",
        "description": "VJP through claim states with public scoring evidence",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-deposits",
        "to": "critic-result-attention",
        "kind": "backward",
        "label": "Gradient through the 32-channel event vectors used for deposit conditioning",
        "source": {
          "path": "model/critic.py",
          "line": 1009
        },
        "id": "critic-backward-critic-deposits-critic-result-attention",
        "phase": "critic",
        "title": "Deposit-mask conditioning → Result attention and event readout",
        "description": "Gradient through the 32-channel event vectors used for deposit conditioning",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-deposits",
        "to": "critic-belief-adapter",
        "kind": "backward",
        "label": "VJP through player embeddings pooled by deposit mask",
        "source": {
          "path": "model/critic.py",
          "line": 1013
        },
        "id": "critic-backward-critic-deposits-critic-belief-adapter",
        "phase": "critic",
        "title": "Deposit-mask conditioning → Shared opponent moment residual",
        "description": "VJP through player embeddings pooled by deposit mask",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "settlement-decoder",
        "to": "critic-result-attention",
        "kind": "backward",
        "label": "VJP through whole-event logits",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        },
        "id": "critic-backward-settlement-decoder-critic-result-attention",
        "phase": "critic",
        "title": "Deterministic settlement decoder → Result attention and event readout",
        "description": "VJP through whole-event logits",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "settlement-decoder",
        "to": "critic-deposits",
        "kind": "backward",
        "label": "VJP through event-conditioned deposit-mask logits",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 462
        },
        "id": "critic-backward-settlement-decoder-critic-deposits",
        "phase": "critic",
        "title": "Deterministic settlement decoder → Deposit-mask conditioning",
        "description": "VJP through event-conditioned deposit-mask logits",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "settlement-decoder",
        "to": "critic-score-head",
        "kind": "backward",
        "label": "VJP through total score probabilities",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 492
        },
        "id": "critic-backward-settlement-decoder-critic-score-head",
        "phase": "critic",
        "title": "Deterministic settlement decoder → Settlement value decoder",
        "description": "VJP through total score probabilities",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-state-assembly",
        "to": "actor-candidate-aux",
        "kind": "stop",
        "label": "Detached route probabilities in the settlement state",
        "source": {
          "path": "model/network.py",
          "line": 208
        },
        "id": "critic-stop-critic-state-assembly-actor-candidate-aux",
        "phase": "critic",
        "title": "Critic state assembly ⊣ Shared route prediction",
        "description": "Detached route probabilities in the settlement state",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "critic-objective",
        "to": "settlement-decoder",
        "kind": "backward",
        "label": "Supported observed-transfer NLL gradient into compatible factor probabilities",
        "source": {
          "path": "training/trainer.py",
          "line": 97
        },
        "id": "critic-backward-critic-objective-settlement-decoder",
        "phase": "critic",
        "title": "Critic pass objective → Deterministic settlement decoder",
        "description": "Supported observed-transfer NLL gradient into compatible factor probabilities",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-objective",
        "to": "critic-score-head",
        "kind": "backward",
        "label": "Raw score-support constraint gradient",
        "source": {
          "path": "training/trainer.py",
          "line": 97
        },
        "id": "critic-backward-critic-objective-critic-score-head",
        "phase": "critic",
        "title": "Critic pass objective → Settlement value decoder",
        "description": "Raw score-support constraint gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-objective",
        "to": "critic-result-attention",
        "kind": "backward",
        "label": "Raw event constraint parameter gradients",
        "source": {
          "path": "training/trainer.py",
          "line": 97
        },
        "id": "critic-backward-critic-objective-critic-result-attention",
        "phase": "critic",
        "title": "Critic pass objective → Result attention and event readout",
        "description": "Raw event constraint parameter gradients",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-objective",
        "to": "critic-deposits",
        "kind": "backward",
        "label": "Raw conditional-deposit constraint gradient",
        "source": {
          "path": "training/trainer.py",
          "line": 97
        },
        "id": "critic-backward-critic-objective-critic-deposits",
        "phase": "critic",
        "title": "Critic pass objective → Deposit-mask conditioning",
        "description": "Raw conditional-deposit constraint gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "belief-refinement",
        "to": "board-output",
        "kind": "backward",
        "label": "Residual identity plus refinement-branch VJP",
        "source": {
          "path": "model/beliefs.py",
          "line": 451
        },
        "id": "critic-backward-belief-refinement-board-output",
        "phase": "critic",
        "title": "Belief residual refinement → Shared decision state",
        "description": "Residual identity plus refinement-branch VJP",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-refinement",
        "to": "critic-common-projection",
        "kind": "backward",
        "label": "Residual identity plus refinement-branch VJP",
        "source": {
          "path": "model/critic.py",
          "line": 832
        },
        "id": "critic-backward-critic-refinement-critic-common-projection",
        "phase": "critic",
        "title": "Critic residual block 1 → Critic candidate projection",
        "description": "Residual identity plus refinement-branch VJP",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-state-assembly",
        "to": "call-candidate-merge",
        "label": "Observed-settlement gradient into shared decision and after-call candidate contexts",
        "kind": "backward",
        "source": {
          "path": "model/network.py",
          "line": 204
        },
        "id": "critic-backward-critic-state-assembly-call-candidate-merge",
        "phase": "critic",
        "title": "Critic state assembly → Map post-call discards to actions",
        "description": "Observed-settlement gradient into shared decision and after-call candidate contexts",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "hand-tokenization",
        "to": "table-conditioning",
        "kind": "backward",
        "label": "VJP through table offset added before first hand GELU",
        "source": {
          "path": "model/encoder.py",
          "line": 339
        },
        "id": "critic-backward-hand-tokenization-table-conditioning",
        "phase": "critic",
        "title": "Context-conditioned hand tokens → Shared-context hand conditioning",
        "description": "VJP through table offset added before first hand GELU",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-common-projection",
        "to": "critic-state-assembly",
        "kind": "backward",
        "label": "VJP: Common-state projection",
        "source": {
          "path": "model/critic.py",
          "line": 677
        },
        "id": "critic-backward-critic-common-projection-critic-state-assembly",
        "phase": "critic",
        "title": "Critic candidate projection → Critic state assembly",
        "description": "VJP: Common-state projection",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-state-assembly",
        "to": "player-descriptors",
        "kind": "backward",
        "label": "VJP: Original-window player descriptors",
        "source": {
          "path": "model/critic.py",
          "line": 677
        },
        "id": "critic-backward-critic-state-assembly-player-descriptors",
        "phase": "critic",
        "title": "Critic state assembly → Deterministic player descriptors",
        "description": "VJP: Original-window player descriptors",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-belief-uncertainty",
        "to": "critic-state-assembly",
        "kind": "backward",
        "label": "VJP: Opponent probability slice",
        "source": {
          "path": "model/critic.py",
          "line": 677
        },
        "id": "critic-backward-critic-belief-uncertainty-critic-state-assembly",
        "phase": "critic",
        "title": "Per-opponent belief moments → Critic state assembly",
        "description": "VJP: Opponent probability slice",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "call-candidate-merge",
        "to": "shared-probabilities",
        "kind": "stop",
        "label": "Detached parent opponent beliefs and local completion probabilities",
        "source": {
          "path": "model/network.py",
          "line": 34
        },
        "id": "critic-stop-call-candidate-merge-shared-probabilities",
        "phase": "critic",
        "title": "Map post-call discards to actions ⊣ Shared FP32 probabilities",
        "description": "Detached parent opponent beliefs and local completion probabilities",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "belief-readouts",
        "to": "river-summaries",
        "kind": "backward",
        "label": "Shared shanten derivative into opponent-local river summaries",
        "source": {
          "path": "model/beliefs.py",
          "line": 291
        },
        "id": "critic-backward-belief-readouts-river-summaries",
        "phase": "critic",
        "title": "Initial belief readouts → River board and player summaries",
        "description": "Shared shanten derivative into opponent-local river summaries",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-belief-adapter",
        "to": "critic-belief-uncertainty",
        "kind": "backward",
        "label": "Payment likelihood VJP through shared opponent residual",
        "source": {
          "path": "model/critic.py",
          "line": 677
        },
        "id": "critic-backward-critic-belief-adapter-critic-belief-uncertainty",
        "phase": "critic",
        "title": "Shared opponent moment residual → Per-opponent belief moments",
        "description": "Payment likelihood VJP through shared opponent residual",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-belief-adapter",
        "to": "critic-player-projection",
        "kind": "backward",
        "label": "Payment likelihood VJP through shared opponent residual",
        "source": {
          "path": "model/critic.py",
          "line": 677
        },
        "id": "critic-backward-critic-belief-adapter-critic-player-projection",
        "phase": "critic",
        "title": "Shared opponent moment residual → Self and opponent player projections",
        "description": "Payment likelihood VJP through shared opponent residual",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "completion-evidence",
        "to": "belief-constraints",
        "kind": "stop",
        "label": "Detached projected held counts",
        "source": {
          "path": "model/beliefs.py",
          "line": 529
        },
        "id": "critic-stop-completion-evidence-belief-constraints",
        "phase": "critic",
        "title": "Opponent completion evidence ⊣ Belief support and count projection",
        "description": "Detached projected held counts",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "completion-evidence",
        "to": "river-summaries",
        "kind": "backward",
        "label": "Completion evidence VJP: Aligned per-opponent river summary 256",
        "source": {
          "path": "model/beliefs.py",
          "line": 336
        },
        "id": "critic-backward-completion-evidence-river-summaries",
        "phase": "critic",
        "title": "Opponent completion evidence → River board and player summaries",
        "description": "Completion evidence VJP: Aligned per-opponent river summary 256",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-completion",
        "to": "completion-evidence",
        "kind": "backward",
        "label": "Completion evidence VJP: Opponent-only 46 yaku +76 score residual before support",
        "source": {
          "path": "model/beliefs.py",
          "line": 336
        },
        "id": "critic-backward-actor-completion-completion-evidence",
        "phase": "critic",
        "title": "Shared completion potential → Opponent completion evidence",
        "description": "Completion evidence VJP: Opponent-only 46 yaku +76 score residual before support",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "candidate-ron-prediction",
        "to": "board-output",
        "kind": "backward",
        "label": "Ron eligibility gradients reach observed board",
        "source": {
          "path": "model/network.py",
          "line": 44
        },
        "id": "critic-backward-candidate-ron-prediction-board-output",
        "phase": "critic",
        "title": "Ron-risk prediction → Shared decision state",
        "description": "Ron eligibility gradients reach observed board",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "candidate-ron-prediction",
        "to": "structural-wait",
        "kind": "stop",
        "label": "Detached structural wait in candidate ron",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 36
        },
        "id": "critic-stop-candidate-ron-prediction-structural-wait",
        "phase": "critic",
        "title": "Ron-risk prediction ⊣ Structural wait prediction",
        "description": "Detached structural wait in candidate ron",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "critic-objective",
        "to": "belief-constraints",
        "kind": "backward",
        "label": "Direct supervised shanten and projected held-count losses",
        "source": {
          "path": "training/auxiliary.py",
          "line": 18
        },
        "id": "critic-backward-critic-objective-belief-constraints",
        "phase": "critic",
        "title": "Critic pass objective → Belief support and count projection",
        "description": "Direct supervised shanten and projected held-count losses",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-objective",
        "to": "actor-completion",
        "kind": "backward",
        "label": "Observed completion yaku and score losses",
        "source": {
          "path": "training/auxiliary.py",
          "line": 18
        },
        "id": "critic-backward-critic-objective-actor-completion",
        "phase": "critic",
        "title": "Critic pass objective → Shared completion potential",
        "description": "Observed completion yaku and score losses",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-objective",
        "to": "actor-candidate-aux",
        "kind": "backward",
        "label": "Observed candidate route loss",
        "source": {
          "path": "training/auxiliary.py",
          "line": 18
        },
        "id": "critic-backward-critic-objective-actor-candidate-aux",
        "phase": "critic",
        "title": "Critic pass objective → Shared route prediction",
        "description": "Observed candidate route loss",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-objective",
        "to": "candidate-ron-prediction",
        "kind": "backward",
        "label": "Observed candidate ron loss",
        "source": {
          "path": "training/auxiliary.py",
          "line": 18
        },
        "id": "critic-backward-critic-objective-candidate-ron-prediction",
        "phase": "critic",
        "title": "Critic pass objective → Ron-risk prediction",
        "description": "Observed candidate ron loss",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-objective",
        "to": "tile-correction",
        "kind": "backward",
        "label": "Direct supervised conditional improving-tile loss",
        "source": {
          "path": "model/beliefs.py",
          "line": 767
        },
        "id": "critic-backward-critic-objective-tile-correction",
        "phase": "critic",
        "title": "Critic pass objective → Residual belief correction",
        "description": "Direct supervised conditional improving-tile loss",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "table-conditioning",
        "to": "shared-public-context",
        "kind": "backward",
        "label": "VJP through shared-context hand projection",
        "source": {
          "path": "model/encoder.py",
          "line": 339
        },
        "id": "critic-backward-table-conditioning-shared-public-context",
        "phase": "critic",
        "title": "Shared-context hand conditioning → Shared public context",
        "description": "VJP through shared-context hand projection",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "board-input-projection",
        "to": "shared-public-context",
        "kind": "backward",
        "label": "VJP through shared context in joint fusion",
        "source": {
          "path": "model/encoder.py",
          "line": 869
        },
        "id": "critic-backward-board-input-projection-shared-public-context",
        "phase": "critic",
        "title": "Joint hand-board fusion → Shared public context",
        "description": "VJP through shared context in joint fusion",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "river-attention",
        "to": "river-conv-2",
        "kind": "backward",
        "label": "VJP through observed-event attention residual",
        "source": {
          "path": "model/river_attention.py",
          "line": 44
        },
        "id": "critic-backward-river-attention-river-conv-2",
        "phase": "critic",
        "title": "Cross-river event attention → River residual block 3",
        "description": "VJP through observed-event attention residual",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-final-score",
        "to": "candidate-projection",
        "kind": "stop",
        "label": "Detached raw state; policy gradients stop before shared candidate encoding",
        "source": {
          "path": "model/network.py",
          "line": 156
        },
        "id": "critic-stop-actor-final-score-candidate-projection",
        "phase": "critic",
        "title": "Final candidate scorer ⊣ Local action queries",
        "description": "Detached raw state; policy gradients stop before shared candidate encoding",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "hand-tokenization",
        "to": "shared-tile-projection",
        "kind": "backward",
        "label": "VJP into the shared tile-identity weights",
        "source": {
          "path": "model/encoder.py",
          "line": 278
        },
        "id": "critic-backward-hand-tokenization-shared-tile-projection",
        "phase": "critic",
        "title": "Context-conditioned hand tokens → Shared tile identity projection",
        "description": "VJP into the shared tile-identity weights",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "river-tokenization",
        "to": "shared-tile-projection",
        "kind": "backward",
        "label": "VJP into the shared tile-identity weights",
        "source": {
          "path": "model/encoder.py",
          "line": 503
        },
        "id": "critic-backward-river-tokenization-shared-tile-projection",
        "phase": "critic",
        "title": "River token projection → Shared tile identity projection",
        "description": "VJP into the shared tile-identity weights",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "shared-public-context",
        "to": "shared-tile-projection",
        "kind": "backward",
        "label": "VJP into the shared tile-identity weights",
        "source": {
          "path": "model/input_features.py",
          "line": 304
        },
        "id": "critic-backward-shared-public-context-shared-tile-projection",
        "phase": "critic",
        "title": "Shared public context → Shared tile identity projection",
        "description": "VJP into the shared tile-identity weights",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "candidate-projection",
        "to": "shared-tile-projection",
        "kind": "backward",
        "label": "VJP into the shared tile-identity weights",
        "source": {
          "path": "model/encoder.py",
          "line": 823
        },
        "id": "critic-backward-candidate-projection-shared-tile-projection",
        "phase": "critic",
        "title": "Local action queries → Shared tile identity projection",
        "description": "VJP into the shared tile-identity weights",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-refinement-1",
        "to": "critic-refinement",
        "kind": "backward",
        "label": "Residual refinement gradient",
        "source": {
          "path": "model/critic.py",
          "line": 832
        },
        "id": "critic-backward-critic-refinement-1-critic-refinement",
        "phase": "critic",
        "title": "Critic residual block 2 → Critic residual block 1",
        "description": "Residual refinement gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-refinement-2",
        "to": "critic-refinement-1",
        "kind": "backward",
        "label": "Residual refinement gradient",
        "source": {
          "path": "model/critic.py",
          "line": 832
        },
        "id": "critic-backward-critic-refinement-2-critic-refinement-1",
        "phase": "critic",
        "title": "Critic residual block 3 → Critic residual block 2",
        "description": "Residual refinement gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-refinement-3",
        "to": "critic-refinement-2",
        "kind": "backward",
        "label": "Residual refinement gradient",
        "source": {
          "path": "model/critic.py",
          "line": 832
        },
        "id": "critic-backward-critic-refinement-3-critic-refinement-2",
        "phase": "critic",
        "title": "Critic residual block 4 → Critic residual block 3",
        "description": "Residual refinement gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-refinement-4",
        "to": "critic-refinement-3",
        "kind": "backward",
        "label": "Residual refinement gradient",
        "source": {
          "path": "model/critic.py",
          "line": 832
        },
        "id": "critic-backward-critic-refinement-4-critic-refinement-3",
        "phase": "critic",
        "title": "Critic residual block 5 → Critic residual block 4",
        "description": "Residual refinement gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-refinement-5",
        "to": "critic-refinement-4",
        "kind": "backward",
        "label": "Residual refinement gradient",
        "source": {
          "path": "model/critic.py",
          "line": 832
        },
        "id": "critic-backward-critic-refinement-5-critic-refinement-4",
        "phase": "critic",
        "title": "Critic residual block 6 → Critic residual block 5",
        "description": "Residual refinement gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-board-input-projection",
        "to": "shared-public-context",
        "kind": "stop",
        "label": "Policy gradients stop before shared lower encodings",
        "source": {
          "path": "model/encoder.py",
          "line": 937
        },
        "id": "critic-stop-actor-board-input-projection-shared-public-context",
        "phase": "critic",
        "title": "Actor hand-board fusion ⊣ Shared public context",
        "description": "Policy gradients stop before shared lower encodings",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "actor-board-input-projection",
        "to": "hand-bank-output",
        "kind": "stop",
        "label": "Policy gradients stop before shared lower encodings",
        "source": {
          "path": "model/encoder.py",
          "line": 937
        },
        "id": "critic-stop-actor-board-input-projection-hand-bank-output",
        "phase": "critic",
        "title": "Actor hand-board fusion ⊣ Conditioned local hand bank",
        "description": "Policy gradients stop before shared lower encodings",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "critic-result-attention",
        "to": "critic-event",
        "kind": "backward",
        "label": "Attention and identity-residual gradient into role-pooled events",
        "source": {
          "path": "model/critic.py",
          "line": 767
        },
        "id": "critic-backward-critic-result-attention-critic-event",
        "phase": "critic",
        "title": "Result attention and event readout → Joint-event role pooling",
        "description": "Attention and identity-residual gradient into role-pooled events",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "candidate-ron-prediction",
        "to": "completion-evidence",
        "kind": "backward",
        "label": "Ron eligibility trains opponent evidence hidden state",
        "source": {
          "path": "model/network.py",
          "line": 50
        },
        "id": "critic-backward-candidate-ron-prediction-completion-evidence",
        "phase": "critic",
        "title": "Ron-risk prediction → Opponent completion evidence",
        "description": "Ron eligibility trains opponent evidence hidden state",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "candidate-ron-prediction",
        "to": "actor-completion",
        "kind": "stop",
        "label": "Detached opponent ron-yaku probabilities",
        "source": {
          "path": "model/network.py",
          "line": 50
        },
        "id": "critic-stop-candidate-ron-prediction-actor-completion",
        "phase": "critic",
        "title": "Ron-risk prediction ⊣ Shared completion potential",
        "description": "Detached opponent ron-yaku probabilities",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "critic-pao-allocation",
        "to": "critic-claim-state",
        "kind": "backward",
        "label": "Settlement likelihood through allocation evidence",
        "source": {
          "path": "model/critic.py",
          "line": 820
        },
        "id": "critic-backward-critic-pao-allocation-critic-claim-state",
        "phase": "critic",
        "title": "Pao allocation → Claim-state projection",
        "description": "Settlement likelihood through allocation evidence",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-pao-allocation",
        "to": "critic-player-projection",
        "kind": "backward",
        "label": "Settlement likelihood through allocation evidence",
        "source": {
          "path": "model/critic.py",
          "line": 820
        },
        "id": "critic-backward-critic-pao-allocation-critic-player-projection",
        "phase": "critic",
        "title": "Pao allocation → Self and opponent player projections",
        "description": "Settlement likelihood through allocation evidence",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "settlement-decoder",
        "to": "critic-pao-allocation",
        "kind": "backward",
        "label": "Observed responsibility allocation likelihood",
        "source": {
          "path": "model/joint_settlement.py",
          "line": 276
        },
        "id": "critic-backward-settlement-decoder-critic-pao-allocation",
        "phase": "critic",
        "title": "Deterministic settlement decoder → Pao allocation",
        "description": "Observed responsibility allocation likelihood",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-candidate-pool",
        "to": "candidate-projection",
        "kind": "stop",
        "label": "Detached candidate inputs; actor gradients stop",
        "source": {
          "path": "model/actor.py",
          "line": 86
        },
        "id": "critic-stop-actor-candidate-pool-candidate-projection",
        "phase": "critic",
        "title": "Legal candidate attention ⊣ Local action queries",
        "description": "Detached candidate inputs; actor gradients stop",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "hand-suit-0",
        "to": "hand-tokenization",
        "kind": "backward",
        "label": "VJP through conditioned suit tokens",
        "source": {
          "path": "model/encoder.py",
          "line": 343
        },
        "id": "actor-backward-hand-suit-0-hand-tokenization",
        "phase": "actor",
        "title": "Suit residual block 1 → Context-conditioned hand tokens",
        "description": "VJP through conditioned suit tokens",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "hand-honors",
        "to": "hand-tokenization",
        "kind": "backward",
        "label": "VJP through conditioned honor tokens",
        "source": {
          "path": "model/encoder.py",
          "line": 368
        },
        "id": "actor-backward-hand-honors-hand-tokenization",
        "phase": "actor",
        "title": "Honor tile projection → Context-conditioned hand tokens",
        "description": "VJP through conditioned honor tokens",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "hand-suit-1",
        "to": "hand-suit-0",
        "kind": "backward",
        "label": "VJP through residual suit sequence",
        "source": {
          "path": "model/encoder.py",
          "line": 357
        },
        "id": "actor-backward-hand-suit-1-hand-suit-0",
        "phase": "actor",
        "title": "Suit residual block 2 → Suit residual block 1",
        "description": "VJP through residual suit sequence",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "hand-suit-2",
        "to": "hand-suit-1",
        "kind": "backward",
        "label": "VJP through residual suit sequence",
        "source": {
          "path": "model/encoder.py",
          "line": 357
        },
        "id": "actor-backward-hand-suit-2-hand-suit-1",
        "phase": "actor",
        "title": "Suit residual block 3 → Suit residual block 2",
        "description": "VJP through residual suit sequence",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "hand-bank-output",
        "to": "hand-suit-2",
        "kind": "backward",
        "label": "VJP through reconstructed 27 suit-tile tokens",
        "source": {
          "path": "model/encoder.py",
          "line": 368
        },
        "id": "actor-backward-hand-bank-output-hand-suit-2",
        "phase": "actor",
        "title": "Conditioned local hand bank → Suit residual block 3",
        "description": "VJP through reconstructed 27 suit-tile tokens",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "hand-bank-output",
        "to": "hand-honors",
        "kind": "backward",
        "label": "VJP through seven honor-tile tokens",
        "source": {
          "path": "model/encoder.py",
          "line": 368
        },
        "id": "actor-backward-hand-bank-output-hand-honors",
        "phase": "actor",
        "title": "Conditioned local hand bank → Honor tile projection",
        "description": "VJP through seven honor-tile tokens",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "board-input-projection",
        "to": "hand-bank-output",
        "kind": "backward",
        "label": "VJP through current hand slot 0",
        "source": {
          "path": "model/encoder.py",
          "line": 935
        },
        "id": "actor-backward-board-input-projection-hand-bank-output",
        "phase": "actor",
        "title": "Joint hand-board fusion → Conditioned local hand bank",
        "description": "VJP through current hand slot 0",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "river-conv-0",
        "to": "river-tokenization",
        "kind": "backward",
        "label": "VJP through masked 64-channel stream tokens",
        "source": {
          "path": "model/encoder.py",
          "line": 521
        },
        "id": "actor-backward-river-conv-0-river-tokenization",
        "phase": "actor",
        "title": "River residual block 1 → River token projection",
        "description": "VJP through masked 64-channel stream tokens",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "river-conv-1",
        "to": "river-conv-0",
        "kind": "backward",
        "label": "VJP through masked residual stream",
        "source": {
          "path": "model/encoder.py",
          "line": 528
        },
        "id": "actor-backward-river-conv-1-river-conv-0",
        "phase": "actor",
        "title": "River residual block 2 → River residual block 1",
        "description": "VJP through masked residual stream",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "river-conv-2",
        "to": "river-conv-1",
        "kind": "backward",
        "label": "VJP through masked residual stream",
        "source": {
          "path": "model/encoder.py",
          "line": 528
        },
        "id": "actor-backward-river-conv-2-river-conv-1",
        "phase": "actor",
        "title": "River residual block 3 → River residual block 2",
        "description": "VJP through masked residual stream",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "river-summaries",
        "to": "river-attention",
        "kind": "backward",
        "label": "VJP through final masked stream tokens",
        "source": {
          "path": "model/encoder.py",
          "line": 539
        },
        "id": "actor-backward-river-summaries-river-attention",
        "phase": "actor",
        "title": "River board and player summaries → Cross-river event attention",
        "description": "VJP through final masked stream tokens",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "shared-public-context",
        "to": "river-summaries",
        "kind": "backward",
        "label": "VJP through six ordered 64-channel summaries",
        "source": {
          "path": "model/encoder.py",
          "line": 916
        },
        "id": "actor-backward-shared-public-context-river-summaries",
        "phase": "actor",
        "title": "Shared public context → River board and player summaries",
        "description": "VJP through six ordered 64-channel summaries",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "board-block-0",
        "to": "board-input-projection",
        "kind": "backward",
        "label": "VJP through joint hand-board fusion",
        "source": {
          "path": "model/encoder.py",
          "line": 869
        },
        "id": "actor-backward-board-block-0-board-input-projection",
        "phase": "actor",
        "title": "Board residual block 1 → Joint hand-board fusion",
        "description": "VJP through joint hand-board fusion",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "board-block-1",
        "to": "board-block-0",
        "kind": "backward",
        "label": "VJP through residual board state",
        "source": {
          "path": "model/encoder.py",
          "line": 890
        },
        "id": "actor-backward-board-block-1-board-block-0",
        "phase": "actor",
        "title": "Board residual block 2 → Board residual block 1",
        "description": "VJP through residual board state",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "board-block-2",
        "to": "board-block-1",
        "kind": "backward",
        "label": "VJP through residual board state",
        "source": {
          "path": "model/encoder.py",
          "line": 890
        },
        "id": "actor-backward-board-block-2-board-block-1",
        "phase": "actor",
        "title": "Board residual block 3 → Board residual block 2",
        "description": "VJP through residual board state",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "board-output",
        "to": "board-block-2",
        "kind": "backward",
        "label": "VJP through final residual trunk state",
        "source": {
          "path": "model/encoder.py",
          "line": 894
        },
        "id": "actor-backward-board-output-board-block-2",
        "phase": "actor",
        "title": "Shared decision state → Board residual block 3",
        "description": "VJP through final residual trunk state",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "candidate-projection",
        "to": "hand-bank-output",
        "kind": "backward",
        "label": "VJP through gathered 512-channel action hand",
        "source": {
          "path": "model/encoder.py",
          "line": 801
        },
        "id": "actor-backward-candidate-projection-hand-bank-output",
        "phase": "actor",
        "title": "Local action queries → Conditioned local hand bank",
        "description": "VJP through gathered 512-channel action hand",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "candidate-projection",
        "to": "board-output",
        "kind": "backward",
        "label": "VJP through board context projected to 192 channels",
        "source": {
          "path": "model/encoder.py",
          "line": 847
        },
        "id": "actor-backward-candidate-projection-board-output",
        "phase": "actor",
        "title": "Local action queries → Shared decision state",
        "description": "VJP through board context projected to 192 channels",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "belief-readouts",
        "to": "belief-refinement",
        "kind": "backward",
        "label": "VJP through shared 512-channel board representation",
        "source": {
          "path": "model/beliefs.py",
          "line": 458
        },
        "id": "actor-backward-belief-readouts-belief-refinement",
        "phase": "actor",
        "title": "Initial belief readouts → Belief residual refinement",
        "description": "VJP through shared 512-channel board representation",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "tile-tokenization",
        "to": "belief-refinement",
        "kind": "backward",
        "label": "VJP through three opponent context slices",
        "source": {
          "path": "model/beliefs.py",
          "line": 241
        },
        "id": "actor-backward-tile-tokenization-belief-refinement",
        "phase": "actor",
        "title": "Tile attention tokenization → Belief residual refinement",
        "description": "VJP through three opponent context slices",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "tile-tokenization",
        "to": "belief-readouts",
        "kind": "stop",
        "label": "Detached initial shanten, conditional improving and count probabilities",
        "source": {
          "path": "model/beliefs.py",
          "line": 207
        },
        "id": "actor-stop-tile-tokenization-belief-readouts",
        "phase": "actor",
        "title": "Tile attention tokenization ⊣ Initial belief readouts",
        "description": "Detached initial shanten, conditional improving and count probabilities",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "tile-attention-0",
        "to": "tile-tokenization",
        "kind": "backward",
        "label": "VJP through 34 tokens per opponent",
        "source": {
          "path": "model/beliefs.py",
          "line": 252
        },
        "id": "actor-backward-tile-attention-0-tile-tokenization",
        "phase": "actor",
        "title": "Tile attention block 1 → Tile attention tokenization",
        "description": "VJP through 34 tokens per opponent",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "tile-attention-1",
        "to": "tile-attention-0",
        "kind": "backward",
        "label": "VJP through refined token sequence",
        "source": {
          "path": "model/beliefs.py",
          "line": 261
        },
        "id": "actor-backward-tile-attention-1-tile-attention-0",
        "phase": "actor",
        "title": "Tile attention block 2 → Tile attention block 1",
        "description": "VJP through refined token sequence",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "tile-correction",
        "to": "tile-attention-1",
        "kind": "backward",
        "label": "VJP through final 128-channel tile tokens",
        "source": {
          "path": "model/beliefs.py",
          "line": 262
        },
        "id": "actor-backward-tile-correction-tile-attention-1",
        "phase": "actor",
        "title": "Residual belief correction → Tile attention block 2",
        "description": "VJP through final 128-channel tile tokens",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "tile-correction",
        "to": "belief-readouts",
        "kind": "backward",
        "label": "VJP through initial count and ukeire logits for residual add",
        "source": {
          "path": "model/beliefs.py",
          "line": 267
        },
        "id": "actor-backward-tile-correction-belief-readouts",
        "phase": "actor",
        "title": "Residual belief correction → Initial belief readouts",
        "description": "VJP through initial count and ukeire logits for residual add",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "belief-constraints",
        "to": "tile-correction",
        "kind": "backward",
        "label": "Gradient through the refined held-count logits",
        "source": {
          "path": "model/beliefs.py",
          "line": 473
        },
        "id": "actor-backward-belief-constraints-tile-correction",
        "phase": "actor",
        "title": "Belief support and count projection → Residual belief correction",
        "description": "Gradient through the refined held-count logits",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "belief-constraints",
        "to": "belief-readouts",
        "kind": "backward",
        "label": "VJP through unmodified shanten logits",
        "source": {
          "path": "model/beliefs.py",
          "line": 474
        },
        "id": "actor-backward-belief-constraints-belief-readouts",
        "phase": "actor",
        "title": "Belief support and count projection → Initial belief readouts",
        "description": "VJP through unmodified shanten logits",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "candidate-ron-prediction",
        "to": "board-output",
        "kind": "backward",
        "label": "Ron eligibility gradients reach observed board",
        "source": {
          "path": "model/network.py",
          "line": 44
        },
        "id": "actor-backward-candidate-ron-prediction-board-output",
        "phase": "actor",
        "title": "Ron-risk prediction → Shared decision state",
        "description": "Ron eligibility gradients reach observed board",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-candidate-aux",
        "to": "candidate-projection",
        "kind": "backward",
        "label": "VJP through route prediction weights and raw candidate state",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 10
        },
        "id": "actor-backward-actor-candidate-aux-candidate-projection",
        "phase": "actor",
        "title": "Shared route prediction → Local action queries",
        "description": "VJP through route prediction weights and raw candidate state",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-completion",
        "to": "belief-refinement",
        "kind": "backward",
        "label": "VJP through shared refined completion readouts",
        "source": {
          "path": "model/beliefs.py",
          "line": 458
        },
        "id": "actor-backward-actor-completion-belief-refinement",
        "phase": "actor",
        "title": "Shared completion potential → Belief residual refinement",
        "description": "VJP through shared refined completion readouts",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-final-score",
        "to": "candidate-projection",
        "kind": "stop",
        "label": "Detached raw state; policy gradients stop before shared candidate encoding",
        "source": {
          "path": "model/network.py",
          "line": 156
        },
        "id": "actor-stop-actor-final-score-candidate-projection",
        "phase": "actor",
        "title": "Final candidate scorer ⊣ Local action queries",
        "description": "Detached raw state; policy gradients stop before shared candidate encoding",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "actor-final-score",
        "to": "candidate-ron-prediction",
        "kind": "stop",
        "label": "Detached candidate ron probabilities",
        "source": {
          "path": "model/actor.py",
          "line": 159
        },
        "id": "actor-stop-actor-final-score-candidate-ron-prediction",
        "phase": "actor",
        "title": "Final candidate scorer ⊣ Ron-risk prediction",
        "description": "Detached candidate ron probabilities",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "actor-final-score",
        "to": "actor-candidate-aux",
        "kind": "stop",
        "label": "Detached candidate route probabilities",
        "source": {
          "path": "model/actor.py",
          "line": 159
        },
        "id": "actor-stop-actor-final-score-actor-candidate-aux",
        "phase": "actor",
        "title": "Final candidate scorer ⊣ Shared route prediction",
        "description": "Detached candidate route probabilities",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "actor-final-score",
        "to": "actor-candidate-pool",
        "kind": "backward",
        "label": "VJP through 768-channel gathered policy context",
        "source": {
          "path": "model/actor.py",
          "line": 530
        },
        "id": "actor-backward-actor-final-score-actor-candidate-pool",
        "phase": "actor",
        "title": "Final candidate scorer → Legal candidate attention",
        "description": "VJP through 768-channel gathered policy context",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-win",
        "to": "actor-candidate-pool",
        "kind": "backward",
        "label": "VJP through private actor board and predictive context",
        "source": {
          "path": "model/actor.py",
          "line": 530
        },
        "id": "actor-backward-actor-win-actor-candidate-pool",
        "phase": "actor",
        "title": "Win/pass head → Legal candidate attention",
        "description": "VJP through private actor board and predictive context",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-state-assembly",
        "to": "actor-candidate-aux",
        "kind": "stop",
        "label": "Detached route probabilities in the settlement state",
        "source": {
          "path": "model/network.py",
          "line": 208
        },
        "id": "actor-stop-critic-state-assembly-actor-candidate-aux",
        "phase": "actor",
        "title": "Critic state assembly ⊣ Shared route prediction",
        "description": "Detached route probabilities in the settlement state",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "actor-objective",
        "to": "continuation-payoffs",
        "kind": "stop",
        "label": "Q is a detached coefficient; only current policy mass differentiates",
        "source": {
          "path": "training/corrections/trainer.py",
          "line": 13
        },
        "id": "actor-stop-actor-objective-continuation-payoffs",
        "phase": "actor",
        "title": "MMD actor pass objective ⊣ Fixed continuation and expected value",
        "description": "Q is a detached coefficient; only current policy mass differentiates",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "actor-objective",
        "to": "actor-final-score",
        "kind": "backward",
        "label": "Policy gain and current-policy KL derivatives",
        "source": {
          "path": "training/corrections/trainer.py",
          "line": 52
        },
        "id": "actor-backward-actor-objective-actor-final-score",
        "phase": "actor",
        "title": "MMD actor pass objective → Final candidate scorer",
        "description": "Policy gain and current-policy KL derivatives",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-objective",
        "to": "actor-win",
        "kind": "backward",
        "label": "Current-policy KL only; WIN candidate-mass Q gain cancels",
        "source": {
          "path": "training/corrections/trainer.py",
          "line": 52
        },
        "id": "actor-backward-actor-objective-actor-win",
        "phase": "actor",
        "title": "MMD actor pass objective → Win/pass head",
        "description": "Current-policy KL only; WIN candidate-mass Q gain cancels",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-objective",
        "to": "tile-correction",
        "kind": "backward",
        "label": "Direct supervised improving-tile loss and weighted raw count-constraint gradient",
        "source": {
          "path": "training/corrections/trainer.py",
          "line": 52
        },
        "id": "actor-backward-actor-objective-tile-correction",
        "phase": "actor",
        "title": "MMD actor pass objective → Residual belief correction",
        "description": "Direct supervised improving-tile loss and weighted raw count-constraint gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-objective",
        "to": "belief-readouts",
        "kind": "backward",
        "label": "0.01 raw shanten/count constraint gradients",
        "source": {
          "path": "training/corrections/trainer.py",
          "line": 52
        },
        "id": "actor-backward-actor-objective-belief-readouts",
        "phase": "actor",
        "title": "MMD actor pass objective → Initial belief readouts",
        "description": "0.01 raw shanten/count constraint gradients",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "belief-refinement",
        "to": "board-output",
        "kind": "backward",
        "label": "Residual identity plus refinement-branch VJP",
        "source": {
          "path": "model/beliefs.py",
          "line": 451
        },
        "id": "actor-backward-belief-refinement-board-output",
        "phase": "actor",
        "title": "Belief residual refinement → Shared decision state",
        "description": "Residual identity plus refinement-branch VJP",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "critic-common-projection",
        "to": "critic-state-assembly",
        "label": "Q evaluation detaches the assembled candidate state.",
        "kind": "stop",
        "source": {
          "path": "training/trainer.py",
          "line": 47
        },
        "id": "actor-stop-critic-common-projection-critic-state-assembly",
        "phase": "actor",
        "title": "Critic candidate projection ⊣ Critic state assembly",
        "description": "Q evaluation detaches the assembled candidate state.",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "critic-player-projection",
        "to": "critic-state-assembly",
        "label": "Q evaluation detaches the assembled candidate state.",
        "kind": "stop",
        "source": {
          "path": "training/trainer.py",
          "line": 47
        },
        "id": "actor-stop-critic-player-projection-critic-state-assembly",
        "phase": "actor",
        "title": "Self and opponent player projections ⊣ Critic state assembly",
        "description": "Q evaluation detaches the assembled candidate state.",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "critic-belief-uncertainty",
        "to": "critic-state-assembly",
        "label": "Q evaluation detaches the assembled candidate state.",
        "kind": "stop",
        "source": {
          "path": "training/trainer.py",
          "line": 47
        },
        "id": "actor-stop-critic-belief-uncertainty-critic-state-assembly",
        "phase": "actor",
        "title": "Per-opponent belief moments ⊣ Critic state assembly",
        "description": "Q evaluation detaches the assembled candidate state.",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "call-choice",
        "to": "actor-candidate-pool",
        "label": "VJP through private actor board and predictive context",
        "kind": "backward",
        "source": {
          "path": "model/actor.py",
          "line": 530
        },
        "id": "actor-backward-call-choice-actor-candidate-pool",
        "phase": "actor",
        "title": "Call choice on decision board → Legal candidate attention",
        "description": "VJP through private actor board and predictive context",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "call-factorization",
        "to": "call-choice",
        "label": "Response-policy gradient through normalized six-way branch probabilities",
        "kind": "backward",
        "source": {
          "path": "model/actor.py",
          "line": 562
        },
        "id": "actor-backward-call-factorization-call-choice",
        "phase": "actor",
        "title": "Post-call discard policy → Call choice on decision board",
        "description": "Response-policy gradient through normalized six-way branch probabilities",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "call-factorization",
        "to": "actor-final-score",
        "label": "Response-policy gradient through ordinary shared follow-up discard probabilities",
        "kind": "backward",
        "source": {
          "path": "model/actor.py",
          "line": 535
        },
        "id": "actor-backward-call-factorization-actor-final-score",
        "phase": "actor",
        "title": "Post-call discard policy → Final candidate scorer",
        "description": "Response-policy gradient through ordinary shared follow-up discard probabilities",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-objective",
        "to": "call-factorization",
        "label": "Response-phase full joint-policy KL and detached-Q policy gain",
        "kind": "backward",
        "source": {
          "path": "training/corrections/trainer.py",
          "line": 52
        },
        "id": "actor-backward-actor-objective-call-factorization",
        "phase": "actor",
        "title": "MMD actor pass objective → Post-call discard policy",
        "description": "Response-phase full joint-policy KL and detached-Q policy gain",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-policy-context",
        "to": "actor-board-output",
        "kind": "backward",
        "label": "Policy gradients train the private actor encoder",
        "source": {
          "path": "model/network.py",
          "line": 22
        },
        "id": "actor-backward-actor-policy-context-actor-board-output",
        "phase": "actor",
        "title": "Policy context projection → Actor Shared decision state",
        "description": "Policy gradients train the private actor encoder",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "hand-tokenization",
        "to": "table-conditioning",
        "kind": "backward",
        "label": "VJP through table offset added before first hand GELU",
        "source": {
          "path": "model/encoder.py",
          "line": 339
        },
        "id": "actor-backward-hand-tokenization-table-conditioning",
        "phase": "actor",
        "title": "Context-conditioned hand tokens → Shared-context hand conditioning",
        "description": "VJP through table offset added before first hand GELU",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-policy-context",
        "to": "shared-probabilities",
        "kind": "stop",
        "label": "Detached policy belief and completion probabilities",
        "source": {
          "path": "model/network.py",
          "line": 34
        },
        "id": "actor-stop-actor-policy-context-shared-probabilities",
        "phase": "actor",
        "title": "Policy context projection ⊣ Shared FP32 probabilities",
        "description": "Detached policy belief and completion probabilities",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "candidate-ron-prediction",
        "to": "structural-wait",
        "label": "Detached structural wait in candidate ron",
        "kind": "stop",
        "source": {
          "path": "model/candidate_predictions.py",
          "line": 36
        },
        "id": "actor-stop-candidate-ron-prediction-structural-wait",
        "phase": "actor",
        "title": "Ron-risk prediction ⊣ Structural wait prediction",
        "description": "Detached structural wait in candidate ron",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "belief-readouts",
        "to": "river-summaries",
        "kind": "backward",
        "label": "Shared shanten derivative into opponent-local river summaries",
        "source": {
          "path": "model/beliefs.py",
          "line": 291
        },
        "id": "actor-backward-belief-readouts-river-summaries",
        "phase": "actor",
        "title": "Initial belief readouts → River board and player summaries",
        "description": "Shared shanten derivative into opponent-local river summaries",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "completion-evidence",
        "to": "belief-constraints",
        "kind": "stop",
        "label": "Detached projected held counts",
        "source": {
          "path": "model/beliefs.py",
          "line": 529
        },
        "id": "actor-stop-completion-evidence-belief-constraints",
        "phase": "actor",
        "title": "Opponent completion evidence ⊣ Belief support and count projection",
        "description": "Detached projected held counts",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "completion-evidence",
        "to": "river-summaries",
        "kind": "backward",
        "label": "Completion evidence VJP: Aligned per-opponent river summary 256",
        "source": {
          "path": "model/beliefs.py",
          "line": 336
        },
        "id": "actor-backward-completion-evidence-river-summaries",
        "phase": "actor",
        "title": "Opponent completion evidence → River board and player summaries",
        "description": "Completion evidence VJP: Aligned per-opponent river summary 256",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-completion",
        "to": "completion-evidence",
        "kind": "backward",
        "label": "Completion evidence VJP: Opponent-only 46 yaku +76 score residual before support",
        "source": {
          "path": "model/beliefs.py",
          "line": 336
        },
        "id": "actor-backward-actor-completion-completion-evidence",
        "phase": "actor",
        "title": "Shared completion potential → Opponent completion evidence",
        "description": "Completion evidence VJP: Opponent-only 46 yaku +76 score residual before support",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-objective",
        "to": "belief-constraints",
        "kind": "backward",
        "label": "Direct supervised shanten and projected held-count losses",
        "source": {
          "path": "training/auxiliary.py",
          "line": 18
        },
        "id": "actor-backward-actor-objective-belief-constraints",
        "phase": "actor",
        "title": "MMD actor pass objective → Belief support and count projection",
        "description": "Direct supervised shanten and projected held-count losses",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-objective",
        "to": "actor-completion",
        "kind": "backward",
        "label": "Observed completion yaku and score losses and belief-owned structural constraint",
        "source": {
          "path": "training/auxiliary.py",
          "line": 18
        },
        "id": "actor-backward-actor-objective-actor-completion",
        "phase": "actor",
        "title": "MMD actor pass objective → Shared completion potential",
        "description": "Observed completion yaku and score losses and belief-owned structural constraint",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-objective",
        "to": "actor-candidate-aux",
        "kind": "backward",
        "label": "Observed candidate route loss and belief-owned structural constraint",
        "source": {
          "path": "training/auxiliary.py",
          "line": 18
        },
        "id": "actor-backward-actor-objective-actor-candidate-aux",
        "phase": "actor",
        "title": "MMD actor pass objective → Shared route prediction",
        "description": "Observed candidate route loss and belief-owned structural constraint",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-objective",
        "to": "candidate-ron-prediction",
        "kind": "backward",
        "label": "Observed candidate ron loss",
        "source": {
          "path": "training/auxiliary.py",
          "line": 18
        },
        "id": "actor-backward-actor-objective-candidate-ron-prediction",
        "phase": "actor",
        "title": "MMD actor pass objective → Ron-risk prediction",
        "description": "Observed candidate ron loss",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "table-conditioning",
        "to": "shared-public-context",
        "kind": "backward",
        "label": "VJP through shared-context hand projection",
        "source": {
          "path": "model/encoder.py",
          "line": 339
        },
        "id": "actor-backward-table-conditioning-shared-public-context",
        "phase": "actor",
        "title": "Shared-context hand conditioning → Shared public context",
        "description": "VJP through shared-context hand projection",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "board-input-projection",
        "to": "shared-public-context",
        "kind": "backward",
        "label": "VJP through shared context in joint fusion",
        "source": {
          "path": "model/encoder.py",
          "line": 869
        },
        "id": "actor-backward-board-input-projection-shared-public-context",
        "phase": "actor",
        "title": "Joint hand-board fusion → Shared public context",
        "description": "VJP through shared context in joint fusion",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "river-attention",
        "to": "river-conv-2",
        "kind": "backward",
        "label": "VJP through observed-event attention residual",
        "source": {
          "path": "model/river_attention.py",
          "line": 44
        },
        "id": "actor-backward-river-attention-river-conv-2",
        "phase": "actor",
        "title": "Cross-river event attention → River residual block 3",
        "description": "VJP through observed-event attention residual",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-refinement",
        "to": "actor-policy-context",
        "kind": "backward",
        "label": "VJP through private actor refinement",
        "source": {
          "path": "model/network.py",
          "line": 108
        },
        "id": "actor-backward-actor-refinement-actor-policy-context",
        "phase": "actor",
        "title": "Actor refinement block 1 → Policy context projection",
        "description": "VJP through private actor refinement",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "hand-tokenization",
        "to": "shared-tile-projection",
        "kind": "backward",
        "label": "VJP into the shared tile-identity weights",
        "source": {
          "path": "model/encoder.py",
          "line": 278
        },
        "id": "actor-backward-hand-tokenization-shared-tile-projection",
        "phase": "actor",
        "title": "Context-conditioned hand tokens → Shared tile identity projection",
        "description": "VJP into the shared tile-identity weights",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "river-tokenization",
        "to": "shared-tile-projection",
        "kind": "backward",
        "label": "VJP into the shared tile-identity weights",
        "source": {
          "path": "model/encoder.py",
          "line": 503
        },
        "id": "actor-backward-river-tokenization-shared-tile-projection",
        "phase": "actor",
        "title": "River token projection → Shared tile identity projection",
        "description": "VJP into the shared tile-identity weights",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "shared-public-context",
        "to": "shared-tile-projection",
        "kind": "backward",
        "label": "VJP into the shared tile-identity weights",
        "source": {
          "path": "model/input_features.py",
          "line": 304
        },
        "id": "actor-backward-shared-public-context-shared-tile-projection",
        "phase": "actor",
        "title": "Shared public context → Shared tile identity projection",
        "description": "VJP into the shared tile-identity weights",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "candidate-projection",
        "to": "shared-tile-projection",
        "kind": "backward",
        "label": "VJP into the shared tile-identity weights",
        "source": {
          "path": "model/encoder.py",
          "line": 823
        },
        "id": "actor-backward-candidate-projection-shared-tile-projection",
        "phase": "actor",
        "title": "Local action queries → Shared tile identity projection",
        "description": "VJP into the shared tile-identity weights",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-board-input-projection",
        "to": "shared-public-context",
        "kind": "stop",
        "label": "Policy gradients stop before shared lower encodings",
        "source": {
          "path": "model/encoder.py",
          "line": 937
        },
        "id": "actor-stop-actor-board-input-projection-shared-public-context",
        "phase": "actor",
        "title": "Actor hand-board fusion ⊣ Shared public context",
        "description": "Policy gradients stop before shared lower encodings",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "actor-board-input-projection",
        "to": "hand-bank-output",
        "kind": "stop",
        "label": "Policy gradients stop before shared lower encodings",
        "source": {
          "path": "model/encoder.py",
          "line": 937
        },
        "id": "actor-stop-actor-board-input-projection-hand-bank-output",
        "phase": "actor",
        "title": "Actor hand-board fusion ⊣ Conditioned local hand bank",
        "description": "Policy gradients stop before shared lower encodings",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "actor-board-block-0",
        "to": "actor-board-input-projection",
        "kind": "backward",
        "label": "Private actor branch gradient",
        "source": {
          "path": "model/encoder.py",
          "line": 869
        },
        "id": "actor-backward-actor-board-block-0-actor-board-input-projection",
        "phase": "actor",
        "title": "Actor residual block 1 → Actor hand-board fusion",
        "description": "Private actor branch gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-board-block-1",
        "to": "actor-board-block-0",
        "kind": "backward",
        "label": "Private actor branch gradient",
        "source": {
          "path": "model/encoder.py",
          "line": 890
        },
        "id": "actor-backward-actor-board-block-1-actor-board-block-0",
        "phase": "actor",
        "title": "Actor residual block 2 → Actor residual block 1",
        "description": "Private actor branch gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-board-block-2",
        "to": "actor-board-block-1",
        "kind": "backward",
        "label": "Private actor branch gradient",
        "source": {
          "path": "model/encoder.py",
          "line": 890
        },
        "id": "actor-backward-actor-board-block-2-actor-board-block-1",
        "phase": "actor",
        "title": "Actor residual block 3 → Actor residual block 2",
        "description": "Private actor branch gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-board-output",
        "to": "actor-board-block-2",
        "kind": "backward",
        "label": "Private actor branch gradient",
        "source": {
          "path": "model/encoder.py",
          "line": 894
        },
        "id": "actor-backward-actor-board-output-actor-board-block-2",
        "phase": "actor",
        "title": "Actor Shared decision state → Actor residual block 3",
        "description": "Private actor branch gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "actor-refinement-1",
        "to": "actor-refinement",
        "kind": "backward",
        "label": "Private actor branch gradient",
        "source": {
          "path": "model/network.py",
          "line": 108
        },
        "id": "actor-backward-actor-refinement-1-actor-refinement",
        "phase": "actor",
        "title": "Actor refinement block 2 → Actor refinement block 1",
        "description": "Private actor branch gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "candidate-ron-prediction",
        "to": "completion-evidence",
        "kind": "backward",
        "label": "Ron eligibility trains opponent evidence hidden state",
        "source": {
          "path": "model/network.py",
          "line": 50
        },
        "id": "actor-backward-candidate-ron-prediction-completion-evidence",
        "phase": "actor",
        "title": "Ron-risk prediction → Opponent completion evidence",
        "description": "Ron eligibility trains opponent evidence hidden state",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      },
      {
        "from": "candidate-ron-prediction",
        "to": "actor-completion",
        "kind": "stop",
        "label": "Detached opponent ron-yaku probabilities",
        "source": {
          "path": "model/network.py",
          "line": 50
        },
        "id": "actor-stop-candidate-ron-prediction-actor-completion",
        "phase": "actor",
        "title": "Ron-risk prediction ⊣ Shared completion potential",
        "description": "Detached opponent ron-yaku probabilities",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "actor-candidate-pool",
        "to": "candidate-projection",
        "kind": "stop",
        "label": "Detached candidate inputs; actor gradients stop",
        "source": {
          "path": "model/actor.py",
          "line": 86
        },
        "id": "actor-stop-actor-candidate-pool-candidate-projection",
        "phase": "actor",
        "title": "Legal candidate attention ⊣ Local action queries",
        "description": "Detached candidate inputs; actor gradients stop",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mfrac><mrow><mo>&#x02202;</mo><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mo>&#x02202;</mo><mi>x</mi></mrow></mfrac><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
      },
      {
        "from": "actor-candidate-pool",
        "to": "actor-refinement-1",
        "kind": "backward",
        "label": "Actor residual keeps context gradient",
        "source": {
          "path": "model/actor.py",
          "line": 530
        },
        "id": "actor-backward-actor-candidate-pool-actor-refinement-1",
        "phase": "actor",
        "title": "Legal candidate attention → Actor refinement block 2",
        "description": "Actor residual keeps context gradient",
        "gradient": true,
        "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mrow><mi>x</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>J</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><msup><mo stretchy=\"false\">&#x00029;</mo><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mover><mrow><mi>y</mi></mrow><mo stretchy=\"true\">&#x000AF;</mo></mover></mrow></math>"
      }
    ]
  },
  "outputs": [
    {
      "id": "discard_policy_logits",
      "name": "discard_policy_logits",
      "title": "Discard policy logits",
      "shape": [
        37
      ],
      "dtype": "float32",
      "description": "Legality-constrained categorical action logits over 34 ordinary tile classes plus three red-five classes. Consumed by live action selection, self-play, policy training and reviewer grading.",
      "row_axis": "position",
      "signatures": [
        "serving_default",
        "policy"
      ],
      "source": {
        "path": "model/actions.py",
        "line": 26
      }
    },
    {
      "id": "riichi_policy_logits",
      "name": "riichi_policy_logits",
      "title": "Riichi policy logits",
      "shape": [
        74
      ],
      "dtype": "float32",
      "description": "Joint categorical action logits over declaration status × discard class: 37 dama choices followed by 37 riichi choices. Consumed by live selection and reviewer branch-conditional discard grading.",
      "row_axis": "position",
      "signatures": [
        "serving_default",
        "policy"
      ],
      "source": {
        "path": "model/actions.py",
        "line": 27
      }
    },
    {
      "id": "response_policy_logits",
      "name": "response_policy_logits",
      "title": "Response policy logits",
      "shape": [
        150
      ],
      "dtype": "float32",
      "description": "Categorical action logits with support [pass, 3×37 chi/discard, 1×37 pon/discard, open kan]; total width 150. Consumed by live selection and joint response/follow-up discard presentation.",
      "row_axis": "position",
      "signatures": [
        "serving_default",
        "policy"
      ],
      "source": {
        "path": "model/actions.py",
        "line": 28
      }
    },
    {
      "id": "kan_action_logits",
      "name": "kan_action_logits",
      "title": "Kan action logits",
      "shape": [
        35
      ],
      "dtype": "float32",
      "description": "Categorical logits over decline followed by 34 tile-indexed kan candidates; total width 35. Consumed by live kan selection, reviewer grading and legal-action presentation.",
      "row_axis": "position",
      "signatures": [
        "serving_default",
        "policy"
      ],
      "source": {
        "path": "model/actions.py",
        "line": 32
      }
    },
    {
      "id": "win_decision_logits",
      "name": "win_decision_logits",
      "title": "Win decision logits",
      "shape": [
        2
      ],
      "dtype": "float32",
      "description": "Two categorical logits: decline (0), accept the currently legal ron/tsumo opportunity (1). Apply softmax on the last axis. Consumed by live WIN accept/decline selection and the five-head policy signature.",
      "row_axis": "position",
      "signatures": [
        "serving_default",
        "policy"
      ],
      "source": {
        "path": "model/actions.py",
        "line": 19
      }
    },
    {
      "id": "opponent_shanten_logits",
      "name": "opponent_shanten_logits",
      "title": "Opponent shanten logits",
      "shape": [
        3,
        4
      ],
      "dtype": "float32",
      "description": "Categorical logits over four clipped shanten classes per opponent; class 0 denotes tenpai. Public constraints mask non-tenpai support where required. HTTP softmax probabilities feed reviewer readiness/difficulty; also an internally supervised prediction.",
      "row_axis": "position",
      "signatures": [
        "serving_default"
      ],
      "source": {
        "path": "model/actions.py",
        "line": 20
      }
    },
    {
      "id": "riichi_action_logits",
      "name": "riichi_action_logits",
      "title": "Riichi action logits",
      "shape": [
        2
      ],
      "dtype": "float32",
      "description": "Branch log-masses obtained by logsumexp over discard classes for dama and riichi; softmax yields the declaration marginal. Derived serving summary used by reviewer declaration grading and live action presentation; no separate learned parameters.",
      "row_axis": "position",
      "signatures": [
        "serving_default"
      ],
      "source": {
        "path": "model/actions.py",
        "line": 29
      }
    },
    {
      "id": "response_action_logits",
      "name": "response_action_logits",
      "title": "Response action logits",
      "shape": [
        4
      ],
      "dtype": "float32",
      "description": "Branch log-masses for pass, chi, pon and open kan, computed by logsumexp over compatible joint response actions. Derived serving summary used by reviewer call grading and live action presentation; no separate learned parameters.",
      "row_axis": "position",
      "signatures": [
        "serving_default"
      ],
      "source": {
        "path": "model/actions.py",
        "line": 30
      }
    },
    {
      "id": "chi_pattern_logits",
      "name": "chi_pattern_logits",
      "title": "Chi pattern logits",
      "shape": [
        3
      ],
      "dtype": "float32",
      "description": "Logsumexp aggregates over follow-up discards for each of the three chi patterns; softmax gives the pattern distribution conditional on the chi branch. Derived serving summary consumed by dynamic reviewer grading of the recorded chi pattern; no separate learned parameters.",
      "row_axis": "position",
      "signatures": [
        "serving_default"
      ],
      "source": {
        "path": "model/actions.py",
        "line": 31
      }
    },
    {
      "id": "terminal_payment_probabilities",
      "name": "terminal_payment_probabilities",
      "title": "Terminal payment probabilities",
      "shape": [
        4,
        4,
        4,
        60
      ],
      "dtype": "float32",
      "description": "Policy-mixture categorical transfer marginals indexed by payment kind, payer, recipient and amount-support class. Consumed by reviewer/live typed-payment outcome estimates.",
      "row_axis": "position",
      "signatures": [
        "serving_default"
      ],
      "source": {
        "path": "model/inference.py",
        "line": 47
      }
    },
    {
      "id": "payment_values",
      "name": "payment_values",
      "title": "Payment values",
      "shape": [
        60
      ],
      "dtype": "float32",
      "description": "Per-position monetary support vector: fixed PAYMENT_VALUES followed by four public-state-dependent bank atoms. HTTP exposes these as structured_outcome.values; live UI aliases them as terminal_payment_values.",
      "row_axis": "position",
      "signatures": [
        "serving_default"
      ],
      "source": {
        "path": "model/inference.py",
        "line": 53
      }
    },
    {
      "id": "final_placement_probabilities",
      "name": "final_placement_probabilities",
      "title": "Final placement probabilities",
      "shape": [
        4
      ],
      "dtype": "float32",
      "description": "Policy-mixture actor final-rank marginal obtained by integrating current-hand outcomes through the fixed continuation distribution. Consumed by the reviewer/live placement display; not an independent learned head.",
      "row_axis": "position",
      "signatures": [
        "serving_default"
      ],
      "source": {
        "path": "model/inference.py",
        "line": 54
      }
    },
    {
      "id": "review_outcome_probabilities",
      "name": "review_outcome_probabilities",
      "title": "Review outcome probabilities",
      "shape": [
        7
      ],
      "dtype": "float32",
      "description": "Policy-mixture marginal over seven disjoint event categories: deal-in, actor win, tenpai draw, noten draw, opponent tsumo, other ron and abort. Consumed by reviewer event summaries.",
      "row_axis": "position",
      "signatures": [
        "serving_default"
      ],
      "source": {
        "path": "model/inference.py",
        "line": 55
      }
    },
    {
      "id": "settlement_mean",
      "name": "settlement_mean",
      "title": "Settlement mean",
      "shape": [
        5
      ],
      "dtype": "float32",
      "description": "First moment of policy-mixture honba-free net transfers for actor-relative players 0–3 and bank. The underlying joint support retains inter-transfer covariance. HTTP structured_outcome.settlement_mean feeds reviewer actor-relative EV display.",
      "row_axis": "position",
      "signatures": [
        "serving_default"
      ],
      "source": {
        "path": "model/inference.py",
        "line": 56
      }
    },
    {
      "id": "settlement_variance",
      "name": "settlement_variance",
      "title": "Settlement variance",
      "shape": [
        5
      ],
      "dtype": "float32",
      "description": "Elementwise second central moment of policy-mixture honba-free player/bank net transfers: max(E[X²] − E[X]², 0). HTTP takes its square root into structured_outcome.settlement_stddev for uncertainty displays.",
      "row_axis": "position",
      "signatures": [
        "serving_default"
      ],
      "source": {
        "path": "model/inference.py",
        "line": 57
      }
    },
    {
      "id": "critic_expected_points",
      "name": "critic_expected_points",
      "title": "Critic expected points",
      "shape": [
        4
      ],
      "dtype": "float32",
      "description": "Per-active-candidate expected post-hand score minus current score for four actor-relative players, in points. HTTP action_values.expected_points feeds reviewer action deltas and live decision timing.",
      "row_axis": "active candidate",
      "signatures": [
        "serving_default"
      ],
      "source": {
        "path": "model/inference.py",
        "line": 58
      }
    },
    {
      "id": "critic_action_indices",
      "name": "critic_action_indices",
      "title": "Critic action indices",
      "shape": [
        2
      ],
      "dtype": "int32",
      "description": "Sparse row index pairs [input-position index, canonical critic-action index]. All other critic_* outputs share this row ordering. HTTP joins candidate point predictions to original actions; reviewer/live code uses the resulting action_values IDs.",
      "row_axis": "active candidate",
      "signatures": [
        "serving_default"
      ],
      "source": {
        "path": "model/inference.py",
        "line": 59
      }
    }
  ],
  "auxiliaries": [
    {
      "id": "route_affinity_logits",
      "name": "route_affinity_logits",
      "title": "Route affinity",
      "shape": [
        3
      ],
      "dtype": "float32",
      "row_axis": "selected candidate",
      "description": "Three candidate-conditioned Bernoulli logits for tanyao, flush and outside-hand affinity. Observed route targets supervise the readout. Actor and critic read detached probabilities.",
      "signatures": [],
      "source": {
        "path": "model/candidate_predictions.py",
        "line": 11
      }
    },
    {
      "id": "candidate_ron_logits",
      "name": "candidate_ron_logits",
      "title": "Candidate ron risk",
      "shape": [
        3
      ],
      "dtype": "float32",
      "row_axis": "selected candidate",
      "description": "Three opponent ron probabilities per supported candidate, trained on observed ron legality. The final actor scorer reads detached probabilities.",
      "signatures": [],
      "source": {
        "path": "model/candidate_predictions.py",
        "line": 25
      }
    },
    {
      "id": "constraint_loss",
      "name": "constraint_loss",
      "title": "Actor structural constraints",
      "shape": [],
      "dtype": "float32",
      "row_axis": "position",
      "description": "Per-position sum of belief, route and completion-yaku/score projection divergences. The MMD actor objective applies coefficient 0.01.",
      "signatures": [],
      "source": {
        "path": "model/network.py",
        "line": 161
      }
    },
    {
      "id": "opponent_ukeire_by_shanten_logits",
      "name": "opponent_ukeire_by_shanten_logits",
      "title": "Opponent ukeire by shanten logits",
      "shape": [
        3,
        4,
        34
      ],
      "dtype": "float32",
      "description": "Internal network output; not exported for serving. Independent Bernoulli logits over 34 structural improving-tile indicators, conditional on each opponent’s shanten class; apply sigmoid.",
      "row_axis": "position",
      "signatures": [],
      "source": {
        "path": "model/actions.py",
        "line": 21
      }
    },
    {
      "id": "opponent_wait_logits",
      "name": "opponent_wait_logits",
      "title": "Opponent wait logits",
      "shape": [
        3,
        34
      ],
      "dtype": "float32",
      "description": "Internal network output; not exported for serving. Bernoulli log-odds for joint tenpai-and-structural-wait events. The probability is P(shanten=0)·P(tile improves | shanten=0); furiten and yaku legality are not equivalent to this event.",
      "row_axis": "position",
      "signatures": [],
      "source": {
        "path": "model/actions.py",
        "line": 22
      }
    },
    {
      "id": "opponent_hand_count_logits",
      "name": "opponent_hand_count_logits",
      "title": "Opponent hand count logits",
      "shape": [
        3,
        37,
        5
      ],
      "dtype": "float32",
      "description": "Internal network output; not exported for serving. Categorical logits over counts 0–4 for each ordinary/red tile class and opponent, after support masking and count projection. Counts include observed meld occupancy.",
      "row_axis": "position",
      "signatures": [],
      "source": {
        "path": "model/actions.py",
        "line": 23
      }
    },
    {
      "id": "round_completion_yaku_logits",
      "name": "round_completion_yaku_logits",
      "title": "Round completion yaku logits",
      "shape": [
        4,
        2,
        23
      ],
      "dtype": "float32",
      "description": "Internal network output; not exported for serving. Constrained Bernoulli logits for 23 yaku labels on the highest-scoring completion of the next observed tenpai shape, indexed by player and ron/tsumo. This conditional completion target is not a win-probability target.",
      "row_axis": "position",
      "signatures": [],
      "source": {
        "path": "model/actions.py",
        "line": 24
      }
    },
    {
      "id": "round_completion_score_logits",
      "name": "round_completion_score_logits",
      "title": "Completion potential (han/fu)",
      "shape": [
        1,
        2,
        38
      ],
      "dtype": "float32",
      "description": "Best ordinary finish of the next observed tenpai shape, for our own hand, separately for ron/tsumo. Includes actual riichi, visible dora/red and applicable menzen tsumo; excludes hypothetical ura, ippatsu and special-event bonuses. Predicts completion potential, not win probability or the eventual winning score. Actor and critic consume these detached probabilities. Softmax over 38 scoring classes, shared with settlement; internal output.",
      "row_axis": "position",
      "signatures": [],
      "source": {
        "path": "model/actions.py",
        "line": 25
      }
    },
    {
      "id": "ron_eligibility_logits",
      "name": "ron_eligibility_logits",
      "title": "Ron eligibility",
      "shape": [
        3,
        34
      ],
      "dtype": "float32",
      "row_axis": "decision",
      "description": "Eligibility table inferred once from the observed board and reused across ordinary, riichi and call-discard alternatives.",
      "signatures": [],
      "source": {
        "path": "model/network.py",
        "line": 44
      }
    }
  ],
  "training": [
    {
      "id": "expert-joint",
      "title": "Three Q-weighted expert passes",
      "description": "Three Q-weighted expert passes. Every stage trains recorded-action mixed settlement NLL/Q-MSE, direct nagashi BCE, critic constraints and seven eligible belief losses alongside policy CE. Each stage starts a fresh 1e-5 optimizer and has N_train exposures from 50% natural and 50% focused sampling. Imitation weights use detached live-Q differences against recorded Mortal choices at 75% ESS. The next match starts the main loop without an extra initializer evaluation.",
      "formula": "3 × N_train exposures; policy CE + mixed settlement NLL/Q-MSE + nagashi BCE + critic constraints + seven beliefs",
      "source": {
        "path": "training/expert.py",
        "line": 83
      }
    },
    {
      "id": "settlement-labels",
      "title": "Observed settlement labels",
      "description": "Required TFRecord targets: label/round_end_kind is scalar int8, label/round_end_source is scalar int8 and label/round_end_tenpai is int8[4]. Source records the actual ron discarder in actor-relative seats 0–3, shared by all simultaneous winners; non-ron endings use −1. Matching this source identifies split-pao payer roles and multi-ron honba allocation. These fields supervise settlement NLL and identified Q targets; they are never prediction inputs.",
      "formula": "payment_labels(..., ending_kind=..., ending_tenpai=..., ending_source=...)",
      "source": {
        "path": "log_dataset/records.py",
        "line": 17
      }
    },
    {
      "id": "imitation-roots",
      "title": "Initializer: windowed critic and MMD updates",
      "description": "Collect balanced focused and natural-source roots over 64 human batches and at pass end. Use one continuation per selected action, finish started hands, and retain all selected outcomes. Snapshot the mirror, fit root settlements and beliefs, then run MMD with the fixed production magnet. Rollout actions are not imitation labels. Six targeted categories include Q disagreement, tenpai with threat, keiten, improving calls, riichi/dama and sakigiri.",
      "formula": "50% targeted + 50% normal roots; 1 continuation per selected action → critic/belief fit → MMD actor fit",
      "source": {
        "path": "training/imitation_rollouts.py",
        "line": 146
      }
    },
    {
      "id": "match",
      "title": "Main loop: Mortal match",
      "description": "After the initializer, collect 10,000 standard-South trajectories against the fixed Mortal opponent using 2,500 wall seeds and all four learner-seat rotations. Convert recoverable decisions from every seat into observed current-hand transfers and seven sets of supervised belief targets.",
      "formula": "10,000 games → all-seat records",
      "source": {
        "path": "training/corrections/run.py",
        "line": 131
      }
    },
    {
      "id": "critic",
      "title": "Main loop: Observed settlement fit",
      "description": "Fit played-action settlement NLL and squared error of expected Q against the identified observed settlement utility, plus direct nagashi BCE, critic constraints and seven supervised beliefs. Required ending-kind, ron-source and tenpai labels constrain matching; source is the actual discarder, including split pao and simultaneous ron. Targets never enter inference features. Settlement gradients train critic layers and shared encodings.",
      "formula": "0.5 payment_nll + 0.5 × 9.921187963468466 q_mse + nagashi_loss + critic_constraint_loss + seven belief losses",
      "source": {
        "path": "training/trainer.py",
        "line": 97
      }
    },
    {
      "id": "actor",
      "title": "Main loop: Magnetic mirror descent",
      "description": "Optimize detached-Q policy gain, two reference-policy KL terms at 0.3 each, belief-owned constraints at 0.01 and seven supervised belief losses. The previous policy stays fixed for the phase and production stays fixed for the run.",
      "formula": "−Eπ[Q] + 0.3 KL(π || previous) + 0.3 KL(π || production) + 0.01 constraints + seven supervised head losses",
      "source": {
        "path": "training/corrections/trainer.py",
        "line": 11
      }
    },
    {
      "id": "roots",
      "title": "Main loop: Balanced root reruns",
      "description": "After each match phase, sample equal counts of eligible targeted roots and unfiltered normal roots, with two continuations per root. Eligibility strata are Q disagreement, tenpai with threat, keiten, improving calls, riichi/dama and future defensive sakigiri. Q disagreement threshold: 0.0025 J.",
      "formula": "50% targeted + 50% normal; 2 continuations per root",
      "source": {
        "path": "training/corrections/collection.py",
        "line": 223
      }
    },
    {
      "id": "descendants",
      "title": "Main loop: Train roots and descendants",
      "description": "Apply the same critic and MMD objectives to eligible root and continuation decisions. A forced intervention at a sampled root supplies an off-policy action. Rows with only one distinct action are excluded from training.",
      "formula": "eligible root and descendant rows → critic → actor",
      "source": {
        "path": "training/corrections/run.py",
        "line": 112
      }
    },
    {
      "id": "optimization",
      "title": "Optimization and replicas",
      "description": "Use independent AdamW optimizer states for actor and critic: learning rate 1 e−5, weight decay 1 e−4 and per-variable clipnorm 1. Sum dense gradients across replicas once before clipping. Exclude padding from masked reductions; physical batch layout can still affect floating-point updates.",
      "formula": "actor LR = critic LR = 1e−5",
      "source": {
        "path": "training/trainer.py",
        "line": 17
      }
    },
    {
      "id": "evaluation",
      "title": "Independent next match",
      "description": "Evaluate each updated checkpoint on the next disjoint 10,000-game seed block. Reuse that match as the next iteration’s data; terminate after the final evaluation without a subsequent optimizer pass.",
      "formula": "new checkpoint → fresh match",
      "source": {
        "path": "training/corrections/run.py",
        "line": 33
      }
    },
    {
      "id": "restoration",
      "title": "Retained path: Separate structural restoration",
      "description": "Recorded action choices supply separate policy imitation targets. Every displayed training phase also uses the seven observed belief targets.",
      "formula": "recorded action → active policy cross-entropy",
      "source": {
        "path": "training/restoration.py",
        "line": 9
      }
    }
  ],
  "mathematics": [
    {
      "id": "legal-policy",
      "title": "Legal policy normalization",
      "description": "Select the native active head, right-pad to width 150, apply the exact legality mask and compute float 32 log_softmax. Masked logits use the finite −10⁹ sentinel; their exponentials underflow to zero under the normal float 32 logit scale. Native head indices and decision_phase IDs are distinct enumerations.",
      "equations": [
        {
          "label": "Masked active-head logits",
          "latex": "\\widetilde z_{i,a}=\\begin{cases}z_{\\theta,h_i}(s_i,a)&m_{i,a}=1\\\\-10^9&m_{i,a}=0\\end{cases}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mover><mi>z</mi><mo>&#x0007E;</mo></mover><mrow><mi>i</mi><mo>&#x0002C;</mo><mi>a</mi></mrow></msub><mo>&#x0003D;</mo><mrow><mo stretchy=\"true\" fence=\"true\" form=\"prefix\">&#x0007B;</mo><mtable><mtr><mtd columnalign=\"left\"><msub><mi>z</mi><mrow><mi>&#x003B8;</mi><mo>&#x0002C;</mo><msub><mi>h</mi><mi>i</mi></msub></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><msub><mi>s</mi><mi>i</mi></msub><mo>&#x0002C;</mo><mi>a</mi><mo stretchy=\"false\">&#x00029;</mo></mtd><mtd columnalign=\"left\"><msub><mi>m</mi><mrow><mi>i</mi><mo>&#x0002C;</mo><mi>a</mi></mrow></msub><mo>&#x0003D;</mo><mn>1</mn></mtd></mtr><mtr><mtd columnalign=\"left\"><mo>&#x02212;</mo><msup><mn>10</mn><mn>9</mn></msup></mtd><mtd columnalign=\"left\"><msub><mi>m</mi><mrow><mi>i</mi><mo>&#x0002C;</mo><mi>a</mi></mrow></msub><mo>&#x0003D;</mo><mn>0</mn></mtd></mtr></mtable></mrow></mrow></math>"
        },
        {
          "label": "Normalized log policy",
          "latex": "\\ell_{\\theta,i,a}=\\widetilde z_{i,a}-\\log\\sum_{b=0}^{149}\\exp(\\widetilde z_{i,b}),\\qquad\\pi_{\\theta,i,a}=\\exp(\\ell_{\\theta,i,a})",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>&#x02113;</mi><mrow><mi>&#x003B8;</mi><mo>&#x0002C;</mo><mi>i</mi><mo>&#x0002C;</mo><mi>a</mi></mrow></msub><mo>&#x0003D;</mo><msub><mover><mi>z</mi><mo>&#x0007E;</mo></mover><mrow><mi>i</mi><mo>&#x0002C;</mo><mi>a</mi></mrow></msub><mo>&#x02212;</mo><mi>log</mi><munderover><mo>&#x02211;</mo><mrow><mi>b</mi><mo>&#x0003D;</mo><mn>0</mn></mrow><mrow><mn>149</mn></mrow></munderover><mi>exp</mi><mo stretchy=\"false\">&#x00028;</mo><msub><mover><mi>z</mi><mo>&#x0007E;</mo></mover><mrow><mi>i</mi><mo>&#x0002C;</mo><mi>b</mi></mrow></msub><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002C;</mo><mspace width=\"2em\" /><msub><mi>&#x003C0;</mi><mrow><mi>&#x003B8;</mi><mo>&#x0002C;</mo><mi>i</mi><mo>&#x0002C;</mo><mi>a</mi></mrow></msub><mo>&#x0003D;</mo><mi>exp</mi><mo stretchy=\"false\">&#x00028;</mo><msub><mi>&#x02113;</mi><mrow><mi>&#x003B8;</mi><mo>&#x0002C;</mo><mi>i</mi><mo>&#x0002C;</mo><mi>a</mi></mrow></msub><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "s_i",
          "meaning": "Public state for decision i.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>s</mi><mi>i</mi></msub></mrow></math>"
        },
        {
          "symbol": "h_i",
          "meaning": "Active policy head: discard, riichi/discard, response, kan or win/pass.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>h</mi><mi>i</mi></msub></mrow></math>"
        },
        {
          "symbol": "m_{i,a}",
          "meaning": "Exact native legality mask; padded columns are illegal.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>m</mi><mrow><mi>i</mi><mo>&#x0002C;</mo><mi>a</mi></mrow></msub></mrow></math>"
        },
        {
          "symbol": "z_{\\theta,h_i}",
          "meaning": "Current head logits after the actor’s policy masks/adjustments.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>z</mi><mrow><mi>&#x003B8;</mi><mo>&#x0002C;</mo><msub><mi>h</mi><mi>i</mi></msub></mrow></msub></mrow></math>"
        }
      ],
      "source": {
        "path": "model/actor.py",
        "line": 325
      }
    },
    {
      "id": "candidate-mass",
      "title": "Policy mass on critic candidates",
      "description": "Push forward active-head probability mass onto the 295-element critic index space. Open-kan response mass is scatter-added to the trigger-tile kan index. WIN uses a policy-independent Dirac mass at 260, yielding an identically zero current-minus-reference Q gain while retaining differentiable head-level KL terms.",
      "equations": [
        {
          "label": "Action-to-candidate mapping",
          "latex": "c_h(a)=\\begin{cases}a&h=\\mathrm{discard}\\\\37+a&h=\\mathrm{riichi}\\\\111+a&h=\\mathrm{response},\\ a<149\\\\261+t&h=\\mathrm{response},\\ a=149\\\\260+a&h=\\mathrm{kan}\\end{cases}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>c</mi><mi>h</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>a</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0003D;</mo><mrow><mo stretchy=\"true\" fence=\"true\" form=\"prefix\">&#x0007B;</mo><mtable><mtr><mtd columnalign=\"left\"><mi>a</mi></mtd><mtd columnalign=\"left\"><mi>h</mi><mo>&#x0003D;</mo><mrow><mi mathvariant=\"normal\">d</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">s</mi><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">d</mi></mrow></mtd></mtr><mtr><mtd columnalign=\"left\"><mn>37</mn><mo>&#x0002B;</mo><mi>a</mi></mtd><mtd columnalign=\"left\"><mi>h</mi><mo>&#x0003D;</mo><mrow><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">h</mi><mi mathvariant=\"normal\">i</mi></mrow></mtd></mtr><mtr><mtd columnalign=\"left\"><mn>111</mn><mo>&#x0002B;</mo><mi>a</mi></mtd><mtd columnalign=\"left\"><mi>h</mi><mo>&#x0003D;</mo><mrow><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">s</mi><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">s</mi><mi mathvariant=\"normal\">e</mi></mrow><mo>&#x0002C;</mo><mtext>&#x000A0;</mtext><mi>a</mi><mo>&#x0003C;</mo><mn>149</mn></mtd></mtr><mtr><mtd columnalign=\"left\"><mn>261</mn><mo>&#x0002B;</mo><mi>t</mi></mtd><mtd columnalign=\"left\"><mi>h</mi><mo>&#x0003D;</mo><mrow><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">s</mi><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">s</mi><mi mathvariant=\"normal\">e</mi></mrow><mo>&#x0002C;</mo><mtext>&#x000A0;</mtext><mi>a</mi><mo>&#x0003D;</mo><mn>149</mn></mtd></mtr><mtr><mtd columnalign=\"left\"><mn>260</mn><mo>&#x0002B;</mo><mi>a</mi></mtd><mtd columnalign=\"left\"><mi>h</mi><mo>&#x0003D;</mo><mrow><mi mathvariant=\"normal\">k</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">n</mi></mrow></mtd></mtr></mtable></mrow></mrow></math>"
        },
        {
          "label": "Candidate probability",
          "latex": "\\rho_{\\theta}(c\\mid s)=\\begin{cases}\\sum_{a:c_h(a)=c}\\pi_{\\theta}(a\\mid s)&\\mathrm{phase}\\ne\\mathrm{WIN}\\\\\\mathbf{1}[c=260]&\\mathrm{phase}=\\mathrm{WIN}\\end{cases}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>&#x003C1;</mi><mrow><mi>&#x003B8;</mi></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mi>c</mi><mo>&#x02223;</mo><mi>s</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0003D;</mo><mrow><mo stretchy=\"true\" fence=\"true\" form=\"prefix\">&#x0007B;</mo><mtable><mtr><mtd columnalign=\"left\"><munder><mo>&#x02211;</mo><mrow><mi>a</mi><mi>:</mi><msub><mi>c</mi><mi>h</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>a</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0003D;</mo><mi>c</mi></mrow></munder><msub><mi>&#x003C0;</mi><mrow><mi>&#x003B8;</mi></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mi>a</mi><mo>&#x02223;</mo><mi>s</mi><mo stretchy=\"false\">&#x00029;</mo></mtd><mtd columnalign=\"left\"><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">h</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">s</mi><mi mathvariant=\"normal\">e</mi></mrow><mo>&#x02260;</mo><mrow><mi mathvariant=\"normal\">W</mi><mi mathvariant=\"normal\">I</mi><mi mathvariant=\"normal\">N</mi></mrow></mtd></mtr><mtr><mtd columnalign=\"left\"><mrow><mn mathvariant=\"bold\">1</mn></mrow><mo stretchy=\"false\">[</mo><mi>c</mi><mo>&#x0003D;</mo><mn>260</mn><mo stretchy=\"false\">]</mo></mtd><mtd columnalign=\"left\"><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">h</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">s</mi><mi mathvariant=\"normal\">e</mi></mrow><mo>&#x0003D;</mo><mrow><mi mathvariant=\"normal\">W</mi><mi mathvariant=\"normal\">I</mi><mi mathvariant=\"normal\">N</mi></mrow></mtd></mtr></mtable></mrow></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "c",
          "meaning": "Critic action slot, 0–294.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>c</mi></mrow></math>"
        },
        {
          "symbol": "t",
          "meaning": "Ordinary tile ID of the triggering discard, 0–33.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>t</mi></mrow></math>"
        },
        {
          "symbol": "\\rho_\\theta",
          "meaning": "Policy mass after mapping legal head actions to critic candidates.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>&#x003C1;</mi><mi>&#x003B8;</mi></msub></mrow></math>"
        }
      ],
      "source": {
        "path": "model/critic.py",
        "line": 1408
      }
    },
    {
      "id": "payment-likelihood",
      "title": "Observed payment likelihood",
      "description": "Marginalize compatible latent event, deposit and score states for the recorded action. Required ending kind separates zero-transfer draws and aborts; actual ron discarder constrains split-pao and simultaneous-ron roles; actor-relative tenpai identifies draw/nagashi continuation. These are supervision-only labels. Simultaneous-claim score factors retain their conditional product factorization.",
      "equations": [
        {
          "label": "Observed score-match mass",
          "latex": "M_j(y\\mid s,c)=\\sum_v I_{y,j}(v)q_{\\psi,j}(v\\mid s,c)",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>M</mi><mi>j</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>y</mi><mo>&#x02223;</mo><mi>s</mi><mo>&#x0002C;</mo><mi>c</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0003D;</mo><munder><mo>&#x02211;</mo><mi>v</mi></munder><msub><mi>I</mi><mrow><mi>y</mi><mo>&#x0002C;</mo><mi>j</mi></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mi>v</mi><mo stretchy=\"false\">&#x00029;</mo><msub><mi>q</mi><mrow><mi>&#x003C8;</mi><mo>&#x0002C;</mo><mi>j</mi></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mi>v</mi><mo>&#x02223;</mo><mi>s</mi><mo>&#x0002C;</mo><mi>c</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        },
        {
          "label": "Compatible-transfer likelihood",
          "latex": "\\begin{array}{rl}P_{\\psi}(y\\mid s,c)=\\sum_{e,d}{}&I_y(e,d)\\,p_{\\psi}(e\\mid s,c)\\\\&\\cdot p_{\\psi}(d\\mid e,s,c)\\prod_{j\\in A(e)}M_j(y\\mid s,c)\\end{array}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mtable><mtr><mtd columnalign=\"right\"><msub><mi>P</mi><mrow><mi>&#x003C8;</mi></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mi>y</mi><mo>&#x02223;</mo><mi>s</mi><mo>&#x0002C;</mo><mi>c</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0003D;</mo><munder><mo>&#x02211;</mo><mrow><mi>e</mi><mo>&#x0002C;</mo><mi>d</mi></mrow></munder><mrow /></mtd><mtd columnalign=\"left\"><msub><mi>I</mi><mi>y</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>e</mi><mo>&#x0002C;</mo><mi>d</mi><mo stretchy=\"false\">&#x00029;</mo><mspace width=\"0.167em\" /><msub><mi>p</mi><mrow><mi>&#x003C8;</mi></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mi>e</mi><mo>&#x02223;</mo><mi>s</mi><mo>&#x0002C;</mo><mi>c</mi><mo stretchy=\"false\">&#x00029;</mo></mtd></mtr><mtr><mtd columnalign=\"right\" /><mtd columnalign=\"left\"><mo>&#x000B7;</mo><msub><mi>p</mi><mrow><mi>&#x003C8;</mi></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mi>d</mi><mo>&#x02223;</mo><mi>e</mi><mo>&#x0002C;</mo><mi>s</mi><mo>&#x0002C;</mo><mi>c</mi><mo stretchy=\"false\">&#x00029;</mo><munder><mo>&#x0220F;</mo><mrow><mi>j</mi><mo>&#x02208;</mo><mi>A</mi><mo stretchy=\"false\">&#x00028;</mo><mi>e</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></munder><msub><mi>M</mi><mi>j</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>y</mi><mo>&#x02223;</mo><mi>s</mi><mo>&#x0002C;</mo><mi>c</mi><mo stretchy=\"false\">&#x00029;</mo></mtd></mtr></mtable></mrow></math>"
        },
        {
          "label": "Total claim-score probability",
          "latex": "q_{\\psi,j}(v\\mid s,c)=\\operatorname{softmax}(z_{j,\\mathrm{score}})_v",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>q</mi><mrow><mi>&#x003C8;</mi><mo>&#x0002C;</mo><mi>j</mi></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mi>v</mi><mo>&#x02223;</mo><mi>s</mi><mo>&#x0002C;</mo><mi>c</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0003D;</mo><mo>softmax</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>z</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mrow><mi mathvariant=\"normal\">s</mi><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">e</mi></mrow></mrow></msub><msub><mo stretchy=\"false\">&#x00029;</mo><mi>v</mi></msub></mrow></math>"
        },
        {
          "label": "Supported observed loss",
          "latex": "L_{\\mathrm{pay}}=-\\frac{\\sum_i u_i k_i\\log\\max(P_{\\psi}(y_i\\mid s_i,c_i),10^{-30})}{\\sum_i u_i k_i}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">y</mi></mrow></mrow></msub><mo>&#x0003D;</mo><mo>&#x02212;</mo><mfrac><mrow><msub><mo>&#x02211;</mo><mi>i</mi></msub><msub><mi>u</mi><mi>i</mi></msub><msub><mi>k</mi><mi>i</mi></msub><mi>log</mi><mo>max</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>P</mi><mrow><mi>&#x003C8;</mi></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><msub><mi>y</mi><mi>i</mi></msub><mo>&#x02223;</mo><msub><mi>s</mi><mi>i</mi></msub><mo>&#x0002C;</mo><msub><mi>c</mi><mi>i</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002C;</mo><msup><mn>10</mn><mrow><mo>&#x02212;</mo><mn>30</mn></mrow></msup><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><msub><mo>&#x02211;</mo><mi>i</mi></msub><msub><mi>u</mi><mi>i</mi></msub><msub><mi>k</mi><mi>i</mi></msub></mrow></mfrac></mrow></math>"
        },
        {
          "label": "Full critic objective",
          "latex": "L_{\\mathrm{critic}}=0.5L_{\\mathrm{pay}}+0.5\\kappa L_Q+L_{\\mathrm{nagashi}}+C_{\\mathrm{critic}}+L_{\\mathrm{aux}},\\quad \\kappa=9.921187963468466",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">c</mi></mrow></mrow></msub><mo>&#x0003D;</mo><mn>0.5</mn><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">y</mi></mrow></mrow></msub><mo>&#x0002B;</mo><mn>0.5</mn><mi>&#x003BA;</mi><msub><mi>L</mi><mi>Q</mi></msub><mo>&#x0002B;</mo><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">g</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">s</mi><mi mathvariant=\"normal\">h</mi><mi mathvariant=\"normal\">i</mi></mrow></mrow></msub><mo>&#x0002B;</mo><msub><mi>C</mi><mrow><mrow><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">c</mi></mrow></mrow></msub><mo>&#x0002B;</mo><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">x</mi></mrow></mrow></msub><mo>&#x0002C;</mo><mspace width=\"1em\" /><mi>&#x003BA;</mi><mo>&#x0003D;</mo><mn>9.921187963468466</mn></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "y_i",
          "meaning": "Observed current-hand transfers and required ending-kind/source/tenpai targets for recorded/rerun action c_i; never model inputs.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>y</mi><mi>i</mi></msub></mrow></math>"
        },
        {
          "symbol": "e,d",
          "meaning": "One of 60 derived event choices and one of 16 conditional deposit masks.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>e</mi><mo>&#x0002C;</mo><mi>d</mi></mrow></math>"
        },
        {
          "symbol": "A(e)",
          "meaning": "Active ron claimants or the single tsumo winner; all tsumo payer shares use one score state.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>A</mi><mo stretchy=\"false\">&#x00028;</mo><mi>e</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        },
        {
          "symbol": "I_y(e,d)",
          "meaning": "Compatibility with observed transfers, ending kind, actual ron discarder, draw tenpai, bank transfers and legal deposit masks.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>I</mi><mi>y</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>e</mi><mo>&#x0002C;</mo><mi>d</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        },
        {
          "symbol": "I_{y,j}(v)",
          "meaning": "Score states matching the observed payment(s) for claim j; unknown labels impose no score match restriction.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>I</mi><mrow><mi>y</mi><mo>&#x0002C;</mo><mi>j</mi></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mi>v</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        },
        {
          "symbol": "u_i,k_i",
          "meaning": "Eligible real decisions and supported payments. A zero denominator returns zero.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>u</mi><mi>i</mi></msub><mo>&#x0002C;</mo><msub><mi>k</mi><mi>i</mi></msub></mrow></math>"
        },
        {
          "symbol": "C_{\\mathrm{critic}}",
          "meaning": "Raw-to-constrained score, event and deposit penalties, averaged over valid rows separately from supported payment NLL.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>C</mi><mrow><mrow><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">c</mi></mrow></mrow></msub></mrow></math>"
        },
        {
          "symbol": "M_j",
          "meaning": "Total score probability matching the observed transfer(s) for active claim j.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>M</mi><mi>j</mi></msub></mrow></math>"
        },
        {
          "symbol": "L_{\\mathrm{aux}}",
          "meaning": "Sum of seven unit-weight supervised belief losses, each normalized on its own eligible, known targets.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">x</mi></mrow></mrow></msub></mrow></math>"
        },
        {
          "symbol": "L_Q",
          "meaning": "Mean squared error of predicted expected Q against uniquely identified observed-settlement J; unknown payment amounts have no invented Q target.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>L</mi><mi>Q</mi></msub></mrow></math>"
        }
      ],
      "source": {
        "path": "model/joint_settlement.py",
        "line": 624
      }
    },
    {
      "id": "settlement-value",
      "title": "From hand outcomes to action value",
      "description": "Integrate action-conditioned scored-event/deposit probabilities against public-state settlement utilities. Compute the deterministic continuation payoff tensor once per position and reuse it across candidate rows. Observed transfer supervision applies only to recorded/rerun actions; Q for unplayed candidates is model-based.",
      "equations": [
        {
          "label": "Outcome utility",
          "latex": "J(s,\\omega)=\\frac{\\mathrm{ST3}(s,\\omega)}{100}+P(\\mathrm{first}\\mid s,\\omega)-P(\\mathrm{fourth}\\mid s,\\omega)",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mi>J</mi><mo stretchy=\"false\">&#x00028;</mo><mi>s</mi><mo>&#x0002C;</mo><mi>&#x003C9;</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0003D;</mo><mfrac><mrow><mrow><mi mathvariant=\"normal\">S</mi><mi mathvariant=\"normal\">T</mi><mn>3</mn></mrow><mo stretchy=\"false\">&#x00028;</mo><mi>s</mi><mo>&#x0002C;</mo><mi>&#x003C9;</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mn>100</mn></mrow></mfrac><mo>&#x0002B;</mo><mi>P</mi><mo stretchy=\"false\">&#x00028;</mo><mrow><mi mathvariant=\"normal\">f</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">s</mi><mi mathvariant=\"normal\">t</mi></mrow><mo>&#x02223;</mo><mi>s</mi><mo>&#x0002C;</mo><mi>&#x003C9;</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x02212;</mo><mi>P</mi><mo stretchy=\"false\">&#x00028;</mo><mrow><mi mathvariant=\"normal\">f</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow><mo>&#x02223;</mo><mi>s</mi><mo>&#x0002C;</mo><mi>&#x003C9;</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        },
        {
          "label": "Action expectation",
          "latex": "Q_{\\psi}(s,c)=\\sum_{\\omega}p_{\\psi}(\\omega\\mid s,c)J(s,\\omega),\\qquad\\omega=(\\text{scored event},\\text{deposit mask})",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>Q</mi><mrow><mi>&#x003C8;</mi></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mi>s</mi><mo>&#x0002C;</mo><mi>c</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0003D;</mo><munder><mo>&#x02211;</mo><mrow><mi>&#x003C9;</mi></mrow></munder><msub><mi>p</mi><mrow><mi>&#x003C8;</mi></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mi>&#x003C9;</mi><mo>&#x02223;</mo><mi>s</mi><mo>&#x0002C;</mo><mi>c</mi><mo stretchy=\"false\">&#x00029;</mo><mi>J</mi><mo stretchy=\"false\">&#x00028;</mo><mi>s</mi><mo>&#x0002C;</mo><mi>&#x003C9;</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002C;</mo><mspace width=\"2em\" /><mi>&#x003C9;</mi><mo>&#x0003D;</mo><mo stretchy=\"false\">&#x00028;</mo><mtext>scored&#x000A0;event</mtext><mo>&#x0002C;</mo><mtext>deposit&#x000A0;mask</mtext><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "p_\\psi",
          "meaning": "Joint current-hand outcome probabilities under hard public scoring/settlement support.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>p</mi><mi>&#x003C8;</mi></msub></mrow></math>"
        },
        {
          "symbol": "J",
          "meaning": "Normalized ST3 with first-place reward and fourth-place penalty.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>J</mi></mrow></math>"
        },
        {
          "symbol": "Q_\\psi",
          "meaning": "Expected J, not raw points or raw ST3.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>Q</mi><mi>&#x003C8;</mi></msub></mrow></math>"
        },
        {
          "symbol": "\\omega",
          "meaning": "A possible current-hand settlement, including score and deposit state.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>&#x003C9;</mi></mrow></math>"
        }
      ],
      "source": {
        "path": "model/joint_settlement.py",
        "line": 737
      }
    },
    {
      "id": "continuation-model",
      "title": "Fixed Gumbel continuation",
      "description": "Independent common-scale Gumbel perturbations of nonterminal score locations induce a Plackett–Luce permutation distribution. Locations and scale use 10,000-point units. Softplus-transformed coefficients are fixed constants. Terminal states bypass the continuation distribution and use deterministic rank, first-place pot assignment and ceiling-rounded ST3.",
      "equations": [
        {
          "label": "Location and common noise scale",
          "latex": "\\begin{array}{rl}\\mu_j&=\\frac{x_j}{10000}+\\alpha(D_j-\\overline D)\\\\\\sigma(T)&=\\sqrt{\\beta+\\gamma T+\\delta T^2}\\end{array}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mtable><mtr><mtd columnalign=\"right\"><msub><mi>&#x003BC;</mi><mi>j</mi></msub></mtd><mtd columnalign=\"left\"><mo>&#x0003D;</mo><mfrac><mrow><msub><mi>x</mi><mi>j</mi></msub></mrow><mrow><mn>10000</mn></mrow></mfrac><mo>&#x0002B;</mo><mi>&#x003B1;</mi><mo stretchy=\"false\">&#x00028;</mo><msub><mi>D</mi><mi>j</mi></msub><mo>&#x02212;</mo><mover><mi>D</mi><mo accent=\"true\">&#x02015;</mo></mover><mo stretchy=\"false\">&#x00029;</mo></mtd></mtr><mtr><mtd columnalign=\"right\"><mi>&#x003C3;</mi><mo stretchy=\"false\">&#x00028;</mo><mi>T</mi><mo stretchy=\"false\">&#x00029;</mo></mtd><mtd columnalign=\"left\"><mo>&#x0003D;</mo><msqrt><mrow><mi>&#x003B2;</mi><mo>&#x0002B;</mo><mi>&#x003B3;</mi><mi>T</mi><mo>&#x0002B;</mo><mi>&#x003B4;</mi><msup><mi>T</mi><mn>2</mn></msup></mrow></msqrt></mtd></mtr></mtable></mrow></math>"
        },
        {
          "label": "Frozen coefficients",
          "latex": "\\begin{array}{rl}(\\alpha,\\beta,\\gamma,\\delta)=\\operatorname{softplus}(&-2.9851044578,\\;-2.9903753151,\\\\&-2.0806273807,\\;-4.2473072284)\\end{array}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mtable><mtr><mtd columnalign=\"right\"><mo stretchy=\"false\">&#x00028;</mo><mi>&#x003B1;</mi><mo>&#x0002C;</mo><mi>&#x003B2;</mi><mo>&#x0002C;</mo><mi>&#x003B3;</mi><mo>&#x0002C;</mo><mi>&#x003B4;</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0003D;</mo><mo>softplus</mo><mo stretchy=\"false\">&#x00028;</mo></mtd><mtd columnalign=\"left\"><mo>&#x02212;</mo><mn>2.9851044578</mn><mo>&#x0002C;</mo><mspace width=\"0.278em\" /><mo>&#x02212;</mo><mn>2.9903753151</mn><mo>&#x0002C;</mo></mtd></mtr><mtr><mtd columnalign=\"right\" /><mtd columnalign=\"left\"><mo>&#x02212;</mo><mn>2.0806273807</mn><mo>&#x0002C;</mo><mspace width=\"0.278em\" /><mo>&#x02212;</mo><mn>4.2473072284</mn><mo stretchy=\"false\">&#x00029;</mo></mtd></mtr></mtable></mrow></math>"
        },
        {
          "label": "Ranking probability",
          "latex": "P(r_1,r_2,r_3,r_4)=\\prod_{k=1}^{3}\\frac{\\exp(\\mu_{r_k}/\\sigma)}{\\sum_{j=k}^{4}\\exp(\\mu_{r_j}/\\sigma)}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mi>P</mi><mo stretchy=\"false\">&#x00028;</mo><msub><mi>r</mi><mn>1</mn></msub><mo>&#x0002C;</mo><msub><mi>r</mi><mn>2</mn></msub><mo>&#x0002C;</mo><msub><mi>r</mi><mn>3</mn></msub><mo>&#x0002C;</mo><msub><mi>r</mi><mn>4</mn></msub><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0003D;</mo><munderover><mo>&#x0220F;</mo><mrow><mi>k</mi><mo>&#x0003D;</mo><mn>1</mn></mrow><mrow><mn>3</mn></mrow></munderover><mfrac><mrow><mi>exp</mi><mo stretchy=\"false\">&#x00028;</mo><msub><mi>&#x003BC;</mi><mrow><msub><mi>r</mi><mi>k</mi></msub></mrow></msub><mo>&#x0002F;</mo><mi>&#x003C3;</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><msubsup><mo>&#x02211;</mo><mrow><mi>j</mi><mo>&#x0003D;</mo><mi>k</mi></mrow><mrow><mn>4</mn></mrow></msubsup><mi>exp</mi><mo stretchy=\"false\">&#x00028;</mo><msub><mi>&#x003BC;</mi><mrow><msub><mi>r</mi><mi>j</mi></msub></mrow></msub><mo>&#x0002F;</mo><mi>&#x003C3;</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></mfrac></mrow></math>"
        },
        {
          "label": "Nonterminal ST3 and rank offsets",
          "latex": "\\begin{array}{rl}\\mathrm{ST3}_{\\mathrm{smooth}}&=10\\mu_0-25+0.5+\\sum_{r=1}^{4}P(R_0=r)o_r\\\\o&=(125,60,-5,-255)\\end{array}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mtable><mtr><mtd columnalign=\"right\"><msub><mrow><mi mathvariant=\"normal\">S</mi><mi mathvariant=\"normal\">T</mi><mn>3</mn></mrow><mrow><mrow><mi mathvariant=\"normal\">s</mi><mi mathvariant=\"normal\">m</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">h</mi></mrow></mrow></msub></mtd><mtd columnalign=\"left\"><mo>&#x0003D;</mo><mn>10</mn><msub><mi>&#x003BC;</mi><mn>0</mn></msub><mo>&#x02212;</mo><mn>25</mn><mo>&#x0002B;</mo><mn>0.5</mn><mo>&#x0002B;</mo><munderover><mo>&#x02211;</mo><mrow><mi>r</mi><mo>&#x0003D;</mo><mn>1</mn></mrow><mrow><mn>4</mn></mrow></munderover><mi>P</mi><mo stretchy=\"false\">&#x00028;</mo><msub><mi>R</mi><mn>0</mn></msub><mo>&#x0003D;</mo><mi>r</mi><mo stretchy=\"false\">&#x00029;</mo><msub><mi>o</mi><mi>r</mi></msub></mtd></mtr><mtr><mtd columnalign=\"right\"><mi>o</mi></mtd><mtd columnalign=\"left\"><mo>&#x0003D;</mo><mo stretchy=\"false\">&#x00028;</mo><mn>125</mn><mo>&#x0002C;</mo><mn>60</mn><mo>&#x0002C;</mo><mo>&#x02212;</mo><mn>5</mn><mo>&#x0002C;</mo><mo>&#x02212;</mo><mn>255</mn><mo stretchy=\"false\">&#x00029;</mo></mtd></mtr></mtable></mrow></math>"
        },
        {
          "label": "Exact terminal value",
          "latex": "\\mathrm{ST3}_{\\mathrm{terminal}}=\\left\\lceil\\frac{x_0+\\mathbf{1}[R_0=1]\\,\\mathrm{pot}-25000}{1000}+o_{R_0}\\right\\rceil",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mrow><mi mathvariant=\"normal\">S</mi><mi mathvariant=\"normal\">T</mi><mn>3</mn></mrow><mrow><mrow><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">m</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">l</mi></mrow></mrow></msub><mo>&#x0003D;</mo><mrow><mo stretchy=\"true\" fence=\"true\" form=\"prefix\">&#x02308;</mo><mfrac><mrow><msub><mi>x</mi><mn>0</mn></msub><mo>&#x0002B;</mo><mrow><mn mathvariant=\"bold\">1</mn></mrow><mo stretchy=\"false\">[</mo><msub><mi>R</mi><mn>0</mn></msub><mo>&#x0003D;</mo><mn>1</mn><mo stretchy=\"false\">]</mo><mspace width=\"0.167em\" /><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">t</mi></mrow><mo>&#x02212;</mo><mn>25000</mn></mrow><mrow><mn>1000</mn></mrow></mfrac><mo>&#x0002B;</mo><msub><mi>o</mi><mrow><msub><mi>R</mi><mn>0</mn></msub></mrow></msub><mo stretchy=\"true\" fence=\"true\" form=\"postfix\">&#x02309;</mo></mrow></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "x_j",
          "meaning": "Post-hand score of actor-relative player j.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>x</mi><mi>j</mi></msub></mrow></math>"
        },
        {
          "symbol": "D_j",
          "meaning": "Scheduled future dealerships; mean is over all four players.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>D</mi><mi>j</mi></msub></mrow></math>"
        },
        {
          "symbol": "T",
          "meaning": "Scheduled hands remaining, max(8 − next_hand, 0).",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>T</mi></mrow></math>"
        },
        {
          "symbol": "R_0",
          "meaning": "Actor’s final rank, 1–4 in these equations; code uses 0–3.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>R</mi><mn>0</mn></msub></mrow></math>"
        },
        {
          "symbol": "o_r",
          "meaning": "Fixed Saint 3 placement offset.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>o</mi><mi>r</mi></msub></mrow></math>"
        },
        {
          "symbol": "P(R_0=r)",
          "meaning": "Sum of rank-permutation probabilities with actor at rank r; implementation enumerates opponent orders.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>P</mi><mo stretchy=\"false\">&#x00028;</mo><msub><mi>R</mi><mn>0</mn></msub><mo>&#x0003D;</mo><mi>r</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        }
      ],
      "source": {
        "path": "model/joint_settlement.py",
        "line": 914
      }
    },
    {
      "id": "mmd",
      "title": "Magnetic mirror descent objective",
      "description": "For each match/root phase, refresh the previous-policy snapshot before one critic pass followed by one actor pass. Hold production parameters fixed across the run. Stop gradients through both reference distributions and Q; the previous-policy expectation is a constant control baseline. Entropy is diagnostic only.",
      "equations": [
        {
          "label": "Detached-Q policy gain",
          "latex": "L_{\\mathrm{gain},i}=-\\sum_c\\bigl(\\rho_{\\theta,i,c}-\\operatorname{sg}(\\rho_{\\mathrm{prev},i,c})\\bigr)\\operatorname{sg}(Q_{i,c})",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">g</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">n</mi></mrow><mo>&#x0002C;</mo><mi>i</mi></mrow></msub><mo>&#x0003D;</mo><mo>&#x02212;</mo><munder><mo>&#x02211;</mo><mi>c</mi></munder><mo stretchy=\"true\" fence=\"true\" minsize=\"1.2em\" maxsize=\"1.2em\">(</mo><msub><mi>&#x003C1;</mi><mrow><mi>&#x003B8;</mi><mo>&#x0002C;</mo><mi>i</mi><mo>&#x0002C;</mo><mi>c</mi></mrow></msub><mo>&#x02212;</mo><mo>sg</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>&#x003C1;</mi><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">v</mi></mrow><mo>&#x0002C;</mo><mi>i</mi><mo>&#x0002C;</mo><mi>c</mi></mrow></msub><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"true\" fence=\"true\" minsize=\"1.2em\" maxsize=\"1.2em\">)</mo><mo>sg</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>Q</mi><mrow><mi>i</mi><mo>&#x0002C;</mo><mi>c</mi></mrow></msub><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        },
        {
          "label": "Two policy anchors",
          "latex": "\\begin{array}{rl}R_i={}&0.3D_{\\mathrm{KL}}(\\pi_{\\theta,i}\\Vert\\operatorname{sg}(\\pi_{\\mathrm{prev},i}))\\\\&+0.3D_{\\mathrm{KL}}(\\pi_{\\theta,i}\\Vert\\operatorname{sg}(\\pi_{\\mathrm{prod},i}))\\end{array}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mtable><mtr><mtd columnalign=\"right\"><msub><mi>R</mi><mi>i</mi></msub><mo>&#x0003D;</mo><mrow /></mtd><mtd columnalign=\"left\"><mn>0.3</mn><msub><mi>D</mi><mrow><mrow><mi mathvariant=\"normal\">K</mi><mi mathvariant=\"normal\">L</mi></mrow></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><msub><mi>&#x003C0;</mi><mrow><mi>&#x003B8;</mi><mo>&#x0002C;</mo><mi>i</mi></mrow></msub><mi>&#x02016;</mi><mo>sg</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>&#x003C0;</mi><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">v</mi></mrow><mo>&#x0002C;</mo><mi>i</mi></mrow></msub><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">&#x00029;</mo></mtd></mtr><mtr><mtd columnalign=\"right\" /><mtd columnalign=\"left\"><mo>&#x0002B;</mo><mn>0.3</mn><msub><mi>D</mi><mrow><mrow><mi mathvariant=\"normal\">K</mi><mi mathvariant=\"normal\">L</mi></mrow></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><msub><mi>&#x003C0;</mi><mrow><mi>&#x003B8;</mi><mo>&#x0002C;</mo><mi>i</mi></mrow></msub><mi>&#x02016;</mi><mo>sg</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>&#x003C0;</mi><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">d</mi></mrow><mo>&#x0002C;</mo><mi>i</mi></mrow></msub><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">&#x00029;</mo></mtd></mtr></mtable></mrow></math>"
        },
        {
          "label": "Per-decision policy and constraint terms",
          "latex": "L_i=L_{\\mathrm{gain},i}+R_i+0.01C_{\\mathrm{actor},i}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>L</mi><mi>i</mi></msub><mo>&#x0003D;</mo><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">g</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">n</mi></mrow><mo>&#x0002C;</mo><mi>i</mi></mrow></msub><mo>&#x0002B;</mo><msub><mi>R</mi><mi>i</mi></msub><mo>&#x0002B;</mo><mn>0.01</mn><msub><mi>C</mi><mrow><mrow><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">r</mi></mrow><mo>&#x0002C;</mo><mi>i</mi></mrow></msub></mrow></math>"
        },
        {
          "label": "KL definition",
          "latex": "D_{\\mathrm{KL}}(\\pi\\Vert\\bar\\pi)=\\sum_a\\pi_a(\\log\\pi_a-\\log\\bar\\pi_a)",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>D</mi><mrow><mrow><mi mathvariant=\"normal\">K</mi><mi mathvariant=\"normal\">L</mi></mrow></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mi>&#x003C0;</mi><mi>&#x02016;</mi><mover><mi>&#x003C0;</mi><mo stretchy=\"true\">&#x000AF;</mo></mover><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0003D;</mo><munder><mo>&#x02211;</mo><mi>a</mi></munder><msub><mi>&#x003C0;</mi><mi>a</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>log</mi><msub><mi>&#x003C0;</mi><mi>a</mi></msub><mo>&#x02212;</mo><mi>log</mi><msub><mover><mi>&#x003C0;</mi><mo stretchy=\"true\">&#x000AF;</mo></mover><mi>a</mi></msub><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        },
        {
          "label": "Full MMD objective",
          "latex": "L_{\\mathrm{actor}}=\\frac{\\sum_i u_iL_i}{\\sum_i u_i}+L_{\\mathrm{aux}}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">r</mi></mrow></mrow></msub><mo>&#x0003D;</mo><mfrac><mrow><msub><mo>&#x02211;</mo><mi>i</mi></msub><msub><mi>u</mi><mi>i</mi></msub><msub><mi>L</mi><mi>i</mi></msub></mrow><mrow><msub><mo>&#x02211;</mo><mi>i</mi></msub><msub><mi>u</mi><mi>i</mi></msub></mrow></mfrac><mo>&#x0002B;</mo><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">x</mi></mrow></mrow></msub></mrow></math>"
        },
        {
          "label": "Value-gradient boundary",
          "latex": "\\begin{array}{rl}\\nabla_{\\theta}L_{\\mathrm{gain}}&=-\\sum_c\\operatorname{sg}(Q_c)\\nabla_{\\theta}\\rho_{\\theta,c}\\\\\\nabla_{\\psi}L_{\\mathrm{actor}}&=0\\end{array}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mtable><mtr><mtd columnalign=\"right\"><msub><mo>&#x02207;</mo><mrow><mi>&#x003B8;</mi></mrow></msub><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">g</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">n</mi></mrow></mrow></msub></mtd><mtd columnalign=\"left\"><mo>&#x0003D;</mo><mo>&#x02212;</mo><munder><mo>&#x02211;</mo><mi>c</mi></munder><mo>sg</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>Q</mi><mi>c</mi></msub><mo stretchy=\"false\">&#x00029;</mo><msub><mo>&#x02207;</mo><mrow><mi>&#x003B8;</mi></mrow></msub><msub><mi>&#x003C1;</mi><mrow><mi>&#x003B8;</mi><mo>&#x0002C;</mo><mi>c</mi></mrow></msub></mtd></mtr><mtr><mtd columnalign=\"right\"><msub><mo>&#x02207;</mo><mrow><mi>&#x003C8;</mi></mrow></msub><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">r</mi></mrow></mrow></msub></mtd><mtd columnalign=\"left\"><mo>&#x0003D;</mo><mn>0</mn></mtd></mtr></mtable></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "\\theta",
          "meaning": "Actor-phase variables. Policy gain and KL train private policy layers; supervised belief losses and belief-owned constraints train their heads and shared representations.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>&#x003B8;</mi></mrow></math>"
        },
        {
          "symbol": "\\psi",
          "meaning": "Critic-private variables; no actor update reaches them through Q.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>&#x003C8;</mi></mrow></math>"
        },
        {
          "symbol": "\\operatorname{sg}",
          "meaning": "Stop-gradient: retain the forward value and set its derivative to zero.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mo>sg</mo></mrow></math>"
        },
        {
          "symbol": "C_{\\mathrm{actor}}",
          "meaning": "Belief-owned shanten/count, route and completion constraints, aggregated at weight 0.01 in the actor phase. They retain gradients to their own predictions and shared representations.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>C</mi><mrow><mrow><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">r</mi></mrow></mrow></msub></mrow></math>"
        },
        {
          "symbol": "u_i",
          "meaning": "Eligible real decisions. Reductions normalize across all replicas.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>u</mi><mi>i</mi></msub></mrow></math>"
        },
        {
          "symbol": "L_{\\mathrm{aux}}",
          "meaning": "Sum of seven unit-weight supervised belief losses, each normalized on its own eligible, known targets.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">x</mi></mrow></mrow></msub></mrow></math>"
        }
      ],
      "source": {
        "path": "training/corrections/trainer.py",
        "line": 11
      }
    },
    {
      "id": "constraint-targets",
      "title": "Detached constraint targets",
      "description": "Raw logits fit detached constrained targets. Policy, settlement and cross-head consumers also detach belief predictions.",
      "equations": [
        {
          "label": "Categorical constraint",
          "latex": "C_{\\mathrm{cat}}=D_{\\mathrm{KL}}\\left(\\operatorname{sg}(\\operatorname{softmax}(z^{\\mathrm{con}}))\\,\\Vert\\,\\operatorname{softmax}(z^{\\mathrm{raw}})\\right)",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>C</mi><mrow><mrow><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>D</mi><mrow><mrow><mi mathvariant=\"normal\">K</mi><mi mathvariant=\"normal\">L</mi></mrow></mrow></msub><mrow><mo stretchy=\"true\" fence=\"true\" form=\"prefix\">&#x00028;</mo><mo>sg</mo><mo stretchy=\"false\">&#x00028;</mo><mo>softmax</mo><mo stretchy=\"false\">&#x00028;</mo><msup><mi>z</mi><mrow><mrow><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">n</mi></mrow></mrow></msup><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">&#x00029;</mo><mspace width=\"0.167em\" /><mi>&#x02016;</mi><mspace width=\"0.167em\" /><mo>softmax</mo><mo stretchy=\"false\">&#x00028;</mo><msup><mi>z</mi><mrow><mrow><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">w</mi></mrow></mrow></msup><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"true\" fence=\"true\" form=\"postfix\">&#x00029;</mo></mrow></mrow></math>"
        },
        {
          "label": "Binary constraint",
          "latex": "C_{\\mathrm{bin}}=\\frac1K\\sum_{k=1}^{K}D_{\\mathrm{KL}}\\left(\\operatorname{Bern}(\\operatorname{sg}(\\sigma(z_k^{\\mathrm{con}})))\\,\\Vert\\,\\operatorname{Bern}(\\sigma(z_k^{\\mathrm{raw}}))\\right)",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>C</mi><mrow><mrow><mi mathvariant=\"normal\">b</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">n</mi></mrow></mrow></msub><mo>&#x0003D;</mo><mfrac><mn>1</mn><mi>K</mi></mfrac><munderover><mo>&#x02211;</mo><mrow><mi>k</mi><mo>&#x0003D;</mo><mn>1</mn></mrow><mrow><mi>K</mi></mrow></munderover><msub><mi>D</mi><mrow><mrow><mi mathvariant=\"normal\">K</mi><mi mathvariant=\"normal\">L</mi></mrow></mrow></msub><mrow><mo stretchy=\"true\" fence=\"true\" form=\"prefix\">&#x00028;</mo><mo>Bern</mo><mo stretchy=\"false\">&#x00028;</mo><mo>sg</mo><mo stretchy=\"false\">&#x00028;</mo><mi>&#x003C3;</mi><mo stretchy=\"false\">&#x00028;</mo><msubsup><mi>z</mi><mi>k</mi><mrow><mrow><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">n</mi></mrow></mrow></msubsup><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">&#x00029;</mo><mspace width=\"0.167em\" /><mi>&#x02016;</mi><mspace width=\"0.167em\" /><mo>Bern</mo><mo stretchy=\"false\">&#x00028;</mo><mi>&#x003C3;</mi><mo stretchy=\"false\">&#x00028;</mo><msubsup><mi>z</mi><mi>k</mi><mrow><mrow><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">w</mi></mrow></mrow></msubsup><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"true\" fence=\"true\" form=\"postfix\">&#x00029;</mo></mrow></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "z^{\\mathrm{raw}}",
          "meaning": "Unconstrained head logits receiving the constraint gradient.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msup><mi>z</mi><mrow><mrow><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">w</mi></mrow></mrow></msup></mrow></math>"
        },
        {
          "symbol": "z^{\\mathrm{con}}",
          "meaning": "Legality/count/scoring-constrained logits used as a fixed target for this penalty.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msup><mi>z</mi><mrow><mrow><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">n</mi></mrow></mrow></msup></mrow></math>"
        },
        {
          "symbol": "K",
          "meaning": "Number of binary channels reduced by the constraint helper.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>K</mi></mrow></math>"
        },
        {
          "symbol": "\\sigma",
          "meaning": "Logistic sigmoid, distinct from the Gumbel noise scale in the continuation section.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>&#x003C3;</mi></mrow></math>"
        }
      ],
      "source": {
        "path": "model/losses.py",
        "line": 6
      }
    },
    {
      "id": "four-player-context",
      "title": "Self and shared-opponent player representations",
      "description": "Apply a self projection and a shared-opponent projection to player-specific descriptors concatenated with common candidate context. Self and dealer are independent descriptor predicates, concatenated with public-state features and river aggregates. Dealer status also conditions deterministic settlement support. Parameter tying does not impose representation equality or global permutation invariance. Opponent tokens additionally receive the shared 147-moment residual before event, claim and deposit pooling; self remains unchanged.",
      "equations": [
        {
          "label": "Common and player-specific encodings",
          "latex": "\\begin{array}{rl}h_c&=\\operatorname{GELU}(W_cc+b_c)\\\\h_0&=h_c\\\\h_{i+1}&=h_i+F_i(h_i),\\quad i=0,\\ldots,5\\\\h&=h_6\\\\t_j&=\\operatorname{GELU}(W_{p,j}[d_j;h]+b_{p,j})\\\\u_0&=t_0\\\\u_j&=t_j+R([t_j;m_j]),\\quad j=1,2,3\\end{array}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mtable><mtr><mtd columnalign=\"right\"><msub><mi>h</mi><mi>c</mi></msub></mtd><mtd columnalign=\"left\"><mo>&#x0003D;</mo><mo>GELU</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>W</mi><mi>c</mi></msub><mi>c</mi><mo>&#x0002B;</mo><msub><mi>b</mi><mi>c</mi></msub><mo stretchy=\"false\">&#x00029;</mo></mtd></mtr><mtr><mtd columnalign=\"right\"><msub><mi>h</mi><mn>0</mn></msub></mtd><mtd columnalign=\"left\"><mo>&#x0003D;</mo><msub><mi>h</mi><mi>c</mi></msub></mtd></mtr><mtr><mtd columnalign=\"right\"><msub><mi>h</mi><mrow><mi>i</mi><mo>&#x0002B;</mo><mn>1</mn></mrow></msub></mtd><mtd columnalign=\"left\"><mo>&#x0003D;</mo><msub><mi>h</mi><mi>i</mi></msub><mo>&#x0002B;</mo><msub><mi>F</mi><mi>i</mi></msub><mo stretchy=\"false\">&#x00028;</mo><msub><mi>h</mi><mi>i</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002C;</mo><mspace width=\"1em\" /><mi>i</mi><mo>&#x0003D;</mo><mn>0</mn><mo>&#x0002C;</mo><mi>&#x02026;</mi><mo>&#x0002C;</mo><mn>5</mn></mtd></mtr><mtr><mtd columnalign=\"right\"><mi>h</mi></mtd><mtd columnalign=\"left\"><mo>&#x0003D;</mo><msub><mi>h</mi><mn>6</mn></msub></mtd></mtr><mtr><mtd columnalign=\"right\"><msub><mi>t</mi><mi>j</mi></msub></mtd><mtd columnalign=\"left\"><mo>&#x0003D;</mo><mo>GELU</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>W</mi><mrow><mi>p</mi><mo>&#x0002C;</mo><mi>j</mi></mrow></msub><mo stretchy=\"false\">[</mo><msub><mi>d</mi><mi>j</mi></msub><mi>;</mi><mi>h</mi><mo stretchy=\"false\">]</mo><mo>&#x0002B;</mo><msub><mi>b</mi><mrow><mi>p</mi><mo>&#x0002C;</mo><mi>j</mi></mrow></msub><mo stretchy=\"false\">&#x00029;</mo></mtd></mtr><mtr><mtd columnalign=\"right\"><msub><mi>u</mi><mn>0</mn></msub></mtd><mtd columnalign=\"left\"><mo>&#x0003D;</mo><msub><mi>t</mi><mn>0</mn></msub></mtd></mtr><mtr><mtd columnalign=\"right\"><msub><mi>u</mi><mi>j</mi></msub></mtd><mtd columnalign=\"left\"><mo>&#x0003D;</mo><msub><mi>t</mi><mi>j</mi></msub><mo>&#x0002B;</mo><mi>R</mi><mo stretchy=\"false\">&#x00028;</mo><mo stretchy=\"false\">[</mo><msub><mi>t</mi><mi>j</mi></msub><mi>;</mi><msub><mi>m</mi><mi>j</mi></msub><mo stretchy=\"false\">]</mo><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002C;</mo><mspace width=\"1em\" /><mi>j</mi><mo>&#x0003D;</mo><mn>1</mn><mo>&#x0002C;</mo><mn>2</mn><mo>&#x0002C;</mo><mn>3</mn></mtd></mtr></mtable></mrow></math>"
        },
        {
          "label": "Independent self and dealer facts",
          "latex": "d_j\\supset\\left[\\mathbf{1}[j=0],\\;\\mathbf{1}[j=\\mathrm{dealer}],\\;\\text{public evidence}_j,\\;\\text{river summaries}_j\\right]",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>d</mi><mi>j</mi></msub><mo>&#x02283;</mo><mrow><mo stretchy=\"true\" fence=\"true\" form=\"prefix\">[</mo><mrow><mn mathvariant=\"bold\">1</mn></mrow><mo stretchy=\"false\">[</mo><mi>j</mi><mo>&#x0003D;</mo><mn>0</mn><mo stretchy=\"false\">]</mo><mo>&#x0002C;</mo><mspace width=\"0.278em\" /><mrow><mn mathvariant=\"bold\">1</mn></mrow><mo stretchy=\"false\">[</mo><mi>j</mi><mo>&#x0003D;</mo><mrow><mi mathvariant=\"normal\">d</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">r</mi></mrow><mo stretchy=\"false\">]</mo><mo>&#x0002C;</mo><mspace width=\"0.278em\" /><msub><mtext>public&#x000A0;evidence</mtext><mi>j</mi></msub><mo>&#x0002C;</mo><mspace width=\"0.278em\" /><msub><mtext>river&#x000A0;summaries</mtext><mi>j</mi></msub><mo stretchy=\"true\" fence=\"true\" form=\"postfix\">]</mo></mrow></mrow></math>"
        },
        {
          "label": "Whole-event role pooling",
          "latex": "\\begin{array}{rl}v_e=\\operatorname{GELU}\\bigg(&W_hh+b_h+k_{\\mathrm{kind}(e)}\\\\&+\\sum_r\\sum_{j=0}^{3}R_{e,j,r}(W_ru_j+b_r)\\bigg)\\\\z_e={}&w_{\\mathrm{out}}^{\\mathsf T}v_e+b_{\\mathrm{out}}\\end{array}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mtable><mtr><mtd columnalign=\"right\"><msub><mi>v</mi><mi>e</mi></msub><mo>&#x0003D;</mo><mo>GELU</mo><mo minsize=\"2.047em\" maxsize=\"2.047em\">(</mo></mtd><mtd columnalign=\"left\"><msub><mi>W</mi><mi>h</mi></msub><mi>h</mi><mo>&#x0002B;</mo><msub><mi>b</mi><mi>h</mi></msub><mo>&#x0002B;</mo><msub><mi>k</mi><mrow><mrow><mi mathvariant=\"normal\">k</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">d</mi></mrow><mo stretchy=\"false\">&#x00028;</mo><mi>e</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></msub></mtd></mtr><mtr><mtd columnalign=\"right\" /><mtd columnalign=\"left\"><mo>&#x0002B;</mo><munder><mo>&#x02211;</mo><mi>r</mi></munder><munderover><mo>&#x02211;</mo><mrow><mi>j</mi><mo>&#x0003D;</mo><mn>0</mn></mrow><mrow><mn>3</mn></mrow></munderover><msub><mi>R</mi><mrow><mi>e</mi><mo>&#x0002C;</mo><mi>j</mi><mo>&#x0002C;</mo><mi>r</mi></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><msub><mi>W</mi><mi>r</mi></msub><msub><mi>u</mi><mi>j</mi></msub><mo>&#x0002B;</mo><msub><mi>b</mi><mi>r</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mo minsize=\"2.047em\" maxsize=\"2.047em\">)</mo></mtd></mtr><mtr><mtd columnalign=\"right\"><msub><mi>z</mi><mi>e</mi></msub><mo>&#x0003D;</mo><mrow /></mtd><mtd columnalign=\"left\"><msubsup><mi>w</mi><mrow><mrow><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">t</mi></mrow></mrow><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msubsup><msub><mi>v</mi><mi>e</mi></msub><mo>&#x0002B;</mo><msub><mi>b</mi><mrow><mrow><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">t</mi></mrow></mrow></msub></mtd></mtr></mtable></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "c",
          "meaning": "Common candidate context: shared state, belief marginals, route and completion predictions.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>c</mi></mrow></math>"
        },
        {
          "symbol": "d_j",
          "meaning": "Public descriptor for player j; self river summary is zero and opponents supply shared river summaries.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>d</mi><mi>j</mi></msub></mrow></math>"
        },
        {
          "symbol": "W_p,b_p",
          "meaning": "Two parameter sets: self at j=0 and one shared across j=1,2,3. Dealer remains an independent conditioning fact.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>W</mi><mi>p</mi></msub><mo>&#x0002C;</mo><msub><mi>b</mi><mi>p</mi></msub></mrow></math>"
        },
        {
          "symbol": "R_{e,j,r}",
          "meaning": "Event-role indicators for winner, source and exhaustive-draw readiness.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>R</mi><mrow><mi>e</mi><mo>&#x0002C;</mo><mi>j</mi><mo>&#x0002C;</mo><mi>r</mi></mrow></msub></mrow></math>"
        },
        {
          "symbol": "k_{\\mathrm{kind}(e)}",
          "meaning": "Embedding of the event kind.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>k</mi><mrow><mrow><mi mathvariant=\"normal\">k</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">d</mi></mrow><mo stretchy=\"false\">&#x00028;</mo><mi>e</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></msub></mrow></math>"
        },
        {
          "symbol": "w_{\\mathrm{out}}",
          "meaning": "One shared scalar event-scoring vector, applied to each event representation.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>w</mi><mrow><mrow><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">t</mi></mrow></mrow></msub></mrow></math>"
        },
        {
          "symbol": "\\mathcal R_{\\mathrm{critic}}",
          "meaning": "Pre-normalized six 384 → 480 → 384 residual refinements of the common critic state, before player and event projections.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi mathvariant=\"script\">R</mi><mrow><mrow><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">c</mi></mrow></mrow></msub></mrow></math>"
        },
        {
          "symbol": "R",
          "meaning": "Shared FP32 opponent moment residual: 243→128 GELU→96 with zero-initialized output.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>R</mi></mrow></math>"
        },
        {
          "symbol": "F_i",
          "meaning": "Residual branch at depth i: LayerNorm→480 GELU→384, FP32 with zero output initialization. Six independent branches.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>F</mi><mi>i</mi></msub></mrow></math>"
        },
        {
          "symbol": "\\widetilde v_e",
          "meaning": "Whole-event vector after result attention, before the shared scalar readout.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mover><mi>v</mi><mo>&#x0007E;</mo></mover><mi>e</mi></msub></mrow></math>"
        }
      ],
      "source": {
        "path": "model/critic.py",
        "line": 855
      }
    },
    {
      "id": "tile-attention-math",
      "title": "Tile-attention refinement",
      "description": "Apply two pre-LayerNorm residual self-attention/MLP blocks to each opponent’s 34 × 128 token matrix. Four heads use key dimension 32 and scaled-dot-product denominator √32. Parameters are tied across opponent axes. A zero-initialized 128 → 14 output projection produces additive ordinary-count, red-count and conditional-ukeire logit residuals. Initial shanten, improving-tile and held-count probabilities enter tile tokens with stopped gradients.",
      "equations": [
        {
          "label": "Scaled dot-product attention",
          "latex": "\\operatorname{Attention}(Q,K,V)=\\operatorname{softmax}\\left(\\frac{QK^{\\mathsf T}}{\\sqrt{32}}\\right)V",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mo>Attention</mo><mo stretchy=\"false\">&#x00028;</mo><mi>Q</mi><mo>&#x0002C;</mo><mi>K</mi><mo>&#x0002C;</mo><mi>V</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0003D;</mo><mo>softmax</mo><mrow><mo stretchy=\"true\" fence=\"true\" form=\"prefix\">&#x00028;</mo><mfrac><mrow><mi>Q</mi><msup><mi>K</mi><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup></mrow><mrow><msqrt><mrow><mn>32</mn></mrow></msqrt></mrow></mfrac><mo stretchy=\"true\" fence=\"true\" form=\"postfix\">&#x00029;</mo></mrow><mi>V</mi></mrow></math>"
        },
        {
          "label": "Pre-normalized residual block",
          "latex": "\\begin{array}{rl}Y&=X+\\operatorname{MHA}(\\operatorname{LN}(X))\\\\X^{\\prime}&=Y+\\operatorname{GELU}(\\operatorname{LN}(Y)W_1+b_1)W_2+b_2\\end{array}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mtable><mtr><mtd columnalign=\"right\"><mi>Y</mi></mtd><mtd columnalign=\"left\"><mo>&#x0003D;</mo><mi>X</mi><mo>&#x0002B;</mo><mo>MHA</mo><mo stretchy=\"false\">&#x00028;</mo><mo>LN</mo><mo stretchy=\"false\">&#x00028;</mo><mi>X</mi><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">&#x00029;</mo></mtd></mtr><mtr><mtd columnalign=\"right\"><msup><mi>X</mi><mrow><mi>&#x02032;</mi></mrow></msup></mtd><mtd columnalign=\"left\"><mo>&#x0003D;</mo><mi>Y</mi><mo>&#x0002B;</mo><mo>GELU</mo><mo stretchy=\"false\">&#x00028;</mo><mo>LN</mo><mo stretchy=\"false\">&#x00028;</mo><mi>Y</mi><mo stretchy=\"false\">&#x00029;</mo><msub><mi>W</mi><mn>1</mn></msub><mo>&#x0002B;</mo><msub><mi>b</mi><mn>1</mn></msub><mo stretchy=\"false\">&#x00029;</mo><msub><mi>W</mi><mn>2</mn></msub><mo>&#x0002B;</mo><msub><mi>b</mi><mn>2</mn></msub></mtd></mtr></mtable></mrow></math>"
        },
        {
          "label": "Residual belief corrections",
          "latex": "\\begin{array}{rl}\\Delta&=X^{(2)}W_{\\mathrm{out}}+b_{\\mathrm{out}}\\in\\mathbb{R}^{34\\times14}\\\\W_{\\mathrm{out}}&=0,\\quad b_{\\mathrm{out}}=0\\quad\\text{at initialization}\\end{array}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mtable><mtr><mtd columnalign=\"right\"><mi>&#x00394;</mi></mtd><mtd columnalign=\"left\"><mo>&#x0003D;</mo><msup><mi>X</mi><mrow><mo stretchy=\"false\">&#x00028;</mo><mn>2</mn><mo stretchy=\"false\">&#x00029;</mo></mrow></msup><msub><mi>W</mi><mrow><mrow><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">t</mi></mrow></mrow></msub><mo>&#x0002B;</mo><msub><mi>b</mi><mrow><mrow><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">t</mi></mrow></mrow></msub><mo>&#x02208;</mo><msup><mi>&#x0211D;</mi><mrow><mn>34</mn><mo>&#x000D7;</mo><mn>14</mn></mrow></msup></mtd></mtr><mtr><mtd columnalign=\"right\"><msub><mi>W</mi><mrow><mrow><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">t</mi></mrow></mrow></msub></mtd><mtd columnalign=\"left\"><mo>&#x0003D;</mo><mn>0</mn><mo>&#x0002C;</mo><mspace width=\"1em\" /><msub><mi>b</mi><mrow><mrow><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">t</mi></mrow></mrow></msub><mo>&#x0003D;</mo><mn>0</mn><mspace width=\"1em\" /><mtext>at&#x000A0;initialization</mtext></mtd></mtr></mtable></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "X",
          "meaning": "One opponent’s 34 × 128 token matrix.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>X</mi></mrow></math>"
        },
        {
          "symbol": "Q,K,V",
          "meaning": "Learned head projections of normalized tokens; four heads are concatenated and output-projected.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>Q</mi><mo>&#x0002C;</mo><mi>K</mi><mo>&#x0002C;</mo><mi>V</mi></mrow></math>"
        },
        {
          "symbol": "W_1,W_2",
          "meaning": "Row-token feed-forward matrices W₁∈ℝ¹²⁸ˣ²⁵⁶ and W₂∈ℝ²⁵⁶ˣ¹²⁸, with broadcast biases.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>W</mi><mn>1</mn></msub><mo>&#x0002C;</mo><msub><mi>W</mi><mn>2</mn></msub></mrow></math>"
        },
        {
          "symbol": "\\Delta",
          "meaning": "Ordinary count channels 0–4, red count channels 5–9 gathered only at tile IDs 4/13/22, and shanten-conditioned ukeire channels 10–13.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>&#x00394;</mi></mrow></math>"
        },
        {
          "symbol": "W_{\\mathrm{out}}",
          "meaning": "128 × 14 residual-output matrix, applied to each row token; initialized to zero.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>W</mi><mrow><mrow><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">t</mi></mrow></mrow></msub></mrow></math>"
        }
      ],
      "source": {
        "path": "model/beliefs.py",
        "line": 157
      }
    },
    {
      "id": "encoder-operators",
      "title": "Shared encoder operators",
      "description": "",
      "equations": [
        {
          "label": "Native tensor contract",
          "latex": "\\mathcal X=\\{X_f\\in\\mathbb D_f^{B\\times s_{f,1}\\times\\cdots\\times s_{f,k_f}}:f\\in\\mathcal F\\}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mi mathvariant=\"script\">X</mi><mo>&#x0003D;</mo><mo stretchy=\"false\">&#x0007B;</mo><msub><mi>X</mi><mi>f</mi></msub><mo>&#x02208;</mo><msubsup><mi mathvariant=\"double-struck\">D</mi><mi>f</mi><mrow><mi>B</mi><mo>&#x000D7;</mo><msub><mi>s</mi><mrow><mi>f</mi><mo>&#x0002C;</mo><mn>1</mn></mrow></msub><mo>&#x000D7;</mo><mo>&#x022EF;</mo><mo>&#x000D7;</mo><msub><mi>s</mi><mrow><mi>f</mi><mo>&#x0002C;</mo><msub><mi>k</mi><mi>f</mi></msub></mrow></msub></mrow></msubsup><mi>:</mi><mi>f</mi><mo>&#x02208;</mo><mi mathvariant=\"script\">F</mi><mo stretchy=\"false\">&#x0007D;</mo></mrow></math>"
        },
        {
          "label": "Pointwise affine GELU",
          "latex": "g(x)=\\operatorname{GELU}(Wx+b)",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mi>g</mi><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0003D;</mo><mo>GELU</mo><mo stretchy=\"false\">&#x00028;</mo><mi>W</mi><mi>x</mi><mo>&#x0002B;</mo><mi>b</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        },
        {
          "label": "Board-conditioned hand token",
          "latex": "h_{n,t}=\\operatorname{GELU}(W_{\\mathrm{token}}x_{n,t}+b_{\\mathrm{token}}+W_bv_{\\operatorname{board}(n)})",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>h</mi><mrow><mi>n</mi><mo>&#x0002C;</mo><mi>t</mi></mrow></msub><mo>&#x0003D;</mo><mo>GELU</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>W</mi><mrow><mrow><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">k</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">n</mi></mrow></mrow></msub><msub><mi>x</mi><mrow><mi>n</mi><mo>&#x0002C;</mo><mi>t</mi></mrow></msub><mo>&#x0002B;</mo><msub><mi>b</mi><mrow><mrow><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">k</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">n</mi></mrow></mrow></msub><mo>&#x0002B;</mo><msub><mi>W</mi><mi>b</mi></msub><msub><mi>v</mi><mrow><mo>board</mo><mo stretchy=\"false\">&#x00028;</mo><mi>n</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></msub><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        },
        {
          "label": "Suit residual convolution",
          "latex": "H^{\\prime}=\\operatorname{GELU}\\!\\left(\\operatorname{LN}\\!\\left(H+\\operatorname{Conv}_{2,d}(\\operatorname{GELU}(\\operatorname{Conv}_{1,d}(H)))\\right)\\right)",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msup><mi>H</mi><mrow><mi>&#x02032;</mi></mrow></msup><mo>&#x0003D;</mo><mo>GELU</mo><mspace width=\"negativethinmathspace\" /><mrow><mo stretchy=\"true\" fence=\"true\" form=\"prefix\">&#x00028;</mo><mo>LN</mo><mspace width=\"negativethinmathspace\" /><mrow><mo stretchy=\"true\" fence=\"true\" form=\"prefix\">&#x00028;</mo><mi>H</mi><mo>&#x0002B;</mo><msub><mo>Conv</mo><mrow><mn>2</mn><mo>&#x0002C;</mo><mi>d</mi></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mo>GELU</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mo>Conv</mo><mrow><mn>1</mn><mo>&#x0002C;</mo><mi>d</mi></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mi>H</mi><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"true\" fence=\"true\" form=\"postfix\">&#x00029;</mo></mrow><mo stretchy=\"true\" fence=\"true\" form=\"postfix\">&#x00029;</mo></mrow></mrow></math>"
        },
        {
          "label": "Hand-bank output",
          "latex": "h_n=\\\\operatorname{LN}\\\\!\\\\left(\\\\operatorname{GELU}\\\\!\\\\left(W_oA_o[\\\\operatorname{vec}([H_{n,\\\\mathrm{suits}};H_{n,\\\\mathrm{honors}}]);y_n]+b_o\\\\right)\\\\right)\\\\in\\\\mathbb R^{512}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>h</mi><mi>n</mi></msub><mo>&#x0003D;</mo><mspace linebreak=\"newline\" /><mi>o</mi><mi>p</mi><mi>e</mi><mi>r</mi><mi>a</mi><mi>t</mi><mi>o</mi><mi>r</mi><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi><mrow><mi>L</mi><mi>N</mi></mrow><mspace linebreak=\"newline\" /><mo>&#x00021;</mo><mspace linebreak=\"newline\" /><mi>l</mi><mi>e</mi><mi>f</mi><mi>t</mi><mo stretchy=\"false\">&#x00028;</mo><mspace linebreak=\"newline\" /><mi>o</mi><mi>p</mi><mi>e</mi><mi>r</mi><mi>a</mi><mi>t</mi><mi>o</mi><mi>r</mi><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi><mrow><mi>G</mi><mi>E</mi><mi>L</mi><mi>U</mi></mrow><mspace linebreak=\"newline\" /><mo>&#x00021;</mo><mspace linebreak=\"newline\" /><mi>l</mi><mi>e</mi><mi>f</mi><mi>t</mi><mo stretchy=\"false\">&#x00028;</mo><msub><mi>W</mi><mi>o</mi></msub><msub><mi>A</mi><mi>o</mi></msub><mo stretchy=\"false\">[</mo><mspace linebreak=\"newline\" /><mi>o</mi><mi>p</mi><mi>e</mi><mi>r</mi><mi>a</mi><mi>t</mi><mi>o</mi><mi>r</mi><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi><mrow><mi>v</mi><mi>e</mi><mi>c</mi></mrow><mo stretchy=\"false\">&#x00028;</mo><mo stretchy=\"false\">[</mo><msub><mi>H</mi><mrow><mi>n</mi><mo>&#x0002C;</mo><mspace linebreak=\"newline\" /><mi>m</mi><mi>a</mi><mi>t</mi><mi>h</mi><mi>r</mi><mi>m</mi><mrow><mi>s</mi><mi>u</mi><mi>i</mi><mi>t</mi><mi>s</mi></mrow></mrow></msub><mi>;</mi><msub><mi>H</mi><mrow><mi>n</mi><mo>&#x0002C;</mo><mspace linebreak=\"newline\" /><mi>m</mi><mi>a</mi><mi>t</mi><mi>h</mi><mi>r</mi><mi>m</mi><mrow><mi>h</mi><mi>o</mi><mi>n</mi><mi>o</mi><mi>r</mi><mi>s</mi></mrow></mrow></msub><mo stretchy=\"false\">]</mo><mo stretchy=\"false\">&#x00029;</mo><mi>;</mi><msub><mi>y</mi><mi>n</mi></msub><mo stretchy=\"false\">]</mo><mo>&#x0002B;</mo><msub><mi>b</mi><mi>o</mi></msub><mspace linebreak=\"newline\" /><mi>r</mi><mi>i</mi><mi>g</mi><mi>h</mi><mi>t</mi><mo stretchy=\"false\">&#x00029;</mo><mspace linebreak=\"newline\" /><mi>r</mi><mi>i</mi><mi>g</mi><mi>h</mi><mi>t</mi><mo stretchy=\"false\">&#x00029;</mo><mspace linebreak=\"newline\" /><mi>i</mi><mi>n</mi><mspace linebreak=\"newline\" /><mi>m</mi><mi>a</mi><mi>t</mi><mi>h</mi><mi>b</mi><mi>b</mi><msup><mi>R</mi><mrow><mn>512</mn></mrow></msup></mrow></math>"
        },
        {
          "label": "Masked river residual",
          "latex": "V^{\\prime}=m\\odot\\operatorname{GELU}\\!\\left(\\operatorname{LN}\\!\\left(V+\\operatorname{Conv}_{d}(V)\\right)\\right)",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msup><mi>V</mi><mrow><mi>&#x02032;</mi></mrow></msup><mo>&#x0003D;</mo><mi>m</mi><mo>&#x02299;</mo><mo>GELU</mo><mspace width=\"negativethinmathspace\" /><mrow><mo stretchy=\"true\" fence=\"true\" form=\"prefix\">&#x00028;</mo><mo>LN</mo><mspace width=\"negativethinmathspace\" /><mrow><mo stretchy=\"true\" fence=\"true\" form=\"prefix\">&#x00028;</mo><mi>V</mi><mo>&#x0002B;</mo><msub><mo>Conv</mo><mrow><mi>d</mi></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mi>V</mi><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"true\" fence=\"true\" form=\"postfix\">&#x00029;</mo></mrow><mo stretchy=\"true\" fence=\"true\" form=\"postfix\">&#x00029;</mo></mrow></mrow></math>"
        },
        {
          "label": "River summary paths",
          "latex": "\\begin{array}{rl}u&=[\\operatorname{mean}_{m}(V);\\operatorname{max}_{m}(V)]\\\\r&=\\mathbf1[\\sum_t m_t>0]\\operatorname{GELU}(W_r[\\operatorname{vec}(V);\\operatorname{max}_{m}(V)]+b_r)\\end{array}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mtable><mtr><mtd columnalign=\"right\"><mi>u</mi></mtd><mtd columnalign=\"left\"><mo>&#x0003D;</mo><mo stretchy=\"false\">[</mo><msub><mo>mean</mo><mrow><mi>m</mi></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mi>V</mi><mo stretchy=\"false\">&#x00029;</mo><mi>;</mi><msub><mo>max</mo><mrow><mi>m</mi></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mi>V</mi><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">]</mo></mtd></mtr><mtr><mtd columnalign=\"right\"><mi>r</mi></mtd><mtd columnalign=\"left\"><mo>&#x0003D;</mo><mn mathvariant=\"bold\">1</mn><mo stretchy=\"false\">[</mo><munder><mo>&#x02211;</mo><mi>t</mi></munder><msub><mi>m</mi><mi>t</mi></msub><mo>&#x0003E;</mo><mn>0</mn><mo stretchy=\"false\">]</mo><mo>GELU</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>W</mi><mi>r</mi></msub><mo stretchy=\"false\">[</mo><mo>vec</mo><mo stretchy=\"false\">&#x00028;</mo><mi>V</mi><mo stretchy=\"false\">&#x00029;</mo><mi>;</mi><msub><mo>max</mo><mrow><mi>m</mi></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mi>V</mi><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">]</mo><mo>&#x0002B;</mo><msub><mi>b</mi><mi>r</mi></msub><mo stretchy=\"false\">&#x00029;</mo></mtd></mtr></mtable></mrow></math>"
        },
        {
          "label": "Shared public context and grouped yaku bases",
          "latex": "t_n=\\operatorname{GELU}\\left(WA[\\phi(X)_{\\mathrm{retained}};\\operatorname{vec}(B_1Y_1);\\ldots;\\operatorname{vec}(B_KY_K)]+b\\right)",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>t</mi><mi>n</mi></msub><mo>&#x0003D;</mo><mo>GELU</mo><mrow><mo stretchy=\"true\" fence=\"true\" form=\"prefix\">&#x00028;</mo><mi>W</mi><mi>A</mi><mo stretchy=\"false\">[</mo><mi>&#x003D5;</mi><mo stretchy=\"false\">&#x00028;</mo><mi>X</mi><msub><mo stretchy=\"false\">&#x00029;</mo><mrow><mrow><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">d</mi></mrow></mrow></msub><mi>;</mi><mo>vec</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>B</mi><mn>1</mn></msub><msub><mi>Y</mi><mn>1</mn></msub><mo stretchy=\"false\">&#x00029;</mo><mi>;</mi><mi>&#x02026;</mi><mi>;</mi><mo>vec</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>B</mi><mi>K</mi></msub><msub><mi>Y</mi><mi>K</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">]</mo><mo>&#x0002B;</mo><mi>b</mi><mo stretchy=\"true\" fence=\"true\" form=\"postfix\">&#x00029;</mo></mrow></mrow></math>"
        },
        {
          "label": "Pre-normalized board residual",
          "latex": "h^{(l+1)}=h^{(l)}+W_{3,l}\\operatorname{GELU}(W_{2,l}\\operatorname{GELU}(W_{1,l}\\operatorname{LN}_l(h^{(l)})+b_{1,l})+b_{2,l})+b_{3,l},\\quad l=0,\\ldots,2",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msup><mi>h</mi><mrow><mo stretchy=\"false\">&#x00028;</mo><mi>l</mi><mo>&#x0002B;</mo><mn>1</mn><mo stretchy=\"false\">&#x00029;</mo></mrow></msup><mo>&#x0003D;</mo><msup><mi>h</mi><mrow><mo stretchy=\"false\">&#x00028;</mo><mi>l</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></msup><mo>&#x0002B;</mo><msub><mi>W</mi><mrow><mn>3</mn><mo>&#x0002C;</mo><mi>l</mi></mrow></msub><mo>GELU</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>W</mi><mrow><mn>2</mn><mo>&#x0002C;</mo><mi>l</mi></mrow></msub><mo>GELU</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>W</mi><mrow><mn>1</mn><mo>&#x0002C;</mo><mi>l</mi></mrow></msub><msub><mo>LN</mo><mi>l</mi></msub><mo stretchy=\"false\">&#x00028;</mo><msup><mi>h</mi><mrow><mo stretchy=\"false\">&#x00028;</mo><mi>l</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></msup><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002B;</mo><msub><mi>b</mi><mrow><mn>1</mn><mo>&#x0002C;</mo><mi>l</mi></mrow></msub><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002B;</mo><msub><mi>b</mi><mrow><mn>2</mn><mo>&#x0002C;</mo><mi>l</mi></mrow></msub><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002B;</mo><msub><mi>b</mi><mrow><mn>3</mn><mo>&#x0002C;</mo><mi>l</mi></mrow></msub><mo>&#x0002C;</mo><mspace width=\"1em\" /><mi>l</mi><mo>&#x0003D;</mo><mn>0</mn><mo>&#x0002C;</mo><mi>&#x02026;</mi><mo>&#x0002C;</mo><mn>2</mn></mrow></math>"
        },
        {
          "label": "Fixed channel normalization",
          "latex": "\\operatorname{LN}_0(x)=\\frac{x-\\operatorname{mean}(x)}{\\sqrt{\\operatorname{var}(x)+10^{-5}}}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mo>LN</mo><mn>0</mn></msub><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0003D;</mo><mfrac><mrow><mi>x</mi><mo>&#x02212;</mo><mo>mean</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><msqrt><mrow><mo>var</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002B;</mo><msup><mn>10</mn><mrow><mo>&#x02212;</mo><mn>5</mn></mrow></msup></mrow></msqrt></mrow></mfrac></mrow></math>"
        },
        {
          "label": "Count-marginal projection",
          "latex": "\\begin{array}{rl}p^*&=\\arg\\min_{p\\in\\mathcal C}\\sum_{j,t}w_{j,t}D_{\\mathrm{KL}}(p_{j,t}\\Vert\\operatorname{softmax}(z_{j,t}))\\\\\\mathcal C&:\\quad\\sum_t\\mathbb E_p[k-L_{j,t}]=S_j,\\quad\\sum_j\\mathbb E_p[k-L_{j,t}]\\le A_t\\end{array}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mtable><mtr><mtd columnalign=\"right\"><msup><mi>p</mi><mo>&#x0002A;</mo></msup></mtd><mtd columnalign=\"left\"><mo>&#x0003D;</mo><mi>\\arg</mi><msub><mo>min</mo><mrow><mi>p</mi><mo>&#x02208;</mo><mi mathvariant=\"script\">C</mi></mrow></msub><munder><mo>&#x02211;</mo><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>t</mi></mrow></munder><msub><mi>w</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>t</mi></mrow></msub><msub><mi>D</mi><mrow><mrow><mi mathvariant=\"normal\">K</mi><mi mathvariant=\"normal\">L</mi></mrow></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><msub><mi>p</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>t</mi></mrow></msub><mi>&#x02016;</mi><mo>softmax</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>z</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>t</mi></mrow></msub><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">&#x00029;</mo></mtd></mtr><mtr><mtd columnalign=\"right\"><mi mathvariant=\"script\">C</mi></mtd><mtd columnalign=\"left\"><mi>:</mi><mspace width=\"1em\" /><munder><mo>&#x02211;</mo><mi>t</mi></munder><msub><mi mathvariant=\"double-struck\">E</mi><mi>p</mi></msub><mo stretchy=\"false\">[</mo><mi>k</mi><mo>&#x02212;</mo><msub><mi>L</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>t</mi></mrow></msub><mo stretchy=\"false\">]</mo><mo>&#x0003D;</mo><msub><mi>S</mi><mi>j</mi></msub><mo>&#x0002C;</mo><mspace width=\"1em\" /><munder><mo>&#x02211;</mo><mi>j</mi></munder><msub><mi mathvariant=\"double-struck\">E</mi><mi>p</mi></msub><mo stretchy=\"false\">[</mo><mi>k</mi><mo>&#x02212;</mo><msub><mi>L</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>t</mi></mrow></msub><mo stretchy=\"false\">]</mo><mo>&#x02264;</mo><msub><mi>A</mi><mi>t</mi></msub></mtd></mtr></mtable></mrow></math>"
        },
        {
          "label": "Zero-initialized residual refinement",
          "latex": "\\mathcal R(x)=x+W_2\\operatorname{GELU}(W_1\\operatorname{LN}(x)+b_1)+b_2,\\quad W_2^{(0)}=0,\\quad b_2^{(0)}=0",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mi mathvariant=\"script\">R</mi><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0003D;</mo><mi>x</mi><mo>&#x0002B;</mo><msub><mi>W</mi><mn>2</mn></msub><mo>GELU</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>W</mi><mn>1</mn></msub><mo>LN</mo><mo stretchy=\"false\">&#x00028;</mo><mi>x</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002B;</mo><msub><mi>b</mi><mn>1</mn></msub><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002B;</mo><msub><mi>b</mi><mn>2</mn></msub><mo>&#x0002C;</mo><mspace width=\"1em\" /><msubsup><mi>W</mi><mn>2</mn><mrow><mo stretchy=\"false\">&#x00028;</mo><mn>0</mn><mo stretchy=\"false\">&#x00029;</mo></mrow></msubsup><mo>&#x0003D;</mo><mn>0</mn><mo>&#x0002C;</mo><mspace width=\"1em\" /><msubsup><mi>b</mi><mn>2</mn><mrow><mo stretchy=\"false\">&#x00028;</mo><mn>0</mn><mo stretchy=\"false\">&#x00029;</mo></mrow></msubsup><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
        },
        {
          "label": "Independent actor and critic/belief fusion",
          "latex": "h_Q^{(0)}=\\operatorname{GELU}(W_Q[t_n;H_{n,0}]+b_Q),\\quad h_\\pi^{(0)}=\\operatorname{GELU}(W_\\pi\\operatorname{sg}([t_n;H_{n,0}])+b_\\pi)",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msubsup><mi>h</mi><mi>Q</mi><mrow><mo stretchy=\"false\">&#x00028;</mo><mn>0</mn><mo stretchy=\"false\">&#x00029;</mo></mrow></msubsup><mo>&#x0003D;</mo><mo>GELU</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>W</mi><mi>Q</mi></msub><mo stretchy=\"false\">[</mo><msub><mi>t</mi><mi>n</mi></msub><mi>;</mi><msub><mi>H</mi><mrow><mi>n</mi><mo>&#x0002C;</mo><mn>0</mn></mrow></msub><mo stretchy=\"false\">]</mo><mo>&#x0002B;</mo><msub><mi>b</mi><mi>Q</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002C;</mo><mspace width=\"1em\" /><msubsup><mi>h</mi><mi>&#x003C0;</mi><mrow><mo stretchy=\"false\">&#x00028;</mo><mn>0</mn><mo stretchy=\"false\">&#x00029;</mo></mrow></msubsup><mo>&#x0003D;</mo><mo>GELU</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>W</mi><mi>&#x003C0;</mi></msub><mo>sg</mo><mo stretchy=\"false\">&#x00028;</mo><mo stretchy=\"false\">[</mo><msub><mi>t</mi><mi>n</mi></msub><mi>;</mi><msub><mi>H</mi><mrow><mi>n</mi><mo>&#x0002C;</mo><mn>0</mn></mrow></msub><mo stretchy=\"false\">]</mo><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002B;</mo><msub><mi>b</mi><mi>&#x003C0;</mi></msub><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        },
        {
          "label": "Cross-river observed-event attention",
          "latex": "E=X+P+S,\\quad X^{\\prime}=X+M\\odot W_{\\mathrm{out}}\\operatorname{MHA}_4(E,E;MM^\\top),\\quad W_{\\mathrm{out}}(0)=0",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mi>E</mi><mo>&#x0003D;</mo><mi>X</mi><mo>&#x0002B;</mo><mi>P</mi><mo>&#x0002B;</mo><mi>S</mi><mo>&#x0002C;</mo><mspace width=\"1em\" /><msup><mi>X</mi><mrow><mi>&#x02032;</mi></mrow></msup><mo>&#x0003D;</mo><mi>X</mi><mo>&#x0002B;</mo><mi>M</mi><mo>&#x02299;</mo><msub><mi>W</mi><mrow><mrow><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">t</mi></mrow></mrow></msub><msub><mo>MHA</mo><mn>4</mn></msub><mo stretchy=\"false\">&#x00028;</mo><mi>E</mi><mo>&#x0002C;</mo><mi>E</mi><mi>;</mi><mi>M</mi><msup><mi>M</mi><mo>&#x022A4;</mo></msup><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002C;</mo><mspace width=\"1em\" /><msub><mi>W</mi><mrow><mrow><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">t</mi></mrow></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mn>0</mn><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
        },
        {
          "label": "One shared tile identity projection",
          "latex": "E=I_{34}W_{\\mathrm{tile}},\\quad W_{\\mathrm{tile}}\\in\\mathbb R^{34\\times8},\\quad e(c)=\\operatorname{valid}(c)E_{\\operatorname{base}(c)}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mi>E</mi><mo>&#x0003D;</mo><msub><mi>I</mi><mrow><mn>34</mn></mrow></msub><msub><mi>W</mi><mrow><mrow><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">e</mi></mrow></mrow></msub><mo>&#x0002C;</mo><mspace width=\"1em\" /><msub><mi>W</mi><mrow><mrow><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">e</mi></mrow></mrow></msub><mo>&#x02208;</mo><msup><mi mathvariant=\"double-struck\">R</mi><mrow><mn>34</mn><mo>&#x000D7;</mo><mn>8</mn></mrow></msup><mo>&#x0002C;</mo><mspace width=\"1em\" /><mi>e</mi><mo stretchy=\"false\">&#x00028;</mo><mi>c</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0003D;</mo><mo>valid</mo><mo stretchy=\"false\">&#x00028;</mo><mi>c</mi><mo stretchy=\"false\">&#x00029;</mo><msub><mi>E</mi><mrow><mo>base</mo><mo stretchy=\"false\">&#x00028;</mo><mi>c</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></msub></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "B,\\mathcal F,\\mathbb D_f,s_f",
          "meaning": "Batch size, current native feature-name set, field scalar dtype and trailing field dimensions.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>B</mi><mo>&#x0002C;</mo><mi mathvariant=\"script\">F</mi><mo>&#x0002C;</mo><msub><mi mathvariant=\"double-struck\">D</mi><mi>f</mi></msub><mo>&#x0002C;</mo><msub><mi>s</mi><mi>f</mi></msub></mrow></math>"
        },
        {
          "symbol": "W,b",
          "meaning": "The local learned affine weights and biases; dimensions and sharing are specified by the block.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>W</mi><mo>&#x0002C;</mo><mi>b</mi></mrow></math>"
        },
        {
          "symbol": "x_{n,t},v_{\\operatorname{board}(n)}",
          "meaning": "Tile descriptor of occupied hand n and the encoded 512-channel shared public context of its owning position. The context-to-tile map is bias-free.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>x</mi><mrow><mi>n</mi><mo>&#x0002C;</mo><mi>t</mi></mrow></msub><mo>&#x0002C;</mo><msub><mi>v</mi><mrow><mo>board</mo><mo stretchy=\"false\">&#x00028;</mo><mi>n</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></msub></mrow></math>"
        },
        {
          "symbol": "d",
          "meaning": "Convolution dilation; successive suit/river blocks use 1, 2 and 4 with independent depth parameters.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>d</mi></mrow></math>"
        },
        {
          "symbol": "m",
          "meaning": "Observed-river token mask, broadcast over channels. Empty-stream masked means and maxima are zero.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>m</mi></mrow></math>"
        },
        {
          "symbol": "Y_k,B_k",
          "meaning": "Matrices of yaku-feasibility channel vectors and their bias-free width-grouped basis maps.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>Y</mi><mi>k</mi></msub><mo>&#x0002C;</mo><msub><mi>B</mi><mi>k</mi></msub></mrow></math>"
        },
        {
          "symbol": "\\operatorname{LN},\\operatorname{LN}_0",
          "meaning": "LayerNorm with learned scale/offset, and the fixed float 32 normalization without those parameters.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mo>LN</mo><mo>&#x0002C;</mo><msub><mo>LN</mo><mn>0</mn></msub></mrow></math>"
        },
        {
          "symbol": "L_{j,t},S_j,A_t,w_{j,t}",
          "meaning": "Known meld-copy lower bound, concealed hand size, remaining physical copy availability and positive projection weight.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>L</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>t</mi></mrow></msub><mo>&#x0002C;</mo><msub><mi>S</mi><mi>j</mi></msub><mo>&#x0002C;</mo><msub><mi>A</mi><mi>t</mi></msub><mo>&#x0002C;</mo><msub><mi>w</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>t</mi></mrow></msub></mrow></math>"
        },
        {
          "symbol": "\\mathcal C",
          "meaning": "Supported count distributions with per-player concealed-size and shared tile-copy constraints. The solver supplies a custom implicit backward.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi mathvariant=\"script\">C</mi></mrow></math>"
        },
        {
          "symbol": "W_{\\mathrm{token}},b_{\\mathrm{token}}",
          "meaning": "One affine token map shared across tiles and occupied hands.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>W</mi><mrow><mrow><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">k</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">n</mi></mrow></mrow></msub><mo>&#x0002C;</mo><msub><mi>b</mi><mrow><mrow><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">k</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">n</mi></mrow></mrow></msub></mrow></math>"
        },
        {
          "symbol": "z_{j,t}",
          "meaning": "HeldCountMask-applied count logits over 37 tile channels, including known held-count support, before CountProjection.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>z</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>t</mi></mrow></msub></mrow></math>"
        },
        {
          "symbol": "\\mathcal R",
          "meaning": "Separate private residuals: belief 512→1152→512, actor 768→384→768, critic six 384→480→384 blocks. Output projections start at zero; parameters are not shared.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi mathvariant=\"script\">R</mi></mrow></math>"
        },
        {
          "symbol": "A_o,A",
          "meaning": "Bias-free rank-256 factors for the 4371-channel hand readout and 1412-channel shared public context; each ends in a 512-channel GELU projection. Joint hand-board fusion is a separate 1024→512 GELU.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>A</mi><mi>o</mi></msub><mo>&#x0002C;</mo><mi>A</mi></mrow></math>"
        },
        {
          "symbol": "\\phi(X)",
          "meaning": "Field-aware encoding: learned tile/river-category embeddings, nominal one-hots, identity flags and asinh numeric magnitudes; invalid fields are masked.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>&#x003D5;</mi><mo stretchy=\"false\">&#x00028;</mo><mi>X</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        },
        {
          "symbol": "y_n",
          "meaning": "Nineteen fixed-meld/public-supply yaku-feasibility flags of this resulting hand; concatenate once at its shared readout.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>y</mi><mi>n</mi></msub></mrow></math>"
        },
        {
          "symbol": "E,P,S,M",
          "meaning": "192 observed/padded river-event embeddings, segment-position embeddings, opponent-seat embeddings and event-validity mask; attention has four heads of width16.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>E</mi><mo>&#x0002C;</mo><mi>P</mi><mo>&#x0002C;</mo><mi>S</mi><mo>&#x0002C;</mo><mi>M</mi></mrow></math>"
        },
        {
          "symbol": "E,W_{\\mathrm{tile}},\\operatorname{base},\\operatorname{valid}",
          "meaning": "Shared 8-channel tile identities, their single 272-parameter projection, red-aware base-tile mapping and padding validity. Red flags remain separate. Hand, river, table and candidate encoder branches reuse the same E.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>E</mi><mo>&#x0002C;</mo><msub><mi>W</mi><mrow><mrow><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">e</mi></mrow></mrow></msub><mo>&#x0002C;</mo><mo>base</mo><mo>&#x0002C;</mo><mo>valid</mo></mrow></math>"
        }
      ],
      "source": {
        "path": "model/encoder.py",
        "line": 906
      }
    },
    {
      "id": "policy-readouts",
      "title": "Prediction and policy readouts",
      "description": "Affine predictions and context fusion before phase-specific legal normalization. These equations describe neural operators; target labels do not enter the forward graph.",
      "equations": [
        {
          "label": "Affine prediction and reshape",
          "latex": "z_k=\\operatorname{reshape}_{s_k}(W_kh+b_k)",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>z</mi><mi>k</mi></msub><mo>&#x0003D;</mo><msub><mo>reshape</mo><mrow><msub><mi>s</mi><mi>k</mi></msub></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><msub><mi>W</mi><mi>k</mi></msub><mi>h</mi><mo>&#x0002B;</mo><msub><mi>b</mi><mi>k</mi></msub><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        },
        {
          "label": "Completion-conditioned policy context",
          "latex": "q=[h_\\pi;\\operatorname{GELU}(W_c[h_\\pi;\\operatorname{sg}(p_s);\\operatorname{sg}(\\operatorname{vec}(p_sp_{u\\mid s}));\\operatorname{sg}(p_c);\\operatorname{sg}(p_y);\\operatorname{sg}(p_{\\mathrm{score}})]+b_c)],\\quad c_{\\mathrm{policy}}=\\mathcal R_2(\\mathcal R_1(q))",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mi>q</mi><mo>&#x0003D;</mo><mo stretchy=\"false\">[</mo><msub><mi>h</mi><mi>&#x003C0;</mi></msub><mi>;</mi><mo>GELU</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>W</mi><mi>c</mi></msub><mo stretchy=\"false\">[</mo><msub><mi>h</mi><mi>&#x003C0;</mi></msub><mi>;</mi><mo>sg</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>p</mi><mi>s</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mi>;</mi><mo>sg</mo><mo stretchy=\"false\">&#x00028;</mo><mo>vec</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>p</mi><mi>s</mi></msub><msub><mi>p</mi><mrow><mi>u</mi><mo>&#x02223;</mo><mi>s</mi></mrow></msub><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">&#x00029;</mo><mi>;</mi><mo>sg</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>p</mi><mi>c</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mi>;</mi><mo>sg</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>p</mi><mi>y</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mi>;</mi><mo>sg</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>p</mi><mrow><mrow><mi mathvariant=\"normal\">s</mi><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">e</mi></mrow></mrow></msub><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">]</mo><mo>&#x0002B;</mo><msub><mi>b</mi><mi>c</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">]</mo><mo>&#x0002C;</mo><mspace width=\"1em\" /><msub><mi>c</mi><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">y</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi mathvariant=\"script\">R</mi><mn>2</mn></msub><mo stretchy=\"false\">&#x00028;</mo><msub><mi mathvariant=\"script\">R</mi><mn>1</mn></msub><mo stretchy=\"false\">&#x00028;</mo><mi>q</mi><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        },
        {
          "label": "Shared final candidate score",
          "latex": "\\begin{array}{rl}f_a&=[\\operatorname{sg}(c_a);\\operatorname{sg}(\\sigma(r_a));\\operatorname{sg}(p_{\\mathrm{ron},a});c_{\\mathrm{policy}}]\\\\z_a&=w_o^{\\mathsf T}\\operatorname{LN}_0(\\operatorname{GELU}(W_ff_a+b_f))+b_o\\end{array}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mtable><mtr><mtd columnalign=\"right\"><msub><mi>f</mi><mi>a</mi></msub></mtd><mtd columnalign=\"left\"><mo>&#x0003D;</mo><mo stretchy=\"false\">[</mo><mo>sg</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>c</mi><mi>a</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mi>;</mi><mo>sg</mo><mo stretchy=\"false\">&#x00028;</mo><mi>&#x003C3;</mi><mo stretchy=\"false\">&#x00028;</mo><msub><mi>r</mi><mi>a</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">&#x00029;</mo><mi>;</mi><mo>sg</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>p</mi><mrow><mrow><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">n</mi></mrow><mo>&#x0002C;</mo><mi>a</mi></mrow></msub><mo stretchy=\"false\">&#x00029;</mo><mi>;</mi><msub><mi>c</mi><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">y</mi></mrow></mrow></msub><mo stretchy=\"false\">]</mo></mtd></mtr><mtr><mtd columnalign=\"right\"><msub><mi>z</mi><mi>a</mi></msub></mtd><mtd columnalign=\"left\"><mo>&#x0003D;</mo><msubsup><mi>w</mi><mi>o</mi><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msubsup><msub><mo>LN</mo><mn>0</mn></msub><mo stretchy=\"false\">&#x00028;</mo><mo>GELU</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>W</mi><mi>f</mi></msub><msub><mi>f</mi><mi>a</mi></msub><mo>&#x0002B;</mo><msub><mi>b</mi><mi>f</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002B;</mo><msub><mi>b</mi><mi>o</mi></msub></mtd></mtr></mtable></mrow></math>"
        },
        {
          "label": "Derived policy-group log mass",
          "latex": "z_g=\\log\\sum_{a\\in g}\\exp(z_a)",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>z</mi><mi>g</mi></msub><mo>&#x0003D;</mo><mi>log</mi><munder><mo>&#x02211;</mo><mrow><mi>a</mi><mo>&#x02208;</mo><mi>g</mi></mrow></munder><mi>exp</mi><mo stretchy=\"false\">&#x00028;</mo><msub><mi>z</mi><mi>a</mi></msub><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "h,z_k,s_k",
          "meaning": "Shared board state, output logits and the tensor shape of readout k. Candidate auxiliary readouts use the candidate state as their input h.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>h</mi><mo>&#x0002C;</mo><msub><mi>z</mi><mi>k</mi></msub><mo>&#x0002C;</mo><msub><mi>s</mi><mi>k</mi></msub></mrow></math>"
        },
        {
          "symbol": "p_s,p_{u\\mid s},p_c,p_y,p_{\\mathrm{score}}",
          "meaning": "Constrained shanten, conditional improving, held-count, completion-yaku and completion-score probabilities. The actor uses joint p_s ×p_(u|s) slices.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>p</mi><mi>s</mi></msub><mo>&#x0002C;</mo><msub><mi>p</mi><mrow><mi>u</mi><mo>&#x02223;</mo><mi>s</mi></mrow></msub><mo>&#x0002C;</mo><msub><mi>p</mi><mi>c</mi></msub><mo>&#x0002C;</mo><msub><mi>p</mi><mi>y</mi></msub><mo>&#x0002C;</mo><msub><mi>p</mi><mrow><mrow><mi mathvariant=\"normal\">s</mi><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">e</mi></mrow></mrow></msub></mrow></math>"
        },
        {
          "symbol": "c_a,r_a,p_{\\mathrm{ron},a}",
          "meaning": "Candidate state 384, route logits 3 and constrained ron probabilities 3.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>c</mi><mi>a</mi></msub><mo>&#x0002C;</mo><msub><mi>r</mi><mi>a</mi></msub><mo>&#x0002C;</mo><msub><mi>p</mi><mrow><mrow><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">n</mi></mrow><mo>&#x0002C;</mo><mi>a</mi></mrow></msub></mrow></math>"
        },
        {
          "symbol": "f_a",
          "meaning": "1158-channel concatenation; W_f projects to 512 channels before the shared scalar readout.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>f</mi><mi>a</mi></msub></mrow></math>"
        },
        {
          "symbol": "\\sigma,\\operatorname{LN}_0",
          "meaning": "Elementwise sigmoid and fixed float 32 LayerNorm with epsilon 1e-5.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>&#x003C3;</mi><mo>&#x0002C;</mo><msub><mo>LN</mo><mn>0</mn></msub></mrow></math>"
        },
        {
          "symbol": "g",
          "meaning": "A policy marginal group: declaration choice, call kind or chi pattern. Serving softmax normalizes across the corresponding groups.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>g</mi></mrow></math>"
        },
        {
          "symbol": "\\mathcal R_1,\\mathcal R_2,\\operatorname{sg}",
          "meaning": "Two independent pre-normalized 768 → 384 → 768 actor residual refinements, and stop-gradient. Belief predictions and shared lower features retain forward values but receive no policy gradient.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi mathvariant=\"script\">R</mi><mn>1</mn></msub><mo>&#x0002C;</mo><msub><mi mathvariant=\"script\">R</mi><mn>2</mn></msub><mo>&#x0002C;</mo><mo>sg</mo></mrow></math>"
        },
        {
          "symbol": "h_\\pi",
          "meaning": "Policy-trained 512-channel output of the private actor upper encoder.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>h</mi><mi>&#x003C0;</mi></msub></mrow></math>"
        }
      ],
      "source": {
        "path": "model/actor.py",
        "line": 155
      }
    },
    {
      "id": "critic-factor-heads",
      "title": "Critic factor projections",
      "description": "A single total han/fu distribution uses the claim state and public scoring evidence.",
      "equations": [
        {
          "label": "Shared claim state",
          "latex": "c_j=\\operatorname{GELU}(W_c[u_{\\mathrm{recipient}(j)};\\mathbf1[j\\in\\mathrm{ron}]u_{\\mathrm{payer}(j)};\\operatorname{onehot}(\\mathrm{kind}(j));f_j]+b_c)\\in\\mathbb R^{96}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>c</mi><mi>j</mi></msub><mo>&#x0003D;</mo><mo>GELU</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>W</mi><mi>c</mi></msub><mo stretchy=\"false\">[</mo><msub><mi>u</mi><mrow><mrow><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">t</mi></mrow><mo stretchy=\"false\">&#x00028;</mo><mi>j</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></msub><mi>;</mi><mn mathvariant=\"bold\">1</mn><mo stretchy=\"false\">[</mo><mi>j</mi><mo>&#x02208;</mo><mrow><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">n</mi></mrow><mo stretchy=\"false\">]</mo><msub><mi>u</mi><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">y</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">r</mi></mrow><mo stretchy=\"false\">&#x00028;</mo><mi>j</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></msub><mi>;</mi><mo>onehot</mo><mo stretchy=\"false\">&#x00028;</mo><mrow><mi mathvariant=\"normal\">k</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">d</mi></mrow><mo stretchy=\"false\">&#x00028;</mo><mi>j</mi><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">&#x00029;</mo><mi>;</mi><msub><mi>f</mi><mi>j</mi></msub><mo stretchy=\"false\">]</mo><mo>&#x0002B;</mo><msub><mi>b</mi><mi>c</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mo>&#x02208;</mo><msup><mi mathvariant=\"double-struck\">R</mi><mrow><mn>96</mn></mrow></msup></mrow></math>"
        },
        {
          "label": "Public scoring evidence",
          "latex": "f_j=[\\mathrm{fu}_j/128;\\mathrm{bonus}_j/5;\\mathrm{opened}_j;\\mathrm{riichi}_j]",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>f</mi><mi>j</mi></msub><mo>&#x0003D;</mo><mo stretchy=\"false\">[</mo><msub><mrow><mi mathvariant=\"normal\">f</mi><mi mathvariant=\"normal\">u</mi></mrow><mi>j</mi></msub><mo>&#x0002F;</mo><mn>128</mn><mi>;</mi><msub><mrow><mi mathvariant=\"normal\">b</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">s</mi></mrow><mi>j</mi></msub><mo>&#x0002F;</mo><mn>5</mn><mi>;</mi><msub><mrow><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">d</mi></mrow><mi>j</mi></msub><mi>;</mi><msub><mrow><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">h</mi><mi mathvariant=\"normal\">i</mi></mrow><mi>j</mi></msub><mo stretchy=\"false\">]</mo></mrow></math>"
        },
        {
          "label": "Total settlement han/fu logits",
          "latex": "z_{j,\\mathrm{score}}=W_sc_j+b_s\\in\\mathbb R^{38}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>z</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mrow><mi mathvariant=\"normal\">s</mi><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">e</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mi>W</mi><mi>s</mi></msub><msub><mi>c</mi><mi>j</mi></msub><mo>&#x0002B;</mo><msub><mi>b</mi><mi>s</mi></msub><mo>&#x02208;</mo><msup><mi mathvariant=\"double-struck\">R</mi><mrow><mn>38</mn></mrow></msup></mrow></math>"
        },
        {
          "label": "Conditional deposit-mask logits",
          "latex": "\\begin{array}{rl}d_{e,D}=\\operatorname{GELU}\\bigg(&A v_e+a+\\sum_jD_j(Bu_j+b)\\\\&+C\\sum_jD_jR_{e,j,:}+c\\bigg)\\\\z_{e,D}={}&w_d^{\\mathsf T}d_{e,D}+b_d\\end{array}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mtable><mtr><mtd columnalign=\"right\"><msub><mi>d</mi><mrow><mi>e</mi><mo>&#x0002C;</mo><mi>D</mi></mrow></msub><mo>&#x0003D;</mo><mo>GELU</mo><mo minsize=\"2.047em\" maxsize=\"2.047em\">(</mo></mtd><mtd columnalign=\"left\"><mi>A</mi><msub><mi>v</mi><mi>e</mi></msub><mo>&#x0002B;</mo><mi>a</mi><mo>&#x0002B;</mo><munder><mo>&#x02211;</mo><mi>j</mi></munder><msub><mi>D</mi><mi>j</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>B</mi><msub><mi>u</mi><mi>j</mi></msub><mo>&#x0002B;</mo><mi>b</mi><mo stretchy=\"false\">&#x00029;</mo></mtd></mtr><mtr><mtd columnalign=\"right\" /><mtd columnalign=\"left\"><mo>&#x0002B;</mo><mi>C</mi><munder><mo>&#x02211;</mo><mi>j</mi></munder><msub><mi>D</mi><mi>j</mi></msub><msub><mi>R</mi><mrow><mi>e</mi><mo>&#x0002C;</mo><mi>j</mi><mo>&#x0002C;</mo><mi>:</mi></mrow></msub><mo>&#x0002B;</mo><mi>c</mi><mo minsize=\"2.047em\" maxsize=\"2.047em\">)</mo></mtd></mtr><mtr><mtd columnalign=\"right\"><msub><mi>z</mi><mrow><mi>e</mi><mo>&#x0002C;</mo><mi>D</mi></mrow></msub><mo>&#x0003D;</mo><mrow /></mtd><mtd columnalign=\"left\"><msubsup><mi>w</mi><mi>d</mi><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msubsup><msub><mi>d</mi><mrow><mi>e</mi><mo>&#x0002C;</mo><mi>D</mi></mrow></msub><mo>&#x0002B;</mo><msub><mi>b</mi><mi>d</mi></msub></mtd></mtr></mtable></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "u_j,v_e",
          "meaning": "96-channel player embedding and attended 32-channel whole-event latent.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>u</mi><mi>j</mi></msub><mo>&#x0002C;</mo><msub><mi>v</mi><mi>e</mi></msub></mrow></math>"
        },
        {
          "symbol": "c_j,f_j",
          "meaning": "96-channel unique claim state and four public scoring features.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>c</mi><mi>j</mi></msub><mo>&#x0002C;</mo><msub><mi>f</mi><mi>j</mi></msub></mrow></math>"
        },
        {
          "symbol": "D_j,R_{e,j,:}",
          "meaning": "Membership of player j in a deposit mask and the three winner/source/ready roles under event e.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>D</mi><mi>j</mi></msub><mo>&#x0002C;</mo><msub><mi>R</mi><mrow><mi>e</mi><mo>&#x0002C;</mo><mi>j</mi><mo>&#x0002C;</mo><mi>:</mi></mrow></msub></mrow></math>"
        },
        {
          "symbol": "A,B,C",
          "meaning": "Attended event 32→8, player 96→8 and pooled-role 3→8 projections, with their broadcast biases.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>A</mi><mo>&#x0002C;</mo><mi>B</mi><mo>&#x0002C;</mo><mi>C</mi></mrow></math>"
        },
        {
          "symbol": "d_{e,D}",
          "meaning": "8-channel conditional deposit state. The same scalar output map scores all 60×16 event/mask pairs.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>d</mi><mrow><mi>e</mi><mo>&#x0002C;</mo><mi>D</mi></mrow></msub></mrow></math>"
        }
      ],
      "source": {
        "path": "model/critic.py",
        "line": 770
      }
    },
    {
      "id": "call-factorization",
      "title": "Call choice and shared post-call discard",
      "description": "Six legal call branches; chi and pon use the ordinary discard network on recomputed accepted-call public states. Joint support and full-distribution KL are retained. Sparse states are conditional inputs, not extra loss rows.",
      "equations": [
        {
          "label": "Joint call and discard mass",
          "latex": "\\pi(c,d\\mid s)=\\pi_{\\mathrm{call}}(c\\mid s)\\pi_{\\mathrm{discard}}(d\\mid T_c(s))",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mi>&#x003C0;</mi><mo stretchy=\"false\">&#x00028;</mo><mi>c</mi><mo>&#x0002C;</mo><mi>d</mi><mo>&#x02223;</mo><mi>s</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0003D;</mo><msub><mi>&#x003C0;</mi><mrow><mrow><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">l</mi></mrow></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mi>c</mi><mo>&#x02223;</mo><mi>s</mi><mo stretchy=\"false\">&#x00029;</mo><msub><mi>&#x003C0;</mi><mrow><mrow><mi mathvariant=\"normal\">d</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">s</mi><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">d</mi></mrow></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mi>d</mi><mo>&#x02223;</mo><msub><mi>T</mi><mi>c</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>s</mi><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        },
        {
          "label": "After-call action mapping",
          "latex": "I(c,d)=112+37c+d,\\qquad z_{\\mathrm{owner},I(c,d)}=z_{T_c(s),d},\\quad c\\in\\{0,1,2,3\\}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mi>I</mi><mo stretchy=\"false\">&#x00028;</mo><mi>c</mi><mo>&#x0002C;</mo><mi>d</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0003D;</mo><mn>112</mn><mo>&#x0002B;</mo><mn>37</mn><mi>c</mi><mo>&#x0002B;</mo><mi>d</mi><mo>&#x0002C;</mo><mspace width=\"2em\" /><msub><mi>z</mi><mrow><mrow><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">w</mi><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">r</mi></mrow><mo>&#x0002C;</mo><mi>I</mi><mo stretchy=\"false\">&#x00028;</mo><mi>c</mi><mo>&#x0002C;</mo><mi>d</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></msub><mo>&#x0003D;</mo><msub><mi>z</mi><mrow><msub><mi>T</mi><mi>c</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>s</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002C;</mo><mi>d</mi></mrow></msub><mo>&#x0002C;</mo><mspace width=\"1em\" /><mi>c</mi><mo>&#x02208;</mo><mo stretchy=\"false\">&#x0007B;</mo><mn>0</mn><mo>&#x0002C;</mo><mn>1</mn><mo>&#x0002C;</mo><mn>2</mn><mo>&#x0002C;</mo><mn>3</mn><mo stretchy=\"false\">&#x0007D;</mo></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "T_c(s)",
          "meaning": "The public state after accepting chi/pon, before its mandatory discard; pass/open-kan do not have this continuation.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>T</mi><mi>c</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>s</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        },
        {
          "symbol": "I(c,d)",
          "meaning": "Original 295-action bookkeeping index for accepted chi/pon option c and follow-up discard d. Shared neural and hand state follows the after-call position. Public settlement legality stays at the original window.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>I</mi><mo stretchy=\"false\">&#x00028;</mo><mi>c</mi><mo>&#x0002C;</mo><mi>d</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        }
      ],
      "source": {
        "path": "model/actor.py",
        "line": 338
      }
    },
    {
      "id": "expert-weights",
      "title": "Detached current-Q expert weights",
      "description": "Live-learner Q differences against recorded Mortal choices set detached imitation weights at 75% ESS. The critic also trains separately on recorded-action settlement likelihood in the same update.",
      "equations": [
        {
          "label": "Relative expert weight",
          "latex": "w_i\\propto\\exp\\left((Q_{\\mathrm{current}}(s_i,a_i^{expert})-Q_{\\mathrm{current}}(s_i,a_i^{reference}))/\\beta\\right)",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>w</mi><mi>i</mi></msub><mo>&#x0221D;</mo><mi>exp</mi><mrow><mo stretchy=\"true\" fence=\"true\" form=\"prefix\">&#x00028;</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>Q</mi><mrow><mrow><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">t</mi></mrow></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><msub><mi>s</mi><mi>i</mi></msub><mo>&#x0002C;</mo><msubsup><mi>a</mi><mi>i</mi><mrow><mi>e</mi><mi>x</mi><mi>p</mi><mi>e</mi><mi>r</mi><mi>t</mi></mrow></msubsup><mo stretchy=\"false\">&#x00029;</mo><mo>&#x02212;</mo><msub><mi>Q</mi><mrow><mrow><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">t</mi></mrow></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><msub><mi>s</mi><mi>i</mi></msub><mo>&#x0002C;</mo><msubsup><mi>a</mi><mi>i</mi><mrow><mi>r</mi><mi>e</mi><mi>f</mi><mi>e</mi><mi>r</mi><mi>e</mi><mi>n</mi><mi>c</mi><mi>e</mi></mrow></msubsup><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002F;</mo><mi>&#x003B2;</mi><mo stretchy=\"true\" fence=\"true\" form=\"postfix\">&#x00029;</mo></mrow></mrow></math>"
        },
        {
          "label": "Effective sample fraction",
          "latex": "\\operatorname{ESS}/N=\\frac{(\\sum_iw_i)^2}{N\\sum_iw_i^2}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mo>ESS</mo><mo>&#x0002F;</mo><mi>N</mi><mo>&#x0003D;</mo><mfrac><mrow><mo stretchy=\"false\">&#x00028;</mo><msub><mo>&#x02211;</mo><mi>i</mi></msub><msub><mi>w</mi><mi>i</mi></msub><msup><mo stretchy=\"false\">&#x00029;</mo><mn>2</mn></msup></mrow><mrow><mi>N</mi><msub><mo>&#x02211;</mo><mi>i</mi></msub><msubsup><mi>w</mi><mi>i</mi><mn>2</mn></msubsup></mrow></mfrac></mrow></math>"
        },
        {
          "label": "Weighted imitation, settlement and belief objective",
          "latex": "L=\\frac{\\sum_i v_i m_i\\operatorname{stop}(w_i)[-\\log\\pi_\\theta(a_i^{\\mathrm{expert}}\\mid s_i)]}{\\sum_i v_i m_i}+L_{\\mathrm{aux}}+L_{\\mathrm{settlement}}+L_{\\mathrm{critic\\ constraints}}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mi>L</mi><mo>&#x0003D;</mo><mfrac><mrow><msub><mo>&#x02211;</mo><mi>i</mi></msub><msub><mi>v</mi><mi>i</mi></msub><msub><mi>m</mi><mi>i</mi></msub><mo>stop</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>w</mi><mi>i</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">[</mo><mo>&#x02212;</mo><mi>log</mi><msub><mi>&#x003C0;</mi><mi>&#x003B8;</mi></msub><mo stretchy=\"false\">&#x00028;</mo><msubsup><mi>a</mi><mi>i</mi><mrow><mrow><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">x</mi><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">t</mi></mrow></mrow></msubsup><mo>&#x02223;</mo><msub><mi>s</mi><mi>i</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">]</mo></mrow><mrow><msub><mo>&#x02211;</mo><mi>i</mi></msub><msub><mi>v</mi><mi>i</mi></msub><msub><mi>m</mi><mi>i</mi></msub></mrow></mfrac><mo>&#x0002B;</mo><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">x</mi></mrow></mrow></msub><mo>&#x0002B;</mo><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">s</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">m</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">t</mi></mrow></mrow></msub><mo>&#x0002B;</mo><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">c</mi><mtext>&#x000A0;</mtext><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">s</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">s</mi></mrow></mrow></msub></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "Q_{\\mathrm{current}}",
          "meaning": "Current learner action value; detached for CE weighting while the separate settlement objective updates critic and shared representations.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>Q</mi><mrow><mrow><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">t</mi></mrow></mrow></msub></mrow></math>"
        },
        {
          "symbol": "\\beta",
          "meaning": "Batch calibration targets 0.75 ESS fraction over policy-labeled rows.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>&#x003B2;</mi></mrow></math>"
        },
        {
          "symbol": "v_i,m_i",
          "meaning": "Eligible real decisions and supported teacher actions. CE uses their intersection. Q-weight calibration uses eligible decisions. Empty masked means contribute zero.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>v</mi><mi>i</mi></msub><mo>&#x0002C;</mo><msub><mi>m</mi><mi>i</mi></msub></mrow></math>"
        },
        {
          "symbol": "L_{\\mathrm{aux}}",
          "meaning": "Sum of seven unit-weight supervised belief losses, each normalized on its own eligible, known targets.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">x</mi></mrow></mrow></msub></mrow></math>"
        }
      ],
      "source": {
        "path": "training/imitation.py",
        "line": 48
      }
    },
    {
      "id": "decision-conditioning",
      "title": "Decision-context conditioning",
      "description": "",
      "equations": [
        {
          "label": "Shared decision-row offset",
          "latex": "c_n=W_{\\mathrm{ctx}}t_n\\in\\mathbb R^{128}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>c</mi><mi>n</mi></msub><mo>&#x0003D;</mo><msub><mi>W</mi><mrow><mrow><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">x</mi></mrow></mrow></msub><msub><mi>t</mi><mi>n</mi></msub><mo>&#x02208;</mo><msup><mi mathvariant=\"double-struck\">R</mi><mrow><mn>128</mn></mrow></msup></mrow></math>"
        },
        {
          "label": "Conditioned local hand token",
          "latex": "h_{n,k,t}=\\operatorname{GELU}(W_{\\mathrm{tile}}x_{n,k,t}+b_{\\mathrm{tile}}+c_n)",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>h</mi><mrow><mi>n</mi><mo>&#x0002C;</mo><mi>k</mi><mo>&#x0002C;</mo><mi>t</mi></mrow></msub><mo>&#x0003D;</mo><mo>GELU</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>W</mi><mrow><mrow><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">e</mi></mrow></mrow></msub><msub><mi>x</mi><mrow><mi>n</mi><mo>&#x0002C;</mo><mi>k</mi><mo>&#x0002C;</mo><mi>t</mi></mrow></msub><mo>&#x0002B;</mo><msub><mi>b</mi><mrow><mrow><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">e</mi></mrow></mrow></msub><mo>&#x0002B;</mo><msub><mi>c</mi><mi>n</mi></msub><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "t_n",
          "meaning": "Shared 512-channel public context from typed global fields and the learned river summaries; computed once per position.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>t</mi><mi>n</mi></msub></mrow></math>"
        },
        {
          "symbol": "x_{n,k,t}",
          "meaning": "Tile descriptor t in local hand slot k of row n.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>x</mi><mrow><mi>n</mi><mo>&#x0002C;</mo><mi>k</mi><mo>&#x0002C;</mo><mi>t</mi></mrow></msub></mrow></math>"
        },
        {
          "symbol": "c_n",
          "meaning": "Same bias-free context projection for every hand/tile in row n; recomputed for after-call positions.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>c</mi><mi>n</mi></msub></mrow></math>"
        }
      ],
      "source": {
        "path": "model/encoder.py",
        "line": 339
      }
    },
    {
      "id": "critic-belief-adapter",
      "title": "Shared opponent moment residual",
      "description": "FP32 residual shared over the three opponent tokens; zero output initialization preserves the initial critic function.",
      "equations": [
        {
          "label": "147 moments per opponent",
          "latex": "m_j=[p_s; p_{s=0}p_{u\\mid0};\\sum_s p_s p_{u\\mid s};\\mathbb E[c]/4;\\operatorname{Var}(c)/4;H_\\epsilon(p_s)/\\log4]",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>m</mi><mi>j</mi></msub><mo>&#x0003D;</mo><mo stretchy=\"false\">[</mo><msub><mi>p</mi><mi>s</mi></msub><mi>;</mi><msub><mi>p</mi><mrow><mi>s</mi><mo>&#x0003D;</mo><mn>0</mn></mrow></msub><msub><mi>p</mi><mrow><mi>u</mi><mo>&#x02223;</mo><mn>0</mn></mrow></msub><mi>;</mi><munder><mo>&#x02211;</mo><mi>s</mi></munder><msub><mi>p</mi><mi>s</mi></msub><msub><mi>p</mi><mrow><mi>u</mi><mo>&#x02223;</mo><mi>s</mi></mrow></msub><mi>;</mi><mi mathvariant=\"double-struck\">E</mi><mo stretchy=\"false\">[</mo><mi>c</mi><mo stretchy=\"false\">]</mo><mo>&#x0002F;</mo><mn>4</mn><mi>;</mi><mo>Var</mo><mo stretchy=\"false\">&#x00028;</mo><mi>c</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002F;</mo><mn>4</mn><mi>;</mi><msub><mi>H</mi><mi>&#x003F5;</mi></msub><mo stretchy=\"false\">&#x00028;</mo><msub><mi>p</mi><mi>s</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002F;</mo><mi>log</mi><mn>4</mn><mo stretchy=\"false\">]</mo></mrow></math>"
        },
        {
          "label": "Shared opponent residual",
          "latex": "r_j=W_o\\operatorname{GELU}(W_h[t_j;m_j]+b_h)+b_o,\\quad t_j^{\\prime}=t_j+r_j,\\quad W_o^{(0)}=b_o^{(0)}=0",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>r</mi><mi>j</mi></msub><mo>&#x0003D;</mo><msub><mi>W</mi><mi>o</mi></msub><mo>GELU</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>W</mi><mi>h</mi></msub><mo stretchy=\"false\">[</mo><msub><mi>t</mi><mi>j</mi></msub><mi>;</mi><msub><mi>m</mi><mi>j</mi></msub><mo stretchy=\"false\">]</mo><mo>&#x0002B;</mo><msub><mi>b</mi><mi>h</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002B;</mo><msub><mi>b</mi><mi>o</mi></msub><mo>&#x0002C;</mo><mspace width=\"1em\" /><msubsup><mi>t</mi><mi>j</mi><mrow><mi>&#x02032;</mi></mrow></msubsup><mo>&#x0003D;</mo><msub><mi>t</mi><mi>j</mi></msub><mo>&#x0002B;</mo><msub><mi>r</mi><mi>j</mi></msub><mo>&#x0002C;</mo><mspace width=\"1em\" /><msubsup><mi>W</mi><mi>o</mi><mrow><mo stretchy=\"false\">&#x00028;</mo><mn>0</mn><mo stretchy=\"false\">&#x00029;</mo></mrow></msubsup><mo>&#x0003D;</mo><msubsup><mi>b</mi><mi>o</mi><mrow><mo stretchy=\"false\">&#x00028;</mo><mn>0</mn><mo stretchy=\"false\">&#x00029;</mo></mrow></msubsup><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
        },
        {
          "label": "Critic state assembly",
          "latex": "x=[c_{\\mathrm{candidate}};p_{\\mathrm{opponent}};c_{\\mathrm{board,hand,public}};p_{\\mathrm{route}};p_{\\mathrm{completion}};d_{0:3}]",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mi>x</mi><mo>&#x0003D;</mo><mo stretchy=\"false\">[</mo><msub><mi>c</mi><mrow><mrow><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">d</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">d</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">e</mi></mrow></mrow></msub><mi>;</mi><msub><mi>p</mi><mrow><mrow><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">t</mi></mrow></mrow></msub><mi>;</mi><msub><mi>c</mi><mrow><mrow><mi mathvariant=\"normal\">b</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">d</mi><mo>&#x0002C;</mo><mi mathvariant=\"normal\">h</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">d</mi><mo>&#x0002C;</mo><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">b</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">c</mi></mrow></mrow></msub><mi>;</mi><msub><mi>p</mi><mrow><mrow><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">e</mi></mrow></mrow></msub><mi>;</mi><msub><mi>p</mi><mrow><mrow><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">m</mi><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">n</mi></mrow></mrow></msub><mi>;</mi><msub><mi>d</mi><mrow><mn>0</mn><mi>:</mi><mn>3</mn></mrow></msub><mo stretchy=\"false\">]</mo></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "t_j",
          "meaning": "Existing opponent token, 64 channels; self token does not receive this residual.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>t</mi><mi>j</mi></msub></mrow></math>"
        },
        {
          "symbol": "m_j",
          "meaning": "147 probability moments aligned to opponent j; count variance clamped nonnegative.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>m</mi><mi>j</mi></msub></mrow></math>"
        },
        {
          "symbol": "H_\\epsilon(p)=-\\sum_i p_i\\log\\max(p_i,10^{-6})",
          "meaning": "Log-floored categorical entropy; division by log 4 normalizes the shanten entropy feature. Deterministic endpoints remain zero.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>H</mi><mi>&#x003F5;</mi></msub><mo stretchy=\"false\">&#x00028;</mo><mi>p</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0003D;</mo><mo>&#x02212;</mo><msub><mo>&#x02211;</mo><mi>i</mi></msub><msub><mi>p</mi><mi>i</mi></msub><mi>log</mi><mo>max</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>p</mi><mi>i</mi></msub><mo>&#x0002C;</mo><msup><mn>10</mn><mrow><mo>&#x02212;</mo><mn>6</mn></mrow></msup><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        },
        {
          "symbol": "p_s",
          "meaning": "Four-class shanten probability vector for one opponent.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>p</mi><mi>s</mi></msub></mrow></math>"
        },
        {
          "symbol": "p_{u\\mid s}",
          "meaning": "34 conditional improving-tile probabilities for each shanten class.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>p</mi><mrow><mi>u</mi><mo>&#x02223;</mo><mi>s</mi></mrow></msub></mrow></math>"
        },
        {
          "symbol": "c",
          "meaning": "Held count in 0…4 for each of 37 physical tile codes.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>c</mi></mrow></math>"
        }
      ],
      "source": {
        "path": "model/critic.py",
        "line": 677
      }
    },
    {
      "id": "candidate-ron-factorization",
      "title": "Structural wait and ron eligibility",
      "description": "A shared opponent eligibility MLP reads the board, attached yaku hidden evidence and detached ron-yaku probabilities. Detached structural wait conditions eligibility; observed ron labels supervise the supported product.",
      "equations": [
        {
          "label": "Joint structural wait",
          "latex": "w_{j,t}=P(s_j=0)P(u_{j,t}=1\\mid s_j=0)",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>w</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>t</mi></mrow></msub><mo>&#x0003D;</mo><mi>P</mi><mo stretchy=\"false\">&#x00028;</mo><msub><mi>s</mi><mi>j</mi></msub><mo>&#x0003D;</mo><mn>0</mn><mo stretchy=\"false\">&#x00029;</mo><mi>P</mi><mo stretchy=\"false\">&#x00028;</mo><msub><mi>u</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>t</mi></mrow></msub><mo>&#x0003D;</mo><mn>1</mn><mo>&#x02223;</mo><msub><mi>s</mi><mi>j</mi></msub><mo>&#x0003D;</mo><mn>0</mn><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        },
        {
          "label": "Supported ron probability",
          "latex": "p_{j,a}=m_{j,a}\\,\\operatorname{sg}(w_{j,t(a)})\\,\\sigma(e_{j,t(a)})",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>p</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>a</mi></mrow></msub><mo>&#x0003D;</mo><msub><mi>m</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>a</mi></mrow></msub><mspace width=\"0.167em\" /><mo>sg</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>w</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>t</mi><mo stretchy=\"false\">&#x00028;</mo><mi>a</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></msub><mo stretchy=\"false\">&#x00029;</mo><mspace width=\"0.167em\" /><mi>&#x003C3;</mi><mo stretchy=\"false\">&#x00028;</mo><msub><mi>e</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>t</mi><mo stretchy=\"false\">&#x00028;</mo><mi>a</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></msub><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        },
        {
          "label": "Stable product logit on supported rows",
          "latex": "\\ell_{j,a}=-\\operatorname{logsumexp}(-\\ell^{w}_{j,t(a)},-e_{j,t(a)},-\\ell^{w}_{j,t(a)}-e_{j,t(a)})",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>&#x02113;</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>a</mi></mrow></msub><mo>&#x0003D;</mo><mo>&#x02212;</mo><mo>logsumexp</mo><mo stretchy=\"false\">&#x00028;</mo><mo>&#x02212;</mo><msubsup><mi>&#x02113;</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>t</mi><mo stretchy=\"false\">&#x00028;</mo><mi>a</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mi>w</mi></mrow></msubsup><mo>&#x0002C;</mo><mo>&#x02212;</mo><msub><mi>e</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>t</mi><mo stretchy=\"false\">&#x00028;</mo><mi>a</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></msub><mo>&#x0002C;</mo><mo>&#x02212;</mo><msubsup><mi>&#x02113;</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>t</mi><mo stretchy=\"false\">&#x00028;</mo><mi>a</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mrow><mi>w</mi></mrow></msubsup><mo>&#x02212;</mo><msub><mi>e</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>t</mi><mo stretchy=\"false\">&#x00028;</mo><mi>a</mi><mo stretchy=\"false\">&#x00029;</mo></mrow></msub><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "m_{j,a}",
          "meaning": "Discard-decision support excluding public guaranteed-safe tiles; unsupported logits are −10000.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>m</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>a</mi></mrow></msub></mrow></math>"
        },
        {
          "symbol": "e_{j,t}",
          "meaning": "Shared 599→128 GELU→34 opponent eligibility from board512, attached yaku hidden64 and detached ron-yaku probabilities23; inherited by hypothetical calls.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>e</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>t</mi></mrow></msub></mrow></math>"
        },
        {
          "symbol": "\\ell^w",
          "meaning": "Stable joint structural-wait logits derived from shanten and conditional improving logits.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msup><mi>&#x02113;</mi><mi>w</mi></msup></mrow></math>"
        }
      ],
      "source": {
        "path": "model/candidate_predictions.py",
        "line": 25
      }
    },
    {
      "id": "shared-opponent-shanten",
      "title": "Shared opponent shanten head",
      "description": "One readout parameter set across opponents; public evidence distinguishes their representations.",
      "equations": [
        {
          "label": "Board prior and local evidence",
          "latex": "z_j=W_o\\operatorname{GELU}(W_bh+W_xo_j+b_x)+b_o\\in\\mathbb R^4,\\quad W_o^{(0)}=b_o^{(0)}=0",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>z</mi><mi>j</mi></msub><mo>&#x0003D;</mo><msub><mi>W</mi><mi>o</mi></msub><mo>GELU</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>W</mi><mi>b</mi></msub><mi>h</mi><mo>&#x0002B;</mo><msub><mi>W</mi><mi>x</mi></msub><msub><mi>o</mi><mi>j</mi></msub><mo>&#x0002B;</mo><msub><mi>b</mi><mi>x</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002B;</mo><msub><mi>b</mi><mi>o</mi></msub><mo>&#x02208;</mo><msup><mi mathvariant=\"double-struck\">R</mi><mn>4</mn></msup><mo>&#x0002C;</mo><mspace width=\"1em\" /><msubsup><mi>W</mi><mi>o</mi><mrow><mo stretchy=\"false\">&#x00028;</mo><mn>0</mn><mo stretchy=\"false\">&#x00029;</mo></mrow></msubsup><mo>&#x0003D;</mo><msubsup><mi>b</mi><mi>o</mi><mrow><mo stretchy=\"false\">&#x00028;</mo><mn>0</mn><mo stretchy=\"false\">&#x00029;</mo></mrow></msubsup><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "h",
          "meaning": "512-channel refined shared belief state.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>h</mi></mrow></math>"
        },
        {
          "symbol": "o_j",
          "meaning": "305 local channels: existing river summary 256 plus 49 public facts (meld/dealer/riichi/discard/wall/last-tedashi).",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>o</mi><mi>j</mi></msub></mrow></math>"
        },
        {
          "symbol": "W_b,W_x,W_o",
          "meaning": "512→48 bias-free prior,305→48 local observation map and shared48→4 output map.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>W</mi><mi>b</mi></msub><mo>&#x0002C;</mo><msub><mi>W</mi><mi>x</mi></msub><mo>&#x0002C;</mo><msub><mi>W</mi><mi>o</mi></msub></mrow></math>"
        }
      ],
      "source": {
        "path": "model/beliefs.py",
        "line": 276
      }
    },
    {
      "id": "completion-evidence",
      "title": "Opponent-only completion conditioning",
      "description": "A shared residual of observed and inferred tile summaries adjusts opponent yaku logits before deterministic support. Self completion uses its base readout. Projected counts enter as detached evidence. The score coupling uses detached yaku probabilities.",
      "equations": [
        {
          "label": "Physical-tile summaries",
          "latex": "\\phi(v)=[S^{\\mathsf T}v/14;S^{\\mathsf T}(d\\odot v)/14;v_{34:37}],\\quad e_j=[\\phi(v_{\\mathrm{own}});\\phi(v_{\\mathrm{supply}});\\phi(\\mathbb E[c_j])]",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mi>&#x003D5;</mi><mo stretchy=\"false\">&#x00028;</mo><mi>v</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0003D;</mo><mo stretchy=\"false\">[</mo><msup><mi>S</mi><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mi>v</mi><mo>&#x0002F;</mo><mn>14</mn><mi>;</mi><msup><mi>S</mi><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msup><mo stretchy=\"false\">&#x00028;</mo><mi>d</mi><mo>&#x02299;</mo><mi>v</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002F;</mo><mn>14</mn><mi>;</mi><msub><mi>v</mi><mrow><mn>34</mn><mi>:</mi><mn>37</mn></mrow></msub><mo stretchy=\"false\">]</mo><mo>&#x0002C;</mo><mspace width=\"1em\" /><msub><mi>e</mi><mi>j</mi></msub><mo>&#x0003D;</mo><mo stretchy=\"false\">[</mo><mi>&#x003D5;</mi><mo stretchy=\"false\">&#x00028;</mo><msub><mi>v</mi><mrow><mrow><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">w</mi><mi mathvariant=\"normal\">n</mi></mrow></mrow></msub><mo stretchy=\"false\">&#x00029;</mo><mi>;</mi><mi>&#x003D5;</mi><mo stretchy=\"false\">&#x00028;</mo><msub><mi>v</mi><mrow><mrow><mi mathvariant=\"normal\">s</mi><mi mathvariant=\"normal\">u</mi><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">y</mi></mrow></mrow></msub><mo stretchy=\"false\">&#x00029;</mo><mi>;</mi><mi>&#x003D5;</mi><mo stretchy=\"false\">&#x00028;</mo><mi mathvariant=\"double-struck\">E</mi><mo stretchy=\"false\">[</mo><msub><mi>c</mi><mi>j</mi></msub><mo stretchy=\"false\">]</mo><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">]</mo></mrow></math>"
        },
        {
          "label": "Opponent-only raw-logit residual",
          "latex": "\\Delta_j=W_o\\operatorname{GELU}(W_h[e_j;r_j]+b_h)+b_o,\\quad z_j^{\\prime}=z_j+\\Delta_j,\\quad z_0^{\\prime}=z_0,\\quad W_o^{(0)}=b_o^{(0)}=0",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>&#x00394;</mi><mi>j</mi></msub><mo>&#x0003D;</mo><msub><mi>W</mi><mi>o</mi></msub><mo>GELU</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>W</mi><mi>h</mi></msub><mo stretchy=\"false\">[</mo><msub><mi>e</mi><mi>j</mi></msub><mi>;</mi><msub><mi>r</mi><mi>j</mi></msub><mo stretchy=\"false\">]</mo><mo>&#x0002B;</mo><msub><mi>b</mi><mi>h</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002B;</mo><msub><mi>b</mi><mi>o</mi></msub><mo>&#x0002C;</mo><mspace width=\"1em\" /><msubsup><mi>z</mi><mi>j</mi><mrow><mi>&#x02032;</mi></mrow></msubsup><mo>&#x0003D;</mo><msub><mi>z</mi><mi>j</mi></msub><mo>&#x0002B;</mo><msub><mi>&#x00394;</mi><mi>j</mi></msub><mo>&#x0002C;</mo><mspace width=\"1em\" /><msubsup><mi>z</mi><mn>0</mn><mrow><mi>&#x02032;</mi></mrow></msubsup><mo>&#x0003D;</mo><msub><mi>z</mi><mn>0</mn></msub><mo>&#x0002C;</mo><mspace width=\"1em\" /><msubsup><mi>W</mi><mi>o</mi><mrow><mo stretchy=\"false\">&#x00028;</mo><mn>0</mn><mo stretchy=\"false\">&#x00029;</mo></mrow></msubsup><mo>&#x0003D;</mo><msubsup><mi>b</mi><mi>o</mi><mrow><mo stretchy=\"false\">&#x00028;</mo><mn>0</mn><mo stretchy=\"false\">&#x00029;</mo></mrow></msubsup><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "v",
          "meaning": "37 physical-code counts: 34 ordinary tile codes plus three red-five codes.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>v</mi></mrow></math>"
        },
        {
          "symbol": "S",
          "meaning": "37×4 suit/honor membership; red fives use their numbered suit.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>S</mi></mrow></math>"
        },
        {
          "symbol": "d",
          "meaning": "Ordinary dora multiplicity by base tile, repeated for red-five codes.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>d</mi></mrow></math>"
        },
        {
          "symbol": "c_j",
          "meaning": "Projected five-class held count per physical tile for opponent j, including known exposed meld copies.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>c</mi><mi>j</mi></msub></mrow></math>"
        },
        {
          "symbol": "r_j",
          "meaning": "Existing per-opponent river summary with 256 channels.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>r</mi><mi>j</mi></msub></mrow></math>"
        },
        {
          "symbol": "z_j",
          "meaning": "46 yaku raw logits per opponent; constrained afterward.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>z</mi><mi>j</mi></msub></mrow></math>"
        }
      ],
      "source": {
        "path": "model/beliefs.py",
        "line": 336
      }
    },
    {
      "id": "count-projection-solver",
      "title": "Bounded count-projection dual updates",
      "description": "Monotone log1p-scaled Newton updates for the weighted KL projection; implicit gradients use the constrained solution rather than differentiating iteration history.",
      "equations": [
        {
          "label": "Bounded scalar dual step",
          "latex": "\\delta(r,v)=\\frac{\\operatorname{sign}(n)}4\\log(1+4|n|),\\quad n=\\frac{r}{\\max(v,10^{-7})}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mi>&#x003B4;</mi><mo stretchy=\"false\">&#x00028;</mo><mi>r</mi><mo>&#x0002C;</mo><mi>v</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0003D;</mo><mfrac><mrow><mo>sign</mo><mo stretchy=\"false\">&#x00028;</mo><mi>n</mi><mo stretchy=\"false\">&#x00029;</mo></mrow><mn>4</mn></mfrac><mi>log</mi><mo stretchy=\"false\">&#x00028;</mo><mn>1</mn><mo>&#x0002B;</mo><mn>4</mn><mo stretchy=\"false\">&#x0007C;</mo><mi>n</mi><mo stretchy=\"false\">&#x0007C;</mo><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002C;</mo><mspace width=\"1em\" /><mi>n</mi><mo>&#x0003D;</mo><mfrac><mrow><mi>r</mi></mrow><mrow><mo>max</mo><mo stretchy=\"false\">&#x00028;</mo><mi>v</mi><mo>&#x0002C;</mo><msup><mn>10</mn><mrow><mo>&#x02212;</mo><mn>7</mn></mrow></msup><mo stretchy=\"false\">&#x00029;</mo></mrow></mfrac></mrow></math>"
        },
        {
          "label": "Alternating equality and capacity updates",
          "latex": "\\alpha_j\\leftarrow\\alpha_j+\\delta(S_j-\\sum_t\\mu_{jt},\\sum_t V_{jt}),\\quad\\beta_t\\leftarrow\\min(0,\\beta_t+\\delta(A_t-\\sum_j\\mu_{jt},\\sum_j V_{jt}))",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>&#x003B1;</mi><mi>j</mi></msub><mo>&#x02190;</mo><msub><mi>&#x003B1;</mi><mi>j</mi></msub><mo>&#x0002B;</mo><mi>&#x003B4;</mi><mo stretchy=\"false\">&#x00028;</mo><msub><mi>S</mi><mi>j</mi></msub><mo>&#x02212;</mo><munder><mo>&#x02211;</mo><mi>t</mi></munder><msub><mi>&#x003BC;</mi><mrow><mi>j</mi><mi>t</mi></mrow></msub><mo>&#x0002C;</mo><munder><mo>&#x02211;</mo><mi>t</mi></munder><msub><mi>V</mi><mrow><mi>j</mi><mi>t</mi></mrow></msub><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002C;</mo><mspace width=\"1em\" /><msub><mi>&#x003B2;</mi><mi>t</mi></msub><mo>&#x02190;</mo><mo>min</mo><mo stretchy=\"false\">&#x00028;</mo><mn>0</mn><mo>&#x0002C;</mo><msub><mi>&#x003B2;</mi><mi>t</mi></msub><mo>&#x0002B;</mo><mi>&#x003B4;</mi><mo stretchy=\"false\">&#x00028;</mo><msub><mi>A</mi><mi>t</mi></msub><mo>&#x02212;</mo><munder><mo>&#x02211;</mo><mi>j</mi></munder><msub><mi>&#x003BC;</mi><mrow><mi>j</mi><mi>t</mi></mrow></msub><mo>&#x0002C;</mo><munder><mo>&#x02211;</mo><mi>j</mi></munder><msub><mi>V</mi><mrow><mi>j</mi><mi>t</mi></mrow></msub><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "\\mu,V",
          "meaning": "Expected concealed count and count variance divided by the KL weight, recomputed after each block of dual updates.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>&#x003BC;</mi><mo>&#x0002C;</mo><mi>V</mi></mrow></math>"
        },
        {
          "symbol": "\\alpha,\\beta",
          "meaning": "Per-opponent size equality and per-tile shared-copy inequality multipliers; beta≤0.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>&#x003B1;</mi><mo>&#x0002C;</mo><mi>&#x003B2;</mi></mrow></math>"
        },
        {
          "symbol": "S,A",
          "meaning": "Required concealed hand sizes and available physical copies. Forward iteration stops at residual≤1e-5 or 2048 iterations; feasibility is checked to tolerance, not exact arithmetic.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>S</mi><mo>&#x0002C;</mo><mi>A</mi></mrow></math>"
        }
      ],
      "source": {
        "path": "model/beliefs.py",
        "line": 617
      }
    },
    {
      "id": "representation-ownership",
      "title": "Shared-representation gradient ownership",
      "description": "Shared lower encodings feed separate upper actor and critic/belief stacks. Policy gradients train the actor upper stack and stop before shared lower features. Belief and settlement objectives train their own upper stack and shared lower encodings. Predictions and actor Q remain detached at their consumers.",
      "equations": [
        {
          "label": "Detached consumer inputs",
          "latex": "h_\\pi=A_{\\psi}(\\operatorname{sg}([t;H_0])),\\quad h_Q=B_{\\theta}([t;H_0]),\\quad z_\\pi=[h_\\pi;\\operatorname{sg}(c);\\operatorname{sg}(p)],\\quad z_Q=[h_Q;c;r]",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>h</mi><mi>&#x003C0;</mi></msub><mo>&#x0003D;</mo><msub><mi>A</mi><mrow><mi>&#x003C8;</mi></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mo>sg</mo><mo stretchy=\"false\">&#x00028;</mo><mo stretchy=\"false\">[</mo><mi>t</mi><mi>;</mi><msub><mi>H</mi><mn>0</mn></msub><mo stretchy=\"false\">]</mo><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002C;</mo><mspace width=\"1em\" /><msub><mi>h</mi><mi>Q</mi></msub><mo>&#x0003D;</mo><msub><mi>B</mi><mrow><mi>&#x003B8;</mi></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mo stretchy=\"false\">[</mo><mi>t</mi><mi>;</mi><msub><mi>H</mi><mn>0</mn></msub><mo stretchy=\"false\">]</mo><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002C;</mo><mspace width=\"1em\" /><msub><mi>z</mi><mi>&#x003C0;</mi></msub><mo>&#x0003D;</mo><mo stretchy=\"false\">[</mo><msub><mi>h</mi><mi>&#x003C0;</mi></msub><mi>;</mi><mo>sg</mo><mo stretchy=\"false\">&#x00028;</mo><mi>c</mi><mo stretchy=\"false\">&#x00029;</mo><mi>;</mi><mo>sg</mo><mo stretchy=\"false\">&#x00028;</mo><mi>p</mi><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">]</mo><mo>&#x0002C;</mo><mspace width=\"1em\" /><msub><mi>z</mi><mi>Q</mi></msub><mo>&#x0003D;</mo><mo stretchy=\"false\">[</mo><msub><mi>h</mi><mi>Q</mi></msub><mi>;</mi><mi>c</mi><mi>;</mi><mi>r</mi><mo stretchy=\"false\">]</mo></mrow></math>"
        },
        {
          "label": "Encoder gradient ownership",
          "latex": "\\nabla_\\phi L_{\\mathrm{policy}}=0,\\quad\\nabla_\\theta L_{\\mathrm{policy}}=0,\\quad\\nabla_\\psi L_{\\mathrm{policy}}\\ne0,\\quad\\nabla_\\phi L_{\\mathrm{phase}}=\\nabla_\\phi(L_{\\mathrm{belief}}+\\lambda_{\\mathrm{belief}}C_{\\mathrm{belief}}+\\mathbb{1}_{\\mathrm{critic}}L_{\\mathrm{settlement}})",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mo>&#x02207;</mo><mi>&#x003D5;</mi></msub><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">y</mi></mrow></mrow></msub><mo>&#x0003D;</mo><mn>0</mn><mo>&#x0002C;</mo><mspace width=\"1em\" /><msub><mo>&#x02207;</mo><mi>&#x003B8;</mi></msub><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">y</mi></mrow></mrow></msub><mo>&#x0003D;</mo><mn>0</mn><mo>&#x0002C;</mo><mspace width=\"1em\" /><msub><mo>&#x02207;</mo><mi>&#x003C8;</mi></msub><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">o</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">y</mi></mrow></mrow></msub><mo>&#x02260;</mo><mn>0</mn><mo>&#x0002C;</mo><mspace width=\"1em\" /><msub><mo>&#x02207;</mo><mi>&#x003D5;</mi></msub><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">p</mi><mi mathvariant=\"normal\">h</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">s</mi><mi mathvariant=\"normal\">e</mi></mrow></mrow></msub><mo>&#x0003D;</mo><msub><mo>&#x02207;</mo><mi>&#x003D5;</mi></msub><mo stretchy=\"false\">&#x00028;</mo><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">b</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">f</mi></mrow></mrow></msub><mo>&#x0002B;</mo><msub><mi>&#x003BB;</mi><mrow><mrow><mi mathvariant=\"normal\">b</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">f</mi></mrow></mrow></msub><msub><mi>C</mi><mrow><mrow><mi mathvariant=\"normal\">b</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">f</mi></mrow></mrow></msub><mo>&#x0002B;</mo><msub><mrow><mn mathvariant=\"double-struck\">1</mn></mrow><mrow><mrow><mi mathvariant=\"normal\">c</mi><mi mathvariant=\"normal\">r</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">c</mi></mrow></mrow></msub><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">s</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">t</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">m</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">t</mi></mrow></mrow></msub><mo stretchy=\"false\">&#x00029;</mo></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "\\phi,h,c,r",
          "meaning": "Shared lower-encoder parameters, critic/belief board state, candidate state and opponent river summaries.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>&#x003D5;</mi><mo>&#x0002C;</mo><mi>h</mi><mo>&#x0002C;</mo><mi>c</mi><mo>&#x0002C;</mo><mi>r</mi></mrow></math>"
        },
        {
          "symbol": "L_{\\mathrm{belief}},C_{\\mathrm{belief}},\\lambda_{\\mathrm{belief}}",
          "meaning": "Seven supervised belief losses, their own structural constraints and phase constraint coefficient. Settlement loss and critic constraints also update the encoder during critic fitting; policy CE/MMD do not.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">b</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">f</mi></mrow></mrow></msub><mo>&#x0002C;</mo><msub><mi>C</mi><mrow><mrow><mi mathvariant=\"normal\">b</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">f</mi></mrow></mrow></msub><mo>&#x0002C;</mo><msub><mi>&#x003BB;</mi><mrow><mrow><mi mathvariant=\"normal\">b</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">l</mi><mi mathvariant=\"normal\">i</mi><mi mathvariant=\"normal\">e</mi><mi mathvariant=\"normal\">f</mi></mrow></mrow></msub></mrow></math>"
        },
        {
          "symbol": "\\psi",
          "meaning": "Private actor upper-encoder parameters.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>&#x003C8;</mi></mrow></math>"
        },
        {
          "symbol": "\\theta",
          "meaning": "Critic/belief upper-encoder parameters.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>&#x003B8;</mi></mrow></math>"
        }
      ],
      "source": {
        "path": "model/network.py",
        "line": 15
      }
    },
    {
      "id": "candidate-set-pooling",
      "title": "Actor attention across legal candidates",
      "description": "The actor context selects a weighted summary of the complete legal set without coupling critic candidate states.",
      "source": {
        "path": "model/actor.py",
        "line": 86
      },
      "equations": [
        {
          "label": "Actor query and detached candidate keys/values",
          "latex": "q_n=W_q\\operatorname{LN}(P_n)+b_q,\\quad [k_i,v_i]=[W_k\\operatorname{LN}(\\operatorname{stopgrad}(A_i))+b_k;W_v\\operatorname{LN}(\\operatorname{stopgrad}(A_i))+b_v]",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>q</mi><mi>n</mi></msub><mo>&#x0003D;</mo><msub><mi>W</mi><mi>q</mi></msub><mo>LN</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>P</mi><mi>n</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002B;</mo><msub><mi>b</mi><mi>q</mi></msub><mo>&#x0002C;</mo><mspace width=\"1em\" /><mo stretchy=\"false\">[</mo><msub><mi>k</mi><mi>i</mi></msub><mo>&#x0002C;</mo><msub><mi>v</mi><mi>i</mi></msub><mo stretchy=\"false\">]</mo><mo>&#x0003D;</mo><mo stretchy=\"false\">[</mo><msub><mi>W</mi><mi>k</mi></msub><mo>LN</mo><mo stretchy=\"false\">&#x00028;</mo><mo>stopgrad</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>A</mi><mi>i</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002B;</mo><msub><mi>b</mi><mi>k</mi></msub><mi>;</mi><msub><mi>W</mi><mi>v</mi></msub><mo>LN</mo><mo stretchy=\"false\">&#x00028;</mo><mo>stopgrad</mo><mo stretchy=\"false\">&#x00028;</mo><msub><mi>A</mi><mi>i</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002B;</mo><msub><mi>b</mi><mi>v</mi></msub><mo stretchy=\"false\">]</mo></mrow></math>"
        },
        {
          "label": "Decision-local attention",
          "latex": "\\alpha_{ni}=\\operatorname{softmax}_{i\\in\\mathcal C_n}(q_n^{\\mathsf T}k_i/\\sqrt{128}),\\quad c_n=\\sum_{i\\in\\mathcal C_n}\\alpha_{ni}v_i",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>&#x003B1;</mi><mrow><mi>n</mi><mi>i</mi></mrow></msub><mo>&#x0003D;</mo><msub><mo>softmax</mo><mrow><mi>i</mi><mo>&#x02208;</mo><msub><mi mathvariant=\"script\">C</mi><mi>n</mi></msub></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><msubsup><mi>q</mi><mi>n</mi><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msubsup><msub><mi>k</mi><mi>i</mi></msub><mo>&#x0002F;</mo><msqrt><mrow><mn>128</mn></mrow></msqrt><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002C;</mo><mspace width=\"1em\" /><msub><mi>c</mi><mi>n</mi></msub><mo>&#x0003D;</mo><munder><mo>&#x02211;</mo><mrow><mi>i</mi><mo>&#x02208;</mo><msub><mi mathvariant=\"script\">C</mi><mi>n</mi></msub></mrow></munder><msub><mi>&#x003B1;</mi><mrow><mi>n</mi><mi>i</mi></mrow></msub><msub><mi>v</mi><mi>i</mi></msub></mrow></math>"
        },
        {
          "label": "Actor residual",
          "latex": "P_n^{\\prime}=P_n+W_oc_n+b_o,\\quad W_o=b_o=0\\text{ at initialization}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msubsup><mi>P</mi><mi>n</mi><mrow><mi>&#x02032;</mi></mrow></msubsup><mo>&#x0003D;</mo><msub><mi>P</mi><mi>n</mi></msub><mo>&#x0002B;</mo><msub><mi>W</mi><mi>o</mi></msub><msub><mi>c</mi><mi>n</mi></msub><mo>&#x0002B;</mo><msub><mi>b</mi><mi>o</mi></msub><mo>&#x0002C;</mo><mspace width=\"1em\" /><msub><mi>W</mi><mi>o</mi></msub><mo>&#x0003D;</mo><msub><mi>b</mi><mi>o</mi></msub><mo>&#x0003D;</mo><mn>0</mn><mtext>&#x000A0;at&#x000A0;initialization</mtext></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "\\mathcal C_n",
          "meaning": "Complete legal candidate set for original decision n, including call-plus-discard actions.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi mathvariant=\"script\">C</mi><mi>n</mi></msub></mrow></math>"
        },
        {
          "symbol": "A_i,q_n,k_i,v_i,c_n",
          "meaning": "384-channel raw candidate; 128-channel actor query, key, value and attended context.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>A</mi><mi>i</mi></msub><mo>&#x0002C;</mo><msub><mi>q</mi><mi>n</mi></msub><mo>&#x0002C;</mo><msub><mi>k</mi><mi>i</mi></msub><mo>&#x0002C;</mo><msub><mi>v</mi><mi>i</mi></msub><mo>&#x0002C;</mo><msub><mi>c</mi><mi>n</mi></msub></mrow></math>"
        },
        {
          "symbol": "P_n",
          "meaning": "768-channel actor policy context.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>P</mi><mi>n</mi></msub></mrow></math>"
        }
      ]
    },
    {
      "id": "result-attention",
      "title": "Attention across critic result hypotheses",
      "description": "Within each candidate, all 49 role-pooled whole-event tokens attend to one another before event scoring and deposit conditioning. Exact support is applied afterward; the claim-score branch is separate.",
      "equations": [
        {
          "label": "Residual event attention",
          "latex": "\\widetilde V=V+W_o\\operatorname{MHA}_{4,16}(\\operatorname{LN}(V),\\operatorname{LN}(V)),\\quad V\\in\\mathbb R^{49\\times32},\\quad W_o^{(0)}=0",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><mover><mi>V</mi><mo>&#x0007E;</mo></mover><mo>&#x0003D;</mo><mi>V</mi><mo>&#x0002B;</mo><msub><mi>W</mi><mi>o</mi></msub><msub><mo>MHA</mo><mrow><mn>4</mn><mo>&#x0002C;</mo><mn>16</mn></mrow></msub><mo stretchy=\"false\">&#x00028;</mo><mo>LN</mo><mo stretchy=\"false\">&#x00028;</mo><mi>V</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002C;</mo><mo>LN</mo><mo stretchy=\"false\">&#x00028;</mo><mi>V</mi><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002C;</mo><mspace width=\"1em\" /><mi>V</mi><mo>&#x02208;</mo><msup><mi mathvariant=\"double-struck\">R</mi><mrow><mn>49</mn><mo>&#x000D7;</mo><mn>32</mn></mrow></msup><mo>&#x0002C;</mo><mspace width=\"1em\" /><msubsup><mi>W</mi><mi>o</mi><mrow><mo stretchy=\"false\">&#x00028;</mo><mn>0</mn><mo stretchy=\"false\">&#x00029;</mo></mrow></msubsup><mo>&#x0003D;</mo><mn>0</mn></mrow></math>"
        },
        {
          "label": "Shared event readout",
          "latex": "z_e=w_e^{\\mathsf T}\\widetilde v_e+b_e",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>z</mi><mi>e</mi></msub><mo>&#x0003D;</mo><msubsup><mi>w</mi><mi>e</mi><mrow><mi mathvariant=\"sans-serif\">T</mi></mrow></msubsup><msub><mover><mi>v</mi><mo>&#x0007E;</mo></mover><mi>e</mi></msub><mo>&#x0002B;</mo><msub><mi>b</mi><mi>e</mi></msub></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "V",
          "meaning": "49 role-pooled, 32-channel whole-event tokens from one candidate.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>V</mi></mrow></math>"
        },
        {
          "symbol": "\\widetilde v_e",
          "meaning": "Attention-refined event vector, also consumed by deposit conditioning.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mover><mi>v</mi><mo>&#x0007E;</mo></mover><mi>e</mi></msub></mrow></math>"
        },
        {
          "symbol": "\\operatorname{MHA}_{4,16}",
          "meaning": "Four attention heads, each with 16 key/value channels; output width is 32.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mo>MHA</mo><mrow><mn>4</mn><mo>&#x0002C;</mo><mn>16</mn></mrow></msub></mrow></math>"
        },
        {
          "symbol": "W_o",
          "meaning": "Bias-free 32→32 residual correction; zero initialized.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>W</mi><mi>o</mi></msub></mrow></math>"
        },
        {
          "symbol": "w_e,b_e",
          "meaning": "Existing shared affine event readout, 32→1.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>w</mi><mi>e</mi></msub><mo>&#x0002C;</mo><msub><mi>b</mi><mi>e</mi></msub></mrow></math>"
        }
      ],
      "source": {
        "path": "model/critic.py",
        "line": 741
      }
    },
    {
      "id": "exceptional-settlement",
      "title": "Pao and nagashi support",
      "description": "Conditional responsibility allocation and four constrained nagashi predictions share the exact settlement law.",
      "equations": [
        {
          "label": "Conditional pao allocation",
          "latex": "a_{j,p}=\\operatorname{softmax}_p z_{j,p},\\quad p=w_j\\text{ denotes ordinary allocation}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>a</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>p</mi></mrow></msub><mo>&#x0003D;</mo><msub><mo>softmax</mo><mi>p</mi></msub><msub><mi>z</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>p</mi></mrow></msub><mo>&#x0002C;</mo><mspace width=\"1em\" /><mi>p</mi><mo>&#x0003D;</mo><msub><mi>w</mi><mi>j</mi></msub><mtext>&#x000A0;denotes&#x000A0;ordinary&#x000A0;allocation</mtext></mrow></math>"
        },
        {
          "label": "Nagashi qualifier-set logit",
          "latex": "z_S=\\sum_{s\\in S}z_{s,\\mathrm{nagashi}},\\quad \\varnothing\\ne S\\subseteq\\{0,1,2,3\\}",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>z</mi><mi>S</mi></msub><mo>&#x0003D;</mo><munder><mo>&#x02211;</mo><mrow><mi>s</mi><mo>&#x02208;</mo><mi>S</mi></mrow></munder><msub><mi>z</mi><mrow><mi>s</mi><mo>&#x0002C;</mo><mrow><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">g</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">s</mi><mi mathvariant=\"normal\">h</mi><mi mathvariant=\"normal\">i</mi></mrow></mrow></msub><mo>&#x0002C;</mo><mspace width=\"1em\" /><mo>&#x02205;</mo><mo>&#x02260;</mo><mi>S</mi><mo>&#x02286;</mo><mo stretchy=\"false\">&#x0007B;</mo><mn>0</mn><mo>&#x0002C;</mo><mn>1</mn><mo>&#x0002C;</mo><mn>2</mn><mo>&#x0002C;</mo><mn>3</mn><mo stretchy=\"false\">&#x0007D;</mo></mrow></math>"
        },
        {
          "label": "Direct constrained nagashi loss",
          "latex": "L_{\\mathrm{nagashi}}=-\\frac14\\sum_{s=0}^3[y_s\\log P(s\\in S)+(1-y_s)\\log P(s\\notin S)]",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><mrow><msub><mi>L</mi><mrow><mrow><mi mathvariant=\"normal\">n</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">g</mi><mi mathvariant=\"normal\">a</mi><mi mathvariant=\"normal\">s</mi><mi mathvariant=\"normal\">h</mi><mi mathvariant=\"normal\">i</mi></mrow></mrow></msub><mo>&#x0003D;</mo><mo>&#x02212;</mo><mfrac><mn>1</mn><mn>4</mn></mfrac><munderover><mo>&#x02211;</mo><mrow><mi>s</mi><mo>&#x0003D;</mo><mn>0</mn></mrow><mn>3</mn></munderover><mo stretchy=\"false\">[</mo><msub><mi>y</mi><mi>s</mi></msub><mi>log</mi><mi>P</mi><mo stretchy=\"false\">&#x00028;</mo><mi>s</mi><mo>&#x02208;</mo><mi>S</mi><mo stretchy=\"false\">&#x00029;</mo><mo>&#x0002B;</mo><mo stretchy=\"false\">&#x00028;</mo><mn>1</mn><mo>&#x02212;</mo><msub><mi>y</mi><mi>s</mi></msub><mo stretchy=\"false\">&#x00029;</mo><mi>log</mi><mi>P</mi><mo stretchy=\"false\">&#x00028;</mo><mi>s</mi><mo>&#x02209;</mo><mi>S</mi><mo stretchy=\"false\">&#x00029;</mo><mo stretchy=\"false\">]</mo></mrow></math>"
        }
      ],
      "symbols": [
        {
          "symbol": "a_{j,p}",
          "meaning": "True-yakuman allocation mass for one winning claim, masked by public responsibility.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>a</mi><mrow><mi>j</mi><mo>&#x0002C;</mo><mi>p</mi></mrow></msub></mrow></math>"
        },
        {
          "symbol": "S",
          "meaning": "A nonempty subset of publicly eligible nagashi qualifiers; four outputs generate all 15 combinations.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><mi>S</mi></mrow></math>"
        },
        {
          "symbol": "y_s",
          "meaning": "Observed nagashi qualifier flag for one player.",
          "mathml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"inline\"><mrow><msub><mi>y</mi><mi>s</mi></msub></mrow></math>"
        }
      ],
      "source": {
        "path": "model/joint_settlement.py",
        "line": 624
      }
    }
  ],
  "vocabulary": [
    {
      "id": "tiles",
      "title": "Tile classes",
      "description": "0–8: 1 m–9 m; 9–17: 1 p–9 p; 18–26: 1 s–9 s; 27–30: East/South/West/North; 31–33: white/green/red dragons. The 37-class action vocabulary appends 34/35/36 for red 5 m/5 p/5 s."
    },
    {
      "id": "seats",
      "title": "Seat axes",
      "description": "Seat axis: self 0, next 1, opposite 2, previous 3; opponent axes omit 0. Shapes exclude batch; masks use 0/1."
    },
    {
      "id": "decision-and-post-call-boards",
      "title": "Decision and after-call positions",
      "description": "A decision position is what the acting player sees when choosing an action. An after-call position shows what that same player would see after one legal chi or pon, before the discard. Pass and open kan have no immediate discard. The critic keeps the original decision board for competing claims."
    },
    {
      "id": "candidate-slots",
      "title": "Critic action slots",
      "description": "0–36 discard; 37–110 riichi/discard; 111–259 response (pass plus chi/pon discard); 260–294 kan. Response policy adds open kan as choice 149; see ResponseKan mapping."
    },
    {
      "id": "yaku",
      "title": "Native yaku feasibility channels",
      "description": "0: tanyao, 1: haku, 2: hatsu, 3: chun, 4: round wind, 5: seat wind, 6: honitsu, 7: chinitsu, 8: toitoi, 9: chiitoitsu, 10: shousangen, 11: daisangen, 12: tsuuiisou, 13: chinroutou, 14: honroutou, 15: kokushi, 16: chanta, 17: junchan, 18: iipeikou. Binary public feasibility predicates; neither guaranteed score labels nor calibrated win marginals."
    },
    {
      "id": "completion-yaku",
      "title": "Completion yaku channels",
      "description": "0: pinfu, 1: tanyao, 2: iipeikou, 3: haku, 4: hatsu, 5: chun, 6: seat_wind, 7: round_wind, 8: sanshoku_doujun, 9: ittsuu, 10: chanta, 11: honroutou, 12: toitoi, 13: sanankou, 14: sankantsu, 15: sanshoku_doukou, 16: chiitoitsu, 17: shousangen, 18: honitsu, 19: junchan, 20: ryanpeikou, 21: chinitsu, 22: yakuman. Conditional next-tenpai completion labels, independently for ron and tsumo."
    },
    {
      "id": "precision",
      "title": "Numeric precision",
      "description": "Encoder construction uses mixed bfloat 16. Belief refinements, probability calculations, actor outputs, critic scoring and loss reductions use float 32 where declared. Native wire dtypes are listed per feature."
    },
    {
      "id": "source-scope",
      "title": "Source scope",
      "description": "Catalog provenance is the current source tree and its content digest. Production checkpoint parameters are not inspected. Frozen SavedModels retain their own computation graph and tensor contract."
    }
  ],
  "source_files": [
    {
      "path": "log_dataset/RECORDS.md",
      "text": "# Record contract\n\n[Build a dataset](README.md)\n\n## Training positions and sampling\n\nReserved evaluation games are excluded before deterministic train, validation\nand held-out partitioning. Historical ranks select all 9+ dan seats, 75% of\n8d seats and 50% of 7d seats. Other players still supply game context.\n\nForced moves supply replay context only. A riichi decision selects both the\ndeclaration and its discard. Staying dama also supplies an ordinary discard\nrow when multiple distinct cuts are legal. Declaration discards and subsequent\nlocked discards supply context only; optional wins and kans remain decisions.\nReplay reconstructs missed-win furiten before exposing ron choices. A passed\nron after riichi cannot create later ron-pass labels in that hand. A legal\nron declined on the last discard remains a win-pass row before an exhaustive\ndraw. Accepted calls censor other seats' losing claims, which are not labeled\nas passes.\n\nExpert imitation draws a corpus-sized budget per pass using 50% natural and\n50% focused examples. The raw reader remains natural; only the training loader\napplies emphasis. Integer `meta/focused_priority` supplies the focused stream\nand never enters model inputs. Stored placement-gap metadata from existing\ncorpora is inert: no loader selects, weights or requires it. There is no\nplacement-based pass or quota. Corpus counts retain their recorded metadata;\nraw inputs need not be rewritten merely to stop consuming a field.\n\nInitializer Monte Carlo pairs focused roots with natural-source roots, and\nmain-loop collection pairs targeted roots with unfiltered normal roots, both\n50/50 by root starts. All generated eligible descendants train normally.\n\nValidation uses a deterministic 1/16 decision sample from the natural\nvalidation partition, stored separately to avoid scanning training shards.\n[afk.py](afk.py) excludes hands with suspected inactivity: consecutive long\nall-tsumogiri hands, or long unforced tsumogiri runs ignoring improving draws\noutside tenpai and opponent riichi. These are behavioral heuristics; archives\nhave no timeout signal. A flagged hand is removed for every seat while other\nhands retain their context.\n\n## Features and labels\n\nThe `root-states/` sidecar stores complete native simulator states for retained\ntraining decisions, keyed by game, hand, decision index, actor and phase. These\nstates contain hidden information for simulation and never enter model inputs.\nThey preserve actual recorded opponent hands; wall randomization happens when\nforking. Loading regenerates pending public feature rows and accepted-call\nrows from the saved simulator state using the current feature producer;\nsaved legal actions, candidate order and decision indices remain unchanged.\nSaved sakigiri witnesses select roots only. Runtime initialization\nrequires the completed sidecar to match the dataset summary and input schema.\n\nThe [native engine](native_collection/README.md) extracts public features.\n[replay.py](replay.py) reconstructs decisions; [training_targets.py](training_targets.py)\nand [scoring.py](scoring.py) produce labels. Hidden hands and later outcomes\nare available to target generation, never to policy inputs.\n[records.py](records.py) defines label names, shapes and serialization.\n\nThe native schema contains 103 tensors and 8,966 bytes per row. Scores and\nranks use current seat-wind order; other seat axes are actor-relative. Each\nstate has a 16-slot bank for its current hand, ordinary discards and kans.\nThe native contract specifies tile sentinels and the 110-row scoring map.\n\nEvery record requires `feature/post_call`, a variable-length byte string.\nEach legal chi/pon entry contains one option byte (chi 0–2, pon 3) followed by\na complete row after the call, totaling 8,967 bytes. Other decisions store an\nempty string. Calls accompanying a ron decision remain available after a\ndeclined win. Open kan has no immediate discard state. Decode after local\nrow selection, concatenate the entries and construct their owner indices.\n\n`reference/dora_tile_id` and `reference/dora_valid` preserve five ordered\nindicator slots for a frozen reference policy, outside the learned feature\nschema. IDs are base-34 marker identities with zero-filled unused slots.\nThe decoder exposes them as `labels.reference_inputs`. Indicator order cannot\nbe recovered from dora multiplicities; `reference_schema` records this\nsideband separately.\n\nSettlement supervision includes `round_end_kind`, `round_end_source` and\n`round_end_tenpai`. The scalar int8 source is the actual ron discarder in\nactor-relative seats, shared by all simultaneous winners; it is `-1` for\nnon-ron endings. It disambiguates split pao payer roles and multi-ron honba\nallocation. These required targets never enter prediction features.\n\nBelief labels cover counterfactual ron, local yaku-route affinity, opponent\nconcealed counts, shanten, ukeire, completion yaku and completion han/fu.\n`candidate_yaku_affinity[16,3]` labels the local hand bank. Joint chi/pon\ncandidates are masked from parent-bank route supervision because their hands\nbelong to accepted-call states.\n\n`round_completion_yaku` and `round_completion_score` use a highest-point\nordinary ron/tsumo witness for the next observed tenpai shape. Completion\nscore includes actual declared riichi, visible dora and applicable menzen\ntsumo, without hypothetical ura, ippatsu or special-event bonuses. Recorded\nscore labels retain their four-seat evidence layout; the current completion\nscore head and loss consume only actor-relative seat zero. Yaku supervision\nstill covers all four seats. No record regeneration is required for this\noutput-head removal.\n\n[training_data.py](training_data.py) also stores `critic/bonus` and\n`critic/score`: categorical added-han labels and total-han/fu classes\nconditional on added han, retained as recorded scoring evidence. The current\ncritic does not consume these sidebands: observed terminal payments supervise\nits single total han/fu distribution through settlement likelihood. Recorded\nfuture scoring values are never encoder inputs.\n\nAction labels include `continuation_discard`. Metadata identifies the game,\nhand, decision, actor and partition; sampling sidebands remain separate.\n[sakigiri_regret.py](sakigiri_regret.py) supplies root-selection witnesses,\nnot restoration targets. `records.parse_batch` returns inputs and labels;\n`training_data.parse_batch` additionally returns critic supervision.\n\nConsumers validate schemas and scoring definitions against\n`dataset_summary.json`. Rebuild into a new directory after a contract change;\nediting metadata cannot convert existing records. See\n[model architecture](../model/ARCHITECTURE.md) for prediction meanings.\n\n## Prepared expert targets\n\nPrepared records preserve the human action, same-hand outcomes and seven\nbelief labels. `expert/mortal_action` is a required scalar int16 byte field\ncontaining Mortal's greedy choice in head-local action space. Decoding maps\nit to the global critic candidate ID, including joint call/discard and open\nkan actions.\n\nThe initializer performs three Q-weighted human imitation passes. Each stage\nalso trains observed settlement and belief losses. Settlement targets always\ndescribe the human action actually played.\nExpert weights compare the live learner's Q for the human action with its Q\nfor the recorded Mortal action; Q values are never cached.\n\nThe summary preserves `preparation.mortal_policy` provenance, source hashes,\npartition counts and validation exclusions. Minibatch updates use prepared\nchoices without running Mortal. The main-loop MMD reference is separate.\n\nFull-game ingestion corroborates an omitted fourth-riichi acceptance against\nthe next hand's scores and riichi pot before generating hand targets. It marks\nthe existing terminal event as a four-riichi abort and includes the missing\n1,000-point bank payment. Event indices and decision inputs stay unchanged.\nA fourth declaration interrupted before payment retains its unpaid stick;\nmissing or inconsistent score evidence is an error, never a masked target.\n",
      "sha256": "ce3b93a56522cd4b02d4e55187fcae6c2854b9c72fe295cac65040efb174dc1e"
    },
    {
      "path": "log_dataset/__init__.py",
      "text": "\"\"\"Recorded-game acquisition, labels, training records and readers.\"\"\"\n",
      "sha256": "9527eec4526e4a49eba77a8b3464a41b0d29be5425b9e5ba8474860a775ec0e0"
    },
    {
      "path": "log_dataset/__main__.py",
      "text": "\"\"\"Prepare source archives and build the joint training dataset.\"\"\"\n\nimport argparse\nimport fcntl\nimport json\nimport os\nimport pathlib\nimport types\n\nfrom log_dataset import download, player_ranks\n\n\ndef run(args):\n    root = pathlib.Path(args.output).resolve()\n    root.mkdir(parents=True, exist_ok=True)\n    with (root / \"pipeline.lock\").open(\"a\") as lock:\n        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)\n        plan = vars(args).copy()\n        del plan[\"workers\"]\n        for name in (\"archives\", \"databases\", \"output\", \"reserve\"):\n            if plan[name] is not None:\n                plan[name] = str(pathlib.Path(plan[name]).resolve())\n        plan[\"extra_archives\"] = [\n            str(pathlib.Path(path).resolve()) for path in args.extra_archives\n        ]\n        if (root / \"pipeline.json\").exists():\n            previous = json.loads((root / \"pipeline.json\").read_text())\n            if previous != plan:\n                raise ValueError(\"Dataset inputs changed; use a fresh output\")\n        else:\n            temporary = root / \"pipeline.json.partial\"\n            temporary.write_text(json.dumps(plan, indent=2) + \"\\n\")\n            temporary.replace(root / \"pipeline.json\")\n        archives = args.archives\n        if archives is None:\n            archives = root / \"downloads\"\n            download.run(archives)\n        if args.databases:\n            enriched = root / \"archives\"\n            if not (enriched / \"player_ranks.json\").exists():\n                player_ranks.run(archives, args.databases, enriched)\n            archives = enriched\n        # Record building is CPU work, including its spawned workers.\n        os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n        from log_dataset import training_data\n\n        training_data.run(\n            types.SimpleNamespace(\n                archives=str(archives),\n                extra_archives=args.extra_archives,\n                output=str(root / \"data\"),\n                reserve=args.reserve,\n                workers=args.workers,\n                limit_games=args.limit_games,\n            )\n        )\n\n\ndef main():\n    parser = argparse.ArgumentParser(description=__doc__)\n    parser.add_argument(\"--output\", required=True)\n    parser.add_argument(\n        \"--archives\",\n        help=\"Existing archives; omit to download pinned Houou logs\",\n    )\n    parser.add_argument(\n        \"--databases\",\n        help=\"Historical rank databases; omit for enriched archives\",\n    )\n    parser.add_argument(\"--extra-archives\", action=\"append\", default=[])\n    parser.add_argument(\"--reserve\", required=True)\n    parser.add_argument(\"--workers\", type=int, default=24)\n    parser.add_argument(\"--limit-games\", type=int)\n    args = parser.parse_args()\n    if args.archives is None and args.databases is None:\n        parser.error(\n            \"downloading archives requires --databases for rank enrichment\"\n        )\n    if args.workers < 1 or (\n        args.limit_games is not None and args.limit_games < 1\n    ):\n        parser.error(\"workers and limit-games must be positive\")\n    run(args)\n\n\nif __name__ == \"__main__\":\n    main()\n",
      "sha256": "935dbce2e1e0a161272a7de0b1894f1863af675a4a0b95cecb9b099e14caaeb0"
    },
    {
      "path": "log_dataset/afk.py",
      "text": "\"\"\"Conservative recorded behavioral evidence for excluding AFK rounds.\"\"\"\n\nimport numpy\n\nfrom log_dataset import replay\n\nfrom . import shanten\n\n\ndef suspected_afk_kyokus(rounds):\n    evidence = {}\n    streaks = [[] for _ in range(4)]\n    for number, events in enumerate(rounds):\n        state = replay.Replay.from_start(\"quality\", events[0])\n        runs = [[] for _ in range(4)]\n        held = [None] * 4\n        active = [False] * 4\n        all_discards = [[] for _ in range(4)]\n        candidates = []\n        for index, event in enumerate(events[1:], 1):\n            state.apply(event)\n            actor = event.get(\"actor\")\n            if event[\"type\"] == \"dahai\":\n                all_discards[actor].append(index)\n                if event[\"tsumogiri\"] and not state.declared[actor]:\n                    if not runs[actor]:\n                        held[actor] = state.concealed_counts(actor).copy()\n                    runs[actor].append(index)\n                else:\n                    if runs[actor]:\n                        candidates.append((actor, runs[actor], held[actor]))\n                    runs[actor] = []\n                    active[actor] = True\n            elif event[\"type\"] in {\n                \"reach\",\n                \"chi\",\n                \"pon\",\n                \"ankan\",\n                \"kakan\",\n                \"daiminkan\",\n                \"hora\",\n            }:\n                if runs[actor]:\n                    candidates.append((actor, runs[actor], held[actor]))\n                runs[actor] = []\n                active[actor] = True\n        candidates.extend(\n            (actor, runs[actor], held[actor])\n            for actor in range(4)\n            if runs[actor]\n        )\n        for actor, indices, counts in candidates:\n            if len(indices) < 12 or any(\n                event[\"type\"] == \"reach\" and event[\"actor\"] != actor\n                for event in events[: indices[-1] + 1]\n            ):\n                continue\n            distance = shanten.calculate_shanten(counts)\n            ignored = [\n                index\n                for index in indices\n                if shanten.calculate_shanten(\n                    counts\n                    + (\n                        numpy.arange(34)\n                        == shanten.base_id(events[index][\"pai\"])\n                    )\n                )\n                < distance\n            ]\n            if distance > 0 and len(ignored) >= 2:\n                evidence.setdefault(number, []).append(\n                    {\n                        \"actor\": actor,\n                        \"discards\": len(indices),\n                        \"held_shanten\": distance,\n                        \"event_indices\": indices,\n                        \"ignored_improving_draws\": ignored,\n                        \"rule\": \"midhand_tsumogiri\",\n                    }\n                )\n        for actor in range(4):\n            if not active[actor] and len(all_discards[actor]) >= 8:\n                streaks[actor].append((number, all_discards[actor]))\n                if len(streaks[actor]) >= 2:\n                    for previous, indices in streaks[actor]:\n                        if previous not in evidence:\n                            evidence[previous] = [\n                                {\n                                    \"actor\": actor,\n                                    \"discards\": len(indices),\n                                    \"event_indices\": indices,\n                                    \"rule\": \"whole_hand_tsumogiri\",\n                                }\n                            ]\n            else:\n                streaks[actor] = []\n    return evidence\n\n\ndef retained_hands(events):\n    \"\"\"Remove every player's decisions in a suspected AFK hand.\"\"\"\n    rounds = []\n    for event in events:\n        if event[\"type\"] == \"start_kyoku\":\n            rounds.append([])\n        if rounds and event[\"type\"] != \"end_game\":\n            rounds[-1].append(event)\n    excluded = suspected_afk_kyokus(rounds)\n    return [\n        hand for number, hand in enumerate(rounds) if number not in excluded\n    ]\n",
      "sha256": "cfd14ddda5ebc6a5ebcf348d01afaef91f1898a7af0af8652b5e59b6afab7376"
    },
    {
      "path": "log_dataset/archives.py",
      "text": "\"\"\"Validate and enumerate the rank-enriched training archives.\"\"\"\n\nimport dataclasses\nimport functools\nimport hashlib\nimport json\nimport pathlib\nimport re\nimport zipfile\n\nfrom . import player_ranks\n\n\n@dataclasses.dataclass\nclass Game:\n    game_id: str\n    archive: pathlib.Path\n    member: str\n\n\n@functools.lru_cache(maxsize=4)\ndef open_archive(path):\n    \"\"\"Worker-owned readers for immutable inputs; eviction closes readers.\"\"\"\n    return zipfile.ZipFile(path)\n\n\ndef games(archives, extra_archives=()):\n    \"\"\"Validate enriched archives and enumerate all eligible game members.\"\"\"\n    rank_summary = json.loads(\n        (pathlib.Path(archives) / \"player_ranks.json\").read_text()\n    )\n    if rank_summary[\"sampling\"] != player_ranks.SAMPLING:\n        raise ValueError(\"player rank sampling contract mismatch\")\n    game_list = []\n    for archive_path in sorted(pathlib.Path(archives).glob(\"*.zip\")):\n        with archive_path.open(\"rb\") as stream:\n            actual = hashlib.file_digest(stream, \"sha256\").hexdigest()\n        if actual != rank_summary[\"years\"][archive_path.stem][\"merged_sha256\"]:\n            raise ValueError(f\"rank archive mismatch: {archive_path.name}\")\n        with zipfile.ZipFile(archive_path) as archive:\n            for member in sorted(archive.namelist()):\n                match = re.search(r\"(20\\d{2})(\\d{2})(\\d{2})\", member)\n                if match and member.endswith((\".mjson\", \".jsonl\")):\n                    game_list.append(\n                        Game(\n                            game_id=pathlib.Path(member).stem,\n                            archive=archive_path,\n                            member=member,\n                        )\n                    )\n    if extra_archives:\n        rank_summary[\"supplemental\"] = []\n        for path in extra_archives:\n            extra_games, extra_summary = games(path)\n            game_list.extend(extra_games)\n            rank_summary[\"supplemental\"].append(\n                {\n                    \"archives\": str(pathlib.Path(path).resolve()),\n                    \"player_ranks\": extra_summary,\n                }\n            )\n    if len({game.game_id for game in game_list}) != len(game_list):\n        raise ValueError(\"duplicate game IDs across training archives\")\n    return game_list, rank_summary\n",
      "sha256": "eb144eaeaa740e307d9070e52fc77c5e9e2752756b994791b89d606eae055052"
    },
    {
      "path": "log_dataset/build_native_collection.py",
      "text": "\"\"\"Build the Linux native collector for the current Python interpreter.\"\"\"\n\nimport os\nimport pathlib\nimport shutil\nimport subprocess\nimport sys\n\n\ndef run():\n    root = pathlib.Path(__file__).resolve().parent.parent\n    target = pathlib.Path(\n        os.environ.get(\n            \"CARGO_TARGET_DIR\", root / \"log_dataset/native_collection/target\"\n        )\n    ).resolve()\n    subprocess.run(\n        [\n            \"cargo\",\n            \"build\",\n            \"--locked\",\n            \"--release\",\n            \"--manifest-path\",\n            str(root / \"log_dataset/native_collection/Cargo.toml\"),\n        ],\n        cwd=root,\n        env={\n            **os.environ,\n            \"PYO3_PYTHON\": sys.executable,\n            \"CARGO_TARGET_DIR\": str(target),\n        },\n        check=True,\n    )\n    destination = root / \"log_dataset/_native_collection.so\"\n    temporary = destination.with_suffix(\".so.tmp\")\n    shutil.copyfile(target / \"release/lib_native_collection.so\", temporary)\n    temporary.replace(destination)\n\n\nif __name__ == \"__main__\":\n    run()\n",
      "sha256": "83e775c349d97a6819bfec40daf9d7b6911e9372db32352bdc7f8c395f8a0380"
    },
    {
      "path": "log_dataset/call_states.py",
      "text": "\"\"\"Sparse accepted-call states alongside ordinary decision feature rows.\"\"\"\n\nimport numpy\n\nfrom log_dataset import _native_collection\n\nROW_DTYPE = numpy.dtype(\n    [\n        (name, spec[\"dtype\"], tuple(spec[\"shape\"]))\n        for name, spec in _native_collection.INPUTS.items()\n    ]\n)\nCALL_DTYPE = numpy.dtype([(\"option\", \"int8\"), (\"features\", ROW_DTYPE)])\nINPUTS = {\n    **_native_collection.INPUTS,\n    **{\n        \"post_call_\" + name: {**spec, \"shape\": [None, *spec[\"shape\"]]}\n        for name, spec in _native_collection.INPUTS.items()\n    },\n    \"post_call_owner\": {\"shape\": [None], \"dtype\": \"int32\"},\n    \"post_call_option\": {\"shape\": [None], \"dtype\": \"int32\"},\n}\n\n\ndef input_specs():\n    import tensorflow as tf\n\n    return {\n        name: tf.TensorSpec(\n            (\n                spec[\"shape\"]\n                if name.startswith(\"post_call_\")\n                else [None, *spec[\"shape\"]]\n            ),\n            spec[\"dtype\"],\n            name=name,\n        )\n        for name, spec in INPUTS.items()\n    }\n\n\ndef base(features):\n    return {name: features[name] for name in _native_collection.INPUTS}\n\n\ndef post(features):\n    return {\n        name: features[\"post_call_\" + name]\n        for name in _native_collection.INPUTS\n    }\n\n\ndef combine(features, calls, owner, option):\n    return {\n        **features,\n        **{\"post_call_\" + name: value for name, value in calls.items()},\n        \"post_call_owner\": owner,\n        \"post_call_option\": option,\n    }\n\n\ndef from_request(request):\n    rows = numpy.frombuffer(request[\"features\"], ROW_DTYPE)\n    calls = numpy.frombuffer(request[\"post_call_features\"], ROW_DTYPE)\n    return combine(\n        {name: rows[name].copy() for name in ROW_DTYPE.names},\n        {name: calls[name].copy() for name in ROW_DTYPE.names},\n        numpy.asarray(request[\"post_call_owner\"], dtype=\"int32\"),\n        numpy.frombuffer(request[\"post_call_option\"], dtype=\"uint8\").astype(\n            \"int32\"\n        ),\n    )\n\n\ndef batch(instances):\n    return concatenate(\n        [\n            combine(\n                {name: value[None] for name, value in base(row).items()},\n                post(row),\n                row[\"post_call_owner\"],\n                row[\"post_call_option\"],\n            )\n            for row in instances\n        ]\n    )\n\n\ndef concatenate(batches):\n    if not batches:\n        rows = numpy.empty(0, ROW_DTYPE)\n        return combine(\n            {name: rows[name] for name in ROW_DTYPE.names},\n            {name: rows[name] for name in ROW_DTYPE.names},\n            numpy.empty(0, dtype=\"int32\"),\n            numpy.empty(0, dtype=\"int32\"),\n        )\n    offsets = numpy.cumsum(\n        [0, *[len(next(iter(base(row).values()))) for row in batches[:-1]]],\n        dtype=\"int32\",\n    )\n    return combine(\n        {\n            name: numpy.concatenate([row[name] for row in batches])\n            for name in _native_collection.INPUTS\n        },\n        {\n            name: numpy.concatenate(\n                [row[\"post_call_\" + name] for row in batches]\n            )\n            for name in _native_collection.INPUTS\n        },\n        numpy.concatenate(\n            [\n                row[\"post_call_owner\"] + offset\n                for row, offset in zip(batches, offsets)\n            ]\n        ),\n        numpy.concatenate([row[\"post_call_option\"] for row in batches]),\n    )\n\n\ndef select(features, indices):\n    indices = numpy.asarray(indices, dtype=\"int64\")\n    owners = numpy.asarray(features[\"post_call_owner\"])\n    starts = numpy.searchsorted(owners, indices, side=\"left\")\n    ends = numpy.searchsorted(owners, indices, side=\"right\")\n    selected = numpy.concatenate(\n        [\n            numpy.empty(0, dtype=\"int64\"),\n            *[numpy.arange(start, end) for start, end in zip(starts, ends)],\n        ]\n    )\n    return combine(\n        {name: value[indices] for name, value in base(features).items()},\n        {name: value[selected] for name, value in post(features).items()},\n        numpy.repeat(numpy.arange(len(indices), dtype=\"int32\"), ends - starts),\n        features[\"post_call_option\"][selected],\n    )\n\n\ndef pack_numpy(features, packing):\n    return {\n        \"base\": packing.pack_numpy(base(features)),\n        \"post\": packing.pack_numpy(post(features)),\n        \"owner\": features[\"post_call_owner\"],\n        \"option\": features[\"post_call_option\"],\n    }\n\n\ndef pack(features, packing):\n    return {\n        \"base\": packing.pack(base(features)),\n        \"post\": packing.pack(post(features)),\n        \"owner\": features[\"post_call_owner\"],\n        \"option\": features[\"post_call_option\"],\n    }\n\n\ndef unpack(packed, packing):\n    return combine(\n        packing.unpack(packed[\"base\"]),\n        packing.unpack(packed[\"post\"]),\n        packed[\"owner\"],\n        packed[\"option\"],\n    )\n\n\ndef serialize(features):\n    calls = numpy.empty(len(features[\"post_call_owner\"]), CALL_DTYPE)\n    calls[\"option\"] = features[\"post_call_option\"]\n    for name, value in post(features).items():\n        calls[\"features\"][name] = value\n    return calls.tobytes()\n\n\ndef decode(serialized):\n    import tensorflow as tf\n\n    lengths = tf.strings.length(serialized, unit=\"BYTE\")\n    counts = lengths // CALL_DTYPE.itemsize\n    with tf.control_dependencies(\n        [\n            tf.debugging.assert_equal(\n                counts * CALL_DTYPE.itemsize,\n                lengths,\n                message=\"Post-call record width mismatch; rebuild from source logs\",\n            )\n        ]\n    ):\n        raw = tf.reshape(\n            tf.io.decode_raw(tf.strings.reduce_join(serialized), tf.int8),\n            [-1, CALL_DTYPE.itemsize],\n        )\n    calls = {}\n    for name, (dtype, offset) in ROW_DTYPE.fields.items():\n        spec = _native_collection.INPUTS[name]\n        bytes_ = raw[:, 1 + offset : 1 + offset + dtype.itemsize]\n        scalar = tf.as_dtype(spec[\"dtype\"])\n        if scalar.size > 1:\n            bytes_ = tf.bitcast(\n                tf.reshape(\n                    bytes_, [-1, dtype.itemsize // scalar.size, scalar.size]\n                ),\n                scalar,\n            )\n        calls[\"post_call_\" + name] = tf.reshape(bytes_, [-1, *spec[\"shape\"]])\n    return {\n        **calls,\n        \"post_call_owner\": tf.repeat(tf.range(tf.size(counts)), counts),\n        \"post_call_option\": tf.cast(raw[:, 0], tf.int32),\n    }\n\n\ndef packed_select(packed, indices):\n    indices = numpy.asarray(indices, dtype=\"int64\")\n    starts = numpy.searchsorted(packed[\"owner\"], indices, side=\"left\")\n    ends = numpy.searchsorted(packed[\"owner\"], indices, side=\"right\")\n    selected = numpy.concatenate(\n        [\n            numpy.empty(0, dtype=\"int64\"),\n            *[numpy.arange(start, end) for start, end in zip(starts, ends)],\n        ]\n    )\n    return {\n        \"base\": {\n            name: value[indices] for name, value in packed[\"base\"].items()\n        },\n        \"post\": {\n            name: value[selected] for name, value in packed[\"post\"].items()\n        },\n        \"owner\": numpy.repeat(\n            numpy.arange(len(indices), dtype=\"int32\"), ends - starts\n        ),\n        \"option\": packed[\"option\"][selected],\n    }\n\n\ndef packed_concatenate(batches):\n    offsets = numpy.cumsum(\n        [0, *[len(next(iter(row[\"base\"].values()))) for row in batches[:-1]]],\n        dtype=\"int32\",\n    )\n    return {\n        group: {\n            name: numpy.concatenate([row[group][name] for row in batches])\n            for name in batches[0][group]\n        }\n        for group in (\"base\", \"post\")\n    } | {\n        \"owner\": numpy.concatenate(\n            [row[\"owner\"] + offset for row, offset in zip(batches, offsets)]\n        ),\n        \"option\": numpy.concatenate([row[\"option\"] for row in batches]),\n    }\n\n\ndef tensor_packed_select(packed, indices):\n    import tensorflow as tf\n\n    groups = tf.RaggedTensor.from_value_rowids(\n        tf.range(tf.size(packed[\"owner\"])),\n        tf.cast(packed[\"owner\"], tf.int64),\n        nrows=tf.cast(\n            tf.shape(next(iter(packed[\"base\"].values())))[0], tf.int64\n        ),\n    )\n    selected = tf.gather(groups, indices)\n    return {\n        \"base\": {\n            name: tf.gather(value, indices)\n            for name, value in packed[\"base\"].items()\n        },\n        \"post\": {\n            name: tf.gather(value, selected.flat_values)\n            for name, value in packed[\"post\"].items()\n        },\n        \"owner\": tf.cast(selected.value_rowids(), tf.int32),\n        \"option\": tf.gather(packed[\"option\"], selected.flat_values),\n    }\n\n\ndef flatten(packed):\n    return {\n        group + \"/\" + name: value\n        for group in (\"base\", \"post\")\n        for name, value in packed[group].items()\n    } | {\"owner\": packed[\"owner\"], \"option\": packed[\"option\"]}\n\n\ndef unflatten(arrays):\n    return {\n        group: {\n            name.removeprefix(group + \"/\"): value\n            for name, value in arrays.items()\n            if name.startswith(group + \"/\")\n        }\n        for group in (\"base\", \"post\")\n    } | {\"owner\": arrays[\"owner\"], \"option\": arrays[\"option\"]}\n",
      "sha256": "7125944846e4b4efd63e4ad9b01ebad111c768b3b779394dc21ba01555a028b0"
    },
    {
      "path": "log_dataset/download.py",
      "text": "\"\"\"Download and verify the fixed Houou MJAI corpus.\"\"\"\n\nimport hashlib\nimport json\nimport pathlib\nimport shutil\nimport urllib.request\nimport zipfile\n\nHOUOU_MJAI_RELEASE = \"https://github.com/NikkeTryHard/tenhou-to-mjai/\"\nHOUOU_MJAI_ARCHIVES = {\n    2024: (\n        HOUOU_MJAI_RELEASE + \"releases/download/v2.0.0/2024.zip\",\n        \"4c0bb20ebdc263ab5819d848b620f6bf36304ccb70914722fd89b524be3afa1f\",\n    ),\n    2025: (\n        HOUOU_MJAI_RELEASE + \"releases/download/v2.0.0/2025.zip\",\n        \"0274e3f2a3b4ed32cd9af6d0f9895c061c5141e63bb6c90e561f349043b7a771\",\n    ),\n}\n\n\ndef file_checksum(path):\n    with open(path, \"rb\") as input_file:\n        return hashlib.file_digest(input_file, \"sha256\").hexdigest()\n\n\ndef validate_archive(path, expected_checksum):\n    summary_path = path.parent / \"player_ranks.json\"\n    if summary_path.exists():\n        summary = json.loads(summary_path.read_text())[\"years\"][path.stem]\n        if summary[\"archive_sha256\"] != expected_checksum:\n            raise ValueError(f\"source SHA256 mismatch: {path}\")\n        expected_checksum = summary[\"merged_sha256\"]\n    if file_checksum(path) != expected_checksum:\n        raise ValueError(f\"SHA256 mismatch: {path}\")\n    with zipfile.ZipFile(path) as archive:\n        names = archive.namelist()\n        if not names or any(not name.endswith(\".mjson\") for name in names):\n            raise ValueError(f\"Expected a nonempty MJAI archive: {path}\")\n\n\ndef fetch_archive(output, year):\n    path = output / f\"{year}.zip\"\n    part_path = output / f\".{year}.zip.part\"\n    url, expected_checksum = HOUOU_MJAI_ARCHIVES[year]\n    if path.exists():\n        validate_archive(path, expected_checksum)\n        return path\n    if part_path.exists() and file_checksum(part_path) == expected_checksum:\n        validate_archive(part_path, expected_checksum)\n        part_path.replace(path)\n        return path\n    offset = part_path.stat().st_size if part_path.exists() else 0\n    request = urllib.request.Request(\n        url,\n        headers={\n            \"User-Agent\": \"nejimakidori-model/1\",\n            **({\"Range\": f\"bytes={offset}-\"} if offset else {}),\n        },\n    )\n    with urllib.request.urlopen(request, timeout=60) as response:\n        append = offset > 0 and response.status == 206\n        if response.status == 206 and not response.headers[\n            \"Content-Range\"\n        ].startswith(f\"bytes {offset}-\"):\n            raise ValueError(f\"Incorrect download resume offset: {url}\")\n        with part_path.open(\"ab\" if append else \"wb\") as output_file:\n            shutil.copyfileobj(response, output_file, length=1024 * 1024)\n    validate_archive(part_path, expected_checksum)\n    part_path.replace(path)\n    return path\n\n\ndef run(output):\n    \"\"\"Return verified archive paths, resuming interrupted downloads.\"\"\"\n    output = pathlib.Path(output).resolve()\n    output.mkdir(parents=True, exist_ok=True)\n    if (output / \"player_ranks.json\").exists():\n        paths = [output / f\"{year}.zip\" for year in HOUOU_MJAI_ARCHIVES]\n        for path in paths:\n            validate_archive(path, HOUOU_MJAI_ARCHIVES[int(path.stem)][1])\n        return paths\n    return [fetch_archive(output, year) for year in HOUOU_MJAI_ARCHIVES]\n",
      "sha256": "fe2467dddd6c57e1e2f9b27052f64f3e799b8b3bdf8eadb02fb9f66ba054b066"
    },
    {
      "path": "log_dataset/features.py",
      "text": "\"\"\"Public decision tensors and deterministic post-action hand banks.\"\"\"\n\nimport json\n\nimport numpy\nimport riichienv\n\nfrom log_dataset import _native_collection, call_states, shanten\n\nPHASES = {\"DISCARD\": 0, \"RESPONSE\": 1, \"KAN\": 2, \"RIICHI\": 3, \"WIN\": 4}\n\n\ndef native_tile_code(tile):\n    return 34 + (tile // 4) // 9 if tile in (16, 52, 88) else tile // 4\n\n\ndef action_event(action, drawn_tile=None):\n    event = json.loads(action.to_mjai())\n    if event[\"type\"] == \"dahai\":\n        event[\"tsumogiri\"] = action.tile == drawn_tile\n    return event\n\n\ndef single_legal_action(legal, drawn_tile):\n    \"\"\"Physical copies of the same held tile are one available action.\"\"\"\n    events = [action_event(action, drawn_tile) for action in legal]\n    for event in events:\n        if event[\"type\"] == \"dahai\":\n            del event[\"tsumogiri\"]\n    if events and all(event == events[0] for event in events):\n        return next(\n            (action for action in legal if action.tile == drawn_tile), legal[0]\n        )\n    return None\n\n\ndef prefer_red_calls(legal):\n    selected = {}\n    for index, action in enumerate(legal):\n        if action.action_type in (\n            riichienv.ActionType.CHI,\n            riichienv.ActionType.PON,\n        ):\n            key = (\n                action.action_type,\n                action.tile // 4,\n                tuple(sorted(tile // 4 for tile in action.consume_tiles)),\n            )\n            if key in selected and any(\n                tile in (16, 52, 88) for tile in selected[key].consume_tiles\n            ):\n                continue\n        else:\n            key = index\n        selected[key] = action\n    return list(selected.values())\n\n\ndef preferred_recorded_call(kind, consumed, legal):\n    return any(\n        event[\"type\"] == kind and sorted(event[\"consumed\"]) == sorted(consumed)\n        for action in prefer_red_calls(legal)\n        if action.action_type\n        in (riichienv.ActionType.CHI, riichienv.ActionType.PON)\n        for event in [action_event(action)]\n    )\n\n\ndef drawn_tile_code(packed):\n    tile = int(packed[\"current_draw_tile_id\"])\n    return 34 + tile // 9 if packed[\"current_draw_is_red\"] else tile\n\n\ndef chii_pattern(called, consumed):\n    called = (\n        shanten.mjai_tile_code(called)\n        if isinstance(called, str)\n        else native_tile_code(called)\n    )\n    consumed = [\n        (\n            shanten.mjai_tile_code(tile)\n            if isinstance(tile, str)\n            else native_tile_code(tile)\n        )\n        for tile in consumed\n    ]\n    return shanten.base_id(called) - min(\n        shanten.base_id(tile) for tile in [called] + consumed\n    )\n\n\ndef reference_inputs(state):\n    \"\"\"Ordered public markers retained only for the frozen reference policy.\"\"\"\n    return {\n        \"dora_tile_id\": numpy.asarray(\n            [\n                shanten.base_id(shanten.mjai_tile_code(marker))\n                for marker in state.dora_markers\n            ]\n            + [0] * (5 - len(state.dora_markers)),\n            dtype=\"int8\",\n        ),\n        \"dora_valid\": numpy.asarray(\n            [1] * len(state.dora_markers) + [0] * (5 - len(state.dora_markers)),\n            dtype=\"int8\",\n        ),\n    }\n\n\ndef pack(state, actor, phase):\n    \"\"\"Expose shared C++ feature buffers for the current public history.\"\"\"\n    if state.feature_replay is None:\n        state.feature_replay = _native_collection.FeatureReplay()\n    state.feature_replay.apply(\n        json.dumps(state.history[state.feature_cursor :])\n    )\n    state.feature_cursor = len(state.history)\n    buffers = state.feature_replay.pack(actor, PHASES[phase])\n    packed = {\n        name: numpy.frombuffer(buffers[name], spec[\"dtype\"])\n        .reshape(spec[\"shape\"])\n        .copy()\n        for name, spec in _native_collection.INPUTS.items()\n    }\n    calls = numpy.frombuffer(buffers[\"post_call\"], call_states.CALL_DTYPE)\n    return call_states.combine(\n        packed,\n        {\n            name: calls[\"features\"][name].copy()\n            for name in _native_collection.INPUTS\n        },\n        numpy.zeros(len(calls), dtype=\"int32\"),\n        calls[\"option\"].astype(\"int32\"),\n    )\n",
      "sha256": "cfffac92125da23f9bfe739e6cd379cf262f03e6188087b6c2bdf467044eb7b0"
    },
    {
      "path": "log_dataset/focus_sampling.py",
      "text": "\"\"\"Observed-state priorities for focused imitation sampling.\"\"\"\n\nimport numpy\n\nfrom log_dataset import scoring, shanten\n\n\ndef visible_threat(features, seat):\n    \"\"\"Historical public threat rule for one relative opponent seat.\"\"\"\n    opened = (features[\"meld_type\"][seat] > 0) & (\n        features[\"meld_type\"][seat] != 4\n    )\n    if (\n        features[\"riichi_state\"][seat] > 0\n        or opened.sum() >= 3\n        or (opened.sum() >= 2 and features[\"opponent_discard_count\"][seat] >= 9)\n    ):\n        return True\n    han = 0\n    suits = set()\n    for slot, kind in enumerate(features[\"meld_type\"][seat]):\n        if not kind:\n            continue\n        tiles = features[\"meld_tiles\"][seat, slot]\n        base = shanten.BASE_IDS[tiles[tiles < 37]]\n        han += int(base[0] >= 31)\n        han += int(base[0] == 27 + features[\"seat_wind\"][seat])\n        han += int(base[0] == 27 + features[\"prevailing_wind\"])\n        han += int(features[\"dora_multiplicity\"][base].sum())\n        han += int(((tiles >= 34) & (tiles < 37)).sum())\n        if opened[slot]:\n            suits.update(base[base < 27] // 9)\n    if opened.sum() >= 2 and len(suits) == 1:\n        middle_suits = set()\n        for segment in (\"pre\", \"post\"):\n            tiles = features[f\"river_{segment}_tile_id\"][seat - 1]\n            middle_suits.update(\n                tiles[\n                    (features[f\"river_{segment}_valid\"][seat - 1] > 0)\n                    & (tiles < 27)\n                    & (tiles % 9 >= 2)\n                    & (tiles % 9 <= 6)\n                ]\n                // 9\n            )\n        if len(middle_suits | suits) == 3:\n            han += 2\n    return han >= 3\n\n\ndef metadata(observation):\n    \"\"\"Return focused multiplicity and the independent placement-gap flag.\n\n    Only observed fields enter this classification. The route search retains\n    legal discard support and its original bounded-search exclusion; rounded\n    auxiliary labels are not used as sampling predicates.\n    \"\"\"\n    features = observation.features\n    phase = int(features[\"decision_phase\"])\n    calls = int(phase in (1, 2))\n    legal = (\n        \"discard_action_legal\",\n        \"response_legal_mask\",\n        \"kan_legal_mask\",\n        \"riichi_legal_mask\",\n    )\n    if phase >= len(legal) or numpy.count_nonzero(features[legal[phase]]) < 2:\n        # Response and kan opportunities qualify even\n        # when the native category classifier found no other eligible choice.\n        return calls, False\n\n    paths = shanten.tenpai_paths(\n        features[\"candidate_hand_counts\"][0],\n        features[\"known_unavailable_counts\"],\n        (\n            numpy.flatnonzero(features[\"discard_action_legal\"])\n            if phase in (0, 3)\n            else None\n        ),\n    )\n    routes = numpy.zeros(3, bool)\n    if paths is not None:\n        melds = tuple(\n            (\n                int(kind) - 1,\n                tuple(\n                    int(shanten.BASE_IDS[tile]) * 4 + copy\n                    for copy, tile in enumerate(tiles)\n                    if tile < 37\n                ),\n                bool(kind != 4),\n            )\n            for kind, tiles in zip(\n                features[\"meld_type\"][0], features[\"meld_tiles\"][0]\n            )\n            if kind\n        )\n        for hand in paths[0]:\n            flags = scoring.path_completion_flags(\n                counts=hand.tobytes(),\n                melds=melds,\n                player_wind=int(features[\"seat_wind\"][0]),\n                round_wind=int(features[\"prevailing_wind\"]),\n            )\n            routes |= [\n                flags[scoring.NAMES.index(name)]\n                for name in (\"tanyao\", \"honitsu\", \"chanta\")\n            ]\n            if routes.all():\n                break\n\n    threat = any(visible_threat(features, seat) for seat in range(1, 4))\n\n    late = features[\"hands_remaining\"] <= 1 or (\n        features[\"live_wall_count\"] <= 16\n        and min(\n            int(features[name])\n            for name in (\n                \"normal_self_shanten\",\n                \"chiitoitsu_self_shanten\",\n                \"kokushi_self_shanten\",\n            )\n        )\n        <= 2\n    )\n    gap = False\n    if features[\"hands_remaining\"] != 7:\n        order = numpy.argsort(features[\"ranks\"])\n        ranked = features[\"scores\"][order]\n        thresholds = numpy.where(\n            order <= max(0, int(features[\"hands_remaining\"])), 16000, 10000\n        )\n        rank = int(features[\"ranks\"][features[\"seat_wind\"][0]])\n        if rank == 1:\n            gap = ranked[0] - ranked[1] > thresholds[1]\n        elif rank == 2:\n            gap = (\n                ranked[0] - ranked[1] < thresholds[1]\n                and ranked[1] - ranked[3] > thresholds[3]\n            )\n        else:\n            gap = ranked[2] - ranked[3] < thresholds[3]\n    return calls + int(routes @ [2, 2, 1]) + int(threat) + int(late), bool(gap)\n",
      "sha256": "3fedf63633a10f956b3267ae7b6aabe3b0f629af809d79c8100073790d0245e7"
    },
    {
      "path": "log_dataset/native_collection/README.md",
      "text": "# Native features and self-play\n\nRust handles RiichiEnv replay, legal transitions, scoring and the Python\ninterface. C++ calculates board and candidate-hand features. Recorded\npositions and self-play use the same engine.\n\n## Build\n\nComplete the [repository setup](../../SETUP.md), including the patched\nRiichiEnv checkout, then run from the repository root:\n\n```sh\npython -m log_dataset.build_native_collection\n```\n\nThis builds `log_dataset/_native_collection.so` using Rust, a C++17 compiler\nand `ar`. Rebuild after changing native code or the input layout.\n\n## Human hand continuations\n\n`NativeCollector.from_hand(events_json, seed)` accepts one complete hand from\n`start_kyoku` through `end_kyoku`. It reconstructs a physical wall compatible\nwith initial hands, observed draws, kans and revealed dora. Unknown slots are\nfilled without replacement. Recorded decision events are checked during\nreplay; archive annotations and terminal scoring detail are not required to\nmatch simulator serialization. `from_match` retains exact seeded-match replay\nvalidation.\n\nAt a pending request, `snapshot(decision, phase=...)` can preserve a prepared\nrecord's decision phase, including an ordinary discard after declining riichi.\nHuman restoration also exposes post-call discards, preserves recorded meld\nordering, and consumes kan-dora reveals at the prepared-record boundary.\nForking with `shuffle_remaining=True` reshuffles all unseen tiles, including\nunrevealed dora/ura, while preserving root hands and revealed indicators.\nDataset preparation verifies restored feature parity before saving roots.\n`NativeRoot.dumps()` and `NativeRoot.loads(bytes)` preserve the complete pending\nstate, including simultaneous requests, legal choices, public history, furiten,\nwall and recorded hands. Loading does not replay events. The dataset's\n`root-states/` store compresses these snapshots by hand; training loads and forks\nthem directly. Serialized rows require the matching packed input schema.\n\n## Input tensors\n\n[src/schema.rs](src/schema.rs) defines names, shapes, dtypes and packed order.\nThe build derives C++ offsets from those declarations. Inspect the installed\nlibrary's schema with:\n\n```sh\npython -c 'from log_dataset import _native_collection as n; print(n.INPUTS)'\n```\n\nShapes exclude the batch dimension. A row contains 103 tensors, 6,436 scalar\nvalues and 8,966 bytes. Fields are consecutive without alignment padding;\n`log_dataset.call_states.ROW_DTYPE` provides NumPy views of packed rows.\nOpponent concealed hands are excluded from feature snapshots.\n`nagashi_possible[4]` is an actor-relative public flag: all discards so far\nare terminals/honors and none has been called. Empty rivers remain eligible.\nIt constrains settlements and final-wall cuts without entering learned\nencoder projections. `pao_payer[4]` identifies the actor-relative liable\nseat for each player, or -1 before liability is established. It derives from\nthe public call that completed all dragon or wind groups, including concealed\nkans in the group count and retaining the original pon source after kakan.\nIt also bypasses learned encoder projections. Rebuild prepared records when\nthis schema changes.\n\nSeats are actor-relative except `scores[4]` and `ranks[4]`, which use current\nseat-wind order: East, South, West, North. Scores are raw int32 points; ranks\nare int8 values 1–4. Equal scores use starting-dealer seat priority.\n`prevailing_wind` and signed `hands_remaining` describe South-game progress:\nEast 1 is 7, South 4 is 0 and West 1 is −1. The latter is\n`7 - (4 * round_wind + zero_based_hand_number)`, including extensions.\nSelf-shanten family categories encode shanten + 1, capped at 4; disabled\nspecial families use 5. Use `self_efficiency[0] * 8` for uncapped current\nshanten. Candidate discard/call shanten fields encode actual shanten + 1:\n0 is complete and 1 is tenpai.\n\n### Tiles and resulting hands\n\nPublic tile codes are 0–33 for base identities and 34–36 for red fives.\n`meld_tiles[4,4,4]` and `last_tedashi_tile_id[4]` use 37 for padding. A meld\nslot is occupied when its first tile is below 37. River fields carry their\nown validity masks and separate base identity from red-five flags.\n\nEach state has a 16-slot local hand bank: the current hand, ordinary-discard\nhands and kan hands. `discard_candidate_hand` and `kan_candidate_hand` are\ngather indices into that bank. Fixed melds use `candidate_meld_tiles[16,4]`\n(base identities, padding 34), `candidate_meld_types[16,4]` (kinds 0–4), and\n`candidate_meld_red[16,3]` (red-five counts). `candidate_fu[16]` stores only\nthe fixed-meld fu contribution.\n\n`candidate_hand_yaku_possibility[16,19]` describes coarse feasibility from\nfixed melds and public tile availability. These flags do not estimate\nreadiness or identify the eventual winning yaku. Bank deduplication includes\nthe flags as well as tile and meld contents. Opponent feasibility uses public\ncontext. [Model architecture](../../model/ARCHITECTURE.md) describes semantic\ndecoding and learned feature ownership.\n\n### Joint calls and discards\n\nChi and pon share four options: chi patterns 0–2 and pon at 3.\n`call_discard_legal`, `call_discard_shanten` and `call_discard_ukeire_count`\nhave shape `[4,37]`; `call_efficiency` has shape `[4,3]`. Each option's legal\ndiscard mask follows its executed call and preserves kuikae restrictions.\n\n`FeatureReplay.pack(actor, phase)` returns field buffers plus `post_call`:\nfor each legal chi/pon, one option byte followed by the full feature row\nwith the meld formed and the follow-up discard pending. These states have\ntheir own local hand banks. Legal calls accompanying a ron decision remain\navailable if the actor declines the win. Open kan has no immediate discard\nstate. Collector requests expose these sparse rows as `post_call_features`,\n`post_call_owner` and `post_call_option`; [call_states.py](../call_states.py)\nassembles model inputs. The exported signature has 103 base tensors, 103\naccepted-call tensors, and owner and option vectors.\n\n### Action-conditioned win values\n\nCanonical action identity uses 295 slots. Scoring transport stores 110 rows:\n\n| Scoring rows | Canonical actions |\n| --- | --- |\n| 0–36 | Ordinary cuts, also used by decline-riichi cuts 37–73. |\n| 37–73 | Declared-riichi cuts 74–110. |\n| 74 | Response pass 111. |\n| 75 | Kan decline 260. |\n| 76–109 | Kan actions 261–294. |\n\nJoint chi/pon actions use their accepted-call state's discard scoring.\n`action_win_value_range[110,2,2]` has ron/tsumo and min/max axes.\n`action_win_value_valid[110,2]` marks legal available completions;\n`action_value_eligible[110]` marks supported searches, and\n`action_open_yaku_restricted[110,2]` identifies open no-yaku restrictions.\nClosed dama is scored without riichi. Declaration actions and actions after\naccepted riichi include it. No-yaku dama can have a legal menzen-tsumo range\nand no legal ron range. One-shanten searches preserve the action's declaration\nstate rather than assuming a later riichi.\n\nCollector requests also expose `reference_dora_tile_id` and\n`reference_dora_valid`, each `[B,5]` int8 bytes, to preserve ordered indicator\nslots for a frozen reference policy. These sidebands are separate from learned\ninputs, which contain dora multiplicities.\n\nDatasets, native libraries and exports must agree on the complete schema.\nRebuild records from source after a schema change; changing summary metadata\ndoes not convert serialized values. Existing exports retain their own input\ncontracts.\n\n## Collector interface\n\n`NativeCollector` runs complete games through three operations:\n\n1. `next()` returns pending decisions and packed rows, or `None` when finished.\n2. `submit(codes)` supplies one legal action per pending decision.\n3. `finish()` returns completed game logs and counters.\n\n[training/self_play.py](../../training/self_play.py) batches worker requests\nfor inference and retains their rows, selected actions and behavior\nprobabilities. Payments and belief targets are reconstructed from logs.\n\n`snapshot(decision)` captures a pending decision between `next()` and\n`submit()`, including simultaneous requests in that game. The root exposes\n`decision` (its local request offset) and\n`fork(copies, seed, shuffle_remaining=True, *, until_hand_end=False)`.\nForks preserve public history, concealed hands, pending actions and prefix\nlogs. They shuffle unrevealed wall tiles without moving revealed indicators,\nand seed future hands from the branch seed. Duplicate-wall forks apply the\nsame physical-tile permutation to each remaining player queue, preserving\nqueue order, counterclockwise borrowing and shared rinshan tiles. With\nshuffling disabled, the initial engine state is identical; subsequent\ncollector randomness still uses the supplied seed. Equal seeds reproduce\nforks, and forking leaves the parent unchanged.\n\nContinuations condition on captured hidden hands; they do not sample an\ninformation-set posterior. Python collection emits suffix decisions only.\nWith `until_hand_end=True`, a branch stops after the current hand settles,\nretaining the next hand's start as a boundary or the real `end_game` event.\nThe pending next hand supplies no training rows. Counters include the initial\npartial hand and its earlier riichi declarations, so fork statistics describe\nroot-conditioned continuations rather than ordinary match rates.\n\n`NativeCollector.from_match(events_json, seed, duplicate)` recreates a seeded\ntrajectory. Use `next()` and `submit_recorded()` to inspect and advance it.\nReplay verifies generated events, including discard origin, consumed tiles\nand settlements. Incompatible seeds or simulator histories fail. Triple-ron\nabortive draws reconstruct all three legal claims. Unobserved losing claims\nare replayed as passes to reconstruct the public trajectory; they are not\nimitation labels. Snapshots leave replay mode, so counterfactual claims follow\nthe supplied policy.\n\n## Source and checks\n\n| Source | Responsibility |\n| --- | --- |\n| [src/features.rs](src/features.rs) | Public snapshots and legal accepted-call states. |\n| [cpp/features.cpp](cpp/features.cpp) | Table, river and meld features. |\n| [cpp/candidate.cpp](cpp/candidate.cpp) | Hands, masks and efficiency features. |\n| [cpp/yaku.cpp](cpp/yaku.cpp) | Public feasibility and fixed-meld values. |\n| [cpp/scoring.cpp](cpp/scoring.cpp) | Completion search scored by RiichiEnv. |\n| [src/lib.rs](src/lib.rs) | Python bindings. |\n\n```sh\npython -m pytest integration/big/test_native_collection.py \\\n  integration/big/test_feature_generation.py \\\n  integration/big/test_self_play.py \\\n  integration/big/test_selected_roots.py\n```\n\nIndependent Python calculations under `integration/` check native parity.\n",
      "sha256": "d095afa886a029f203f8e7cfc7f1120906c3f86c1b232b10f43ad6f1e9fecdd7"
    },
    {
      "path": "log_dataset/native_collection/cpp/candidate.cpp",
      "text": "#include \"analysis.hpp\"\n#include \"features.hpp\"\n#include <tuple>\nnamespace feature {\nusing namespace fields;\nvoid Ranges::merge(Ranges const &other) {\n  eligible |= other.eligible;\n  for (int s = 0; s < 4; ++s)\n    if (other.valid[s]) {\n      values[s * 2] = valid[s]\n          ? std::min(values[s * 2], other.values[s * 2])\n          : other.values[s * 2];\n      values[s * 2 + 1] = valid[s]\n          ? std::max(values[s * 2 + 1], other.values[s * 2 + 1])\n          : other.values[s * 2 + 1];\n      valid[s] = 1;\n    }\n  for (int i = 0; i < 2; ++i)\n    restricted[i] |= other.restricted[i];\n}\nvoid write(Row row, Ranges const &v, int action) {\n  double values[4];\n  uint8_t valid[2];\n  for (int method = 0; method < 2; ++method) {\n    valid[method] = v.valid[method] | v.valid[2 + method];\n    for (int bound = 0; bound < 2; ++bound)\n      values[method * 2 + bound] = v.values[method * 2 + bound] +\n          v.values[4 + method * 2 + bound];\n  }\n  row.put(action_win_value_range, action * 4, values, 4);\n  row.put(action_win_value_valid, action * 2, valid, 2);\n  row.put(action_open_yaku_restricted, action * 2, v.restricted, 2);\n  row.set(action_value_eligible, action, v.eligible);\n}\nstd::array<uint8_t, 34> counts(Hand const &h) {\n  std::array<uint8_t, 34> out{};\n  for (int i = 0; i < h.size; ++i)\n    ++out[h.tiles[i] / 4];\n  return out;\n}\nHand cut_hand(Hand h, int cut) {\n  int pos = 0;\n  while (code(h.tiles[pos]) != cut)\n    ++pos;\n  std::move(h.tiles + pos + 1, h.tiles + h.size, h.tiles + pos);\n  --h.size;\n  return h;\n}\nint Bank::add(Row row, Hand const &h, uint8_t const *yaku) {\n  std::array<uint8_t, 63> key{};\n  std::copy_n(yaku, 19, key.begin() + 44);\n  for (int i = 0; i < h.size; ++i) {\n    int t = h.tiles[i];\n    ++key[t / 4];\n    if (red(t))\n      ++key[34 + t / 36];\n  }\n  int fu = 0;\n  uint8_t fixed[16];\n  std::fill_n(fixed, 16, 34);\n  for (int i = 0; i < h.meld_count; ++i) {\n    auto const &m = h.melds[i];\n    fu += meld_fu(m);\n    int lowest = 34;\n    for (int j = 0; j < m.size; ++j) {\n      int t = m.tiles[j];\n      lowest = std::min(lowest, t / 4);\n      fixed[i * 4 + j] = t / 4;\n      if (red(t))\n        ++key[41 + t / 36];\n    }\n    key[37 + i] = lowest * 5 + m.kind + 1;\n  }\n  std::sort(key.begin() + 37, key.begin() + 41);\n  for (int i = 0; i < size; ++i)\n    if (keys[i] == key)\n      return i;\n  int index = size++;\n  keys[index] = key;\n  for (int i = 0; i < 4; ++i) {\n    row.set(candidate_meld_tiles, index * 4 + i,\n            key[37 + i] ? (key[37 + i] - 1) / 5 : 34);\n    row.set(candidate_meld_types, index * 4 + i,\n            key[37 + i] ? (key[37 + i] - 1) % 5 : 0);\n  }\n  row.put(candidate_meld_red, index * 3, key.data() + 41, 3);\n  row.put(candidate_hand_counts, index * 34, key.data(), 34);\n  row.put(candidate_hand_red, index * 3, key.data() + 34, 3);\n  row.put(candidate_hand_yaku_possibility, index * 19, key.data() + 44, 19);\n  auto y = nyanten_yaku_shanten(key.data(), fixed, h.meld_count);\n  for (int i = 0; i < 3; ++i)\n    row.set(candidate_yaku_shanten, index * 3 + i, int((y >> (8 * i)) & 255) - 1);\n  row.set(candidate_hand_valid, index, 1);\n  row.set(candidate_fu, index, fu);\n  return index;\n}\nstd::vector<int> cuts(uint8_t const *legal) {\n  std::vector<int> out;\n  for (int t = 0; t < 37; ++t)\n    if (legal[t])\n      out.push_back(t);\n  return out;\n}\nvoid sort_cuts(std::vector<int> &cuts) {\n  std::sort(cuts.begin(), cuts.end(), [](int x, int y) {\n    return std::make_pair(base(x), x < 34) < std::make_pair(base(y), y < 34);\n  });\n}\nstd::array<double, 3> efficiency(::Analysis const &a, std::vector<int> const &cuts) {\n  int t = base(*std::min_element(cuts.begin(), cuts.end(), [&](int x, int y) {\n    x = base(x);\n    y = base(y);\n    return std::make_tuple(a.shanten[x], -int(a.ukeire_count[x]),\n                           -__builtin_popcountll(a.ukeire_mask[x])) <\n           std::make_tuple(a.shanten[y], -int(a.ukeire_count[y]),\n                           -__builtin_popcountll(a.ukeire_mask[y]));\n  }));\n  return {a.shanten[t] / 8., __builtin_popcountll(a.ukeire_mask[t]) / 34.,\n          a.ukeire_count[t] / 80.};\n}\nstd::array<double, 3> efficiency(uint64_t v, uint8_t const *unavailable) {\n  uint64_t mask = v & ((1ull << 34) - 1);\n  int total = 0;\n  for (int t = 0; t < 34; ++t)\n    if (mask & (1ull << t))\n      total += 4 - unavailable[t];\n  return {double(v >> 34) / 8. - 1. / 8., __builtin_popcountll(mask) / 34., total / 80.};\n}\nvoid flags(Hand const &h, int const *exposed, int round, int seat, uint8_t *out,\n           int cut = -1) {\n  int available[34];\n  for (int t = 0; t < 34; ++t)\n    available[t] = 4 - exposed[t] - (t == cut);\n  for (int i = 0; i < h.meld_count; ++i)\n    for (int j = 0; j < h.melds[i].size; ++j)\n      ++available[h.melds[i].tiles[j] / 4];\n  yaku(h.melds, h.meld_count, available, round, seat, out);\n}\nvoid pack_candidates(Row row, State const &s, feature::Analysis const &a,\n                     Branch const *branches, size_t branch_count, Legal &legal,\n                     RangeContext const &availability, void *context,\n                     Score score) {\n  row.set(riichi_legal_mask, 0, 1);\n  row.set(response_legal_mask, 0, 1);\n  row.set(kan_legal_mask, 0, 1);\n  row.put(discard_action_legal, 0, legal.discards, 37);\n  row.put(riichi_discard_legal_mask, 0, legal.riichi, 37);\n  for (int t = 0; t < 37; ++t)\n    if (legal.riichi[t])\n      row.set(riichi_legal_mask, 1, 1);\n  bool removed = false;\n  for (int i = 0; i < s.hand.size; ++i) {\n    int t = code(s.hand.tiles[i]);\n    if (!removed && s.draw == t) {\n      removed = true;\n      continue;\n    }\n    row.set(discard_tedashi_legal, t, legal.discards[t] && !s.accepted[s.actor]);\n  }\n  Bank bank;\n  bank.add(row, s.hand, row.bytes + candidate_hand_yaku_possibility.offset);\n  auto choices = cuts(legal.discards);\n  std::array<double, 3> self;\n  if (!choices.empty()) {\n    uint64_t mask = 0;\n    for (int t : choices)\n      mask |= 1ull << base(t);\n    uint8_t modes[] = {0, 1};\n    ::Analysis analyses[2]{};\n    uint64_t structural[34]{};\n    nyanten_analyze_features(a.counts, a.unavailable, mask, modes, 2, analyses,\n                             structural);\n    Field shanten[] = {discard_action_normal_shanten, discard_action_all_shanten};\n    Field ukeire[] = {discard_action_normal_ukeire_count,\n                      discard_action_all_ukeire_count};\n    for (int i = 0; i < 2; ++i)\n      for (int cut : choices) {\n        row.set(shanten[i], cut, analyses[i].shanten[base(cut)] + 1);\n        row.set(ukeire[i], cut, analyses[i].ukeire_count[base(cut)]);\n      }\n    uint8_t y[19];\n    flags(s.hand, s.exposed, s.wind, (s.actor + 4 - s.oya) % 4, y);\n    int retained[4]{};\n    for (int seat = 0; seat < 4; ++seat)\n      for (int t = 0; t < 34; ++t)\n        retained[seat] += a.genbutsu[seat][t] * a.counts[t];\n    Ranges decline{};\n    self = efficiency(analyses[1], choices);\n    sort_cuts(choices);\n    for (int cut : choices) {\n      int t = base(cut);\n      auto after = cut_hand(s.hand, cut);\n      uint8_t cut_y[19];\n      if (t < 27 && t % 9 >= 1 && t % 9 <= 7)\n        std::copy_n(y, 19, cut_y);\n      else\n        flags(after, s.exposed, s.wind, (s.actor + 4 - s.oya) % 4, cut_y, t);\n      row.set(discard_candidate_hand, cut, bank.add(row, after, cut_y));\n      auto v = ranges(after, availability, t, context, score, structural[t]);\n      write(row, v, cut);\n      if (legal.riichi[cut]) {\n        auto declared = availability;\n        declared.riichi = 1;\n        write(row, ranges(after, declared, t, context, score, structural[t]),\n              37 + cut);\n      }\n      decline.merge(v);\n      for (int seat = 0; seat < 4; ++seat)\n        row.set(discard_retained_genbutsu, cut * 4 + seat,\n                retained[seat] - a.genbutsu[seat][t]);\n    }\n    write(row, decline, 75);\n  } else {\n    auto draw = nyanten_draw(a.counts, 1);\n    self = efficiency(draw, a.unavailable);\n    auto v = ranges(s.hand, availability, -1, context, score, draw);\n    write(row, v, 74);\n    write(row, v, 75);\n  }\n  row.put(self_efficiency, 0, self.data(), 3);\n  for (size_t b = 0; b < branch_count; ++b) {\n    auto const &branch = branches[b];\n    auto const &h = branch.hand;\n    if (branch.response)\n      row.set(response_legal_mask, branch.response, 1);\n    if (branch.response != 1 && branch.response != 2) {\n      uint8_t yaku[19];\n      flags(h, branch.exposed, s.wind, (s.actor + 4 - s.oya) % 4, yaku);\n      int t = branch.tile;\n      row.set(kan_legal_mask, t + 1, 1);\n      row.set(kan_candidate_hand, t, bank.add(row, h, yaku));\n      auto draw = nyanten_draw(counts(h).data(), 1);\n      auto v = ranges(h, availability, -1, context, score, draw);\n      write(row, v, 76 + t);\n      auto eff = efficiency(draw, a.unavailable);\n      row.put(kan_efficiency, t * 3, eff.data(), 3);\n      continue;\n    }\n    int option = branch.option;\n    auto call_cuts = cuts(branch.cuts);\n    uint64_t mask = 0;\n    for (int t : call_cuts)\n      mask |= 1ull << base(t);\n    uint8_t mode = 1;\n    ::Analysis analysis{};\n    uint64_t structural[34]{};\n    nyanten_analyze_features(counts(h).data(), a.unavailable, mask, &mode, 1, &analysis,\n                             structural);\n    if (!call_cuts.empty()) {\n      auto eff = efficiency(analysis, call_cuts);\n      row.put(call_efficiency, option * 3, eff.data(), 3);\n    }\n    sort_cuts(call_cuts);\n    for (int cut : call_cuts) {\n      int position = option * 37 + cut;\n      legal.calls[option][cut] = 1;\n      row.set(call_discard_legal, position, 1);\n      row.set(call_discard_shanten, position,\n              analysis.shanten[base(cut)] + 1);\n      row.set(call_discard_ukeire_count, position,\n              analysis.ukeire_count[base(cut)]);\n    }\n  }\n}\n} // namespace feature\nextern \"C\" void feature_pack_candidates(uint8_t *row, feature::State const *s,\n                                        feature::Analysis const *a,\n                                        feature::Branch const *branches, size_t size,\n                                        feature::Legal *legal,\n                                        feature::RangeContext const *availability,\n                                        void *context, feature::Score score) {\n  feature::pack_candidates({row}, *s, *a, branches, size, *legal, *availability,\n                           context, score);\n}\n\nextern \"C\" int feature_bank_hand(uint8_t *row, feature::Bank *bank,\n                                 feature::Hand const *hand, uint8_t const *yaku) {\n  return bank->add({row}, *hand, yaku);\n}\n",
      "sha256": "1f64558a0cba74aad8b5a504a352f35a7a6538a2cd5682891e3540bb4f71919c"
    },
    {
      "path": "log_dataset/native_collection/cpp/features.cpp",
      "text": "#include \"features.hpp\"\n#include \"analysis.hpp\"\n#include <numeric>\n#include <tuple>\nnamespace feature {\nusing namespace fields;\nvoid pack_base(Row row, State const &s, feature::Analysis &a) {\n  int actor = s.actor;\n  uint8_t hand_red[3]{}, public_red[3]{};\n  for (int i = 0; i < s.hand.size; ++i) {\n    int t = s.hand.tiles[i];\n    ++a.counts[t / 4];\n    if (red(t))\n      ++hand_red[t / 36];\n  }\n  row.put(candidate_hand_counts, 0, a.counts, 34);\n  row.put(candidate_hand_red, 0, hand_red, 3);\n  bool closed = true;\n  for (int i = 0; i < s.meld_count[actor]; ++i)\n    closed &= !s.melds[actor][i].opened;\n  row.set(closed_hand, 0, closed);\n  auto packed = nyanten_families(a.counts);\n  int families[3];\n  Field family_fields[] = {normal_self_shanten, chiitoitsu_self_shanten,\n                           kokushi_self_shanten};\n  for (int i = 0; i < 3; ++i) {\n    families[i] = int((packed >> (8 * i)) & 255) - 1;\n    row.set(family_fields[i], 0,\n            i > 0 && s.meld_count[actor] ? 5 : std::min(families[i] + 1, 4));\n  }\n  uint8_t flags[4][19]{};\n  for (int seat = 0; seat < 4; ++seat) {\n    int available[34];\n    for (int t = 0; t < 34; ++t)\n      available[t] = 4 - s.exposed[t];\n    for (int i = 0; i < s.meld_count[seat]; ++i)\n      for (int j = 0; j < s.melds[seat][i].size; ++j)\n        ++available[s.melds[seat][i].tiles[j] / 4];\n    if (s.trigger_seat >= 0 && s.trigger_seat != seat)\n      ++available[base(s.trigger_tile)];\n    yaku(s.melds[seat], s.meld_count[seat], available, s.wind, (seat + 4 - s.oya) % 4,\n         flags[seat]);\n  }\n  row.put(candidate_hand_yaku_possibility, 0, flags[actor], 19);\n  if (s.draw >= 0) {\n    row.set(current_draw_valid, 0, 1);\n    row.set(current_draw_tile_id, 0, base(s.draw));\n    row.set(current_draw_is_red, 0, s.draw >= 34);\n  }\n  row.set(decision_phase, 0, s.phase);\n  if (s.phase == 4)\n    row.set(win_kind, 0, s.tsumo ? 2 : 1);\n  row.set(rinshan_state, 0, s.rinshan == actor);\n  for (int i = 0; i < s.dora_size; ++i) {\n    int t = base(s.dora[i]);\n    int next = t < 27   ? t / 9 * 9 + (t + 1) % 9\n               : t < 31 ? 27 + (t - 26) % 4\n                        : 31 + (t - 30) % 3;\n    ++a.dora_counts[next];\n  }\n  row.put(dora_multiplicity, 0, a.dora_counts, 34);\n  std::copy_n(a.counts, 34, a.unavailable);\n  for (int t = 0; t < 37; ++t) {\n    a.unavailable[base(t)] += s.public_counts[t];\n    if (t >= 34)\n      public_red[t - 34] += s.public_counts[t];\n  }\n  row.put(known_unavailable_counts, 0, a.unavailable, 34);\n  row.put(public_visible_red_counts, 0, public_red, 3);\n  row.set(prevailing_wind, 0, s.wind);\n  row.set(hands_remaining, 0, 7 - (s.wind * 4 + s.kyoku - 1));\n  row.set(dealer_relative_seat, 0, (s.oya + 4 - actor) % 4);\n  row.set(honba, 0, s.honba);\n  row.set(riichi_sticks, 0, s.sticks);\n  row.set(live_wall_count, 0, s.wall);\n  int kans = 0, first_kan = -1;\n  bool multiple = false, no_melds = true;\n  for (int seat = 0; seat < 4; ++seat) {\n    no_melds &= s.meld_count[seat] == 0;\n    for (int i = 0; i < s.meld_count[seat]; ++i)\n      if (s.melds[seat][i].kind >= 2) {\n        ++kans;\n        if (first_kan < 0)\n          first_kan = seat;\n        multiple |= seat != first_kan;\n      }\n  }\n  row.set(total_kan_count, 0, kans);\n  for (int decl = 0; decl < 2; ++decl) {\n    bool all = true;\n    for (int seat = 0; seat < 4; ++seat)\n      all &= s.declared[seat] || (seat == actor && decl == 1);\n    bool abort = (kans == 4 && multiple) || all;\n    for (int t = 0; t < 37; ++t)\n      row.set(discard_abort, decl * 37 + t, abort);\n  }\n  bool first = no_melds && s.river_count[actor] == 0;\n  for (int seat = 0; seat < 4; ++seat)\n    if (seat != actor)\n      first &= s.river_count[seat] == 1;\n  if (first) {\n    int t = s.rivers[(actor + 1) % 4][0].tile;\n    bool same = t >= 27 && t < 31;\n    for (int seat = 0; seat < 4; ++seat)\n      if (seat != actor)\n        same &= s.rivers[seat][0].tile == t;\n    if (same) {\n      row.set(discard_abort, t, 1);\n      row.set(discard_abort, 37 + t, 1);\n    }\n  }\n  int order[4];\n  int first_dealer = (s.oya + 5 - s.kyoku) % 4;\n  std::iota(order, order + 4, 0);\n  std::sort(order, order + 4, [&](int x, int y) {\n    return std::make_pair(-s.scores[x], (x + 4 - first_dealer) % 4) <\n           std::make_pair(-s.scores[y], (y + 4 - first_dealer) % 4);\n  });\n  for (int i = 0; i < 3; ++i)\n    a.unavailable_red[i] = hand_red[i] + public_red[i];\n  uint64_t riichi_safe[4]{};\n  std::vector<std::pair<int, River const *>> discards;\n  for (int seat = 0; seat < 4; ++seat)\n    for (size_t i = 0; i < s.river_count[seat]; ++i)\n      discards.emplace_back(seat, &s.rivers[seat][i]);\n  std::sort(discards.begin(), discards.end(), [](auto const &x, auto const &y) {\n    return x.second->event < y.second->event;\n  });\n  uint8_t pushes[16]{};\n  for (int target = 0; target < 4; ++target)\n    if (s.accepted[target]) {\n      int declared = s.accepted_event[target];\n      uint64_t safe = 0;\n      for (size_t i = 0; i < s.river_count[target]; ++i)\n        if (s.rivers[target][i].event < declared)\n          safe |= 1ull << base(s.rivers[target][i].tile);\n      for (auto const &[seat, ptr] : discards) {\n        auto const &cut = *ptr;\n        if (cut.event <= declared)\n          continue;\n        int tile = base(cut.tile);\n        if (seat != target && !cut.tsumogiri && !(safe & (1ull << tile)))\n          ++pushes[((seat + 4 - actor) % 4) * 4 + (target + 4 - actor) % 4];\n        if (cut.resolution)\n          safe |= 1ull << tile;\n      }\n      riichi_safe[target] = safe;\n    }\n  row.put(riichi_push_count, 0, pushes, 16);\n  for (int relative = 0; relative < 4; ++relative) {\n    int seat = (actor + relative) % 4;\n    row.set(public_bonus, relative, meld_bonus(s.melds[seat], s.meld_count[seat],\n                                            a.dora_counts));\n    auto river = s.rivers[seat];\n    int size = s.river_count[seat];\n    for (int i = size - 1; i >= 0; --i)\n      if (!river[i].tsumogiri) {\n        row.set(last_tedashi_tile_id, relative, river[i].tile);\n        break;\n      }\n    row.set(seat_wind, relative, (seat + 4 - s.oya) % 4);\n    row.set(scores, (seat + 4 - s.oya) % 4, s.scores[seat]);\n    row.set(ranks, (seat + 4 - s.oya) % 4,\n            std::find(order, order + 4, seat) - order + 1);\n    row.set(riichi_state, relative, s.declared[seat] + s.accepted[seat]);\n    row.set(ippatsu_alive, relative, s.ippatsu[seat]);\n    row.set(opponent_discard_count, relative, size);\n    bool nagashi = true;\n    for (int i = 0; i < size; ++i) {\n      int tile = base(river[i].tile);\n      nagashi &= (tile >= 27 || tile % 9 == 0 || tile % 9 == 8) &&\n                 river[i].resolution < 2;\n    }\n    row.set(nagashi_possible, relative, nagashi);\n    int groups[2]{}, last[2]{-1, -1};\n    for (int i = 0; i < s.meld_count[seat]; ++i) {\n      auto const &m = s.melds[seat][i];\n      int tile = m.tiles[0] / 4;\n      if (tile < 27 || m.kind == 0)\n        continue;\n      int family = tile >= 31 ? 0 : 1;\n      ++groups[family];\n      if (last[family] < 0 || m.event > s.melds[seat][last[family]].event)\n        last[family] = i;\n    }\n    int payer = -1;\n    for (int family = 0; family < 2; ++family)\n      if (groups[family] == 3 + family) {\n        auto const &m = s.melds[seat][last[family]];\n        if (m.opened)\n          payer = (m.target + 4 - actor) % 4;\n      }\n    row.set(pao_payer, relative, payer);\n    int called = 0;\n    for (int i = 0; i < s.meld_count[seat]; ++i)\n      if (s.melds[seat][i].opened)\n        called += s.melds[seat][i].size;\n    if (relative) {\n      row.set(opponent_called_tile_count, relative, called);\n      constexpr int indices[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 14, 16, 17};\n      if (called)\n        for (int i = 0; i < 13; ++i)\n          row.set(open_opponent_yaku_possibility, relative * 13 + i,\n                  flags[seat][indices[i]]);\n    }\n    int last_change = -1;\n    for (int i = 0; i < s.meld_count[seat]; ++i) {\n      auto const &m = s.melds[seat][i];\n      int slot = relative * 4 + i;\n      last_change = std::max({last_change, m.event, m.upgrade});\n      row.set(meld_type, slot, m.kind + 1);\n      for (int j = 0; j < m.event_size; ++j) {\n        row.set(meld_tiles, slot * 4 + j, m.event_tiles[j]);\n      }\n      row.set(meld_source, slot, m.opened ? (m.target + 4 - actor) % 4 + 1 : 0);\n      row.set(meld_call_age, slot, std::min(1., (s.events - m.event) / 100.));\n      if (m.upgrade >= 0)\n        row.set(meld_upgrade_age, slot, std::min(1., (s.events - m.upgrade) / 100.));\n    }\n    for (int i = 0; i < size; ++i)\n      if (!river[i].tsumogiri)\n        last_change = std::max(last_change, river[i].event);\n    uint8_t passed[34]{}, earliest[34]{};\n    for (int other = 0; other < 4; ++other)\n      if (other != seat)\n        for (size_t i = 0; i < s.river_count[other]; ++i) {\n          auto const &cut = s.rivers[other][i];\n          if (cut.resolution && cut.event > last_change)\n            passed[base(cut.tile)] = 1;\n        }\n    row.put(passed_unchanged_to_seat, relative * 34, passed, 34);\n    for (int t = 0; t < 34; ++t)\n      a.genbutsu[relative][t] = (riichi_safe[seat] >> t) & 1;\n    int boundary = s.boundary[seat] < 0 ? size : s.boundary[seat];\n    Field river_fields[12][2] = {\n        {river_pre_tile_id, river_post_tile_id},\n        {river_pre_is_red, river_post_is_red},\n        {river_pre_tsumogiri, river_post_tsumogiri},\n        {river_pre_valid, river_post_valid},\n        {river_pre_origin, river_post_origin},\n        {river_pre_call_resolution, river_post_call_resolution},\n        {river_pre_caller, river_post_caller},\n        {river_pre_event_age, river_post_event_age},\n        {river_pre_own_gap, river_post_own_gap},\n        {river_pre_live_wall, river_post_live_wall},\n        {river_pre_current_dora_multiplicity, river_post_current_dora_multiplicity},\n        {river_pre_dora_multiplicity_at_discard, river_post_dora_multiplicity_at_discard}};\n    for (int i = 0; i < size; ++i) {\n      auto const &cut = river[i];\n      int t = base(cut.tile);\n      a.genbutsu[relative][t] = 1;\n      if (i < 6 && !cut.riichi && t < 27)\n        for (int o : outside[t % 9])\n          if (o >= 0 && !earliest[t / 9 * 9 + o])\n            earliest[t / 9 * 9 + o] = i + 1;\n      if (!relative)\n        continue;\n      int phase = i >= boundary, end = phase ? size : boundary;\n      if (32 + i < end)\n        continue;\n      int slot = (relative - 1) * 32 + 32 + i - end;\n      if (!phase)\n        row.set(river_pre_riichi, slot, cut.riichi);\n      int origin = seat == s.oya && i == 0 ? 1\n                   : cut.origin == 2       ? 4\n                   : cut.origin == 3       ? 5\n                   : cut.tsumogiri         ? 2\n                                           : 3;\n      double values[] = {double(t),\n                         double(cut.tile >= 34),\n                         double(cut.tsumogiri),\n                         1.,\n                         double(origin),\n                         double(cut.resolution + 1),\n                         cut.resolution == 0 ? 1.\n                         : cut.caller < 0    ? 0.\n                                             : double((cut.caller + 4 - actor) % 4 + 2),\n                         std::min(1., (s.events - cut.event) / 100.),\n                         std::min(1., (s.river_count[actor] - cut.turns[actor]) / 24.),\n                         cut.wall / 70.,\n                         double(a.dora_counts[t]),\n                         double(cut.dora)};\n      for (int k = 0; k < 12; ++k)\n        row.set(river_fields[k][phase], slot, values[k]);\n    }\n    row.put(genbutsu_to_seat, relative * 34, a.genbutsu[relative], 34);\n    row.put(sotogawa_earliest_turn_to_seat, relative * 34, earliest, 34);\n  }\n  if (s.trigger_seat >= 0) {\n    row.set(trigger_valid, 0, 1);\n    row.set(trigger_tile_id, 0, base(s.trigger_tile));\n    row.set(trigger_is_red, 0, s.trigger_tile >= 34);\n    row.set(trigger_source, 0, (s.trigger_seat + 4 - actor) % 4);\n  }\n}\n} // namespace feature\nextern \"C\" void feature_pack_base(uint8_t *row, feature::State const *state,\n                                  feature::Analysis *analysis) {\n  feature::pack_base({row}, *state, *analysis);\n}\nextern \"C\" void feature_row_set(uint8_t *row, size_t offset, int dtype, size_t index,\n                                double value) {\n  feature::Row{row}.set({offset, dtype}, index, value);\n}\n// Check the Rust/C++ transport ABI without relying on particular game states.\nextern \"C\" void feature_layout(size_t *out) {\n  using namespace feature;\n  size_t layout[] = {sizeof(Meld),\n                     sizeof(River),\n                     sizeof(Hand),\n                     sizeof(State),\n                     sizeof(feature::Analysis),\n                     sizeof(Branch),\n                     sizeof(Legal),\n                     sizeof(Ranges),\n                     sizeof(RangeContext),\n                     sizeof(Bank),\n                     offsetof(State, rivers),\n                     offsetof(State, exposed),\n                     offsetof(feature::Analysis, genbutsu),\n                     offsetof(RangeContext, unavailable_red)};\n  std::copy_n(layout, 14, out);\n}\n",
      "sha256": "773a1edb15a4498bb828a17ed24ec2268b84a6c9e4d480ba599821f33a78e1ed"
    },
    {
      "path": "log_dataset/native_collection/cpp/features.hpp",
      "text": "#pragma once\n#include \"feature_fields.hpp\"\n#include <algorithm>\n#include <array>\n#include <cstdint>\n#include <cstring>\n#include <vector>\n\nnamespace feature {\nstruct Meld {\n  int kind, opened, size, tiles[4], called;\n  int event_size, event_tiles[4], target, event, upgrade;\n};\nstruct River {\n  int tile, event, wall, turns[4], origin, riichi, resolution, caller, dora, tsumogiri;\n};\nstruct Hand {\n  int size, tiles[14], meld_count;\n  Meld melds[4];\n};\nstruct State {\n  Hand hand;\n  Meld melds[4][4];\n  int meld_count[4];\n  River const *rivers[4];\n  size_t river_count[4];\n  int boundary[4], accepted_event[4], declared[4], accepted[4], ippatsu[4];\n  int draw, actor, phase, tsumo, rinshan, events, wall;\n  int oya, kyoku, wind, honba, sticks, scores[4];\n  int dora_size, dora[5], public_counts[37], exposed[34];\n  int trigger_seat, trigger_tile;\n};\nstruct Analysis {\n  uint8_t counts[34], unavailable[34];\n  int unavailable_red[3];\n  uint8_t genbutsu[4][34];\n  int dora_counts[34];\n};\nstruct Branch {\n  Hand hand;\n  int response, option, tile;\n  uint8_t cuts[37];\n  int exposed[34];\n};\nstruct Legal {\n  uint8_t discards[37], riichi[37], calls[4][37];\n};\nstruct Ranges {\n  double values[8];\n  uint8_t valid[4];\n  uint8_t restricted[2], eligible;\n  void merge(Ranges const &other);\n};\nstruct RangeContext {\n  uint64_t own_discards;\n  int missed_agari;\n  uint8_t unavailable[34];\n  int unavailable_red[3];\n  uint8_t riichi;\n};\nusing Score = void (*)(void *, Hand const *, RangeContext const *, int, uint64_t,\n                       Ranges *);\nRanges ranges(Hand const &, RangeContext const &, int, void *, Score, uint64_t);\n\n// Packed rows retain their existing wire layout. Field offsets are generated\n// from the same typed declarations that expose INPUTS to Python.\nstruct Row {\n  uint8_t *bytes;\n  void set(fields::Field field, size_t index, double value) {\n    switch (field.dtype) {\n    case 0:\n      bytes[field.offset + index] = static_cast<int8_t>(value);\n      break;\n    case 1: {\n      auto v = static_cast<int16_t>(value);\n      std::memcpy(bytes + field.offset + index * 2, &v, 2);\n      break;\n    }\n    case 2: {\n      auto v = static_cast<_Float16>(value);\n      std::memcpy(bytes + field.offset + index * 2, &v, 2);\n      break;\n    }\n    case 3: {\n      auto v = static_cast<float>(value);\n      std::memcpy(bytes + field.offset + index * 4, &v, 4);\n      break;\n    }\n    case 4: {\n      auto v = static_cast<int32_t>(value);\n      std::memcpy(bytes + field.offset + index * 4, &v, 4);\n      break;\n    }\n    }\n  }\n  template <class T>\n  void put(fields::Field field, size_t offset, T const *values, size_t size) {\n    if (field.dtype == 0 && sizeof(T) == 1) {\n      std::memcpy(bytes + field.offset + offset, values, size);\n    } else {\n      for (size_t i = 0; i < size; ++i)\n        set(field, offset + i, values[i]);\n    }\n  }\n};\n// Local state, ordinary discards and kans only. With m fixed melds the\n// concealed hand has H <= 14 - 3m tiles. Each ankan saves at least two\n// distinct discard codes, and there are at most m added-kan branches:\n// 1 + discard_codes + ankans + added_kans <= 15. Response daiminkan has\n// no ordinary discards. Chi/pon child states have their own local banks.\nstruct Bank {\n  std::array<std::array<uint8_t, 63>, 16> keys{};\n  int size = 0;\n  int add(Row, Hand const &, uint8_t const *);\n};\ninline int base(int code) { return code < 34 ? code : 4 + 9 * (code - 34); }\ninline bool red(int tile) { return tile == 16 || tile == 52 || tile == 88; }\ninline int code(int tile) { return red(tile) ? 34 + tile / 36 : tile / 4; }\ninline constexpr int outside[9][2] = {{-1, -1}, {0, -1}, {0, 1},  {1, 2},  {2, 6},\n                                      {6, 7},   {7, 8},  {8, -1}, {-1, -1}};\nvoid yaku(Meld const *melds, int size, int const *available, int round, int seat,\n          uint8_t *out);\nint meld_fu(Meld const &meld);\nint meld_bonus(Meld const *melds, int size, int const *dora);\nvoid pack_base(Row row, State const &state, Analysis &analysis);\nvoid pack_candidates(Row row, State const &state, Analysis const &analysis,\n                     Branch const *branches, size_t branch_count, Legal &legal,\n                     RangeContext const &availability, void *context,\n                     Score score);\n} // namespace feature\n",
      "sha256": "59d17ef8d1a5758bbb0b1dc73d64c8c03d1ba19f9a33236b4ce77f7eb01b707b"
    },
    {
      "path": "log_dataset/native_collection/cpp/scoring.cpp",
      "text": "#include \"analysis.hpp\"\n#include \"features.hpp\"\nnamespace feature {\nRanges ranges(Hand const &hand, RangeContext const &ctx, int cut, void *context,\n              Score score, uint64_t draw) {\n  uint8_t counts[34]{};\n  for (int i = 0; i < hand.size; ++i)\n    ++counts[hand.tiles[i] / 4];\n  int shanten = int(draw >> 34) - 1;\n  uint64_t improving = draw & ((1ull << 34) - 1);\n  Ranges result{};\n  if (shanten < 0 || shanten > 1)\n    return result;\n  result.eligible = 1;\n  if (shanten == 0) {\n    score(context, &hand, &ctx, cut, improving, &result);\n    return result;\n  }\n  auto next = ctx;\n  next.missed_agari = 0;\n  if (cut >= 0)\n    next.own_discards |= 1ull << cut;\n  for (int base = 0; base < 34; ++base)\n    if ((improving & (1ull << base)) && ctx.unavailable[base] < 4) {\n      ++counts[base];\n      ++next.unavailable[base];\n      uint64_t waits[34]{};\n      nyanten_tenpai_discards(counts, waits);\n      bool five = base == 4 || base == 13 || base == 22;\n      int reds = five ? 1 - ctx.unavailable_red[base / 9] : 0;\n      int copies[] = {4 - ctx.unavailable[base] - reds, reds};\n      for (int is_red = 0; is_red < 2; ++is_red)\n        if (copies[is_red] > 0) {\n          int tile = base * 4 + (five && !is_red);\n          while (std::find(hand.tiles, hand.tiles + hand.size, tile) !=\n                 hand.tiles + hand.size)\n            ++tile;\n          auto after = hand;\n          after.tiles[after.size++] = tile;\n          if (is_red)\n            ++next.unavailable_red[base / 9];\n          bool seen[37]{};\n          for (int pos = 0; pos < after.size; ++pos) {\n            int discarded = after.tiles[pos], code = feature::code(discarded);\n            if (seen[code] || !waits[discarded / 4])\n              continue;\n            seen[code] = true;\n            auto ready = after;\n            std::move(ready.tiles + pos + 1, ready.tiles + ready.size, ready.tiles + pos);\n            --ready.size;\n            Ranges value{};\n            score(context, &ready, &next, discarded / 4, waits[discarded / 4], &value);\n            result.merge(value);\n          }\n          if (is_red)\n            --next.unavailable_red[base / 9];\n        }\n      --counts[base];\n      --next.unavailable[base];\n    }\n  return result;\n}\n} // namespace feature\nextern \"C\" void feature_ranges(feature::Hand const *hand,\n                               feature::RangeContext const *ctx, int cut, void *opaque,\n                               feature::Score score, feature::Ranges *out) {\n  uint8_t counts[34]{};\n  for (int i = 0; i < hand->size; ++i)\n    ++counts[hand->tiles[i] / 4];\n  *out = feature::ranges(*hand, *ctx, cut, opaque, score, nyanten_draw(counts, 1));\n}\n",
      "sha256": "7017d8c375234cca13e6d03ccd8c5716dd33e1d51f6a04f0595aa54cab595fdf"
    },
    {
      "path": "log_dataset/native_collection/cpp/yaku.cpp",
      "text": "#include \"features.hpp\"\nnamespace feature {\nint meld_fu(Meld const &m) {\n  constexpr int values[] = {0, 2, 8, 16, 8};\n  int t = m.tiles[0] / 4;\n  return values[m.kind] * (1 + (t >= 27 || t % 9 == 0 || t % 9 == 8));\n}\nint meld_bonus(Meld const *melds, int size, int const *dora) {\n  int bonus = 0;\n  for (int i = 0; i < size; ++i)\n    for (int j = 0; j < melds[i].size; ++j) {\n      int t = melds[i].tiles[j];\n      bonus += dora[t / 4] + red(t);\n    }\n  return bonus;\n}\nvoid yaku(Meld const *melds, int size, int const *available, int round, int seat,\n          uint8_t *out) {\n  bool fixed[34]{};\n  bool simple = true, suited = true, honors = true, terminals = true,\n       terminal_honor = true, outside_all = true, closed = true;\n  unsigned suits = 0;\n  int sequences = 0, free = 4 - size;\n  auto terminal = [](int t) { return t < 27 && (t % 9 == 0 || t % 9 == 8); };\n  for (int i = 0; i < size; ++i) {\n    auto const &m = melds[i];\n    sequences += m.kind == 0;\n    if (m.kind != 0)\n      fixed[m.tiles[0] / 4] = true;\n    bool outside = false;\n    closed &= !m.opened;\n    for (int j = 0; j < m.size; ++j) {\n      int t = m.tiles[j] / 4;\n      if (t < 27)\n        suits |= 1u << (t / 9);\n      simple &= t < 27 && !terminal(t);\n      suited &= t < 27;\n      honors &= t >= 27;\n      terminals &= terminal(t);\n      terminal_honor &= t >= 27 || terminal(t);\n      outside |= t >= 27 || terminal(t);\n    }\n    outside_all &= outside;\n  }\n  auto triplet = [&](int t) { return fixed[t] || (free > 0 && available[t] >= 3); };\n  std::fill_n(out, 19, 0);\n  out[0] = simple;\n  int dragons[] = {31, 32, 33, 27 + round, 27 + seat};\n  for (int i = 0; i < 5; ++i)\n    out[1 + i] = triplet(dragons[i]);\n  out[6] = __builtin_popcount(suits) <= 1;\n  out[7] = out[6] && suited;\n  out[8] = sequences == 0;\n  out[9] = size == 0;\n  for (int pair = 31; pair < 34; ++pair) {\n    bool valid = !fixed[pair] && available[pair] >= 2;\n    int needed = 0;\n    for (int t = 31; t < 34; ++t)\n      if (t != pair) {\n        valid &= triplet(t);\n        needed += !fixed[t];\n      }\n    out[10] |= valid && needed <= free;\n  }\n  int needed = 0;\n  bool valid = true;\n  for (int t = 31; t < 34; ++t) {\n    valid &= triplet(t);\n    needed += !fixed[t];\n  }\n  out[11] = valid && needed <= free;\n  out[12] = honors;\n  out[13] = terminals;\n  out[14] = terminal_honor;\n  out[15] = size == 0;\n  for (int t = 0; t < 34; ++t)\n    if (t >= 27 || terminal(t))\n      out[15] &= available[t] > 0;\n  out[16] = outside_all && (sequences > 0 || free > 0);\n  out[17] = out[16] && suited;\n  out[18] = closed && free >= 2;\n}\n} // namespace feature\nextern \"C\" void feature_yaku(feature::Meld const *melds, int size, int const *available,\n                             int round, int seat, uint8_t *out) {\n  feature::yaku(melds, size, available, round, seat, out);\n}\nextern \"C\" void feature_public_values(feature::Meld const *melds, int size,\n                                      int const *dora, int *out) {\n  out[0] = 0;\n  for (int i = 0; i < size; ++i)\n    out[0] += feature::meld_fu(melds[i]);\n  out[1] = feature::meld_bonus(melds, size, dora);\n}\n",
      "sha256": "ac713fb42c1d9c94715c9039ec64d195bf2425fb68ff465bc7a9aee5c562cac6"
    },
    {
      "path": "log_dataset/native_collection/src/features.rs",
      "text": "//! Typed engine snapshots for the shared C++ feature calculator.\nuse crate::{candidate, history::PublicHistory, packed::Row, scoring};\nuse riichienv_core::{\n    action::ActionType,\n    observation::Observation,\n    replay::MjaiEvent,\n    types::{Meld, MeldType},\n};\n\n#[repr(C)]\n#[derive(Clone, Copy, Default)]\npub struct NativeMeld {\n    kind: i32,\n    opened: i32,\n    size: i32,\n    tiles: [i32; 4],\n    called: i32,\n    event_size: i32,\n    event_tiles: [i32; 4],\n    target: i32,\n    event: i32,\n    upgrade: i32,\n}\nimpl NativeMeld {\n    pub fn new(meld: &Meld) -> Self {\n        let mut out = Self {\n            kind: meld.meld_type as i32,\n            opened: meld.opened as i32,\n            size: meld.tiles.len() as i32,\n            called: meld.called_tile.map_or(-1, i32::from),\n            ..Self::default()\n        };\n        for (i, &tile) in meld.tiles.iter().enumerate() {\n            out.tiles[i] = tile as i32;\n        }\n        out\n    }\n    fn meld(&self) -> Meld {\n        Meld {\n            meld_type: match self.kind {\n                0 => MeldType::Chi,\n                1 => MeldType::Pon,\n                2 => MeldType::Daiminkan,\n                3 => MeldType::Ankan,\n                4 => MeldType::Kakan,\n                _ => unreachable!(),\n            },\n            tiles: self.tiles[..self.size as usize]\n                .iter()\n                .map(|&t| t as u8)\n                .collect(),\n            opened: self.opened != 0,\n            from_who: -1,\n            called_tile: (self.called >= 0).then_some(self.called as u8),\n        }\n    }\n}\n#[repr(C)]\n#[derive(Clone, Copy, Default)]\nstruct NativeRiver {\n    tile: i32,\n    event: i32,\n    wall: i32,\n    turns: [i32; 4],\n    origin: i32,\n    riichi: i32,\n    resolution: i32,\n    caller: i32,\n    dora: i32,\n    tsumogiri: i32,\n}\n#[repr(C)]\n#[derive(Clone, Copy, Default)]\npub struct NativeHand {\n    size: i32,\n    tiles: [i32; 14],\n    meld_count: i32,\n    melds: [NativeMeld; 4],\n}\nimpl NativeHand {\n    fn new(obs: &Observation, actor: usize) -> Self {\n        let mut out = Self {\n            size: obs.hands[actor].len() as i32,\n            meld_count: obs.melds[actor].len() as i32,\n            ..Self::default()\n        };\n        for (i, &tile) in obs.hands[actor].iter().enumerate() {\n            out.tiles[i] = tile as i32;\n        }\n        for (i, meld) in obs.melds[actor].iter().enumerate() {\n            out.melds[i] = NativeMeld::new(meld);\n        }\n        out\n    }\n}\n#[repr(C)]\nstruct State {\n    hand: NativeHand,\n    melds: [[NativeMeld; 4]; 4],\n    meld_count: [i32; 4],\n    rivers: [*const NativeRiver; 4],\n    river_count: [usize; 4],\n    boundary: [i32; 4],\n    accepted_event: [i32; 4],\n    declared: [i32; 4],\n    accepted: [i32; 4],\n    ippatsu: [i32; 4],\n    draw: i32,\n    actor: i32,\n    phase: i32,\n    tsumo: i32,\n    rinshan: i32,\n    events: i32,\n    wall: i32,\n    oya: i32,\n    kyoku: i32,\n    wind: i32,\n    honba: i32,\n    sticks: i32,\n    scores: [i32; 4],\n    dora_size: i32,\n    dora: [i32; 5],\n    public_counts: [i32; 37],\n    exposed: [i32; 34],\n    trigger_seat: i32,\n    trigger_tile: i32,\n}\n#[repr(C)]\nstruct Analysis {\n    counts: [u8; 34],\n    unavailable: [u8; 34],\n    unavailable_red: [i32; 3],\n    genbutsu: [[u8; 34]; 4],\n    dora_counts: [i32; 34],\n}\n#[repr(C)]\nstruct Branch {\n    hand: NativeHand,\n    response: i32,\n    option: i32,\n    tile: i32,\n    cuts: [u8; 37],\n    exposed: [i32; 34],\n}\n#[repr(C)]\nstruct Legal {\n    discards: [u8; 37],\n    riichi: [u8; 37],\n    calls: [[u8; 37]; 4],\n}\n#[repr(C)]\n#[derive(Default)]\npub struct Ranges {\n    pub values: [f64; 8],\n    pub valid: [u8; 4],\n    pub restricted: [u8; 2],\n    pub eligible: u8,\n}\n#[repr(C)]\npub struct RangeContext {\n    pub own_discards: u64,\n    pub missed_agari: i32,\n    pub unavailable: [u8; 34],\n    pub unavailable_red: [i32; 3],\n    pub riichi: u8,\n}\nimpl RangeContext {\n    pub fn new(ctx: &scoring::Context) -> Self {\n        Self {\n            own_discards: ctx.own_discards.iter().fold(0, |mask, &t| mask | (1 << t)),\n            missed_agari: ctx.missed_agari as i32,\n            unavailable: ctx.unavailable,\n            unavailable_red: ctx.unavailable_red,\n            riichi: 0,\n        }\n    }\n    pub fn available_tiles(&self, base: u8) -> impl Iterator<Item = (u8, bool)> {\n        let five = matches!(base, 4 | 13 | 22);\n        let reds = if five {\n            1 - self.unavailable_red[base as usize / 9]\n        } else {\n            0\n        };\n        [\n            (\n                base * 4 + u8::from(five),\n                false,\n                4 - self.unavailable[base as usize] as i32 - reds,\n            ),\n            (base * 4, true, reds),\n        ]\n        .into_iter()\n        .filter(|&(_, _, copies)| copies > 0)\n        .map(|(tile, red, _)| (tile, red))\n    }\n}\ntype Score = unsafe extern \"C\" fn(\n    *mut std::ffi::c_void,\n    *const NativeHand,\n    *const RangeContext,\n    i32,\n    u64,\n    *mut Ranges,\n);\nunsafe extern \"C\" {\n    fn feature_pack_base(row: *mut u8, state: *const State, analysis: *mut Analysis);\n    fn feature_pack_candidates(\n        row: *mut u8,\n        state: *const State,\n        analysis: *const Analysis,\n        branches: *const Branch,\n        size: usize,\n        legal: *mut Legal,\n        availability: *const RangeContext,\n        context: *mut std::ffi::c_void,\n        score: Score,\n    );\n    #[cfg(test)]\n    fn feature_ranges(\n        hand: *const NativeHand,\n        ctx: *const RangeContext,\n        cut: i32,\n        opaque: *mut std::ffi::c_void,\n        score: Score,\n        out: *mut Ranges,\n    );\n}\nunsafe extern \"C\" fn score(\n    context: *mut std::ffi::c_void,\n    hand: *const NativeHand,\n    availability: *const RangeContext,\n    cut: i32,\n    waits: u64,\n    out: *mut Ranges,\n) {\n    let ctx = unsafe { &*(context as *const scoring::Context) };\n    let hand = unsafe { &*hand };\n    let tiles: Vec<u8> = hand.tiles[..hand.size as usize]\n        .iter()\n        .map(|&t| t as u8)\n        .collect();\n    let melds: Vec<Meld> = hand.melds[..hand.meld_count as usize]\n        .iter()\n        .map(NativeMeld::meld)\n        .collect();\n    let result = scoring::ready_ranges(\n        tiles,\n        melds,\n        ctx,\n        unsafe { &*availability },\n        (cut >= 0).then_some(cut as u8),\n        waits,\n    );\n    unsafe {\n        *out = Ranges {\n            values: result.values,\n            valid: result.valid,\n            restricted: result.restricted,\n            eligible: result.eligible as u8,\n        };\n    }\n}\n#[cfg(test)]\npub fn ranges(\n    tiles: &[u8],\n    melds: &[Meld],\n    ctx: &scoring::Context,\n    cut: Option<u8>,\n) -> scoring::Ranges {\n    let mut hand = NativeHand {\n        size: tiles.len() as i32,\n        meld_count: melds.len() as i32,\n        ..NativeHand::default()\n    };\n    for (i, &t) in tiles.iter().enumerate() {\n        hand.tiles[i] = t as i32;\n    }\n    for (i, m) in melds.iter().enumerate() {\n        hand.melds[i] = NativeMeld::new(m);\n    }\n    let mut out = Ranges::default();\n    unsafe {\n        feature_ranges(\n            &hand,\n            &RangeContext::new(ctx),\n            cut.map_or(-1, i32::from),\n            ctx as *const _ as *mut std::ffi::c_void,\n            score,\n            &mut out,\n        );\n    }\n    scoring::Ranges {\n        values: out.values,\n        valid: out.valid,\n        restricted: out.restricted,\n        eligible: out.eligible != 0,\n    }\n}\n// This is a public observation snapshot, not hidden opponent hand data.\npub fn exposed(obs: &Observation) -> [i32; 34] {\n    let mut values = [0; 34];\n    for tile in obs\n        .discards\n        .iter()\n        .flatten()\n        .chain(obs.dora_indicators.iter())\n    {\n        values[*tile as usize / 4] += 1;\n    }\n    for meld in obs.melds.iter().flatten() {\n        for &tile in &meld.tiles {\n            values[tile as usize / 4] += 1;\n        }\n        if let Some(tile) = meld.called_tile {\n            values[tile as usize / 4] -= 1;\n        }\n    }\n    values\n}\npub fn pack(\n    row: &mut Row,\n    history: &mut PublicHistory,\n    obs: &Observation,\n    actor: usize,\n    phase: u8,\n) -> candidate::Legal {\n    for (index, tile) in history.dora_markers.iter().enumerate() {\n        row.reference_dora[index] = candidate::base(*tile) as u8;\n        row.reference_dora[5 + index] = 1;\n    }\n    let rivers: [Vec<NativeRiver>; 4] = std::array::from_fn(|seat| {\n        history.rivers[seat]\n            .iter()\n            .map(|cut| NativeRiver {\n                tile: cut.tile as i32,\n                event: cut.event_index as i32,\n                wall: cut.live_wall,\n                turns: cut.own_turns.map(|x| x as i32),\n                origin: cut.origin as i32,\n                riichi: cut.riichi as i32,\n                resolution: cut.resolution as i32,\n                caller: cut.caller.map_or(-1, |x| x as i32),\n                dora: cut.dora_multiplicity as i32,\n                tsumogiri: cut.tsumogiri as i32,\n            })\n            .collect()\n    });\n    let mut state = State {\n        hand: NativeHand::new(obs, actor),\n        melds: [[NativeMeld::default(); 4]; 4],\n        meld_count: std::array::from_fn(|seat| history.replay.players[seat].melds.len() as i32),\n        rivers: std::array::from_fn(|seat| rivers[seat].as_ptr()),\n        river_count: std::array::from_fn(|seat| rivers[seat].len()),\n        boundary: history.riichi_boundary.map(|v| v.map_or(-1, |x| x as i32)),\n        accepted_event: history.accepted_event.map(|v| v.map_or(-1, |x| x as i32)),\n        declared: history.declared.map(i32::from),\n        accepted: history.accepted.map(i32::from),\n        ippatsu: history.ippatsu.map(i32::from),\n        draw: history.draws[actor].map_or(-1, |x| x as i32),\n        actor: actor as i32,\n        phase: phase as i32,\n        tsumo: obs\n            .legal_actions_method()\n            .iter()\n            .any(|a| a.action_type == ActionType::Tsumo) as i32,\n        rinshan: history.rinshan_actor.map_or(-1, |x| x as i32),\n        events: history.events.len() as i32,\n        wall: history.live_wall,\n        oya: history.start[\"oya\"].as_i64().unwrap() as i32,\n        kyoku: history.start[\"kyoku\"].as_i64().unwrap() as i32,\n        wind: \"ESWN\"\n            .find(history.start[\"bakaze\"].as_str().unwrap())\n            .unwrap() as i32,\n        honba: history.start[\"honba\"].as_i64().unwrap() as i32,\n        sticks: obs.riichi_sticks as i32,\n        scores: obs.scores.clone().try_into().unwrap(),\n        dora_size: history.dora_markers.len() as i32,\n        dora: [0; 5],\n        public_counts: [0; 37],\n        exposed: exposed(obs),\n        trigger_seat: history.pending_discard.map_or(-1, |(seat, _)| seat as i32),\n        trigger_tile: history\n            .pending_discard\n            .map_or(-1, |(seat, index)| history.rivers[seat][index].tile as i32),\n    };\n    for seat in 0..4 {\n        for (i, meld) in history.replay.players[seat].melds.iter().enumerate() {\n            let event = &history.meld_events[seat][i];\n            let mut m = NativeMeld::new(meld);\n            let tiles: Vec<usize> = event\n                .tile\n                .iter()\n                .chain(event.consumed.iter())\n                .chain(event.upgrade_tile.iter())\n                .copied()\n                .collect();\n            m.event_size = tiles.len() as i32;\n            for (j, tile) in tiles.into_iter().enumerate() {\n                m.event_tiles[j] = tile as i32;\n            }\n            m.target = event.target.map_or(-1, |x| x as i32);\n            m.event = event.event_index as i32;\n            m.upgrade = event.upgrade_index.map_or(-1, |x| x as i32);\n            state.melds[seat][i] = m;\n        }\n    }\n    for (i, &tile) in history.dora_markers.iter().enumerate() {\n        state.dora[i] = tile as i32;\n    }\n    for tile in history.public_tiles() {\n        state.public_counts[tile] += 1;\n    }\n    let mut analysis: Analysis = unsafe { std::mem::zeroed() };\n    unsafe {\n        feature_pack_base(row.bytes.as_mut_ptr(), &state, &mut analysis);\n    }\n    let mut legal = Legal {\n        discards: [0; 37],\n        riichi: [0; 37],\n        calls: [[0; 37]; 4],\n    };\n    let actions = obs.legal_actions_method();\n    for action in &actions {\n        if action.action_type == ActionType::Discard {\n            legal.discards[candidate::code(action.tile.unwrap())] = 1;\n        }\n        if action.action_type == ActionType::Riichi {\n            let mut declared = history.replay.clone();\n            declared.apply_mjai_event(MjaiEvent::Reach { actor });\n            for cut in declared.get_observation(actor as u8).legal_actions_method() {\n                if cut.action_type == ActionType::Discard {\n                    legal.riichi[candidate::code(cut.tile.unwrap())] = 1;\n                }\n            }\n        }\n    }\n    let mut branches = Vec::new();\n    for action in candidate::prefer_red_calls(actions) {\n        let response = match action.action_type {\n            ActionType::Chi => 1,\n            ActionType::Pon => 2,\n            ActionType::Daiminkan => 3,\n            ActionType::Ankan | ActionType::Kakan => 0,\n            _ => continue,\n        };\n        let mut event: serde_json::Value = serde_json::from_str(&action.to_mjai()).unwrap();\n        event[\"actor\"] = serde_json::json!(actor);\n        if response != 0 {\n            event[\"target\"] = serde_json::json!(history.pending_discard.unwrap().0);\n        }\n        let mut env = history.replay.clone();\n        env.apply_mjai_event(serde_json::from_value(event.clone()).unwrap());\n        let next = env.get_observation(actor as u8);\n        let tile = action.tile.unwrap() / 4;\n        let option = if response == 1 {\n            tile - action\n                .consume_tiles\n                .iter()\n                .map(|t| t / 4)\n                .chain([tile])\n                .min()\n                .unwrap()\n        } else if response == 2 {\n            3\n        } else {\n            0\n        };\n        let mut branch = Branch {\n            hand: NativeHand::new(&next, actor),\n            response,\n            option: option as i32,\n            tile: tile as i32,\n            cuts: [0; 37],\n            exposed: exposed(&next),\n        };\n        if response == 1 || response == 2 {\n            for cut in next.legal_actions_method() {\n                if cut.action_type == ActionType::Discard {\n                    branch.cuts[candidate::code(cut.tile.unwrap())] = 1;\n                }\n            }\n            if phase == 1 || phase == 4 {\n                let mut called_history = history.clone();\n                called_history.apply(&event);\n                let called_observation = called_history.legal_observation(actor);\n                let mut called_row = Row::new();\n                pack(\n                    &mut called_row,\n                    &mut called_history,\n                    &called_observation,\n                    actor,\n                    0,\n                );\n                row.post_calls.push((option, called_row));\n            }\n        }\n        branches.push(branch);\n    }\n    let mut ctx = scoring::Context {\n        own_discards: history.rivers[actor]\n            .iter()\n            .map(|event| candidate::base(event.tile) as u8)\n            .collect(),\n        missed_agari: history.missed_agari(actor),\n        unavailable: analysis.unavailable,\n        unavailable_red: analysis.unavailable_red,\n        dora: obs.dora_indicators.iter().map(|&t| t as u8).collect(),\n        player_wind: ((actor + 4 - state.oya as usize) % 4) as u8,\n        round_wind: state.wind as u8,\n    };\n    unsafe {\n        feature_pack_candidates(\n            row.bytes.as_mut_ptr(),\n            &state,\n            &analysis,\n            branches.as_ptr(),\n            branches.len(),\n            &mut legal,\n            &RangeContext {\n                riichi: state.accepted[actor] as u8,\n                ..RangeContext::new(&ctx)\n            },\n            &mut ctx as *mut _ as *mut std::ffi::c_void,\n            score,\n        );\n    }\n    candidate::Legal {\n        discards: legal.discards.map(|v| v != 0),\n        riichi: legal.riichi.map(|v| v != 0),\n        calls: legal.calls.map(|v| v.map(|x| x != 0)),\n    }\n}\n\n#[cfg(test)]\n#[repr(C)]\npub struct Bank {\n    keys: [[u8; 63]; 16],\n    size: i32,\n}\n#[cfg(test)]\nimpl Default for Bank {\n    fn default() -> Self {\n        Self {\n            keys: [[0; 63]; 16],\n            size: 0,\n        }\n    }\n}\n#[cfg(test)]\npub fn bank_hand(\n    row: &mut Row,\n    bank: &mut Bank,\n    tiles: &[u8],\n    melds: &[Meld],\n    yaku: &[u8; 19],\n) -> usize {\n    let mut hand = NativeHand {\n        size: tiles.len() as i32,\n        meld_count: melds.len() as i32,\n        ..NativeHand::default()\n    };\n    for (i, &t) in tiles.iter().enumerate() {\n        hand.tiles[i] = t as i32;\n    }\n    for (i, m) in melds.iter().enumerate() {\n        hand.melds[i] = NativeMeld::new(m);\n    }\n    unsafe extern \"C\" {\n        fn feature_bank_hand(\n            row: *mut u8,\n            bank: *mut Bank,\n            hand: *const NativeHand,\n            yaku: *const u8,\n        ) -> i32;\n    }\n    unsafe { feature_bank_hand(row.bytes.as_mut_ptr(), bank, &hand, yaku.as_ptr()) as usize }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n    #[test]\n    fn transport_layout_matches_cpp() {\n        use std::mem::{offset_of, size_of};\n        unsafe extern \"C\" {\n            fn feature_layout(out: *mut usize);\n        }\n        let mut layout = [0usize; 14];\n        unsafe {\n            feature_layout(layout.as_mut_ptr());\n        }\n        assert_eq!(\n            layout,\n            [\n                size_of::<NativeMeld>(),\n                size_of::<NativeRiver>(),\n                size_of::<NativeHand>(),\n                size_of::<State>(),\n                size_of::<Analysis>(),\n                size_of::<Branch>(),\n                size_of::<Legal>(),\n                size_of::<Ranges>(),\n                size_of::<RangeContext>(),\n                size_of::<Bank>(),\n                offset_of!(State, rivers),\n                offset_of!(State, exposed),\n                offset_of!(Analysis, genbutsu),\n                offset_of!(RangeContext, unavailable_red)\n            ]\n        );\n    }\n}\n",
      "sha256": "e03d24e1a111840c0724651f2338faa3226ea81b67dbd91b9e5032c7c047db3a"
    },
    {
      "path": "log_dataset/native_collection/src/lib.rs",
      "text": "mod actions;\nmod candidate;\nmod collector;\nmod features;\nmod history;\n#[cfg(test)]\nmod nyanten;\nmod packed;\nmod schema;\nmod scoring;\n#[cfg(test)]\nmod yaku;\nuse packed::{FIELDS, Row};\nuse pyo3::{\n    prelude::*,\n    types::{PyBytes, PyDict},\n};\nfn columns<'py>(py: Python<'py>, rows: &[&Row]) -> PyResult<Bound<'py, PyDict>> {\n    let output = PyDict::new(py);\n    for field in FIELDS {\n        let bytes = PyBytes::new_with(py, field.size * rows.len(), |bytes| {\n            for (destination, row) in bytes.chunks_exact_mut(field.size).zip(rows) {\n                destination.copy_from_slice(&row.bytes[field.offset..field.offset + field.size]);\n            }\n            Ok(())\n        })?;\n        output.set_item(field.name, bytes)?;\n    }\n    let mut calls = Vec::new();\n    for row in rows {\n        for (option, state) in &row.post_calls {\n            calls.push(*option);\n            calls.extend_from_slice(&state.bytes);\n        }\n    }\n    output.set_item(\"post_call\", PyBytes::new(py, &calls))?;\n    Ok(output)\n}\n#[pyclass]\nstruct FeatureReplay {\n    history: history::PublicHistory,\n}\n#[pymethods]\nimpl FeatureReplay {\n    #[new]\n    fn new() -> Self {\n        Self {\n            history: history::PublicHistory::new(),\n        }\n    }\n    fn apply(&mut self, events: &str) -> PyResult<()> {\n        let events: Vec<serde_json::Value> = serde_json::from_str(events)\n            .map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))?;\n        for event in events {\n            self.history.apply(&event);\n            if event[\"type\"] == \"tsumo\" {\n                if let Some(left) = event[\"tiles_left\"].as_i64() {\n                    self.history.live_wall = left as i32;\n                }\n            }\n        }\n        Ok(())\n    }\n    fn pack<'py>(\n        &mut self,\n        py: Python<'py>,\n        actor: usize,\n        phase: u8,\n    ) -> PyResult<Bound<'py, PyDict>> {\n        let row = py.detach(|| {\n            let obs = self.history.legal_observation(actor);\n            let mut row = Row::new();\n            features::pack(&mut row, &mut self.history, &obs, actor, phase);\n            row\n        });\n        columns(py, &[&row])\n    }\n}\n#[pymodule]\nfn _native_collection(m: &Bound<'_, PyModule>) -> PyResult<()> {\n    let inputs = PyDict::new(m.py());\n    for field in FIELDS {\n        let spec = PyDict::new(m.py());\n        spec.set_item(\"shape\", field.shape.to_vec())?;\n        spec.set_item(\"dtype\", field.dtype.name())?;\n        inputs.set_item(field.name, spec)?;\n    }\n    m.add(\"INPUTS\", inputs)?;\n    m.add_function(wrap_pyfunction!(scoring::score_hand, m)?)?;\n    m.add_class::<FeatureReplay>()?;\n    m.add_class::<collector::NativeCollector>()?;\n    m.add_class::<collector::NativeRoot>()?;\n    Ok(())\n}\n",
      "sha256": "af43a4a56471f584f7970565baa7db4946a596c58b247e777bf4e3091cb5dd25"
    },
    {
      "path": "log_dataset/native_collection/src/schema.rs",
      "text": "#[derive(Clone, Copy)]\npub enum Dtype {\n    INT8,\n    INT16,\n    FLOAT16,\n    FLOAT32,\n    INT32,\n}\nimpl Dtype {\n    pub const fn name(self) -> &'static str {\n        match self {\n            Self::INT8 => \"int8\",\n            Self::INT16 => \"int16\",\n            Self::FLOAT16 => \"float16\",\n            Self::FLOAT32 => \"float32\",\n            Self::INT32 => \"int32\",\n        }\n    }\n    const fn width(self) -> usize {\n        match self {\n            Self::INT8 => 1,\n            Self::INT16 | Self::FLOAT16 => 2,\n            Self::FLOAT32 | Self::INT32 => 4,\n        }\n    }\n}\npub struct Field {\n    pub name: &'static str,\n    pub shape: &'static [usize],\n    pub dtype: Dtype,\n    pub count: usize,\n    pub width: usize,\n    pub offset: usize,\n    pub size: usize,\n}\nconst fn layout<const N: usize>(mut fields: [Field; N]) -> [Field; N] {\n    let mut offset = 0;\n    let mut index = 0;\n    while index < N {\n        fields[index].count = 1;\n        let mut dimension = 0;\n        while dimension < fields[index].shape.len() {\n            fields[index].count *= fields[index].shape[dimension];\n            dimension += 1;\n        }\n        fields[index].width = fields[index].dtype.width();\n        fields[index].size = fields[index].count * fields[index].width;\n        fields[index].offset = offset;\n        offset += fields[index].size;\n        index += 1;\n    }\n    fields\n}\nmacro_rules! fields {\n    ($($name:ident: $dtype:ident [$($dimension:literal),*]),* $(,)?) => {\n        pub const FIELDS: &[Field] = &layout([$(Field {\n            name: stringify!($name), shape: &[$($dimension),*], dtype: Dtype::$dtype,\n            count: 0, width: 0, offset: 0, size: 0,\n        }),*]);\n    };\n}\n// Keep declaration order stable: Python model projections use this order.\n// Names, dimensions and storage types belong to the native output boundary.\nfields! {\n    candidate_hand_counts: INT8 [16, 34],\n    candidate_hand_red: INT8 [16, 3],\n    candidate_hand_yaku_possibility: INT8 [16, 19],\n    candidate_meld_tiles: INT8 [16, 4],\n    candidate_meld_types: INT8 [16, 4],\n    candidate_meld_red: INT8 [16, 3],\n    candidate_hand_valid: INT8 [16],\n    discard_candidate_hand: INT8 [37],\n    kan_candidate_hand: INT8 [34],\n    river_pre_tile_id: INT8 [3, 32],\n    river_pre_is_red: INT8 [3, 32],\n    river_pre_tsumogiri: INT8 [3, 32],\n    river_pre_origin: INT8 [3, 32],\n    river_pre_riichi: INT8 [3, 32],\n    river_pre_call_resolution: INT8 [3, 32],\n    river_pre_caller: INT8 [3, 32],\n    river_pre_event_age: FLOAT16 [3, 32],\n    river_pre_own_gap: FLOAT16 [3, 32],\n    river_pre_live_wall: FLOAT16 [3, 32],\n    river_pre_current_dora_multiplicity: INT8 [3, 32],\n    river_pre_dora_multiplicity_at_discard: INT8 [3, 32],\n    river_pre_valid: INT8 [3, 32],\n    river_post_tile_id: INT8 [3, 32],\n    river_post_is_red: INT8 [3, 32],\n    river_post_tsumogiri: INT8 [3, 32],\n    river_post_origin: INT8 [3, 32],\n    river_post_call_resolution: INT8 [3, 32],\n    river_post_caller: INT8 [3, 32],\n    river_post_event_age: FLOAT16 [3, 32],\n    river_post_own_gap: FLOAT16 [3, 32],\n    river_post_live_wall: FLOAT16 [3, 32],\n    river_post_current_dora_multiplicity: INT8 [3, 32],\n    river_post_dora_multiplicity_at_discard: INT8 [3, 32],\n    river_post_valid: INT8 [3, 32],\n    meld_type: INT8 [4, 4],\n    meld_tiles: INT8 [4, 4, 4],\n    meld_source: INT8 [4, 4],\n    meld_call_age: FLOAT16 [4, 4],\n    meld_upgrade_age: FLOAT16 [4, 4],\n    current_draw_tile_id: INT8 [],\n    current_draw_is_red: INT8 [],\n    current_draw_valid: INT8 [],\n    normal_self_shanten: INT8 [],\n    chiitoitsu_self_shanten: INT8 [],\n    kokushi_self_shanten: INT8 [],\n    closed_hand: INT8 [],\n    self_efficiency: FLOAT32 [3],\n    dora_multiplicity: INT8 [34],\n    public_visible_red_counts: INT8 [3],\n    known_unavailable_counts: INT8 [34],\n    prevailing_wind: INT8 [],\n    hands_remaining: INT8 [],\n    dealer_relative_seat: INT8 [],\n    honba: INT16 [],\n    riichi_sticks: INT8 [],\n    live_wall_count: INT8 [],\n    total_kan_count: INT8 [],\n    scores: INT32 [4],\n    ranks: INT8 [4],\n    seat_wind: INT8 [4],\n    open_opponent_yaku_possibility: INT8 [4, 13],\n    opponent_called_tile_count: INT8 [4],\n    opponent_discard_count: INT8 [4],\n    nagashi_possible: INT8 [4],\n    pao_payer: INT8 [4],\n    last_tedashi_tile_id: INT8 [4],\n    riichi_push_count: INT8 [4, 4],\n    genbutsu_to_seat: INT8 [4, 34],\n    passed_unchanged_to_seat: INT8 [4, 34],\n    sotogawa_earliest_turn_to_seat: INT8 [4, 34],\n    win_kind: INT8 [],\n    decision_phase: INT8 [],\n    trigger_tile_id: INT8 [],\n    trigger_is_red: INT8 [],\n    trigger_valid: INT8 [],\n    trigger_source: INT8 [],\n    riichi_state: INT8 [4],\n    ippatsu_alive: INT8 [4],\n    rinshan_state: INT8 [],\n    riichi_legal_mask: INT8 [2],\n    riichi_discard_legal_mask: INT8 [37],\n    response_legal_mask: INT8 [4],\n    call_discard_legal: INT8 [4, 37],\n    call_discard_shanten: INT8 [4, 37],\n    call_discard_ukeire_count: INT16 [4, 37],\n    kan_legal_mask: INT8 [35],\n    call_efficiency: FLOAT32 [4, 3],\n    kan_efficiency: FLOAT32 [34, 3],\n    discard_abort: INT8 [2, 37],\n    discard_action_legal: INT8 [37],\n    discard_tedashi_legal: INT8 [37],\n    discard_action_normal_shanten: INT8 [37],\n    discard_action_normal_ukeire_count: INT16 [37],\n    discard_action_all_shanten: INT8 [37],\n    discard_action_all_ukeire_count: INT16 [37],\n    discard_retained_genbutsu: INT8 [37, 4],\n    action_win_value_range: FLOAT32 [110, 2, 2],\n    action_win_value_valid: INT8 [110, 2],\n    action_value_eligible: INT8 [110],\n    action_open_yaku_restricted: INT8 [110, 2],\n    candidate_yaku_shanten: INT8 [16, 3],\n    public_bonus: INT8 [4],\n    candidate_fu: INT16 [16],\n}\npub const ROW_BYTES: usize = FIELDS[FIELDS.len() - 1].offset + FIELDS[FIELDS.len() - 1].size;\n",
      "sha256": "5d55e96b7be50007d76ebb52559513b6749330925e212f350e92dc9255127f45"
    },
    {
      "path": "log_dataset/player_ranks.py",
      "text": "\"\"\"Create a fixed player-game selection from original Tenhou databases.\"\"\"\n\nimport collections\nimport gzip\nimport hashlib\nimport json\nimport pathlib\nimport re\nimport sqlite3\nimport urllib.parse\nimport xml.etree.ElementTree\nimport zipfile\n\nSAMPLING = {\n    \"unit\": \"game_id_seat\",\n    \"rank\": \"historical_tenhou_dan\",\n    \"rates\": {\"7\": 0.5, \"8\": 0.75, \"9+\": 1.0},\n    \"allocation\": \"floor_per_year_rank_sha256_order\",\n    \"seed\": \"nejimakidori-player-ranks-20260921\",\n    \"unverified\": \"exclude\",\n}\n\n\ndef select(rows):\n    strata = collections.defaultdict(list)\n    for row in rows:\n        row[\"seats\"] = []\n        for seat, dan in enumerate(row[\"dan\"]):\n            if dan is not None and dan >= 7:\n                strata[(row[\"game_id\"][:4], min(dan, 9))].append((row, seat))\n    for (_, dan), players in strata.items():\n        players.sort(\n            key=lambda player: hashlib.sha256(\n                f\"{SAMPLING['seed']}:{player[0]['game_id']}:{player[1]}\".encode()\n            ).digest()\n        )\n        rate = SAMPLING[\"rates\"][str(dan) if dan < 9 else \"9+\"]\n        for row, seat in players[: int(len(players) * rate)]:\n            row[\"seats\"].append(seat)\n    for row in rows:\n        row[\"seats\"].sort()\n\n\ndef run(archives, databases, output):\n    if (pathlib.Path(archives) / \"player_ranks.json\").exists():\n        raise ValueError(\"archives already stratified\")\n    root = pathlib.Path(output)\n    # An existing selection is never overwritten or sampled again.\n    root.mkdir(parents=True, exist_ok=False)\n    rows = []\n    summary = {\"sampling\": SAMPLING, \"years\": {}}\n    for path in sorted(pathlib.Path(archives).glob(\"*.zip\")):\n        database = pathlib.Path(databases) / f\"{path.stem}.db\"\n        with path.open(\"rb\") as stream, database.open(\"rb\") as db_stream:\n            year = {\n                \"archive_sha256\": hashlib.file_digest(\n                    stream, \"sha256\"\n                ).hexdigest(),\n                \"database_sha256\": hashlib.file_digest(\n                    db_stream, \"sha256\"\n                ).hexdigest(),\n                \"database\": str(database.resolve()),\n            }\n        with zipfile.ZipFile(path) as archive:\n            members = {\n                pathlib.Path(member).stem: member\n                for member in archive.namelist()\n                if member.endswith(\".mjson\")\n            }\n            year[\"games\"] = len(members)\n            matched = set()\n            connection = sqlite3.connect(\n                f\"file:{database.resolve()}?mode=ro\", uri=True\n            )\n            try:\n                for game_id, payload in connection.execute(\n                    \"SELECT id, log FROM logs WHERE log IS NOT NULL\"\n                ):\n                    if game_id not in members:\n                        continue\n                    player = xml.etree.ElementTree.fromstring(\n                        re.search(\n                            rb\"<UN\\s[^>]+/>\", gzip.decompress(payload)\n                        ).group()\n                    ).attrib\n                    names = [\n                        urllib.parse.unquote(player[f\"n{seat}\"])\n                        for seat in range(4)\n                    ]\n                    raw = archive.read(members[game_id])\n                    if raw.startswith(b\"\\x1f\\x8b\"):\n                        raw = gzip.decompress(raw)\n                    start = json.loads(raw.split(b\"\\n\", 1)[0])\n                    if names != start[\"names\"]:\n                        raise ValueError(f\"seat names mismatch: {game_id}\")\n                    ranks = list(map(int, player[\"dan\"].split(\",\")))\n                    if len(ranks) != 4 or any(\n                        rank < 0 or rank > 20 for rank in ranks\n                    ):\n                        raise ValueError(f\"invalid ranks: {game_id} {ranks}\")\n                    rows.append(\n                        {\n                            \"game_id\": game_id,\n                            # Tenhou codes 10..19 = 1..10 dan; 20 = Tenhoui.\n                            \"dan\": [rank - 9 for rank in ranks],\n                            \"rating\": list(\n                                map(float, player[\"rate\"].split(\",\"))\n                            ),\n                        }\n                    )\n                    matched.add(game_id)\n            finally:\n                connection.close()\n            year[\"verified_games\"] = len(matched)\n            year[\"missing_games\"] = len(members) - len(matched)\n            rows.extend(\n                {\"game_id\": game_id, \"dan\": [], \"rating\": []}\n                for game_id in sorted(members.keys() - matched)\n            )\n        summary[\"years\"][path.stem] = year\n        print(json.dumps({path.stem: year}), flush=True)\n    select(rows)\n    for year, counts in summary[\"years\"].items():\n        games = [row for row in rows if row[\"game_id\"].startswith(year)]\n        counts[\"retained_games\"] = sum(bool(row[\"seats\"]) for row in games)\n        counts[\"rank_counts\"] = dict(\n            collections.Counter(dan for row in games for dan in row[\"dan\"])\n        )\n        counts[\"retained_rank_counts\"] = dict(\n            collections.Counter(\n                row[\"dan\"][seat] for row in games for seat in row[\"seats\"]\n            )\n        )\n    lookup = {row[\"game_id\"]: row for row in rows}\n    for path in sorted(pathlib.Path(archives).glob(\"*.zip\")):\n        with zipfile.ZipFile(path) as source, zipfile.ZipFile(\n            root / path.name,\n            \"w\",\n            compression=zipfile.ZIP_DEFLATED,\n            compresslevel=1,\n        ) as target:\n            for member in source.namelist():\n                raw = source.read(member)\n                if raw.startswith(b\"\\x1f\\x8b\"):\n                    raw = gzip.decompress(raw)\n                first, rest = raw.split(b\"\\n\", 1)\n                start = json.loads(first)\n                if \"player_ranks\" in start:\n                    raise ValueError(f\"already stratified: {path} {member}\")\n                row = lookup[pathlib.Path(member).stem]\n                start[\"player_ranks\"] = {\n                    \"dan\": row[\"dan\"],\n                    \"rating\": row[\"rating\"],\n                    \"retained_seats\": row[\"seats\"],\n                }\n                target.writestr(\n                    member,\n                    json.dumps(start, ensure_ascii=False).encode()\n                    + b\"\\n\"\n                    + rest,\n                )\n        with (root / path.name).open(\"rb\") as stream:\n            summary[\"years\"][path.stem][\"merged_sha256\"] = hashlib.file_digest(\n                stream, \"sha256\"\n            ).hexdigest()\n    (root / \"player_ranks.json\").write_text(json.dumps(summary, indent=2))\n    return summary\n",
      "sha256": "90e2a216e62fb482accc062eab4f047e829b4164a5f6967a4ffc200573db963e"
    },
    {
      "path": "log_dataset/records.py",
      "text": "\"\"\"Single numeric TFRecord contract for training and inference.\"\"\"\n\nimport hashlib\nimport json\nimport math\nimport pathlib\n\nimport numpy\n\nfrom log_dataset import _native_collection, call_states\n\nREFERENCE_INPUTS = {\n    name: {\"shape\": [5], \"dtype\": \"int8\"}\n    for name in (\"dora_tile_id\", \"dora_valid\")\n}\n\nLABELS = {\n    \"ron_payments\": {\"shape\": [3, 37], \"dtype\": \"int32\"},\n    \"ron_legal\": {\"shape\": [3, 37], \"dtype\": \"int8\"},\n    \"win_action\": {\"shape\": [], \"dtype\": \"int8\"},\n    \"candidate_yaku_affinity\": {\"shape\": [16, 3], \"dtype\": \"float16\"},\n    \"opponent_shanten\": {\"shape\": [3], \"dtype\": \"int8\"},\n    \"opponent_ukeire\": {\"shape\": [3, 34], \"dtype\": \"int8\"},\n    \"opponent_hand_counts\": {\"shape\": [3, 37], \"dtype\": \"int8\"},\n    \"terminal_payment\": {\"shape\": [4, 4, 4], \"dtype\": \"int32\"},\n    \"round_end_kind\": {\"shape\": [], \"dtype\": \"int8\"},\n    \"round_end_source\": {\"shape\": [], \"dtype\": \"int8\"},\n    \"round_end_tenpai\": {\"shape\": [4], \"dtype\": \"int8\"},\n    \"round_completion_yaku\": {\"shape\": [4, 2, 23], \"dtype\": \"int8\"},\n    \"round_completion_score\": {\"shape\": [4, 2], \"dtype\": \"int16\"},\n    \"discard_action\": {\"shape\": [], \"dtype\": \"int8\"},\n    \"continuation_discard\": {\"shape\": [], \"dtype\": \"int8\"},\n    \"riichi_action\": {\"shape\": [], \"dtype\": \"int8\"},\n    \"response_action\": {\"shape\": [], \"dtype\": \"int8\"},\n    \"chi_pattern\": {\"shape\": [], \"dtype\": \"int8\"},\n    \"kan_action\": {\"shape\": [], \"dtype\": \"int8\"},\n}\n\n\nPACKING = {\n    \"feature/river_pre_tsumogiri\": (1, 0),\n    \"feature/river_pre_current_dora_multiplicity\": (3, 0),\n    \"feature/river_pre_dora_multiplicity_at_discard\": (3, 0),\n    \"feature/river_post_tsumogiri\": (1, 0),\n    \"feature/river_post_current_dora_multiplicity\": (3, 0),\n    \"feature/river_post_dora_multiplicity_at_discard\": (3, 0),\n    \"feature/candidate_hand_yaku_possibility\": (1, 0),\n    \"feature/open_opponent_yaku_possibility\": (1, 0),\n    \"feature/opponent_called_tile_count\": (5, 0),\n    \"feature/opponent_discard_count\": (6, 0),\n    \"feature/nagashi_possible\": (1, 0),\n    \"feature/pao_payer\": (3, 1),\n    \"feature/riichi_push_count\": (7, 0),\n    \"feature/genbutsu_to_seat\": (1, 0),\n    \"feature/passed_unchanged_to_seat\": (1, 0),\n    \"feature/sotogawa_earliest_turn_to_seat\": (3, 0),\n    \"label/opponent_ukeire\": (2, 1),\n    \"label/round_completion_yaku\": (2, 1),\n}\n\nFIELDS = {\n    prefix + \"/\" + name: definition\n    for prefix, fields in (\n        (\"feature\", _native_collection.INPUTS),\n        (\"label\", LABELS),\n    )\n    for name, definition in fields.items()\n}\nFIELDS[\"feature/post_call\"] = {\"shape\": [], \"dtype\": \"string\"}\nFIELDS.update(\n    {\"reference/\" + name: spec for name, spec in REFERENCE_INPUTS.items()}\n)\n\n\ndef game_partition(game_id):\n    \"\"\"Keep original games in the same corpus and rollout holdout bucket.\"\"\"\n    return int.from_bytes(hashlib.sha256(game_id.encode()).digest()[:4]) % 10\n\n\ndef encode(name, value):\n    value = numpy.asarray(value, dtype=FIELDS[name][\"dtype\"])\n    if name in PACKING:\n        width, offset = PACKING[name]\n        values = value.reshape(-1).astype(numpy.int64) + offset\n        bits = ((values[:, None] >> numpy.arange(width)) & 1).reshape(-1)\n        raw = numpy.packbits(\n            bits.astype(numpy.uint8), bitorder=\"little\"\n        ).tobytes()\n    else:\n        raw = value.tobytes()\n    return raw.rstrip(b\"\\0\")\n\n\ndef serialize_observation(observation):\n    import tensorflow as tf\n\n    example = tf.train.Example()\n    for prefix, values, definitions in (\n        (\"feature\", observation.features, _native_collection.INPUTS),\n        (\"label\", vars(observation), LABELS),\n    ):\n        for name, definition in definitions.items():\n            example.features.feature[\n                prefix + \"/\" + name\n            ].bytes_list.value.append(\n                encode(\n                    prefix + \"/\" + name,\n                    numpy.asarray(\n                        values[name], dtype=definition[\"dtype\"]\n                    ).reshape(definition[\"shape\"]),\n                )\n            )\n    example.features.feature[\"feature/post_call\"].bytes_list.value.append(\n        call_states.serialize(observation.features)\n    )\n    for name, value in observation.reference_inputs.items():\n        example.features.feature[\"reference/\" + name].bytes_list.value.append(\n            numpy.asarray(value, dtype=\"int8\").tobytes()\n        )\n    for name in (\"game_id\", \"kyoku_id\"):\n        example.features.feature[\"meta/\" + name].bytes_list.value.append(\n            getattr(observation, name).encode()\n        )\n    for name in (\"decision_index\", \"actor\"):\n        example.features.feature[\"meta/\" + name].int64_list.value.append(\n            int(getattr(observation, name))\n        )\n    return example.SerializeToString()\n\n\ndef parse_batch(examples):\n    import tensorflow as tf\n\n    parsed = tf.io.parse_example(\n        examples,\n        {name: tf.io.FixedLenFeature([], tf.string) for name in FIELDS},\n    )\n    return decode_batch(parsed)\n\n\ndef decode_batch(parsed):\n    \"\"\"Decode shared numeric fields from one parsed Example batch.\"\"\"\n    import tensorflow as tf\n\n    decoded = {}\n    for name, definition in FIELDS.items():\n        if name == \"feature/post_call\":\n            continue\n        size = math.prod(definition[\"shape\"])\n        dtype = tf.as_dtype(definition[\"dtype\"])\n        if name in PACKING:\n            width, offset = PACKING[name]\n            bit = numpy.arange(size) * width\n            raw = tf.io.decode_raw(\n                parsed[name], tf.uint8, fixed_length=(size * width + 7) // 8\n            )\n            if 8 % width == 0:\n                words = tf.gather(raw, bit // 8, axis=1)\n            else:\n                # Read at most two bytes per value, including crossings.\n                raw = tf.pad(tf.cast(raw, tf.uint16), [[0, 0], [0, 1]])\n                words = tf.bitwise.bitwise_or(\n                    tf.gather(raw, bit // 8, axis=1),\n                    tf.bitwise.left_shift(\n                        tf.gather(raw, bit // 8 + 1, axis=1), 8\n                    ),\n                )\n            values = (\n                tf.cast(\n                    tf.bitwise.bitwise_and(\n                        tf.bitwise.right_shift(\n                            words, tf.constant(bit % 8, words.dtype)\n                        ),\n                        (1 << width) - 1,\n                    ),\n                    tf.int32,\n                )\n                - offset\n            )\n            values = tf.cast(values, dtype)\n        else:\n            values = tf.io.decode_raw(\n                parsed[name],\n                tf.uint16 if dtype == tf.float16 else dtype,\n                fixed_length=size * dtype.size,\n            )\n            if dtype == tf.float16:\n                values = tf.bitcast(values, tf.float16)\n        decoded[name] = tf.reshape(values, [-1, *definition[\"shape\"]])\n    inputs = {\n        name: decoded[\"feature/\" + name] for name in _native_collection.INPUTS\n    }\n    inputs.update(call_states.decode(parsed[\"feature/post_call\"]))\n    labels = {name: decoded[\"label/\" + name] for name in LABELS}\n    labels[\"reference_inputs\"] = {\n        name: decoded[\"reference/\" + name] for name in REFERENCE_INPUTS\n    }\n    labels.update(\n        {\n            \"win_decision_logits\": labels[\"win_action\"],\n            \"discard_policy_logits\": labels[\"discard_action\"],\n            \"riichi_policy_logits\": tf.where(\n                labels[\"riichi_action\"] >= 0,\n                tf.cast(labels[\"riichi_action\"], tf.int32) * 37\n                + tf.cast(labels[\"continuation_discard\"], tf.int32),\n                -1,\n            ),\n            \"response_policy_logits\": tf.where(\n                labels[\"response_action\"] == 0,\n                0,\n                tf.where(\n                    labels[\"response_action\"] == 1,\n                    1\n                    + tf.cast(labels[\"chi_pattern\"], tf.int32) * 37\n                    + tf.cast(labels[\"continuation_discard\"], tf.int32),\n                    tf.where(\n                        labels[\"response_action\"] == 2,\n                        112 + tf.cast(labels[\"continuation_discard\"], tf.int32),\n                        tf.where(labels[\"response_action\"] == 3, 149, -1),\n                    ),\n                ),\n            ),\n            \"kan_action_logits\": labels[\"kan_action\"],\n        }\n    )\n    return inputs, labels\n\n\ndef validate_summary(data):\n    summary = json.loads(\n        (pathlib.Path(data) / \"dataset_summary.json\").read_text()\n    )\n    for name, expected in {\n        \"input_schema\": _native_collection.INPUTS,\n        \"label_schema\": LABELS,\n        \"reference_schema\": REFERENCE_INPUTS,\n    }.items():\n        if name not in summary or summary[name] != expected:\n            raise ValueError(f\"dataset {name} requires regeneration\")\n",
      "sha256": "2ee27134b1faac4cf5eed79aa4912cd5bdccb460ef7b1c6710736e04e0f76027"
    },
    {
      "path": "log_dataset/replay.py",
      "text": "\"\"\"Incremental MJAI state and ordered decision-time training observations.\"\"\"\n\nimport dataclasses\nimport inspect\n\nimport numpy\nimport riichienv\n\nfrom log_dataset import records, shanten\nfrom model import actions\n\nCALL_TYPES = {\"chi\", \"pon\", \"daiminkan\"}\nOBSERVATION_FIELDS = tuple(\n    name\n    for name in inspect.signature(riichienv.Observation).parameters\n    if name not in {\"legal_actions\", \"hands\", \"drawn_tile\", \"events\"}\n)\n\nObservation = dataclasses.make_dataclass(\n    \"Observation\",\n    [\n        (name, object, dataclasses.field(default=None))\n        for name in (\n            \"game_id\",\n            \"kyoku_id\",\n            \"decision_index\",\n            \"actor\",\n            \"features\",\n            \"reference_inputs\",\n            *records.LABELS,\n        )\n    ],\n)\n\n\ndef recorded_win_choices(state, index, next_index):\n    event = state.events[index]\n    if event[\"type\"] not in {\"tsumo\", \"dahai\", \"kakan\", \"ankan\"}:\n        return {}\n    while next_index < len(state.events) and state.events[next_index][\n        \"type\"\n    ] in {\"dora\", \"reach_accepted\"}:\n        next_index += 1\n    if next_index == len(state.events):\n        return {}\n    winners = {}\n    end = next_index\n    while end < len(state.events) and state.events[end][\"type\"] == \"hora\":\n        winners[state.events[end][\"actor\"]] = end\n        end += 1\n    if (\n        not winners\n        and state.events[next_index][\"type\"]\n        not in {\n            \"tsumo\",\n            \"dahai\",\n            \"reach\",\n            \"chi\",\n            \"pon\",\n            \"daiminkan\",\n            \"ankan\",\n            \"kakan\",\n        }\n        and not (\n            state.events[next_index][\"type\"] == \"ryukyoku\"\n            # Tenhou archive draws omit reason; only wall exhaustion proves\n            # that such an event follows an unclaimed last discard.\n            and state.events[next_index].get(\n                \"reason\",\n                \"exhaustive_draw\" if state.live_wall == 0 else \"abortive_draw\",\n            )\n            == \"exhaustive_draw\"\n        )\n    ):\n        return {}\n    choices = {}\n    # A draw offers tsumo to its owner. A discard or kan offers ron only\n    # to other seats; event replay may still expose the declarer's old tsumo.\n    for actor in (\n        (event[\"actor\"],)\n        if event[\"type\"] == \"tsumo\"\n        else (seat for seat in range(4) if seat != event[\"actor\"])\n    ):\n        if not any(\n            action.action_type\n            == (\n                riichienv.ActionType.TSUMO\n                if event[\"type\"] == \"tsumo\"\n                else riichienv.ActionType.RON\n            )\n            for action in state.legal_observation(actor).legal_actions()\n        ):\n            continue\n        if actor in winners:\n            choices[actor] = (1, winners[actor])\n        elif not winners:\n            choices[actor] = (0, index)\n    return choices\n\n\nclass Replay:\n    def __init__(self, game_id, events):\n        self.game_id = game_id\n        self.events = events\n        self.native_env = riichienv.RiichiEnv(\n            rule=riichienv.GameRule.default_tenhou()\n        )\n        self.history = []\n        self.event_index = -1\n        self.decision_index = 0\n        self.pending_discard = None\n        self.observation_cache = {}\n        self.feature_replay = None\n        self.feature_cursor = 0\n\n    @classmethod\n    def from_start(cls, game_id, event):\n        state = cls(game_id, [])\n        state.apply(event)\n        return state\n\n    @property\n    def melds(self):\n        return self.native_env.melds\n\n    def public_tiles(self):\n        return (\n            list(self.dora_markers)\n            + [row[\"pai\"] for river in self.rivers for row in river]\n            + [\n                tile\n                for melds in self.meld_events\n                for meld in melds\n                for tile in meld[\"consumed\"]\n            ]\n            + [\n                meld[\"upgrade_tile\"]\n                for melds in self.meld_events\n                for meld in melds\n                if meld[\"type\"] == \"kakan\"\n            ]\n        )\n\n    def concealed_counts(self, actor):\n        return numpy.bincount(\n            [tile // 4 for tile in self.native_env.hands[actor] if tile < 136],\n            minlength=34,\n        )\n\n    def missed_agari(self, actor):\n        if self.native_env.missed_agari_doujun[actor]:\n            return True\n        waits = riichienv.HandEvaluator(\n            self.native_env.hands[actor], self.melds[actor]\n        ).get_waits()\n        for index in range(len(self.history) - 1, -1, -1):\n            event = self.history[index]\n            if event.get(\"actor\") == actor and (\n                event[\"type\"] == \"reach_accepted\"\n                or (\n                    not self.accepted[actor]\n                    and event[\"type\"]\n                    in {\"tsumo\", \"chi\", \"pon\", \"daiminkan\", \"ankan\", \"kakan\"}\n                )\n            ):\n                break\n            if (\n                event[\"type\"] == \"dahai\"\n                and event[\"actor\"] != actor\n                and (\n                    self.pending_discard is None\n                    or index != self.pending_discard[\"event_index\"]\n                )\n                and shanten.base_id(event[\"pai\"]) in waits\n            ):\n                return True\n        return False\n\n    def legal_observation(self, actor):\n        from log_dataset import features\n\n        if actor in self.observation_cache:\n            return self.observation_cache[actor]\n        original = self.native_env.get_observation(actor)\n        hand = []\n        for tile in original.hand:\n            physical = tile // 4 * 4\n            if tile not in (16, 52, 88) and physical in (16, 52, 88):\n                physical += 1\n            while physical in hand:\n                physical += 1\n            hand.append(physical)\n        drawn = None\n        if self.draws[actor] is not None and self.draws[actor] != \"?\":\n            code = shanten.mjai_tile_code(self.draws[actor])\n            drawn = next(\n                tile\n                for tile in reversed(hand)\n                if features.native_tile_code(tile) == code\n            )\n        legal = []\n        for action in original.legal_actions():\n            # Event replay does not preserve passed-ron furiten in the engine.\n            if (\n                action.action_type == riichienv.ActionType.RON\n                and self.missed_agari(actor)\n            ):\n                continue\n            if action.action_type == riichienv.ActionType.DISCARD:\n                for tile in hand:\n                    if features.native_tile_code(\n                        tile\n                    ) == features.native_tile_code(action.tile):\n                        if self.accepted[actor] and tile != drawn:\n                            continue\n                        if not any(\n                            item.action_type == action.action_type\n                            and item.tile == tile\n                            for item in legal\n                        ):\n                            legal.append(\n                                riichienv.Action(\n                                    type=action.action_type,\n                                    tile=tile,\n                                    actor=actor,\n                                )\n                            )\n            else:\n                legal.append(action)\n        values = {name: getattr(original, name) for name in OBSERVATION_FIELDS}\n        values.update(\n            hands=original.hands,\n            legal_actions=legal,\n            drawn_tile=drawn,\n        )\n        values[\"hands\"][actor] = hand\n        values[\"events\"] = original.new_events()\n        self.observation_cache[actor] = riichienv.Observation(**values)\n        return self.observation_cache[actor]\n\n    def apply(self, event):\n        self.observation_cache.clear()\n        self.event_index += 1\n        self.history.append(event)\n        kind = event[\"type\"]\n        if kind == \"start_kyoku\":\n            self.start = event\n            self.kyoku_id = (\n                f\"{event['bakaze']}{event['kyoku']}-{event['honba']}\"\n            )\n            self.history = [event]\n            self.feature_replay = None\n            self.feature_cursor = 0\n            self.rivers = [[] for _ in range(4)]\n            self.meld_events = [[] for _ in range(4)]\n            self.declared = [False] * 4\n            self.accepted = [False] * 4\n            self.ippatsu = [False] * 4\n            self.draws = [None] * 4\n            self.live_wall = 70\n            self.pending_discard = None\n            self.last_origin = [0] * 4\n            self.rinshan_actor = None\n            self.dora_markers = [event[\"dora_marker\"]]\n        elif kind == \"tsumo\":\n            self.live_wall -= 1\n            self.draws[event[\"actor\"]] = event[\"pai\"]\n            self.last_origin[event[\"actor\"]] = 1\n            if self.pending_discard:\n                self.pending_discard[\"resolution\"] = 1\n            self.pending_discard = None\n        elif kind == \"dahai\":\n            actor = event[\"actor\"]\n            if self.pending_discard:\n                self.pending_discard[\"resolution\"] = 1\n            record = {\n                **event,\n                \"event_index\": len(self.history) - 1,\n                \"live_wall\": self.live_wall,\n                \"own_turns\": [len(river) for river in self.rivers],\n                \"origin\": self.last_origin[actor],\n                \"riichi\": self.declared[actor] and not self.accepted[actor],\n                \"resolution\": 0,\n                \"caller\": None,\n                \"dora_markers\": list(self.dora_markers),\n            }\n            self.rivers[actor].append(record)\n            self.pending_discard = record\n            self.draws[actor] = None\n            self.rinshan_actor = None\n            if self.accepted[actor]:\n                self.ippatsu[actor] = False\n        elif kind == \"reach\":\n            self.declared[event[\"actor\"]] = True\n        elif kind == \"reach_accepted\":\n            self.accepted[event[\"actor\"]] = True\n            self.ippatsu[event[\"actor\"]] = True\n        elif kind in CALL_TYPES | {\"ankan\", \"kakan\"}:\n            self.ippatsu = [False] * 4\n            if self.pending_discard and kind in CALL_TYPES:\n                self.pending_discard[\"resolution\"] = {\n                    \"chi\": 2,\n                    \"pon\": 3,\n                    \"daiminkan\": 4,\n                }[kind]\n                self.pending_discard[\"caller\"] = event[\"actor\"]\n            self.pending_discard = None\n            self.draws[event[\"actor\"]] = None\n            self.last_origin[event[\"actor\"]] = kind\n            if kind in {\"ankan\", \"kakan\", \"daiminkan\"}:\n                self.rinshan_actor = event[\"actor\"]\n            if kind == \"kakan\":\n                for meld in self.meld_events[event[\"actor\"]]:\n                    if meld[\"type\"] == \"pon\" and shanten.base_id(\n                        meld[\"pai\"]\n                    ) == shanten.base_id(event[\"pai\"]):\n                        meld[\"upgrade_index\"] = len(self.history) - 1\n                        meld[\"upgrade_tile\"] = event[\"pai\"]\n                        meld[\"type\"] = \"kakan\"\n            else:\n                self.meld_events[event[\"actor\"]].append(\n                    {**event, \"event_index\": len(self.history) - 1}\n                )\n        elif kind == \"dora\":\n            self.dora_markers.append(event[\"dora_marker\"])\n        self.native_env.apply_event(event)\n        if kind == \"tsumo\":\n            self.native_env.is_rinshan_flag = (\n                self.rinshan_actor == event[\"actor\"]\n            )\n        elif kind == \"dahai\":\n            self.native_env.is_rinshan_flag = False\n\n    def replay_events(self):\n        index = 0\n        while index < len(self.events):\n            event = self.events[index]\n            self.apply(event)\n            if event[\"type\"] == \"tsumo\":\n                while self.events[index + 1][\"type\"] == \"dora\":\n                    index += 1\n                    self.apply(self.events[index])\n            self.event_index = index\n            yield index, event\n            index += 1\n\n    def decisions(self):\n        from log_dataset import features\n\n        for index, event in self.replay_events():\n            requests = []\n            next_index = index + 1\n            while (\n                next_index < len(self.events)\n                and self.events[next_index][\"type\"] == \"reach_accepted\"\n            ):\n                next_index += 1\n            win_choices = (\n                recorded_win_choices(self, index, next_index)\n                if next_index < len(self.events)\n                else {}\n            )\n            requests.extend((actor, \"WIN\") for actor in win_choices)\n            if event[\"type\"] in {\n                \"tsumo\",\n                \"chi\",\n                \"pon\",\n                \"reach\",\n            } and self.events[next_index][\"type\"] not in {\"hora\", \"ryukyoku\"}:\n                actor = event[\"actor\"]\n                legal = self.legal_observation(actor).legal_actions()\n                types = {action.action_type for action in legal}\n                if (\n                    riichienv.ActionType.ANKAN in types\n                    or riichienv.ActionType.KAKAN in types\n                ):\n                    requests.append((actor, \"KAN\"))\n                    if self.events[next_index][\"type\"] in {\"ankan\", \"kakan\"}:\n                        types = set()\n                if riichienv.ActionType.RIICHI in types:\n                    requests.append((actor, \"RIICHI\"))\n                    if self.events[next_index][\"type\"] != \"reach\":\n                        requests.append((actor, \"DISCARD\"))\n                elif riichienv.ActionType.DISCARD in types:\n                    requests.append((actor, \"DISCARD\"))\n            elif (\n                event[\"type\"] == \"dahai\"\n                and self.events[next_index][\"type\"] != \"hora\"\n            ):\n                # Other seats' intentions are censored by an accepted\n                # call; a losing claim must not be labeled as a pass.\n                for actor in (\n                    (self.events[next_index][\"actor\"],)\n                    if self.events[next_index][\"type\"] in CALL_TYPES\n                    else range(4)\n                ):\n                    legal = self.legal_observation(actor).legal_actions()\n                    if any(\n                        action.action_type\n                        in {\n                            riichienv.ActionType.CHI,\n                            riichienv.ActionType.PON,\n                            riichienv.ActionType.DAIMINKAN,\n                        }\n                        for action in legal\n                    ):\n                        requests.append((actor, \"RESPONSE\"))\n            for actor, phase in requests:\n                next_event = self.events[next_index]\n                if (\n                    phase == \"RESPONSE\"\n                    and next_event[\"type\"] in {\"chi\", \"pon\"}\n                    and next_event[\"actor\"] == actor\n                    and not features.preferred_recorded_call(\n                        next_event[\"type\"],\n                        next_event[\"consumed\"],\n                        self.legal_observation(actor).legal_actions(),\n                    )\n                ):\n                    continue\n                yield index, actor, phase, next_index, win_choices\n                self.decision_index += 1\n\n    def policy_decisions(self):\n        \"\"\"Replay policy choices without computing features or labels.\"\"\"\n        from log_dataset import features\n\n        for index, actor, phase, next_index, win_choices in self.decisions():\n            legal_observation = self.legal_observation(actor)\n            legal = legal_observation.legal_actions()\n            if actions.forced_policy_action(self, actor, legal) is not None:\n                continue\n            # Keep the ordinary cut when staying dama. Declaring commits\n            # the tile, and subsequent ordinary discards remain locked.\n            if phase == \"DISCARD\" and (\n                self.declared[actor]\n                or features.single_legal_action(\n                    [\n                        a\n                        for a in legal\n                        if a.action_type == riichienv.ActionType.DISCARD\n                    ],\n                    legal_observation.drawn_tile,\n                )\n                is not None\n            ):\n                continue\n            yield index, actor, phase, next_index, win_choices\n\n    def recorded_action(self, observation, *, phase, next_index, win_choices):\n        \"\"\"Attach the observed action without computing hindsight targets.\"\"\"\n        from log_dataset import features\n\n        actor = observation.actor\n        next_event = self.events[next_index]\n        if phase == \"WIN\":\n            observation.win_action = win_choices[actor][0]\n        elif phase == \"DISCARD\" and next_event[\"type\"] == \"dahai\":\n            if (\n                not self.accepted[actor]\n                and observation.features[\"discard_action_legal\"].sum() > 1\n            ):\n                observation.discard_action = shanten.mjai_tile_code(\n                    next_event[\"pai\"]\n                )\n        elif phase == \"RIICHI\":\n            declaration = next_event[\"type\"] == \"reach\"\n            cut = self.events[next_index + 1] if declaration else next_event\n            observation.riichi_action = int(declaration)\n            observation.continuation_discard = shanten.mjai_tile_code(\n                cut[\"pai\"]\n            )\n        elif phase == \"RESPONSE\":\n            observation.response_action = 0\n            if (\n                next_event[\"type\"] in CALL_TYPES\n                and next_event[\"actor\"] == actor\n            ):\n                observation.response_action = {\n                    \"chi\": 1,\n                    \"pon\": 2,\n                    \"daiminkan\": 3,\n                }[next_event[\"type\"]]\n                if next_event[\"type\"] == \"chi\":\n                    observation.chi_pattern = features.chii_pattern(\n                        next_event[\"pai\"], next_event[\"consumed\"]\n                    )\n                if next_event[\"type\"] != \"daiminkan\":\n                    observation.continuation_discard = shanten.mjai_tile_code(\n                        self.events[next_index + 1][\"pai\"]\n                    )\n        elif phase == \"KAN\":\n            observation.kan_action = 0\n            if next_event[\"type\"] in {\"ankan\", \"kakan\"}:\n                observation.kan_action = 1 + shanten.base_id(\n                    next_event[\"consumed\"][0]\n                    if next_event[\"type\"] == \"ankan\"\n                    else next_event[\"pai\"]\n                )\n\n    def observations(self, *, actors=(0, 1, 2, 3)):\n        from log_dataset import features, training_targets\n\n        self.targets = training_targets.round_targets(\n            Replay.from_start(self.game_id, self.events[0]), self.events\n        )\n        for (\n            index,\n            actor,\n            phase,\n            next_index,\n            win_choices,\n        ) in self.policy_decisions():\n            if actor not in actors:\n                continue\n            packed = features.pack(state=self, actor=actor, phase=phase)\n            observation = Observation(\n                game_id=self.game_id,\n                kyoku_id=self.kyoku_id,\n                decision_index=self.decision_index,\n                actor=actor,\n                features=packed,\n                reference_inputs=features.reference_inputs(self),\n            )\n            for name, definition in records.LABELS.items():\n                setattr(\n                    observation,\n                    name,\n                    numpy.full(definition[\"shape\"], -1, definition[\"dtype\"]),\n                )\n            self.recorded_action(\n                observation=observation,\n                phase=phase,\n                next_index=next_index,\n                win_choices=win_choices,\n            )\n            training_targets.attach(observation, self, index)\n            for name, value in training_targets.ron_labels(\n                self, actor, phase\n            ).items():\n                setattr(observation, name, value)\n            yield observation\n",
      "sha256": "9ac1044227d261a0e2108874061ebf8a8c769033226dae8148e01ad5c9fecd2f"
    },
    {
      "path": "log_dataset/root_states.py",
      "text": "\"\"\"Prepare and load persistent simulator states for human-root continuations.\"\"\"\n\nimport argparse\nimport collections\nimport concurrent.futures\nimport fcntl\nimport functools\nimport gzip\nimport hashlib\nimport json\nimport lzma\nimport multiprocessing\nimport pathlib\nimport shutil\nimport sqlite3\nimport time\n\nimport numpy\n\nfrom log_dataset import (\n    _native_collection,\n    afk,\n    archives,\n    call_states,\n    features,\n    records,\n    replay,\n    sakigiri_regret,\n)\n\n\nclass Store:\n    \"\"\"Read saved roots and selection witnesses without replaying source logs.\"\"\"\n\n    def __init__(self, directory):\n        self.directory = pathlib.Path(directory).resolve()\n        self.index = sqlite3.connect(\n            f\"file:{self.directory / 'index.sqlite'}?mode=ro\", uri=True\n        )\n        self.connections = collections.OrderedDict()\n\n    def close(self):\n        self.index.close()\n        for connection in self.connections.values():\n            connection.close()\n        self.hand.cache_clear()\n        self.witnesses.cache_clear()\n\n    def connection(self, game_id):\n        row = self.index.execute(\n            \"SELECT shard FROM games WHERE game_id = ?\", (game_id,)\n        ).fetchone()\n        if row is None:\n            raise KeyError(f\"No prepared roots for game {game_id}\")\n        if row[0] not in self.connections:\n            if len(self.connections) == 32:\n                self.connections.popitem(last=False)[1].close()\n            self.connections[row[0]] = sqlite3.connect(\n                f\"file:{self.directory / row[0]}?mode=ro\", uri=True\n            )\n        self.connections.move_to_end(row[0])\n        return self.connections[row[0]]\n\n    @functools.lru_cache(maxsize=4)\n    def hand(self, game_id, kyoku_id):\n        payload = (\n            self.connection(game_id)\n            .execute(\n                \"SELECT roots FROM hands WHERE game_id = ? AND kyoku_id = ?\",\n                (game_id, kyoku_id),\n            )\n            .fetchone()\n        )\n        if payload is None:\n            raise KeyError(f\"No prepared roots for {game_id}/{kyoku_id}\")\n        return {\n            tuple(key): value\n            for key, value in json.loads(lzma.decompress(payload[0]))\n        }\n\n    @functools.lru_cache(maxsize=256)\n    def witnesses(self, game_id, kyoku_id):\n        payload = (\n            self.connection(game_id)\n            .execute(\n                \"SELECT witnesses FROM hands \"\n                \"WHERE game_id = ? AND kyoku_id = ?\",\n                (game_id, kyoku_id),\n            )\n            .fetchone()\n        )\n        if payload is None:\n            raise KeyError(f\"No prepared witnesses for {game_id}/{kyoku_id}\")\n        return {tuple(key): value for key, value in json.loads(payload[0])}\n\n    def root(self, game_id, kyoku_id, decision_index, actor, phase):\n        return _native_collection.NativeRoot.loads(\n            self.hand(game_id, kyoku_id)[decision_index, actor, phase][\n                \"root\"\n            ].encode()\n        )\n\n    def witness(self, game_id, kyoku_id, decision_index, actor, phase):\n        return self.witnesses(game_id, kyoku_id).get(\n            (decision_index, actor, phase)\n        )\n\n\ndef prepare_hand(game_id, events, actors=(0, 1, 2, 3)):\n    \"\"\"Verify and snapshot each retained policy decision once during building.\"\"\"\n    state = replay.Replay(game_id, events)\n    pending = collections.defaultdict(list)\n    for event, actor, phase, _, _ in state.policy_decisions():\n        if actor in actors:\n            pending[event + 1, actor].append(\n                (\n                    (state.decision_index, actor, features.PHASES[phase]),\n                    call_states.batch([features.pack(state, actor, phase)]),\n                )\n            )\n    witnesses = {\n        (index, events[index][\"actor\"]): witness\n        for index, witness in sakigiri_regret.round_pairs(\n            game_id, events\n        ).items()\n    }\n    collector = _native_collection.NativeCollector.from_hand(\n        json.dumps(events), 941\n    )\n    prepared = {}\n    while pending and (request := collector.next()) is not None:\n        for decision, identity in enumerate(\n            zip(request[\"event\"], request[\"seat\"])\n        ):\n            for key, expected in pending.pop(identity, []):\n                root = collector.snapshot(decision, phase=int(key[2]))\n                actual = call_states.select(\n                    call_states.from_request(root.fork(1, 941, False).next()),\n                    [root.decision],\n                )\n                for name in expected:\n                    numpy.testing.assert_array_equal(\n                        actual[name], expected[name], err_msg=f\"{key}/{name}\"\n                    )\n                prepared[key] = {\n                    \"root\": root.dumps().decode(),\n                    \"event\": identity[0],\n                    \"witness\": witnesses.get(identity),\n                }\n        if pending:\n            collector.submit_recorded()\n    if pending:\n        raise ValueError(\n            f\"Missing roots in {game_id}/{state.kyoku_id}: {pending.keys()}\"\n        )\n    return prepared\n\n\ndef build_shard(task):\n    index, directory, games = task\n    path = pathlib.Path(directory) / f\"roots-{index:05d}.sqlite\"\n    receipt = path.with_suffix(\".json\")\n    if receipt.exists():\n        result = json.loads(receipt.read_text())\n        if result[\"sakigiri\"] != sakigiri_regret.DEFINITION:\n            raise ValueError(f\"Outdated sakigiri witnesses: {path}\")\n        if path.stat().st_size != result[\"bytes\"]:\n            raise ValueError(f\"Incomplete root-state shard: {path}\")\n        return result\n    if shutil.disk_usage(directory).free < 15 * 1024**3:\n        raise OSError(\"Root-state build requires at least 15 GiB free space\")\n    temporary = path.with_suffix(\".sqlite.partial\")\n    temporary.unlink(missing_ok=True)\n    connection = sqlite3.connect(temporary)\n    connection.execute(\n        \"CREATE TABLE hands (game_id TEXT, kyoku_id TEXT, roots BLOB, \"\n        \"witnesses TEXT, PRIMARY KEY (game_id, kyoku_id)) WITHOUT ROWID\"\n    )\n    count = 0\n    hands = 0\n    raw_bytes = 0\n    for game in games:\n        payload = archives.open_archive(game[\"archive\"]).read(game[\"member\"])\n        if payload.startswith(b\"\\x1f\\x8b\"):\n            payload = gzip.decompress(payload)\n        events = [json.loads(line) for line in payload.splitlines()]\n        for hand in afk.retained_hands(events):\n            prepared = prepare_hand(\n                game[\"game_id\"],\n                hand,\n                actors=events[0][\"player_ranks\"][\"retained_seats\"],\n            )\n            payload = json.dumps(list(prepared.items()), separators=(\",\", \":\"))\n            connection.execute(\n                \"INSERT INTO hands VALUES (?, ?, ?, ?)\",\n                (\n                    game[\"game_id\"],\n                    f\"{hand[0]['bakaze']}{hand[0]['kyoku']}-{hand[0]['honba']}\",\n                    lzma.compress(payload.encode(), preset=3),\n                    json.dumps(\n                        [\n                            (key, value[\"witness\"])\n                            for key, value in prepared.items()\n                            if value[\"witness\"] is not None\n                        ]\n                    ),\n                ),\n            )\n            count += len(prepared)\n            hands += 1\n            raw_bytes += len(payload)\n    connection.commit()\n    connection.close()\n    temporary.replace(path)\n    result = {\n        \"path\": path.name,\n        \"games\": [game[\"game_id\"] for game in games],\n        \"hands\": hands,\n        \"roots\": count,\n        \"raw_bytes\": raw_bytes,\n        \"bytes\": path.stat().st_size,\n        \"sakigiri\": sakigiri_regret.DEFINITION,\n    }\n    receipt.with_suffix(\".json.partial\").write_text(\n        json.dumps(result, indent=2) + \"\\n\"\n    )\n    receipt.with_suffix(\".json.partial\").replace(receipt)\n    return result\n\n\ndef run(args):\n    directory = pathlib.Path(args.output).resolve()\n    directory.mkdir(parents=True, exist_ok=True)\n    with (directory / \"build.lock\").open(\"a\") as lock:\n        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)\n        source = pathlib.Path(args.data).resolve()\n        games = [\n            json.loads(line)\n            for line in (source / \"games.jsonl\").read_text().splitlines()\n        ]\n        games = [\n            game\n            for game in games\n            if records.game_partition(game[\"game_id\"]) < 7\n        ]\n        if args.limit_games is not None:\n            games = games[: args.limit_games]\n        if not games:\n            raise ValueError(\"No training games selected for root states\")\n        plan = {\n            \"data\": str(source),\n            \"compression\": \"lzma-preset-3\",\n            \"input_schema\": _native_collection.INPUTS,\n            \"seed\": 941,\n            \"sakigiri\": sakigiri_regret.DEFINITION,\n            \"summary_sha256\": hashlib.sha256(\n                (source / \"dataset_summary.json\").read_bytes()\n            ).hexdigest(),\n            \"games_sha256\": hashlib.sha256(\n                json.dumps(games, sort_keys=True).encode()\n            ).hexdigest(),\n            \"games\": len(games),\n            \"limit_games\": args.limit_games,\n        }\n        plan_path = directory / \"build-plan.json\"\n        if plan_path.exists() and json.loads(plan_path.read_text()) != plan:\n            raise ValueError(\"Root-state inputs changed; use a fresh output\")\n        plan_path.write_text(json.dumps(plan, indent=2) + \"\\n\")\n        tasks = [\n            (index, str(directory), games[start : start + 32])\n            for index, start in enumerate(range(0, len(games), 32))\n        ]\n        started = time.monotonic()\n        results = []\n        with concurrent.futures.ProcessPoolExecutor(\n            max_workers=args.workers,\n            mp_context=multiprocessing.get_context(\"spawn\"),\n        ) as pool:\n            for result in pool.map(build_shard, tasks):\n                results.append(result)\n                status = {\n                    \"shards\": len(results),\n                    \"total_shards\": len(tasks),\n                    \"roots\": sum(row[\"roots\"] for row in results),\n                    \"bytes\": sum(row[\"bytes\"] for row in results),\n                    \"elapsed_seconds\": time.monotonic() - started,\n                }\n                (directory / \"status.json\").write_text(\n                    json.dumps(status, indent=2) + \"\\n\"\n                )\n                print(json.dumps(status), flush=True)\n        temporary = directory / \"index.sqlite.partial\"\n        temporary.unlink(missing_ok=True)\n        connection = sqlite3.connect(temporary)\n        connection.execute(\n            \"CREATE TABLE games (game_id TEXT PRIMARY KEY, shard TEXT) \"\n            \"WITHOUT ROWID\"\n        )\n        connection.executemany(\n            \"INSERT INTO games VALUES (?, ?)\",\n            [\n                (game_id, result[\"path\"])\n                for result in results\n                for game_id in result[\"games\"]\n            ],\n        )\n        connection.commit()\n        connection.close()\n        temporary.replace(directory / \"index.sqlite\")\n        (directory / \"complete.json\").write_text(\n            json.dumps({**plan, **status}, indent=2) + \"\\n\"\n        )\n\n\ndef main():\n    parser = argparse.ArgumentParser(description=__doc__)\n    parser.add_argument(\"--data\", required=True)\n    parser.add_argument(\"--output\", required=True)\n    parser.add_argument(\"--workers\", type=int, default=8)\n    parser.add_argument(\"--limit-games\", type=int)\n    args = parser.parse_args()\n    if args.workers < 1 or (\n        args.limit_games is not None and args.limit_games < 1\n    ):\n        parser.error(\"workers and limit-games must be positive\")\n    run(args)\n\n\nif __name__ == \"__main__\":\n    main()\n",
      "sha256": "7cefac9ba35375d058c8a5117b13e3eae3a561411b727b70a74bc70925621bf3"
    },
    {
      "path": "log_dataset/sakigiri_regret.py",
      "text": "\"\"\"Later danger nominates earlier legal discards for fresh rollouts.\"\"\"\n\nimport collections\nimport types\n\nimport riichienv\n\nfrom log_dataset import (\n    _native_collection,\n    features,\n    focus_sampling,\n    replay,\n    shanten,\n)\n\nDEFINITION = {\n    \"endpoint\": (\n        \"first historical visible-threat genbutsu/non-genbutsu dilemma \"\n        \"at minimum legal shanten\"\n    ),\n    \"earlier\": \"both safe, equal immediate shanten to recorded cut\",\n    \"endpoints_are_roots\": False,\n    \"actions\": \"all qualifying alternatives plus recorded cut\",\n}\n\n\ndef ron_exposure(state, actor, codes):\n    \"\"\"Binary legal ron evidence, independent of payment magnitude.\"\"\"\n    result = dict.fromkeys(codes, 0)\n    for opponent in range(4):\n        if opponent == actor:\n            continue\n        hand = state.legal_observation(opponent).hand\n        if len(hand) % 3 != 1:\n            continue\n        waits = riichienv.HandEvaluator(hand, state.melds[opponent]).get_waits()\n        if state.missed_agari(opponent) or set(waits) & {\n            shanten.base_id(row[\"pai\"]) for row in state.rivers[opponent]\n        }:\n            continue\n        for code in codes:\n            base = shanten.base_id(code)\n            if base not in waits:\n                continue\n            physical = next(\n                tile\n                for tile in range(base * 4, base * 4 + 4)\n                if tile not in hand\n            )\n            result[code] += int(\n                _native_collection.score_hand(\n                    types.SimpleNamespace(\n                        tiles=hand + [physical],\n                        melds=state.melds[opponent],\n                        agari_tile=physical,\n                        dora_indicators=[],\n                    ),\n                    conditions=riichienv.Conditions(\n                        riichi=state.accepted[opponent],\n                        houtei=state.live_wall == 0,\n                        player_wind=(\n                            riichienv.Wind.East,\n                            riichienv.Wind.South,\n                            riichienv.Wind.West,\n                            riichienv.Wind.North,\n                        )[(opponent - state.start[\"oya\"]) % 4],\n                        round_wind=\"ESWN\".index(state.start[\"bakaze\"]),\n                    ),\n                    ura=[],\n                ).is_win\n            )\n    return result\n\n\ndef round_pairs(game_id, events):\n    \"\"\"Nominate safe early cuts before the first future defensive dilemma.\n\n    At the endpoint, genbutsu and non-genbutsu alternatives against the same\n    publicly threatening opponent must both achieve best immediate shanten.\n    Only earlier safe, equal-shanten alternatives become roots; calls and\n    changed later hands are allowed. All qualifying alternative tiles precede\n    the recorded cut in each action list. Ordering is not an actor target.\n    \"\"\"\n    state = replay.Replay.from_start(game_id, events[0])\n    history = [[] for _ in range(4)]\n    seen_endpoint = [False] * 4\n    candidates = {}\n    for index, event in enumerate(events[1:], 1):\n        if event[\"type\"] == \"reach_accepted\":\n            history[event[\"actor\"]] = []\n        if (\n            event[\"type\"] == \"dahai\"\n            and not seen_endpoint[event[\"actor\"]]\n            and not state.accepted[event[\"actor\"]]\n        ):\n            actor = event[\"actor\"]\n            cut = shanten.mjai_tile_code(event[\"pai\"])\n            legal = {\n                features.native_tile_code(action.tile)\n                for action in state.legal_observation(actor).legal_actions()\n                if action.action_type == riichienv.ActionType.DISCARD\n            }\n            packed = features.pack(state, actor, \"DISCARD\")\n            threatening = [\n                seat\n                for seat in range(1, 4)\n                if focus_sampling.visible_threat(packed, seat)\n            ]\n            non_genbutsu = set()\n            if threatening:\n                best = min(\n                    packed[\"discard_action_all_shanten\"][tile] for tile in legal\n                )\n                efficient = {\n                    tile\n                    for tile in legal\n                    if packed[\"discard_action_all_shanten\"][tile] == best\n                }\n                for opponent in threatening:\n                    safe = {\n                        tile\n                        for tile in efficient\n                        if packed[\"genbutsu_to_seat\"][\n                            opponent, shanten.base_id(tile)\n                        ]\n                    }\n                    if safe:\n                        non_genbutsu.update(efficient - safe)\n            if non_genbutsu:\n                seen_endpoint[actor] = True\n                for row in history[actor]:\n                    alternatives = sorted(\n                        (non_genbutsu & row[\"legal\"]) - {row[\"cut\"]}\n                    )\n                    if alternatives:\n                        candidates[row[\"index\"]] = (\n                            index,\n                            [*alternatives, row[\"cut\"]],\n                        )\n            else:\n                history[actor].append(\n                    {\n                        \"index\": index,\n                        \"cut\": cut,\n                        \"legal\": {\n                            tile\n                            for tile in legal\n                            if packed[\"discard_action_all_shanten\"][tile]\n                            == packed[\"discard_action_all_shanten\"][cut]\n                        },\n                    }\n                )\n        state.apply(event)\n\n    # Future threat selects roots only. Equal-shanten earlier actions must\n    # also both be safe at the original decision.\n    state = replay.Replay.from_start(game_id, events[0])\n    retained = {}\n    for index, (endpoint, actions) in sorted(candidates.items()):\n        while state.event_index < index - 1:\n            state.apply(events[state.event_index + 1])\n        actor = events[index][\"actor\"]\n        exposure = ron_exposure(state, actor, actions)\n        if exposure[actions[-1]]:\n            continue\n        alternatives = [tile for tile in actions[:-1] if not exposure[tile]]\n        if alternatives:\n            retained[index] = (endpoint, [*alternatives, actions[-1]])\n    counts = collections.Counter(endpoint for endpoint, _ in retained.values())\n    return {\n        index: (actions, 1 / counts[endpoint])\n        for index, (endpoint, actions) in retained.items()\n    }\n",
      "sha256": "363a99d841206dba435636c93d6fee8abdfc0a9187517a3a612b9542e202e5fd"
    },
    {
      "path": "log_dataset/scoring.py",
      "text": "\"\"\"Native scoring consumers: completion evidence, waits and bonus-han labels.\"\"\"\n\nimport functools\nimport types\n\nimport numpy\nimport riichienv\n\nfrom model import outcomes\n\nfrom . import _native_collection, shanten\n\n# Bonus counts are exact until ordinary hand value saturates at kazoe.\nBONUS_HAN = tuple(range(14))\nCELLS = tuple(map(tuple, numpy.argwhere(outcomes.PAYMENT_CELLS)))\n\nNAMES = (\n    \"pinfu\",\n    \"tanyao\",\n    \"iipeikou\",\n    \"haku\",\n    \"hatsu\",\n    \"chun\",\n    \"seat_wind\",\n    \"round_wind\",\n    \"sanshoku_doujun\",\n    \"ittsuu\",\n    \"chanta\",\n    \"honroutou\",\n    \"toitoi\",\n    \"sanankou\",\n    \"sankantsu\",\n    \"sanshoku_doukou\",\n    \"chiitoitsu\",\n    \"shousangen\",\n    \"honitsu\",\n    \"junchan\",\n    \"ryanpeikou\",\n    \"chinitsu\",\n    \"yakuman\",\n)\nYAKU_IDS = {\n    \"pinfu\": 14,\n    \"tanyao\": 12,\n    \"iipeikou\": 13,\n    \"haku\": 7,\n    \"hatsu\": 8,\n    \"chun\": 9,\n    \"seat_wind\": 10,\n    \"round_wind\": 11,\n    \"sanshoku_doujun\": 17,\n    \"ittsuu\": 16,\n    \"chanta\": 15,\n    \"honroutou\": 24,\n    \"toitoi\": 21,\n    \"sanankou\": 22,\n    \"sankantsu\": 20,\n    \"sanshoku_doukou\": 19,\n    \"chiitoitsu\": 25,\n    \"shousangen\": 23,\n    \"honitsu\": 27,\n    \"junchan\": 26,\n    \"ryanpeikou\": 28,\n    \"chinitsu\": 29,\n}\n\nYAKU_BITS = {value: 1 << NAMES.index(name) for name, value in YAKU_IDS.items()}\n\n\ndef completion_flags(\n    tiles, melds, player_wind, round_wind, require_all=True, family_routes=False\n):\n    counts = numpy.bincount(numpy.asarray(tiles) // 4, minlength=34)\n    distance = shanten.calculate_shanten(counts)\n    if distance not in (0, 1):\n        return numpy.full(len(NAMES), -1, numpy.int8)\n    if distance == 0:\n        waits = riichienv.HandEvaluator(tiles, melds).get_waits()\n        if not waits:\n            return numpy.full(len(NAMES), -1, numpy.int8)\n        flags = (1 << len(NAMES)) - 1 if require_all else 0\n        for tile in waits:\n            physical = tile * 4 + (1 if tile in (4, 13, 22) else 0)\n            for tsumo in (False, True):\n                score = _native_collection.score_hand(\n                    types.SimpleNamespace(\n                        tiles=list(tiles) + [physical],\n                        melds=melds,\n                        agari_tile=physical,\n                        dora_indicators=[],\n                    ),\n                    riichienv.Conditions(\n                        tsumo=tsumo,\n                        player_wind=(\n                            riichienv.Wind.East,\n                            riichienv.Wind.South,\n                            riichienv.Wind.West,\n                            riichienv.Wind.North,\n                        )[player_wind],\n                        round_wind=round_wind,\n                    ),\n                    [],\n                )\n                candidate = int(bool(score.yakuman)) << NAMES.index(\"yakuman\")\n                for yaku in score.yaku:\n                    candidate |= YAKU_BITS.get(yaku, 0)\n                if family_routes:\n                    for name, distance in zip(\n                        (\"tanyao\", \"honitsu\", \"chanta\"),\n                        shanten.calculate_yaku_shanten(\n                            counts + (numpy.arange(34) == tile),\n                            [[t // 4 for t in meld.tiles] for meld in melds],\n                        ),\n                    ):\n                        candidate &= ~(1 << NAMES.index(name))\n                        candidate |= int(distance == -1) << NAMES.index(name)\n                flags = flags & candidate if require_all else flags | candidate\n                if require_all and not flags:\n                    return numpy.zeros(len(NAMES), numpy.int8)\n        return numpy.array(\n            [(flags >> index) & 1 for index in range(len(NAMES))], numpy.int8\n        )\n    first_draws = shanten.improving(counts)[1]\n    if not first_draws:\n        return numpy.full(len(NAMES), -1, numpy.int8)\n    result = numpy.full(len(NAMES), int(require_all), numpy.int8)\n    for draw in first_draws:\n        added = draw * 4 + (1 if draw in (4, 13, 22) else 0)\n        hand = list(tiles) + [added]\n        next_counts = counts + (numpy.arange(34) == draw)\n        flags = numpy.zeros(len(NAMES), numpy.int8)\n        for cut in numpy.flatnonzero(next_counts):\n            if (\n                shanten.calculate_shanten(\n                    next_counts - (numpy.arange(34) == cut)\n                )\n                != 0\n            ):\n                continue\n            retained = list(hand)\n            retained.remove(next(tile for tile in retained if tile // 4 == cut))\n            candidate = completion_flags(\n                tiles=retained,\n                melds=melds,\n                player_wind=player_wind,\n                round_wind=round_wind,\n                require_all=require_all,\n                family_routes=family_routes,\n            )\n            flags |= numpy.maximum(candidate, 0)\n        result = result & flags if require_all else result | flags\n    return result\n\n\n@functools.lru_cache(maxsize=65536)\ndef path_completion_flags(counts, melds, player_wind, round_wind):\n    \"\"\"Share immutable scoring evidence across overlapping shortest paths.\"\"\"\n    return tuple(\n        completion_flags(\n            tiles=[\n                tile * 4 + copy\n                for tile, count in enumerate(counts)\n                for copy in range(count)\n            ],\n            melds=[\n                riichienv.Meld(\n                    (\n                        riichienv.MeldType.Chi,\n                        riichienv.MeldType.Pon,\n                        riichienv.MeldType.Daiminkan,\n                        riichienv.MeldType.Ankan,\n                        riichienv.MeldType.Kakan,\n                    )[kind],\n                    list(hand),\n                    opened,\n                )\n                for kind, hand, opened in melds\n            ],\n            player_wind=player_wind,\n            round_wind=round_wind,\n            family_routes=True,\n        )\n        > 0\n    )\n\n\ndef hand_yaku_fractions(\n    counts, unavailable, melds, player_wind, round_wind, cuts=None, names=NAMES\n):\n    \"\"\"Copy-weighted shortest routes; truncated searches are unknown.\"\"\"\n    paths = shanten.tenpai_paths(counts, unavailable, cuts)\n    if paths is None:\n        return numpy.full(len(names), -1.0)\n    if set(names) <= {\"tanyao\", \"honitsu\", \"chanta\"}:\n        # Necessary shape conditions only: rejected routes cannot carry any\n        # requested family, regardless of winning tile or decomposition.\n        # Honitsu/chanta include their full-flush/pure-outside counterparts.\n        whole = paths[0] + numpy.bincount(\n            [tile // 4 for meld in melds for tile in meld.tiles], minlength=34\n        )\n        possible = {\n            \"tanyao\": ~whole[:, [0, 8, 9, 17, 18, 26, *range(27, 34)]].any(\n                axis=1\n            ),\n            \"honitsu\": (\n                whole[:, :27].reshape(-1, 3, 9).any(axis=2).sum(axis=1) <= 1\n            ),\n            \"chanta\": ~whole[:, [3, 4, 5, 12, 13, 14, 21, 22, 23]].any(axis=1),\n        }\n        possible = numpy.any([possible[name] for name in names], axis=0)\n    else:\n        possible = numpy.ones(len(paths[0]), numpy.bool_)\n    melds = tuple(\n        (int(meld.meld_type), tuple(meld.tiles), meld.opened) for meld in melds\n    )\n    supported = numpy.array(\n        [\n            (\n                path_completion_flags(\n                    counts=hand.tobytes(),\n                    melds=melds,\n                    player_wind=player_wind,\n                    round_wind=round_wind,\n                )\n                if viable\n                else (False,) * len(NAMES)\n            )\n            for hand, viable in zip(paths[0], possible)\n        ],\n        numpy.bool_,\n    )\n    return (paths[1] @ supported[:, [NAMES.index(name) for name in names]]) / (\n        paths[1].sum()\n    )\n\n\ndef score_waits(tiles, melds, context):\n    evaluator = riichienv.HandEvaluator(list(tiles), list(melds))\n    waits = evaluator.get_waits()\n    furiten = context[\"missed_agari\"] or bool(\n        set(context[\"own_discards\"]) & set(waits)\n    )\n    rows = []\n    closed = all(not meld.opened for meld in melds)\n    for base in waits:\n        for red in (False, True) if base in (4, 13, 22) else (False,):\n            suit = base // 9\n            unseen = (\n                1 - context[\"unavailable_red\"][suit]\n                if red\n                else 4\n                - context[\"unavailable_counts\"][base]\n                - (\n                    1 - context[\"unavailable_red\"][suit]\n                    if base in (4, 13, 22)\n                    else 0\n                )\n            )\n            tile = base * 4 + (0 if red or base not in (4, 13, 22) else 1)\n            while tile in tiles and tile < base * 4 + 3:\n                tile += 1\n            values = []\n            for riichi, tsumo in (\n                (False, False),\n                (False, True),\n                (True, False),\n                (True, True),\n            ):\n                score = _native_collection.score_hand(\n                    types.SimpleNamespace(\n                        tiles=list(tiles) + [tile],\n                        melds=melds,\n                        agari_tile=tile,\n                        dora_indicators=context[\"dora_indicators\"],\n                    ),\n                    riichienv.Conditions(\n                        riichi=riichi,\n                        tsumo=tsumo,\n                        player_wind=(\n                            riichienv.Wind.East,\n                            riichienv.Wind.South,\n                            riichienv.Wind.West,\n                            riichienv.Wind.North,\n                        )[context[\"player_wind\"]],\n                        round_wind=context[\"round_wind\"],\n                    ),\n                    [],\n                )\n                legal = (\n                    score.is_win\n                    and (not riichi or closed)\n                    and (tsumo or not furiten)\n                )\n                points = (\n                    score.tsumo_agari_ko\n                    * (3 if context[\"player_wind\"] == 0 else 2)\n                    + (\n                        0\n                        if context[\"player_wind\"] == 0\n                        else score.tsumo_agari_oya\n                    )\n                    if tsumo\n                    else score.ron_agari\n                )\n                yaku_ids = set(score.yaku)\n                values.append(\n                    {\n                        \"points\": int(points) if legal else 0,\n                        \"han\": score.han if legal else 0,\n                        \"fu\": score.fu if legal else 0,\n                        \"legal\": bool(legal),\n                        \"yakuman\": bool(score.yakuman),\n                        \"yaku\": [\n                            int(\n                                bool(score.yakuman)\n                                if name == \"yakuman\"\n                                else YAKU_IDS[name] in yaku_ids\n                            )\n                            for name in NAMES\n                        ],\n                    }\n                )\n            rows.append(\n                {\n                    \"tile\": 34 + suit if red else base,\n                    \"unseen\": int(max(0, unseen)),\n                    \"values\": values,\n                }\n            )\n    summary = numpy.zeros((4, 8), numpy.float32)\n    for scenario in range(4):\n        legal = [\n            row\n            for row in rows\n            if row[\"unseen\"] > 0 and row[\"values\"][scenario][\"legal\"]\n        ]\n        if legal:\n            weights = numpy.array([row[\"unseen\"] for row in legal])\n            points = [row[\"values\"][scenario][\"points\"] for row in legal]\n            summary[scenario, :4] = [\n                len({shanten.base_id(row[\"tile\"]) for row in legal}),\n                weights.sum(),\n                min(points),\n                max(points),\n            ]\n            for column, key in ((4, \"points\"), (5, \"han\"), (6, \"fu\")):\n                summary[scenario, column] = numpy.average(\n                    [row[\"values\"][scenario][key] for row in legal],\n                    weights=weights,\n                )\n        summary[scenario, 7] = int(furiten and scenario % 2 == 0)\n    return summary, rows\n\n\ndef win_contexts(events):\n    \"\"\"Use the training replay's physical tiles, including concealed kans.\"\"\"\n    from log_dataset import replay\n\n    state = replay.Replay(\"payment-bonus\", [])\n    for event in events:\n        if event[\"type\"] in (\"start_game\", \"end_game\"):\n            continue\n        if event[\"type\"] in {\"ankan\", \"kakan\"}:\n            # A robbed kan never completes and does not cancel ippatsu.\n            kan_ippatsu = tuple(state.ippatsu)\n        if event[\"type\"] == \"hora\":\n            actor = event[\"actor\"]\n            tsumo = actor == event[\"target\"]\n            last = next(\n                row\n                for row in reversed(state.history)\n                if row[\"type\"] in (\"tsumo\", \"dahai\", \"kakan\", \"ankan\")\n            )\n            tile = shanten.base_id(last[\"pai\"]) * 4\n            tile += int(\n                tile in (16, 52, 88) and not shanten.is_red(last[\"pai\"])\n            )\n            observation = state.legal_observation(actor)\n            hand = observation.hand if tsumo else [*observation.hand, tile]\n            chankan = not tsumo and last[\"type\"] in {\"kakan\", \"ankan\"}\n            ctx = types.SimpleNamespace(\n                tiles=hand,\n                melds=state.melds[actor],\n                seat=actor,\n                agari_tile=tile,\n                dora_indicators=observation.dora_indicators,\n                ura_indicators=[\n                    shanten.base_id(marker) * 4\n                    for marker in event[\"ura_markers\"]\n                ],\n                conditions=riichienv.Conditions(\n                    tsumo=tsumo,\n                    riichi=state.accepted[actor],\n                    double_riichi=(\n                        state.accepted[actor]\n                        and state.rivers[actor][0][\"riichi\"]\n                        and not any(\n                            row[\"type\"]\n                            in replay.CALL_TYPES | {\"ankan\", \"kakan\"}\n                            for row in state.history[\n                                : state.rivers[actor][0][\"event_index\"]\n                            ]\n                        )\n                    ),\n                    ippatsu=(\n                        kan_ippatsu[actor] if chankan else state.ippatsu[actor]\n                    ),\n                    haitei=tsumo\n                    and state.live_wall == 0\n                    and state.rinshan_actor != actor,\n                    houtei=not tsumo and state.live_wall == 0,\n                    rinshan=tsumo and state.rinshan_actor == actor,\n                    chankan=chankan,\n                    tsumo_first_turn=tsumo\n                    and not state.rivers[actor]\n                    and not any(state.melds),\n                    player_wind=(\n                        riichienv.Wind.East,\n                        riichienv.Wind.South,\n                        riichienv.Wind.West,\n                        riichienv.Wind.North,\n                    )[(actor - state.start[\"oya\"]) % 4],\n                    round_wind=\"ESWN\".index(state.start[\"bakaze\"]),\n                ),\n            )\n            if state.accepted[actor]:\n                assert len(ctx.ura_indicators) == len(ctx.dora_indicators), (\n                    state.kyoku_id,\n                    actor,\n                    \"Missing hidden bonus indicators\",\n                )\n            ctx.actual = _native_collection.score_hand(\n                ctx, ctx.conditions, ctx.ura_indicators\n            )\n            if not ctx.actual.is_win:\n                raise ValueError((state.kyoku_id, event, \"Unscorable win\"))\n            yield state.kyoku_id, ctx\n        state.apply(event)\n\n\ndef bonus_han_scores(ctx):\n    \"\"\"One base hand, rescored by total situational/hidden bonus han.\n\n    Riichi (including double riichi), ippatsu, last tile, rinshan, chankan\n    and ura contribute only their combined han. Public dora/red and menzen\n    tsumo stay in the base hand. The last bucket is 13+, already kazoe.\n    True yakuman retain their actual multiplicity, independently of bonuses.\n    \"\"\"\n    base = _native_collection.score_hand(\n        ctx,\n        riichienv.Conditions(\n            tsumo=ctx.conditions.tsumo,\n            tsumo_first_turn=ctx.conditions.tsumo_first_turn,\n            player_wind=ctx.conditions.player_wind,\n            round_wind=ctx.conditions.round_wind,\n        ),\n        [],\n    )\n    observed = 0 if base.yakuman else min(ctx.actual.han - base.han, 13)\n    result = numpy.full((len(BONUS_HAN), 3), -1, numpy.int32)\n    details = numpy.full((len(BONUS_HAN), 3), -1, numpy.int32)\n    for bonus in (\n        BONUS_HAN[:2] if any(meld.opened for meld in ctx.melds) else BONUS_HAN\n    ):\n        if not base.is_win and bonus == 0:\n            continue\n        han = base.han if base.yakuman else base.han + bonus\n        points = (\n            8000 * (han // 13)\n            if base.yakuman\n            else outcomes.basic_points(han, base.fu)\n        )\n        dealer = ctx.conditions.player_wind == riichienv.Wind.East\n        result[bonus] = [\n            (\n                0\n                if ctx.conditions.tsumo\n                else 100 * ((points * (6 if dealer else 4) + 99) // 100)\n            ),\n            (\n                100 * ((points * (2 if dealer else 1) + 99) // 100)\n                if ctx.conditions.tsumo\n                else 0\n            ),\n            (\n                100 * ((points * 2 + 99) // 100)\n                if ctx.conditions.tsumo and not dealer\n                else 0\n            ),\n        ]\n        details[bonus] = (han, base.fu, int(base.yakuman))\n    numpy.testing.assert_array_equal(\n        result[observed],\n        [\n            ctx.actual.ron_agari,\n            ctx.actual.tsumo_agari_ko,\n            ctx.actual.tsumo_agari_oya,\n        ],\n    )\n    return result, observed, details\n\n\ndef round_labels(events):\n    \"\"\"Absolute-seat labels, checked against the canonical payment tensor.\"\"\"\n    from model import payment_scoring\n\n    rounds = {}\n    for event in events:\n        if event[\"type\"] == \"start_kyoku\":\n            key = f\"{event['bakaze']}{event['kyoku']}-{event['honba']}\"\n            rounds[key] = []\n        if event[\"type\"] not in (\"start_game\", \"end_game\"):\n            rounds[key].append(event)\n    result = {\n        key: {\n            \"bonus\": numpy.full((2, 4, 4), -1, numpy.int16),\n            \"score\": numpy.full((2, 4, 4, len(BONUS_HAN)), -1, numpy.int16),\n            \"payment\": outcomes.terminal_payments(rows),\n        }\n        for key, rows in rounds.items()\n    }\n    for key, ctx in win_contexts(events):\n        amounts, observed, details = bonus_han_scores(ctx)\n        kind = int(ctx.conditions.tsumo)\n        payments = result[key][\"payment\"][kind, :, ctx.seat]\n        dealer = ctx.conditions.player_wind == riichienv.Wind.East\n        total = (\n            amounts[:, 1] * (3 if dealer else 2)\n            + (0 if dealer else amounts[:, 2])\n            if kind\n            else amounts[:, 0]\n        )\n        assert total[observed] == payments.sum(), (\n            key,\n            ctx.seat,\n            total[observed],\n            payments.tolist(),\n        )\n        for payer in numpy.flatnonzero(payments):\n            if kind:\n                dealer_seat = (\n                    ctx.seat\n                    - (\n                        riichienv.Wind.East,\n                        riichienv.Wind.South,\n                        riichienv.Wind.West,\n                        riichienv.Wind.North,\n                    ).index(ctx.conditions.player_wind)\n                ) % 4\n                shares = amounts[:, 2 if payer == dealer_seat else 1]\n            else:\n                shares = amounts[:, 0]\n            # Pao changes which seat pays the same scored total. The observed\n            # allocation is label-only; ordinary transfers use scorer shares.\n            if shares[observed] != payments[payer]:\n                # Replayed native state can omit the pao flag. The recorded\n                # allocation and independently scored yakuman total establish\n                # this label; ordinary hands must match their scorer shares.\n                if not ctx.actual.yakuman:\n                    raise ValueError((key, \"Unexpected payment allocation\"))\n                shares = (\n                    total.astype(numpy.int64)\n                    * payments[payer]\n                    // total[observed]\n                )\n            valid = numpy.all(amounts >= 0, axis=1)\n            result[key][\"score\"][kind, payer, ctx.seat, valid] = [\n                payment_scoring.score_class(int(han), int(fu), bool(yakuman))\n                for han, fu, yakuman in details[valid]\n            ]\n            result[key][\"bonus\"][kind, payer, ctx.seat] = (\n                -1 if ctx.actual.yakuman else observed\n            )\n            assert shares[observed] == payments[payer]\n    return result\n",
      "sha256": "ba4bdcdfea3f4b0bedb2cc6fdfdc8118152cf6bdfa00fb1e2a31f19486234a60"
    },
    {
      "path": "log_dataset/shanten.py",
      "text": "\"\"\"Structural Mahjong distances and available improving continuations.\"\"\"\n\nimport ctypes\nimport fcntl\nimport functools\nimport os\nimport pathlib\nimport subprocess\n\nimport numpy\n\nBASE_IDS = numpy.array(list(range(34)) + [4, 13, 22, 0])\nNYANTEN = pathlib.Path(__file__).parent / \"nyanten\"\nLIBRARY = NYANTEN / \".native\" / \"analysis.so\"\n\n\n@functools.lru_cache(maxsize=1)\ndef native():\n    LIBRARY.parent.mkdir(exist_ok=True)\n    sources = sorted(NYANTEN.glob(\"*.cpp\"))\n    with (LIBRARY.parent / \"build.lock\").open(\"w\") as lock:\n        fcntl.flock(lock, fcntl.LOCK_EX)\n        if not LIBRARY.exists() or LIBRARY.stat().st_mtime_ns < max(\n            path.stat().st_mtime_ns\n            for path in (\n                pathlib.Path(__file__),\n                *sources,\n                *NYANTEN.rglob(\"*.hpp\"),\n            )\n        ):\n            subprocess.run(\n                [\n                    \"c++\",\n                    \"-O3\",\n                    \"-DNDEBUG\",\n                    \"-std=c++17\",\n                    \"-shared\",\n                    \"-fPIC\",\n                    \"-I\" + str(NYANTEN / \"vendor\"),\n                    *map(str, sources),\n                    \"-o\",\n                    str(LIBRARY.with_suffix(\".tmp\")),\n                ],\n                check=True,\n            )\n            os.replace(LIBRARY.with_suffix(\".tmp\"), LIBRARY)\n    dll = ctypes.CDLL(str(LIBRARY))\n    dll.nyanten_shanten.argtypes = [ctypes.c_char_p]\n    dll.nyanten_shanten.restype = ctypes.c_uint8\n    dll.nyanten_families.argtypes = [ctypes.c_char_p]\n    dll.nyanten_families.restype = ctypes.c_uint32\n    dll.nyanten_yaku_shanten.argtypes = [\n        ctypes.c_char_p,\n        ctypes.c_char_p,\n        ctypes.c_uint,\n    ]\n    dll.nyanten_yaku_shanten.restype = ctypes.c_uint32\n    dll.nyanten_draw.argtypes = [ctypes.c_char_p, ctypes.c_uint]\n    dll.nyanten_draw.restype = ctypes.c_uint64\n    dll.nyanten_tenpai_paths.argtypes = [\n        ctypes.c_char_p,\n        ctypes.c_char_p,\n        ctypes.c_uint64,\n        ctypes.c_uint,\n        ctypes.c_uint,\n        ctypes.c_void_p,\n        ctypes.c_void_p,\n        ctypes.c_uint,\n        ctypes.c_void_p,\n    ]\n    dll.nyanten_tenpai_paths.restype = ctypes.c_bool\n    return dll\n\n\ndef calculate_families(counts):\n    values = native().nyanten_families(bytes(map(int, counts)))\n    return tuple(((values >> shift) & 255) - 1 for shift in (0, 8, 16))\n\n\ndef calculate_shanten(counts, all_forms=True):\n    if all_forms:\n        return native().nyanten_shanten(bytes(map(int, counts))) - 1\n    return calculate_families(counts)[0]\n\n\ndef calculate_yaku_shanten(counts, melds=()):\n    \"\"\"Exact tanyao, flush and outside distances; 14 is impossible.\n\n    Counts exclude fixed melds. Each meld contains three or four base tile IDs.\n    Distances are missing draws minus one, with physical copy limits but no\n    public-availability constraint. Flush includes honitsu and chinitsu.\n    Outside includes chanta, junchan, honroutou and chinroutou: every group\n    and pair contains a terminal or honor. Closed seven pairs is included.\n    \"\"\"\n    values = native().nyanten_yaku_shanten(\n        bytes(map(int, counts)),\n        bytes(\n            int(tile)\n            for meld in melds\n            for tile in (*meld, *([34] * (4 - len(meld))))\n        ),\n        len(melds),\n    )\n    return tuple(((values >> shift) & 255) - 1 for shift in (0, 8, 16))\n\n\ndef improving(counts, unavailable=None, all_forms=True):\n    value = native().nyanten_draw(bytes(map(int, counts)), int(all_forms))\n    tiles = [tile for tile in range(34) if value & (1 << tile)]\n    unseen = 4 - numpy.asarray(counts if unavailable is None else unavailable)\n    return (value >> 34) - 1, tiles, int(unseen[tiles].sum())\n\n\nTILE_NAMES = tuple(\n    [f\"{rank}{suit}\" for suit in \"mps\" for rank in range(1, 10)]\n    + [\"E\", \"S\", \"W\", \"N\", \"P\", \"F\", \"C\"]\n    + [\"5mr\", \"5pr\", \"5sr\"]\n)\nTILE_CODES = {tile: code for code, tile in enumerate(TILE_NAMES)}\n\n\ndef mjai_tile_code(tile):\n    return TILE_CODES[tile]\n\n\ndef base_id(tile):\n    return int(\n        BASE_IDS[mjai_tile_code(tile) if isinstance(tile, str) else tile]\n    )\n\n\ndef is_red(tile):\n    return (mjai_tile_code(tile) if isinstance(tile, str) else tile) >= 34\n\n\ndef tenpai_paths(counts, unavailable, tile_ids=None):\n    \"\"\"Copy-weighted shortest routes, or None if the search is incomplete.\"\"\"\n    hands = numpy.empty((4096, 34), numpy.uint8)\n    weights = numpy.empty(4096, numpy.uint64)\n    size = ctypes.c_uint()\n    complete = native().nyanten_tenpai_paths(\n        bytes(map(int, counts)),\n        bytes(map(int, unavailable)),\n        (\n            1 << 34\n            if int(numpy.sum(counts)) % 3 == 1\n            else sum(\n                1 << int(cut)\n                for cut in (\n                    numpy.flatnonzero(counts)\n                    if tile_ids is None\n                    else numpy.unique(BASE_IDS[numpy.asarray(tile_ids, int)])\n                )\n            )\n        ),\n        3,\n        512,\n        hands.ctypes.data,\n        weights.ctypes.data,\n        len(hands),\n        ctypes.byref(size),\n    )\n    return (hands[: size.value], weights[: size.value]) if complete else None\n",
      "sha256": "c81b58ccd5bfc2471fb1133d5ed012cd1bb2aa5804b9a1215eabb06182f664f7"
    },
    {
      "path": "log_dataset/training_data.py",
      "text": "\"\"\"Streamable full-corpus critic records with same-hand scoring labels.\"\"\"\n\nimport concurrent.futures\nimport contextlib\nimport fcntl\nimport gzip\nimport hashlib\nimport json\nimport multiprocessing\nimport pathlib\nimport shutil\nimport time\n\nimport numpy\nimport tensorflow as tf\n\nfrom log_dataset import (\n    _native_collection,\n    afk,\n    archives,\n    focus_sampling,\n    records,\n    replay,\n    scoring,\n    shanten,\n)\nfrom model import critic, joint_settlement, outcomes, payment_scoring\n\nAUXILIARY = {\n    \"bonus\": [24],\n    \"score\": [24, len(scoring.BONUS_HAN)],\n}\n\n\nSAMPLING_FIELDS = (\"meta/focused_priority\", \"meta/placement_gap\")\n\n\nVALIDATION_SAMPLE = {\n    \"partition\": 7,\n    \"decision_hash_modulus\": 16,\n    \"hash\": \"sha256:validation-941:game_id:kyoku_id:decision_index:actor\",\n}\n\n\ndef serialize(observation, target):\n    example = tf.train.Example.FromString(\n        records.serialize_observation(observation)\n    )\n    example.features.feature[\"critic/partition\"].int64_list.value[:] = [\n        records.game_partition(observation.game_id)\n    ]\n    order = (observation.actor + numpy.arange(4)) % 4\n    cells = numpy.asarray(scoring.CELLS[:24])\n    numpy.testing.assert_array_equal(\n        observation.terminal_payment[:2],\n        target[\"payment\"][:2, order][:, :, order],\n    )\n    for name in AUXILIARY:\n        value = target[name][:, order][:, :, order][\n            cells[:, 0], cells[:, 1], cells[:, 2]\n        ]\n        example.features.feature[\"critic/\" + name].bytes_list.value[:] = [\n            value.astype(\"int16\").tobytes()\n        ]\n    return example.SerializeToString()\n\n\ndef parse_batch(raw):\n    parsed = tf.io.parse_example(\n        raw,\n        {\n            **{\n                name: tf.io.FixedLenFeature([], tf.string)\n                for name in records.FIELDS\n            },\n            \"critic/score\": tf.io.FixedLenFeature([], tf.string),\n            \"critic/bonus\": tf.io.FixedLenFeature([], tf.string),\n        },\n    )\n    return decode_batch(parsed)\n\n\ndef decode_batch(parsed):\n    \"\"\"Decode rich recorded supervision from already parsed fields.\"\"\"\n    features, labels = records.decode_batch(parsed)\n    auxiliary = {\n        name: tf.cast(\n            tf.reshape(\n                tf.io.decode_raw(\n                    parsed[\"critic/\" + name],\n                    tf.int16,\n                ),\n                [-1, *shape],\n            ),\n            tf.int32,\n        )\n        for name, shape in AUXILIARY.items()\n    }\n    cells = numpy.asarray(scoring.CELLS)\n    payments = tf.gather(\n        tf.reshape(labels[\"terminal_payment\"], [-1, 64]),\n        numpy.ravel_multi_index(cells.T, (4, 4, 4)),\n        axis=1,\n    )\n    public = joint_settlement.public_inputs(features)\n    auxiliary.update(\n        {\n            **critic.public_inputs(features),\n            **public,\n            **joint_settlement.payment_labels(\n                points=payments,\n                public=public,\n                ending_kind=labels[\"round_end_kind\"],\n                ending_source=labels[\"round_end_source\"],\n                ending_tenpai=labels[\"round_end_tenpai\"],\n            ),\n        }\n    )\n    return features, labels, auxiliary\n\n\nclass PackedBatch:\n    \"\"\"Transfer one buffer per dtype, then restore the existing input tree.\"\"\"\n\n    def __init__(self, inputs):\n        self.structure = tf.nest.map_structure(\n            lambda value: tf.TensorSpec(value.shape[1:], value.dtype), inputs\n        )\n        self.specs = tf.nest.flatten(self.structure)\n        self.widths = [spec.shape.num_elements() for spec in self.specs]\n        self.groups = {\n            dtype: [\n                index\n                for index, spec in enumerate(self.specs)\n                if spec.dtype.name == dtype\n            ]\n            for dtype in sorted({spec.dtype.name for spec in self.specs})\n        }\n\n    def pack(self, inputs):\n        values = tf.nest.flatten(inputs)\n        batch = tf.shape(values[0])[0]\n        packed = {}\n        for dtype, indices in self.groups.items():\n            parts = []\n            for index in indices:\n                width = self.widths[index]\n                value = tf.reshape(values[index], (batch, width))\n                if dtype in (\"bool\", \"int8\", \"int16\", \"int32\"):\n                    slots = 4 // self.specs[index].dtype.size\n                    if dtype == \"bool\":\n                        value = tf.cast(value, tf.uint8)\n                    if slots > 1:\n                        value = tf.reshape(\n                            tf.pad(value, ((0, 0), (0, (-width) % slots))),\n                            (batch, -1, slots),\n                        )\n                    value = tf.bitcast(value, tf.float32)\n                parts.append(value)\n            packed[dtype] = tf.concat(parts, axis=1)\n        return packed\n\n    def pack_numpy(self, inputs):\n        \"\"\"Pack CPU arrays without constructing a tensor for every field.\"\"\"\n        values = tf.nest.flatten(inputs)\n        batch = values[0].shape[0]\n        packed = {}\n        for dtype, indices in self.groups.items():\n            slots = (\n                4 // self.specs[indices[0]].dtype.size\n                if dtype in (\"bool\", \"int8\", \"int16\", \"int32\")\n                else 1\n            )\n            widths = [\n                (self.widths[index] + slots - 1) // slots for index in indices\n            ]\n            packed[dtype] = numpy.zeros(\n                (batch, sum(widths)),\n                (\n                    \"float32\"\n                    if dtype in (\"bool\", \"int8\", \"int16\", \"int32\")\n                    else dtype\n                ),\n            )\n            offset = 0\n            for index, width in zip(indices, widths):\n                packed[dtype][:, offset : offset + width].view(dtype)[\n                    :, : self.widths[index]\n                ] = values[index].reshape(batch, self.widths[index])\n                offset += width\n        return packed\n\n    def unpack(self, inputs):\n        values = [None] * len(self.specs)\n        for dtype, indices in self.groups.items():\n            # Narrow integer/bool SplitV kernels run on the host. Transfer\n            # bit patterns in float32 buffers so splitting stays on device.\n            slots = (\n                4 // self.specs[indices[0]].dtype.size\n                if dtype in (\"bool\", \"int8\", \"int16\", \"int32\")\n                else 1\n            )\n            parts = tf.split(\n                inputs[dtype],\n                [\n                    (self.widths[index] + slots - 1) // slots\n                    for index in indices\n                ],\n                axis=1,\n            )\n            for index, value in zip(indices, parts):\n                if dtype == \"int32\":\n                    # Int32 Reshape places its data on the host. Reshape the\n                    # transported float bits first, then reinterpret on GPU.\n                    values[index] = tf.bitcast(\n                        tf.reshape(value, (-1, *self.specs[index].shape)),\n                        tf.int32,\n                    )\n                    continue\n                if dtype in (\"bool\", \"int8\", \"int16\"):\n                    value = tf.bitcast(\n                        value, tf.uint8 if dtype == \"bool\" else dtype\n                    )\n                    value = tf.reshape(value, (tf.shape(value)[0], -1))\n                    # Aligned fields have no padding to trim.\n                    if self.widths[index] % slots:\n                        value = value[:, : self.widths[index]]\n                    if dtype == \"bool\":\n                        value = tf.cast(value, tf.bool)\n                values[index] = tf.reshape(\n                    value, (-1, *self.specs[index].shape)\n                )\n        return tf.nest.pack_sequence_as(self.structure, values)\n\n\ndef process_shard(task):\n    index, root, games = task\n    path = pathlib.Path(root) / f\"train-{index:05d}.tfrecord.gz\"\n    validation_path = pathlib.Path(root) / f\"validation-{index:05d}.tfrecord.gz\"\n    summary_path = path.with_suffix(\".json\")\n    if summary_path.exists():\n        summary = json.loads(summary_path.read_text())\n        if (\n            path.stat().st_size != summary[\"bytes\"]\n            or validation_path.stat().st_size != summary[\"validation_bytes\"]\n        ):\n            raise ValueError(f\"Incomplete dataset shard: {path}\")\n        return summary\n    if shutil.disk_usage(root).free < 15 * 1024**3:\n        raise OSError(\"Corpus rebuild requires at least 15 GiB free space\")\n    validation_count = 0\n    counts = numpy.zeros(10, numpy.int64)\n    sampling_counts = numpy.zeros((10, 2), numpy.int64)\n    with contextlib.ExitStack() as stack:\n        source_archives = {\n            path: archives.open_archive(path)\n            for path in {game.archive for game in games}\n        }\n        writer = stack.enter_context(\n            tf.io.TFRecordWriter(str(path) + \".partial\", options=\"GZIP\")\n        )\n        validation_writer = stack.enter_context(\n            tf.io.TFRecordWriter(\n                str(validation_path) + \".partial\", options=\"GZIP\"\n            )\n        )\n        for game in games:\n            raw = source_archives[game.archive].read(game.member)\n            if raw.startswith(b\"\\x1f\\x8b\"):\n                raw = gzip.decompress(raw)\n            events = [json.loads(line) for line in raw.splitlines()]\n            outcomes.normalize_recorded_endings(events)\n            seats = events[0][\"player_ranks\"][\"retained_seats\"]\n            if not seats:\n                continue\n            targets = scoring.round_labels(events)\n            partition = records.game_partition(game.game_id)\n            for round_events in afk.retained_hands(events):\n                state = replay.Replay(game.game_id, round_events)\n                for observation in state.observations(actors=seats):\n                    sampling = focus_sampling.metadata(observation)\n                    example = tf.train.Example.FromString(\n                        serialize(observation, targets[observation.kyoku_id])\n                    )\n                    for name, value in zip(SAMPLING_FIELDS, sampling):\n                        example.features.feature[name].int64_list.value[:] = [\n                            int(value)\n                        ]\n                    raw = example.SerializeToString()\n                    sampling_counts[partition] += sampling\n                    writer.write(raw)\n                    if partition == VALIDATION_SAMPLE[\"partition\"] and (\n                        int.from_bytes(\n                            hashlib.sha256(\n                                (\n                                    f\"validation-941:{observation.game_id}:\"\n                                    f\"{observation.kyoku_id}:\"\n                                    f\"{observation.decision_index}:\"\n                                    f\"{observation.actor}\"\n                                ).encode()\n                            ).digest()[:8]\n                        )\n                        % VALIDATION_SAMPLE[\"decision_hash_modulus\"]\n                        == 0\n                    ):\n                        validation_writer.write(raw)\n                        validation_count += 1\n                    counts[partition] += 1\n    pathlib.Path(str(path) + \".partial\").replace(path)\n    pathlib.Path(str(validation_path) + \".partial\").replace(validation_path)\n    summary = {\n        \"path\": path.name,\n        \"validation_path\": validation_path.name,\n        \"validation_count\": validation_count,\n        \"validation_bytes\": validation_path.stat().st_size,\n        \"games\": len(games),\n        \"counts\": counts.tolist(),\n        \"sampling_counts\": sampling_counts.tolist(),\n        \"bytes\": path.stat().st_size,\n    }\n    write_json(summary_path, summary)\n    return summary\n\n\ndef dataset(root, partition, batch_size, *, rank=0, replicas=1, seed=None):\n    \"\"\"Read a natural partition, retaining its final partial batch.\"\"\"\n    summary = json.loads(\n        (pathlib.Path(root) / \"dataset_summary.json\").read_text()\n    )\n    assert summary[\"critic_scoring_states\"] == [\n        list(s) for s in payment_scoring.SCORES\n    ]\n    assert summary[\"critic_auxiliary\"] == AUXILIARY\n    assert summary[\"critic_bonus_han\"] == list(scoring.BONUS_HAN)\n    records.validate_summary(root)\n    assert summary[\"validation_sample\"] == VALIDATION_SAMPLE\n    paths = [\n        str(\n            pathlib.Path(root)\n            / row[\"validation_path\" if partition == \"validation\" else \"path\"]\n        )\n        for row in summary[\"shard_manifest\"][rank::replicas]\n    ]\n    stream = tf.data.Dataset.from_tensor_slices(paths)\n    if seed is not None:\n        stream = stream.shuffle(len(paths), seed=seed)\n    stream = stream.interleave(\n        lambda path: tf.data.TFRecordDataset(path, compression_type=\"GZIP\"),\n        cycle_length=min(8, len(paths)),\n        block_length=1,\n        num_parallel_calls=min(8, len(paths)),\n        deterministic=True,\n    )\n\n    def select(raw):\n        partitions = tf.io.parse_example(\n            raw, {\"critic/partition\": tf.io.FixedLenFeature([], tf.int64)}\n        )[\"critic/partition\"]\n        selected = partitions < 7 if partition == \"train\" else partitions == 7\n        return tf.boolean_mask(raw, selected)\n\n    stream = stream.batch(1024).map(select, num_parallel_calls=2).unbatch()\n    options = tf.data.Options()\n    options.threading.private_threadpool_size = 12\n    return stream.batch(batch_size).with_options(options).prefetch(2)\n\n\ndef write_json(path, value):\n    temporary = path.with_name(path.name + \".partial\")\n    temporary.write_text(json.dumps(value, indent=2) + \"\\n\")\n    temporary.replace(path)\n\n\ndef run(args):\n    root = pathlib.Path(args.output)\n    root.mkdir(parents=True, exist_ok=True)\n    with (root / \"build.lock\").open(\"a\") as lock:\n        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)\n        games, ranks = archives.games(args.archives, args.extra_archives)\n        excluded = {\n            row[\"game_id\"]\n            for row in json.loads(pathlib.Path(args.reserve).read_text())[\n                \"games\"\n            ]\n        }\n        games = [game for game in games if game.game_id not in excluded]\n        if not games:\n            raise ValueError(\n                \"No eligible training games after reserve exclusion\"\n            )\n        if args.limit_games and args.limit_games < len(games):\n            games = [\n                games[index]\n                for index in numpy.linspace(\n                    0, len(games) - 1, args.limit_games, dtype=int\n                )\n            ]\n        plan = {\n            \"archives\": str(pathlib.Path(args.archives).resolve()),\n            \"games\": len(games),\n            \"excluded_reserve_games\": sorted(excluded),\n            \"critic_auxiliary\": AUXILIARY,\n            \"critic_bonus_han\": list(scoring.BONUS_HAN),\n            \"validation_sample\": VALIDATION_SAMPLE,\n            \"sampling_fields\": list(SAMPLING_FIELDS),\n            \"critic_scoring_states\": [list(s) for s in payment_scoring.SCORES],\n            \"limit_games\": args.limit_games,\n            \"player_ranks\": ranks,\n            \"input_schema\": _native_collection.INPUTS,\n            \"label_schema\": records.LABELS,\n            \"reference_schema\": records.REFERENCE_INPUTS,\n        }\n        if (root / \"build-plan.json\").exists():\n            if json.loads((root / \"build-plan.json\").read_text()) != plan:\n                raise ValueError(\"Dataset inputs changed; use a fresh output\")\n        write_json(root / \"build-plan.json\", plan)\n        (root / \"games.jsonl\").write_text(\n            \"\".join(\n                json.dumps(\n                    {\n                        \"game_id\": game.game_id,\n                        \"archive\": str(game.archive),\n                        \"member\": game.member,\n                    }\n                )\n                + \"\\n\"\n                for game in games\n            )\n        )\n        tasks = [\n            (index, str(root), tuple(games[start : start + 32]))\n            for index, start in enumerate(range(0, len(games), 32))\n        ]\n        shanten.native()\n        started = time.monotonic()\n        results = []\n        with concurrent.futures.ProcessPoolExecutor(\n            max_workers=args.workers,\n            mp_context=multiprocessing.get_context(\"spawn\"),\n        ) as pool:\n            for row in pool.map(process_shard, tasks):\n                results.append(row)\n                status = {\n                    \"stage\": \"building\",\n                    \"shards\": len(results),\n                    \"total_shards\": len(tasks),\n                    \"rows\": sum(sum(r[\"counts\"]) for r in results),\n                    \"elapsed_seconds\": time.monotonic() - started,\n                }\n                write_json(root / \"status.json\", status)\n                print(status, flush=True)\n        write_json(\n            root / \"dataset_summary.json\",\n            {\n                **plan,\n                \"shard_manifest\": results,\n                \"partition_counts\": numpy.sum(\n                    [row[\"counts\"] for row in results], axis=0\n                ).tolist(),\n                \"validation_examples\": sum(\n                    row[\"validation_count\"] for row in results\n                ),\n                \"examples\": sum(sum(row[\"counts\"]) for row in results),\n            },\n        )\n        write_json(root / \"status.json\", {**status, \"stage\": \"complete\"})\n",
      "sha256": "7130f38f2d9858a7f0f2d0d8f638291acf73f9ab53897b7fd107cc8a2b07ccdb"
    },
    {
      "path": "log_dataset/training_targets.py",
      "text": "\"\"\"Complete-round labels separated from decision-time visible inputs.\"\"\"\n\nimport types\n\nimport numpy\nimport riichienv\n\nfrom log_dataset import (\n    _native_collection,\n    features,\n    scoring,\n    shanten,\n)\nfrom model import outcomes, payment_scoring\n\n\ndef ron_labels(state, actor, phase):\n    \"\"\"Known ron and abortive-draw payments for one decision.\"\"\"\n    payments = numpy.full((3, 37), -1, numpy.int32)\n    legal_ron = numpy.full((3, 37), -1, numpy.int8)\n    if phase in (\"DISCARD\", \"RIICHI\", \"RESPONSE\", \"KAN\"):\n        cuts = {\n            features.native_tile_code(action.tile): action.tile\n            for action in state.legal_observation(actor).legal_actions()\n            if action.action_type == riichienv.ActionType.DISCARD\n        }\n        kans = {}\n        if phase == \"KAN\":\n            kans = {\n                action.tile // 4: action\n                for action in state.legal_observation(actor).legal_actions()\n                if action.action_type\n                in (riichienv.ActionType.ANKAN, riichienv.ActionType.KAKAN)\n            }\n            cuts = {code: action.tile for code, action in kans.items()}\n        if phase == \"RESPONSE\":\n            for action in features.prefer_red_calls(\n                state.legal_observation(actor).legal_actions()\n            ):\n                if action.action_type not in (\n                    riichienv.ActionType.CHI,\n                    riichienv.ActionType.PON,\n                ):\n                    continue\n                env = state.native_env.clone()\n                env.apply_event(\n                    {\n                        **features.action_event(action),\n                        \"actor\": actor,\n                        \"target\": state.pending_discard[\"actor\"],\n                    }\n                )\n                cuts.update(\n                    {\n                        features.native_tile_code(cut.tile): cut.tile\n                        for cut in env.get_observation(actor).legal_actions()\n                        if cut.action_type == riichienv.ActionType.DISCARD\n                    }\n                )\n        payments[:, list(cuts)] = 0\n        legal_ron[:, list(cuts)] = 0\n        ura = next(\n            (\n                event[\"ura_markers\"]\n                for event in state.events\n                if event[\"type\"] == \"hora\" and event[\"ura_markers\"]\n            ),\n            [],\n        )\n        for relative in range(3):\n            opponent = (actor + relative + 1) % 4\n            hand = state.legal_observation(opponent).hand\n            if len(hand) % 3 != 1:\n                continue\n            waits = riichienv.HandEvaluator(\n                hand, state.melds[opponent]\n            ).get_waits()\n            if (\n                not waits\n                or state.missed_agari(opponent)\n                or (\n                    phase == \"RESPONSE\"\n                    and state.pending_discard[\"actor\"] != opponent\n                    and shanten.base_id(state.pending_discard[\"pai\"]) in waits\n                )\n                or set(waits)\n                & {\n                    shanten.base_id(row[\"pai\"])\n                    for row in state.rivers[opponent]\n                }\n            ):\n                continue\n            for code, tile in cuts.items():\n                if tile // 4 not in waits:\n                    continue\n                if (\n                    phase == \"KAN\"\n                    and kans[code].action_type == riichienv.ActionType.ANKAN\n                    and (\n                        state.melds[opponent]\n                        or len({t // 4 for t in hand + [tile]}) != 13\n                        or any(\n                            t // 4 < 27 and t // 4 % 9 not in (0, 8)\n                            for t in hand + [tile]\n                        )\n                    )\n                ):\n                    continue\n                riichi = (\n                    state.declared[opponent]\n                    if phase == \"RESPONSE\"\n                    else state.accepted[opponent]\n                )\n                score = _native_collection.score_hand(\n                    types.SimpleNamespace(\n                        tiles=hand + [tile],\n                        melds=state.melds[opponent],\n                        agari_tile=tile,\n                        dora_indicators=state.legal_observation(\n                            opponent\n                        ).dora_indicators,\n                    ),\n                    conditions=riichienv.Conditions(\n                        riichi=riichi,\n                        double_riichi=(\n                            riichi\n                            and state.rivers[opponent][0][\"riichi\"]\n                            and not any(\n                                event[\"type\"]\n                                in {\"chi\", \"pon\", \"daiminkan\", \"ankan\", \"kakan\"}\n                                for event in state.history[\n                                    : state.rivers[opponent][0][\"event_index\"]\n                                ]\n                            )\n                        ),\n                        ippatsu=state.ippatsu[opponent] and phase != \"RESPONSE\",\n                        houtei=state.live_wall == 0 and phase != \"KAN\",\n                        chankan=phase == \"KAN\",\n                        player_wind=(\n                            riichienv.Wind.East,\n                            riichienv.Wind.South,\n                            riichienv.Wind.West,\n                            riichienv.Wind.North,\n                        )[(opponent - state.start[\"oya\"]) % 4],\n                        round_wind=\"ESWN\".index(state.start[\"bakaze\"]),\n                    ),\n                    ura=(\n                        [\n                            shanten.base_id(marker) * 4\n                            for marker in ura[: len(state.dora_markers)]\n                        ]\n                        if riichi\n                        else []\n                    ),\n                )\n                if score.is_win:\n                    legal_ron[relative, code] = 1\n                    payments[relative, code] = (\n                        -1\n                        if (\n                            (\n                                riichi\n                                and not score.yakuman\n                                and len(ura) < len(state.dora_markers)\n                            )\n                            or state.native_env.pao[opponent]\n                        )\n                        else score.ron_agari + 300 * state.start[\"honba\"]\n                    )\n        payments[:, (payments > 0).sum(axis=0) == 3] = -1\n    return {\"ron_payments\": payments, \"ron_legal\": legal_ron}\n\n\ndef round_targets(state, events, indices=None):\n    \"\"\"Forecast first tenpai witnesses, scoring only requested decisions.\"\"\"\n    length = len(events)\n    ready = numpy.zeros((length, 4), bool)\n    completion = numpy.full((length, 4, 2, len(scoring.NAMES)), -1, numpy.int8)\n    completion_score = numpy.full((length, 4, 2), -1, numpy.int16)\n    pending = numpy.zeros(4, bool)\n    requested = None if indices is None else set(indices)\n    for index, event in enumerate(events):\n        if index:\n            state.apply(event)\n        if requested is None or index in requested:\n            pending[:] = True\n        for actor in numpy.flatnonzero(pending):\n            counts = state.concealed_counts(actor)\n            if counts.sum() % 3 != 1:\n                continue\n            ready[index, actor] = shanten.calculate_shanten(counts) == 0\n            if not ready[index, actor]:\n                continue\n            observation = state.legal_observation(actor)\n            visible = state.public_tiles()\n            _, waits = scoring.score_waits(\n                observation.hand,\n                state.melds[actor],\n                {\n                    \"own_discards\": [\n                        shanten.base_id(row[\"pai\"])\n                        for row in state.rivers[actor]\n                    ],\n                    \"missed_agari\": state.missed_agari(actor),\n                    \"unavailable_counts\": counts\n                    + numpy.bincount(\n                        [shanten.base_id(tile) for tile in visible],\n                        minlength=34,\n                    ),\n                    \"unavailable_red\": [\n                        observation.hand.count(tile) + visible.count(name)\n                        for tile, name in zip(\n                            (16, 52, 88), (\"5mr\", \"5pr\", \"5sr\")\n                        )\n                    ],\n                    \"dora_indicators\": observation.dora_indicators,\n                    \"player_wind\": (actor - state.start[\"oya\"]) % 4,\n                    \"round_wind\": \"ESWN\".index(state.start[\"bakaze\"]),\n                },\n            )\n            # Yaku and value are one scorer witness, selected by points.\n            # Ordinary ron/tsumo use the actual declaration and known dora,\n            # with no hypothetical ura, ippatsu or special-event bonuses.\n            for mode in range(2):\n                candidates = [\n                    wait[\"values\"][2 * int(state.declared[actor]) + mode]\n                    for wait in waits\n                    if wait[\"unseen\"] > 0\n                    and wait[\"values\"][2 * int(state.declared[actor]) + mode][\n                        \"legal\"\n                    ]\n                ]\n                if candidates:\n                    best = max(candidates, key=lambda value: value[\"points\"])\n                    completion[index, actor, mode] = best[\"yaku\"]\n                    completion_score[index, actor, mode] = (\n                        payment_scoring.score_class(\n                            best[\"han\"],\n                            best[\"fu\"],\n                            best[\"yakuman\"],\n                        )\n                    )\n        if event[\"type\"] == \"hora\":\n            ready[index, event[\"actor\"]] = True\n        pending &= ~ready[index]\n        if (\n            requested is not None\n            and index >= max(requested)\n            and not pending.any()\n        ):\n            break\n    # Forecast the next recorded tenpai shape, never a maximum over future\n    # shapes. A tenpai with no legal completion stays unknown for that mode.\n    following = numpy.minimum.accumulate(\n        numpy.where(ready, numpy.arange(length)[:, None], length - 1)[::-1],\n        axis=0,\n    )[::-1]\n    return {\n        \"completion\": completion[following, numpy.arange(4)],\n        \"completion_score\": completion_score[following, numpy.arange(4)],\n        \"payments\": outcomes.terminal_payments(events),\n        **outcomes.terminal_ending(events),\n    }\n\n\ndef candidate_yaku_affinity(packed):\n    \"\"\"Action-specific visible route labels, not realized future yaku.\"\"\"\n    result = numpy.full((16, 3), -1, numpy.float16)\n    for hand_ix in numpy.flatnonzero(packed[\"candidate_hand_valid\"]):\n        melds = []\n        for tile, kind in zip(\n            packed[\"candidate_meld_tiles\"][hand_ix],\n            packed[\"candidate_meld_types\"][hand_ix],\n            strict=True,\n        ):\n            if tile == 34:\n                continue\n            melds.append(\n                riichienv.Meld(\n                    (\n                        riichienv.MeldType.Chi,\n                        riichienv.MeldType.Pon,\n                        riichienv.MeldType.Daiminkan,\n                        riichienv.MeldType.Ankan,\n                        riichienv.MeldType.Kakan,\n                    )[kind],\n                    (\n                        [int(tile + offset) * 4 for offset in range(3)]\n                        if kind == 0\n                        else [\n                            int(tile) * 4 + copy\n                            for copy in range(3 if kind == 1 else 4)\n                        ]\n                    ),\n                    bool(kind != 3),\n                )\n            )\n        removed = numpy.flatnonzero(\n            packed[\"candidate_hand_counts\"][0]\n            != packed[\"candidate_hand_counts\"][hand_ix]\n        )\n        shared_discard = len(removed) == 1 and (\n            packed[\"candidate_hand_counts\"][0, removed[0]]\n            - packed[\"candidate_hand_counts\"][hand_ix, removed[0]]\n            == 1\n        )\n        # Search each discard from the common parent so its first draw/cut\n        # nodes reuse the already-computed ukeire neighborhood. Routes and\n        # their separate search budgets are identical to the post-cut hand.\n        result[hand_ix] = scoring.hand_yaku_fractions(\n            counts=packed[\"candidate_hand_counts\"][\n                0 if shared_discard else hand_ix\n            ],\n            unavailable=packed[\"known_unavailable_counts\"],\n            melds=melds,\n            player_wind=int(packed[\"seat_wind\"][0]),\n            round_wind=int(packed[\"prevailing_wind\"]),\n            cuts=removed if shared_discard else None,\n            names=(\"tanyao\", \"honitsu\", \"chanta\"),\n        )\n    return result\n\n\ndef attach_beliefs(observation, state):\n    \"\"\"Decision-time hidden hands are labels, never public model features.\"\"\"\n    observation.opponent_shanten = numpy.full(3, -1, numpy.int8)\n    observation.opponent_ukeire = numpy.full((3, 34), -1, numpy.int8)\n    observation.opponent_hand_counts = numpy.zeros((3, 37), numpy.int8)\n    for relative, seat in enumerate(\n        (observation.actor + offset) % 4 for offset in range(1, 4)\n    ):\n        hand = state.legal_observation(seat).hand\n        for tile in hand + [\n            tile for meld in state.melds[seat] for tile in meld.tiles\n        ]:\n            observation.opponent_hand_counts[\n                relative, features.native_tile_code(tile)\n            ] += 1\n        if len(hand) % 3 == 1:\n            distance, improving, _ = shanten.improving(\n                state.concealed_counts(seat)\n            )\n            observation.opponent_shanten[relative] = min(3, distance)\n            observation.opponent_ukeire[relative] = 0\n            observation.opponent_ukeire[relative, improving] = 1\n\n\ndef attach(observation, state, index, *, affinity=None):\n    actor = observation.actor\n    order = [(actor + offset) % 4 for offset in range(4)]\n    observation.candidate_yaku_affinity = (\n        candidate_yaku_affinity(observation.features)\n        if affinity is None\n        else affinity\n    )\n    observation.terminal_payment = outcomes.relative_payments(\n        state.targets[\"payments\"], actor, state.accepted\n    )\n    observation.round_end_kind = state.targets[\"round_end_kind\"]\n    observation.round_end_source = numpy.int8(\n        (int(state.targets[\"round_end_source\"]) - actor) % 4\n        if state.targets[\"round_end_source\"] >= 0\n        else -1\n    )\n    observation.round_end_tenpai = state.targets[\"round_end_tenpai\"][order]\n    attach_beliefs(observation, state)\n    observation.round_completion_yaku = state.targets[\"completion\"][\n        index, order\n    ]\n    observation.round_completion_score = state.targets[\"completion_score\"][\n        index, order\n    ]\n",
      "sha256": "80b0617fbb1ae60731dcaecf2fe50408c385e7a624c41b5042da51b89ce94f88"
    },
    {
      "path": "model/ARCHITECTURE.md",
      "text": "# Model architecture\n\nNejimakidori predicts legal actions, opponent beliefs and current-hand\nsettlements for four-player South games. Shared lower encodings combine the known\nhand with public table state; separate upper stacks serve the actor and\ncritic/beliefs. The actor chooses an action; the critic predicts\nits consequences. Hidden opponent tiles are training labels, never inputs.\n\nThis document describes the source architecture. Use the source bundled with\na released checkpoint for its exact input and output contract.\n\n[Model guide](README.md) · [Constraints](CONSTRAINTS.md) ·\n[Training objective](../training/OBJECTIVE.md) ·\n[Interactive atlas](https://ogame.squareqrow.com/atlas/)\n\n## Inputs and representations\n\nThe [native interface](../log_dataset/native_collection/README.md) defines\n103 feature tensors for each decision state. Their main groups are:\n\n| Group | Contents |\n| --- | --- |\n| Table | Scores, ranks, round wind, hands remaining, wall, dealer and deposits |\n| Hand | Concealed tile counts, red fives, fixed melds and resulting-hand states |\n| Opponents | Public melds, discards, riichi declarations and visible tile evidence |\n| Candidates | Legal actions, resulting-hand references and deterministic scoring support |\n\nScores and ranks use East, South, West, North order. Opponent-specific tensors\nuse seats relative to the acting player. `seat_wind` connects these axes.\nThe constraint-only `nagashi_possible[4]` and `pao_payer[4]` encode exact\npublic river eligibility and established responsibility (-1 when absent).\n`hands_remaining` is 7 at East 1, 0 at South 4 and negative in extensions.\n\nTiles share one base-34 identity projection across hand, river, table and\ncandidate encoders. Red fives use the corresponding ordinary five plus a red\nflag. Padding contributes no tile identity. Other categorical values use\none-hot coordinates or shared category embeddings; counts and magnitudes are\nscaled separately from masks and probabilities.\n\nEach state has a bank of up to 16 distinct hand states, including the current\nhand and legal discard/kan results. Every hand state carries its own melds and\n19 yaku-feasibility flags. These flags describe possible routes; they are not\npredicted yaku probabilities. `candidate_fu` records the fixed-meld fu\ncontribution, not a completed hand's total fu.\n\n## Shared encoder\n\nPublic river events pass through shared convolutions and attention across\nopponents and riichi segments. Their summaries join table features to form a\nshared context. That context conditions the hand encoder before suit-local\nconvolutions; honors have their own projection. Hand and public readouts use\n384-wide linear factors before their 512-wide outputs. The current hand\n(bank slot zero) and table context then split into two independent upper\nencoders, each with its own fusion, three residual blocks and board readout.\nThe actor branch reads detached lower encodings; policy gradients train its\nfusion and residual stack. The other branch trains through critic and belief\nsupervision. Candidate hands, action legality and candidate shanten/ukeire summaries\ndo not enter that table or board representation. Our current concealed tiles\nremain evidence about the copies available to opponents.\n\nEvery legal candidate receives the representation of its resulting hand,\nshared board context and action-specific evidence. The actor queries the\ncomplete legal action set, including call-plus-discard choices, using its\nnormalized policy context. Detached normalized candidate vectors supply\n128-wide keys and values; scaled dot-product softmax weights are normalized\nwithin each decision. A zero-initialized 128-to-768 projection adds the\nattention summary to the actor's policy context. Accepted-call states receive\nthe same parent decision summary.\nWin, call-branch and per-candidate policy scores consume this pooled context.\nDifferent decisions never share a pool; empty sets contribute zero.\nExact candidate yaku distances, discard analysis, retained safe tiles, kan\nefficiency and abort flags enter candidate scoring rather than board inference.\n\nCandidate route readouts and the settlement critic consume each candidate's\nunmixed representation. Immediate ron eligibility is predicted once per opponent and\nbase tile from the board, then indexed by the proposed cut. The policy reads\ndetached copies. Attention trains only through actor objectives; settlement and\nroute supervision retain their direct paths to shared candidate encodings.\n\nThe complete model has **18,929,944 trainable parameters**, including\n**6,091,273** in the private actor branch and **3,357,361** in the settlement\ncritic. Each upper encoder has three 512 → 576 → 576 → 512 residual blocks.\nThe actor combines its 512-wide board with 256-wide policy evidence and\napplies two 768 → 384 → 768 residual blocks before the shared\n1158 → 512 → 1 candidate scorer. The critic has six 384 → 480 → 384\nresidual blocks, 96-wide player and claim representations, and 32-wide event\nrepresentations. Residual skips preserve the full state across narrower\ninternal transforms. No convolution stage was added.\nThe actor-only candidate attention has 298,368 parameters. It uses one\nquery per decision and linear memory in the number of legal candidates.\n\nShared hand, river, both upper board stacks and initial candidate projections use BF16 computation with FP32\nvariables. The opponent tile-attention projections, attention and feedforward\nblocks also compute in BF16, retaining FP32 normalization and belief readouts.\nPredictions, probabilities and losses use FP32; constrained count\ngradients use higher precision for numerical stability.\n\n## Calls and action selection\n\nA chi or pon and its follow-up discard form one candidate. Feature extraction\nconstructs the hypothetical accepted-call state, including changed melds and\nkuikae restrictions. That state uses the same encoder and discard scorer as an\nordinary decision.\n\nHypothetical calls reuse the original decision's opponent shanten, improving\ntiles, held-count distributions, structural waits and ron eligibility. A call\nproposal adds no hidden-hand evidence. Its changed board and hand still\ndetermine candidate representations and completion potential. Once a new\nstate is actually observed, ordinary inference runs on that observation.\n\nThe response policy first assigns probability to six branches: pass, three\nchi patterns, pon and open kan. Each chi/pon branch is multiplied by its\nconditional discard distribution. Pass and open kan have no immediate discard\ncontinuation. Greedy selection chooses the branch by marginal probability\nbefore choosing its discard.\n\nThe other policy heads cover ordinary discard, dama versus riichi with a\ndiscard, concealed/added kan, and win versus decline. Red fives remain distinct\nactions. Equivalent physical copies share a tile action. Automatic aborts\nand forced choices are handled by the game rules.\n\nCall settlement forecasts include competing claims that may preempt the\nattempt. Accepted-call features describe the proposed result; guaranteed\npublic constraints remain those of the original call window.\n\n## Supervised predictions\n\nThe model trains seven named prediction groups alongside the policy and\nsettlement objectives:\n\n| Prediction | Meaning |\n| --- | --- |\n| Opponent shanten | Four classes: tenpai, one away, two away and three or more away |\n| Opponent improving tiles | Structural improvement probability for each tile, conditional on shanten |\n| Opponent tile counts | Marginal held-count distributions, constrained by known melds, hand sizes and remaining copies |\n| Completion yaku | Yaku of the highest-scoring ordinary completion witness for the next observed tenpai shape, separately for ron and tsumo |\n| Completion score | Our own total han/fu for that same completion witness; ron and tsumo |\n| Candidate route affinity | Visible shortest-route support for tanyao, flush and outside-hand families |\n| Candidate ron | Each opponent's legal ron probability on the proposed discard |\n\nOpponent and completion predictions share a board representation. Tile\nattention couples count and improving-tile predictions across suits. Opponent\nyaku evidence includes our hand, public availability and detached\nopponent count predictions. Completion-score logits have shape `[1, 2, 38]`:\nonly our own seat, for ron and tsumo. No opponent completion-score readout,\nresidual, supervised loss or actor/critic score input remains.\n\nStructural wait probability is tenpai probability multiplied by conditional\nwait probability. Candidate ron combines that structural wait with learned\ntile-specific eligibility. A shared 128-wide nonlinear opponent readout\ncombines board context, detached opponent ron-yaku probabilities and attached\n64-wide yaku evidence features. Ron supervision trains those features without\nflowing through yaku probability readouts or structural waits. Completion yaku\nis soft evidence, not a current-tile legality gate. Dama, riichi and alternative\ncalls offering the same tile share immediate danger under the same observed state;\nred and ordinary fives share their base-tile danger. Known-safe tiles and\nactions without a discard have zero ron\nliability. Structural waits alone do not imply legal ron: furiten and yaku\nrequirements still matter.\n\nCompletion yaku and score targets refer to one shared witness. Scores include\nknown riichi, visible dora and menzen tsumo where applicable, but exclude\nhypothetical ura and situational bonuses. Completion potential and route\nsupport do not represent the probability of eventually winning.\n\nThis separation changes table, board-fusion, candidate and ron-readout shapes.\nEarlier checkpoints require an explicit architecture transfer before training\nwith this source; their frozen source remains the matching evaluation path.\n\n## Settlement and action value\n\nThe critic predicts how the current hand ends: ron claims, tsumo, exhaustive\ndraw, nagashi mangan or abort, with deposit states and conditional winning-hand values.\nRule-based settlement converts these predictions to transfers, including\ndealer shares, honba, riichi deposits and pot priority. Multiple ron claims\nare represented jointly; triple ron shares the general abort event, including its\npre-acceptance deposit possibilities.\n\nThe 49 learned event representations exchange information through one residual\nattention block before the event and deposit readouts. Each candidate has its\nown 49 × 32 tensor; attention never crosses candidate rows. Pre-LayerNorm\nfeeds four heads with 16 channels per head, followed by a bias-free 32-channel\ncorrection initialized to zero. The block initially preserves every event\nrepresentation and adds 9,504 parameters. No event-index positional embedding\nis used, preserving the role-based permutation structure. These are all fixed\nhypothetical event slots, not padding or observed future outcomes. Exact legal\nsettlement support still applies after the learned readouts. The total han/fu\nscore head remains a separate prediction.\n\nEach claim predicts one distribution over total han/fu, including future\nsituational yaku and hidden ura. Fixed-meld fu, visible bonus han, open/closed\nstatus and required riichi enter the score network directly; player and\ncandidate context supplies yaku evidence. Public minima and legal score\nsupport constrain the distribution. Fixed-meld fu is not completed-hand fu,\nand possible yaku are not guaranteed han. There is no separate added-han\nprediction or bonus-conditioned score axis. This differs from the ordinary\ncompletion prediction above. Claim amounts are conditionally factorized\ngiven their shared context; all tsumo payer shares use the same score law.\nObserved settlement likelihood trains the total score prediction without\nseparate han/fu supervision.\n\nFour learned nagashi readouts generate all 15 nonempty qualifier masks, giving\n60 derived event choices. Exact public river eligibility masks impossible\nqualifiers. A middle discard removes our eligibility; an accepted call removes\nthe source player's eligibility. Nagashi transfers use fixed mangan payments\nbetween all relevant players, including transfers between qualifiers, retain\nthe riichi pot and add no honba. Dealer continuation marginalizes the existing\nexhaustive-draw tenpai prediction; it has no separate learned readout.\n\nEach winning claim also predicts a four-seat payment allocation, used only\nfor named yakuman. The winner's allocation entry denotes ordinary payment;\nthe other entries denote the responsible payer. The selected Tenhou rules\napply responsibility to the whole yakuman stack. Established public liability\nfixes the payer and requires yakuman scoring. An attempted decisive dragon or\nwind call fixes liability if that call leads to our eventual win. A prospective\ndiscard flag identifies offers that could complete an opponent's third dragon\nor fourth wind group; this is learned risk evidence, not automatic liability\nor an action ban. Known liability and nagashi eligibility bypass learned\nencoders, leaving their widths unchanged.\n\nObserved payments supervise the action actually played. Unknown winning\namounts are marginalized. Settlement likelihood and a unit-weight four-seat\nnagashi classification loss share the constrained distribution. An assertion\noutside the compiled chunks rejects unsupported valid targets using the\nexisting likelihood denominator; no coverage scalar is reported. Unplayed\nactions receive no observed settlement target.\n\nAction value is derived from settlements through a fixed continuation model:\n\n`J = expected ST3 / 100 + P(first) - P(fourth)`\n\nCompleted matches use exact scores and ranks. Earlier hands use scores,\nremaining hands and scheduled dealerships to forecast final placement. The\ncontinuation coefficients are fixed during training. There is no separate\nstate-value head or final-match-return regression.\n\n## Gradient ownership\n\nEvery belief is detached wherever another prediction, the actor or critic\nconsumes it. Its own direct supervision still trains its readout and upstream\nshared representations and the critic/belief upper encoder. Settlement\nsupervision also trains that upper encoder and the shared lower and candidate\nencodings. Policy losses train the separate actor upper encoder,\npolicy evidence/refinement, candidate pooling and scoring layers. The actor's lower inputs,\nshared candidate evidence and consumed beliefs are detached; its own board\noutput remains attached. Critic and belief losses do not train the private\nactor branch. Q is detached in policy objectives. Accepted-call positions\nrecompute both upper encoders with the same respective weights.\n\nThis changes checkpoint shapes and adds private actor weights. Existing\ncheckpoints require an explicit architecture transfer before a warm start.\n\nAll seven prediction groups train on eligible decisions with known labels.\nAlready-riichi and forced decisions are excluded; discretionary dama choices\nremain eligible. See [constraints](CONSTRAINTS.md) and the\n[training objective](../training/OBJECTIVE.md) for loss and phase coverage.\n\n## SavedModel interface\n\nBoth signatures accept 208 named inputs: 103 base tensors, 103 sparse\naccepted-call tensors, and their owner and option vectors. Base tensors have\n`B` decision rows; accepted-call tensors have `C` rows, which may be zero.\nUse [call_states.py](../log_dataset/call_states.py) to batch and select them.\n\nThe `policy` signature returns the five policy heads. `serving_default`\nreturns the following tensors. Shapes omit the leading decision axis unless\nmarked as candidate outputs.\n\n| Output | Shape |\n| --- | --- |\n| `discard_policy_logits` | `[37]` |\n| `riichi_policy_logits` | `[74]` |\n| `response_policy_logits` | `[150]` |\n| `kan_action_logits` | `[35]` |\n| `win_decision_logits` | `[2]` |\n| `opponent_shanten_logits` | `[3, 4]` |\n| `riichi_action_logits` | `[2]` |\n| `response_action_logits` | `[4]` |\n| `chi_pattern_logits` | `[3]` |\n| `terminal_payment_probabilities` | `[4, 4, 4, 60]` |\n| `payment_values` | `[60]` |\n| `final_placement_probabilities` | `[4]` |\n| `review_outcome_probabilities` | `[7]` |\n| `settlement_mean`, `settlement_variance` | `[5]` each |\n| `critic_expected_points` | `[4]` per active candidate |\n| `critic_action_indices` | `[2]` per active candidate |\n\n`critic_action_indices` identifies each candidate as `(decision, action)`.\nDecision-level forecasts average over the active policy. Typed payments and\nsettlement moments exclude honba; current-hand action values use the complete\nsettlement rules. Other belief predictions are internal training and policy\ninputs rather than serving outputs.\n",
      "sha256": "36846b5dc053eac4722d0309e63376fdc4431bc214a104168de897761d56a585"
    },
    {
      "path": "model/CONSTRAINTS.md",
      "text": "# Constraints and gradients\n\n[Architecture](ARCHITECTURE.md) · [Training objective](../training/OBJECTIVE.md)\n\n## Legal support\n\nThe native engine determines legal actions. Forward masks remove unavailable\nchoices before policy normalization. Uncomputed candidate slots are padding;\nthey do not receive a penalty for their arbitrary score offset. Positions\nwithout a legal win opportunity do not train the model to decline wins.\n\nOpponent shanten is fixed to tenpai after declared riichi or four fixed melds.\nCount marginals respect known meld copies, concealed hand sizes and shared\nremaining-copy limits. These marginals do not define a joint distribution\nover complete hidden hands.\n\nCompletion yaku masks exclude publicly impossible combinations. Our own\ncompletion-score probabilities respect the corresponding yaku lower bounds and yakuman mass.\nPossible yaku do not become positive labels merely because they are feasible.\nCandidate ron requires a structural wait and learned eligibility, with zero\nliability for publicly safe tiles and actions without a discard.\nBoth wait and eligibility are inferred from the observed state once per\nopponent and tile. Changing a hypothetical hand or cut does not change the\nopponent posterior. Hypothetical calls inherit the parent posterior; their\nfuture completion and settlement predictions can depend on the action.\n\nSettlement support enforces score legality, dealer shares, deposits, claim\npriority and hand-ending rules. Public river eligibility constrains the four\nnagashi outputs and their derived qualifier combinations; exact rules supply\ntheir transfers. Established pao fixes the responsible payer and yakuman\nscore support. Prospective third-dragon/fourth-wind discard flags inform\nlearned future risk without forbidding those actions. Last-discard boundaries still allow ron before\na draw or abort. Four fixed melds imply tenpai but do not imply a riichi\ndeposit. Call attempts retain the possibility of preemption by other claims.\n\nOpening symmetry pools equivalent discards without changing their total\nprobability. Final-wall safety rules preserve legal branch mass and retain\npossible nagashi mangan outcomes.\n\n## Gradient boundaries\n\n| Objective or connection | Gradient behavior |\n| --- | --- |\n| Direct belief supervision | Trains the belief readout and its shared representation |\n| Observed settlement likelihood | Trains the critic and shared candidate/board encodings |\n| Candidate route supervision | Trains the readout and shared candidate/board encodings |\n| Immediate ron supervision | Trains the board-level eligibility readout and shared encoder; structural waits are detached |\n| Belief consumed by another prediction | Detached at the consumption boundary |\n| Shared lower encodings, candidate features and beliefs consumed by the actor | Detached |\n| Policy losses through the private actor upper encoder | Train its fusion, three board blocks, candidate attention and private policy layers |\n| Q used by policy optimization | Detached |\n\nBoard-level beliefs read observed state and our current concealed hand, with\nno candidate-bank pooling or candidate-analysis inputs. The actor alone attends to\ndetached legal-candidate vectors; its attention cannot change the representations\nconsumed by beliefs, candidate readouts or the settlement critic. Unknown targets,\npadding, already-riichi decisions and forced choices contribute no supervised\ntraining mass. Discretionary dama discards remain eligible.\n\nForward constraints also provide detached targets for raw predictions.\nCategorical projections use forward KL; binary marginals use Bernoulli KL.\nCount supervision differentiates the constrained solution while enforcing\nhand-size and copy limits. Each constraint belongs to its producing head and\nis included once in the relevant objective.\n\nThe critic trains observed settlement likelihood and legal-support\nconstraints. It does not train tenpai, wait or own-shanten directional\npenalties or evaluate counterfactual direction probes during training.\n\n## Data and checkpoint contracts\n\nFeature layouts, labels and score vocabularies must agree across datasets,\nweights and exports. Consumers validate the declared schema and signatures.\nRegenerate records when their contract changes; changing metadata does not\nconvert stored tensors. A released export must be used with its matching\nsource and feature producer.\n",
      "sha256": "f356dea1ea773bcf85c316fd1bb8a121c614d4196bfbc2d28e841d8de8aadf90"
    },
    {
      "path": "model/README.md",
      "text": "# Model\n\n## Guides\n\n| Topic | Read |\n| --- | --- |\n| Inputs, predictions and settlement | [Architecture](ARCHITECTURE.md) |\n| Legality, gradient constraints and compatibility | [Constraints](CONSTRAINTS.md) |\n| Training objective | [Objective](../training/OBJECTIVE.md) |\n| Export and match evaluation | [Evaluation](../training/EVALUATION.md) |\n| Explore inputs, outputs and architecture | [Interactive catalog](https://ogame.squareqrow.com/atlas/) |\n\n## Source map\n\n| Area | Modules |\n| --- | --- |\n| Network and shared representations | [network.py](network.py), [encoder.py](encoder.py) |\n| Actor candidate attention and river attention | [actor.py](actor.py), [river_attention.py](river_attention.py) |\n| Neural input encoding and categorical masks | [input_features.py](input_features.py) |\n| Candidate route and ron heads | [candidate_predictions.py](candidate_predictions.py) |\n| Policy and legal choices | [actor.py](actor.py), [actions.py](actions.py) |\n| Shared opponent and completion beliefs | [beliefs.py](beliefs.py) |\n| Action outcomes and settlement | [critic.py](critic.py), [joint_settlement.py](joint_settlement.py) |\n| Score vocabulary and legality | [outcomes.py](outcomes.py), [payment_scoring.py](payment_scoring.py) |\n| Shared loss reductions | [losses.py](losses.py) |\n| SavedModel creation and loading | [export.py](export.py), [inference.py](inference.py) |\n\nTraining and evaluation commands are in [training/](../training/README.md).\n\n## Prediction inputs\n\n`Predictor.infer()` accepts a list of feature objects produced by\n`log_dataset.features.pack()`. Each object includes its legal chi/pon states.\nUse `log_dataset.call_states.batch()` to prepare direct SavedModel inputs.\n\n| Fields | Batched shape | Meaning |\n| --- | --- | --- |\n| Base features | `[B, ...]` | Current decision states |\n| `post_call_<feature>` | `[C, ...]` | Accepted chi/pon states before discarding |\n| `post_call_owner` | `[C]` | Index into the base decision batch |\n| `post_call_option` | `[C]` | Chi patterns 0–2 or pon 3 |\n\n`C` counts available call branches across the batch and may be zero. Pass and\nopen kan have no immediate discard state. For a single feature object, owners\nare zero; batching offsets them. Empty JSON call arrays are valid. Base and\npost-call tensors must not be stacked or sliced as if they shared a row axis.\n",
      "sha256": "1db473f9912c8777cfdf7f2d5364154c5816638dc1f22a76da11007cda974592"
    },
    {
      "path": "model/__init__.py",
      "text": "\"\"\"Mahjong network components, scoring, export and inference.\"\"\"\n",
      "sha256": "3900be222ffa7e80ceefe0debc84374d70f0726bacc31b15d2d4bab4221f3666"
    },
    {
      "path": "model/actions.py",
      "text": "\"\"\"Legal actions, physical-copy selection and model action indexing.\"\"\"\n\nimport numpy\nimport riichienv\n\nfrom log_dataset import features\nfrom model import outcomes\n\nTRAIN_POLICY_HEADS = (\n    \"discard_policy_logits\",\n    \"riichi_policy_logits\",\n    \"response_policy_logits\",\n    \"kan_action_logits\",\n    \"win_decision_logits\",\n)\n\n# All actor outputs use float32; only their shapes vary.\nACTOR_OUTPUTS = {\n    \"win_decision_logits\": [2],\n    \"opponent_shanten_logits\": [3, 4],\n    \"opponent_ukeire_by_shanten_logits\": [3, 4, 34],\n    \"opponent_wait_logits\": [3, 34],\n    \"opponent_hand_count_logits\": [3, 37, 5],\n    \"round_completion_yaku_logits\": [4, 2, 23],\n    \"round_completion_score_logits\": [1, 2, len(outcomes.SCORE_STATES)],\n    \"discard_policy_logits\": [37],\n    \"riichi_policy_logits\": [74],\n    \"response_policy_logits\": [150],\n    \"riichi_action_logits\": [2],\n    \"response_action_logits\": [4],\n    \"chi_pattern_logits\": [3],\n    \"kan_action_logits\": [35],\n}\n\n\n# Public serving tensors; other actor outputs remain internal training/context.\nSERVING_ACTOR_OUTPUTS = {\n    name: ACTOR_OUTPUTS[name]\n    for name in (\n        *TRAIN_POLICY_HEADS,\n        \"opponent_shanten_logits\",\n        \"riichi_action_logits\",\n        \"response_action_logits\",\n        \"chi_pattern_logits\",\n    )\n}\n\n\nKAN_ACTIONS = {riichienv.ActionType.ANKAN, riichienv.ActionType.KAKAN}\nWIN_ACTIONS = {riichienv.ActionType.RON, riichienv.ActionType.TSUMO}\n\n\ndef phase_for_actions(legal_actions):\n    kinds = {action.action_type for action in legal_actions}\n    if kinds & WIN_ACTIONS:\n        return \"WIN\"\n    if kinds & KAN_ACTIONS:\n        return \"KAN\"\n    if riichienv.ActionType.RIICHI in kinds:\n        return \"RIICHI\"\n    if riichienv.ActionType.DISCARD in kinds:\n        return \"DISCARD\"\n    return \"RESPONSE\"\n\n\ndef forced_policy_action(state, actor, legal_actions):\n    # Kyuushu remains automatic; optional wins belong to the policy.\n    for action in legal_actions:\n        if action.action_type == riichienv.ActionType.KYUSHU_KYUHAI:\n            return action\n    if len(legal_actions) == 1:\n        return legal_actions[0]\n    selected = features.single_legal_action(\n        legal_actions, state.legal_observation(actor).drawn_tile\n    )\n    if (\n        selected is not None\n        and selected.action_type == riichienv.ActionType.DISCARD\n    ):\n        return select_discard(\n            legal_actions,\n            features.native_tile_code(selected.tile),\n            state.legal_observation(actor).drawn_tile,\n        )\n    return selected\n\n\ndef policy_request(state, actor, observation):\n    legal = observation.legal_actions()\n    phase = phase_for_actions(legal)\n    packed = features.pack(state=state, actor=actor, phase=phase)\n    return phase, {\n        \"features\": packed,\n        \"actor\": actor,\n        \"legal_actions\": legal,\n        \"drawn_tile\": observation.drawn_tile,\n        \"phase\": phase,\n    }\n\n\ndef continue_request(request):\n    declined = WIN_ACTIONS if request[\"phase\"] == \"WIN\" else KAN_ACTIONS\n    legal = [\n        action\n        for action in request[\"legal_actions\"]\n        if action.action_type not in declined\n    ]\n    phase = phase_for_actions(legal)\n    return {\n        **request,\n        \"legal_actions\": legal,\n        \"phase\": phase,\n        \"features\": {\n            **request[\"features\"],\n            \"decision_phase\": numpy.array(features.PHASES[phase], numpy.int8),\n            \"win_kind\": numpy.array(0, numpy.int8),\n        },\n    }\n\n\ndef select_discard(legal_actions, discard_action, drawn_tile):\n    candidates = [\n        action\n        for action in legal_actions\n        if action.action_type == riichienv.ActionType.DISCARD\n        and features.native_tile_code(action.tile) == discard_action\n    ]\n    # Balance drawn/held origins when both are legal for this tile class.\n    origins = [\n        copies\n        for drawn in (False, True)\n        if (\n            copies := [\n                action\n                for action in candidates\n                if (action.tile == drawn_tile) == drawn\n            ]\n        )\n    ]\n    copies = origins[numpy.random.randint(len(origins))]\n    return copies[numpy.random.randint(len(copies))]\n\n\ndef policy_candidates(request):\n    if request[\"phase\"] == \"WIN\":\n        return (\n            [(\"win_decision_logits\", 0, None, {})]\n            if any(\n                action.action_type not in WIN_ACTIONS\n                for action in request[\"legal_actions\"]\n            )\n            else []\n        ) + [\n            (\n                \"win_decision_logits\",\n                1,\n                next(\n                    action\n                    for action in request[\"legal_actions\"]\n                    if action.action_type in WIN_ACTIONS\n                ),\n                {},\n            ),\n        ]\n    if request[\"phase\"] == \"DISCARD\":\n        return [\n            (\n                \"discard_policy_logits\",\n                code,\n                select_discard(\n                    request[\"legal_actions\"], code, request[\"drawn_tile\"]\n                ),\n                {},\n            )\n            for code in numpy.flatnonzero(\n                request[\"features\"][\"discard_action_legal\"]\n            )\n        ]\n    result = []\n    if request[\"phase\"] == \"RIICHI\":\n        for code in numpy.flatnonzero(\n            request[\"features\"][\"discard_action_legal\"]\n        ):\n            action = select_discard(\n                request[\"legal_actions\"], code, request[\"drawn_tile\"]\n            )\n            result.append(\n                (\n                    \"riichi_policy_logits\",\n                    int(code),\n                    action,\n                    {\"discard_action\": int(code)},\n                )\n            )\n            if request[\"features\"][\"riichi_discard_legal_mask\"][code]:\n                declaration = next(\n                    value\n                    for value in request[\"legal_actions\"]\n                    if value.action_type == riichienv.ActionType.RIICHI\n                )\n                result.append(\n                    (\n                        \"riichi_policy_logits\",\n                        37 + int(code),\n                        declaration,\n                        {\"discard_action\": int(code)},\n                    )\n                )\n    elif request[\"phase\"] == \"RESPONSE\":\n        for action in features.prefer_red_calls(request[\"legal_actions\"]):\n            if action.action_type == riichienv.ActionType.PASS:\n                result.append((\"response_policy_logits\", 0, action, {}))\n            elif action.action_type == riichienv.ActionType.DAIMINKAN:\n                result.append((\"response_policy_logits\", 149, action, {}))\n            elif action.action_type in (\n                riichienv.ActionType.CHI,\n                riichienv.ActionType.PON,\n            ):\n                option = (\n                    features.chii_pattern(action.tile, action.consume_tiles)\n                    if action.action_type == riichienv.ActionType.CHI\n                    else 3\n                )\n                for cut in numpy.flatnonzero(\n                    request[\"features\"][\"call_discard_legal\"][option]\n                ):\n                    result.append(\n                        (\n                            \"response_policy_logits\",\n                            1 + option * 37 + int(cut),\n                            action,\n                            {\n                                \"discard_action\": int(cut),\n                                \"continuation_discard\": int(cut),\n                            },\n                        )\n                    )\n    else:\n        result.append((\"kan_action_logits\", 0, None, {}))\n        for action in request[\"legal_actions\"]:\n            if action.action_type in KAN_ACTIONS:\n                result.append(\n                    (\"kan_action_logits\", 1 + action.tile // 4, action, {})\n                )\n    return list({(row[0], row[1]): row for row in result}.values())\n\n\ndef opening_temperature(state, actor):\n    return max(0.0, 1.5 - 0.5 * len(state.rivers[actor]))\n\n\ndef select_policy_action(request, outputs, batch_index, temperature=0.0):\n    candidates = policy_candidates(request)\n    if not candidates:\n        return None, {\"candidate_count\": 0, \"probability\": 1.0}\n    # A decision's candidates all use the head chosen by policy_candidates.\n    scores = numpy.asarray(outputs[candidates[0][0]])[\n        batch_index, [code for _, code, _, _ in candidates]\n    ]\n    weights = numpy.exp(scores - scores.max())\n    probability = weights / weights.sum()\n    if temperature > 0:\n        weights = numpy.exp((scores - scores.max()) / temperature)\n        selected = int(\n            numpy.random.choice(len(candidates), p=weights / weights.sum())\n        )\n        return candidates[selected][2], {\n            **candidates[selected][3],\n            \"candidate_count\": len(candidates),\n            \"probability\": float(probability[selected]),\n        }\n    # Select the immediate decision by its marginal mass before choosing\n    # its continuation. Otherwise several good discards split a call's vote.\n    groups = []\n    if request[\"phase\"] == \"RIICHI\":\n        groups = [numpy.array([code // 37 for _, code, _, _ in candidates])]\n    elif request[\"phase\"] == \"RESPONSE\":\n        groups = [\n            numpy.array(\n                [\n                    0 if code == 0 else (code - 1) // 37 + 1\n                    for _, code, _, _ in candidates\n                ]\n            ),\n        ]\n    eligible = numpy.ones(len(candidates), dtype=bool)\n    for group in groups:\n        totals = numpy.bincount(group, weights=probability * eligible)\n        branch = numpy.random.choice(numpy.flatnonzero(totals == totals.max()))\n        eligible &= group == branch\n    selected = int(\n        numpy.random.choice(\n            numpy.flatnonzero(\n                eligible & (probability == probability[eligible].max())\n            )\n        )\n    )\n    return candidates[selected][2], {\n        **candidates[selected][3],\n        \"candidate_count\": len(candidates),\n        \"probability\": float(probability[selected]),\n    }\n\n\ndef legal_choices(inputs):\n    import tensorflow as tf\n\n    discard = tf.cast(inputs[\"discard_action_legal\"], tf.bool)\n    declaration = tf.cast(inputs[\"riichi_discard_legal_mask\"], tf.bool)\n    return {\n        \"win_decision_logits\": tf.stack(\n            [\n                tf.ones_like(inputs[\"win_kind\"], dtype=tf.bool),\n                inputs[\"win_kind\"] > 0,\n            ],\n            axis=-1,\n        ),\n        \"discard_policy_logits\": discard,\n        \"riichi_policy_logits\": tf.concat([discard, discard & declaration], 1),\n        \"response_policy_logits\": tf.concat(\n            [\n                tf.cast(inputs[\"response_legal_mask\"][:, :1], tf.bool),\n                tf.reshape(\n                    tf.cast(inputs[\"call_discard_legal\"], tf.bool), (-1, 148)\n                ),\n                tf.cast(inputs[\"response_legal_mask\"][:, 3:], tf.bool),\n            ],\n            axis=1,\n        ),\n        \"kan_action_logits\": tf.cast(inputs[\"kan_legal_mask\"], tf.bool),\n    }\n\n\ndef guaranteed_safe_tiles(inputs):\n    \"\"\"Publicly proven ron safety, by opponent and base tile.\"\"\"\n    import tensorflow as tf\n\n    exhausted = inputs[\"known_unavailable_counts\"] == 4\n    # The offered honor itself cannot rule out a kokushi wait for that honor.\n    kokushi_blocked = (\n        tf.reduce_sum(\n            tf.cast(\n                tf.gather(\n                    exhausted,\n                    [0, 8, 9, 17, 18, 26, 27, 28, 29, 30, 31, 32, 33],\n                    axis=1,\n                ),\n                tf.int32,\n            ),\n            axis=1,\n        )\n        >= 2\n    )\n    return (inputs[\"genbutsu_to_seat\"][:, 1:] > 0) | (\n        exhausted[:, None, :]\n        & (tf.range(34)[None, None, :] >= 27)\n        & (\n            kokushi_blocked[:, None, None]\n            | tf.reduce_any(\n                inputs[\"meld_tiles\"][:, 1:, :, 0] < 37, axis=-1, keepdims=True\n            )\n        )\n    )\n\n\ndef candidate_hand_indices(inputs):\n    \"\"\"Local hand indices in the joint 295-action address space.\n\n    Call-window slots retain the original hand here; their accepted-call\n    representations are encoded from sparse child states separately.\n    \"\"\"\n    import tensorflow as tf\n\n    discard = inputs[\"discard_candidate_hand\"]\n    batch = tf.shape(discard)[0]\n    return tf.concat(\n        [\n            discard,\n            discard,\n            discard,\n            tf.zeros((batch, 149), discard.dtype),\n            tf.zeros((batch, 1), discard.dtype),\n            inputs[\"kan_candidate_hand\"],\n        ],\n        axis=1,\n    )\n\n\ndef discard_decisions(inputs, selected):\n    \"\"\"Actions ending in a discard, including chii/pon then discard.\"\"\"\n    import tensorflow as tf\n\n    phase = tf.gather(inputs[\"decision_phase\"], selected[:, 0])\n    return (\n        ((phase == 0) & (selected[:, 1] < 37))\n        | ((phase == 3) & (selected[:, 1] >= 37) & (selected[:, 1] < 111))\n        | ((phase == 1) & (selected[:, 1] >= 112) & (selected[:, 1] < 260))\n    )\n",
      "sha256": "a42fdb210b4231645cad6e17da45768e9d204891eb4e2cc85388bc746499a875"
    },
    {
      "path": "model/actor.py",
      "text": "\"\"\"Policy heads, legal masks and final candidate scoring.\"\"\"\n\nimport tensorflow as tf\n\nfrom log_dataset import call_states\nfrom model import actions, beliefs\n\n\n@tf.keras.utils.register_keras_serializable(package=\"nejimakidori\")\nclass PolicyMask(tf.keras.layers.Layer):\n    def __init__(self, head, **kwargs):\n        super().__init__(**kwargs)\n        self.head = head\n\n    def get_config(self):\n        return {**super().get_config(), \"head\": self.head}\n\n    def call(self, values):\n        logits, inputs = values\n        mask = actions.legal_choices(inputs)[self.head]\n        if self.head in (\"discard_policy_logits\", \"riichi_policy_logits\"):\n            branches = []\n            for start in range(\n                0, 74 if self.head == \"riichi_policy_logits\" else 37, 37\n            ):\n                branch = logits[:, start : start + 37]\n                legal = mask[:, start : start + 37]\n                branch = tf.where(\n                    (\n                        (inputs[\"opponent_discard_count\"][:, 0] == 0)\n                        & (inputs[\"dealer_relative_seat\"] == 0)\n                    )[:, None],\n                    opening_discard_symmetry(branch, inputs, legal),\n                    branch,\n                )\n                if start == 0:\n                    safe = final_wall_safe_cuts(inputs, legal)\n                    # Preserve the branch mass. Even a suppressed legal cut\n                    # must shift with the branch's additive logit offset.\n                    total = tf.reduce_logsumexp(\n                        tf.where(legal, branch, -1e4), axis=-1, keepdims=True\n                    )\n                    count = tf.reduce_sum(\n                        tf.cast(safe, tf.float32), axis=-1, keepdims=True\n                    )\n                    branch = tf.where(\n                        count > 0,\n                        total\n                        + tf.where(\n                            safe, -tf.math.log(tf.maximum(count, 1.0)), -1e4\n                        ),\n                        branch,\n                    )\n                branches.append(branch)\n            logits = tf.concat(branches, axis=-1)\n        return tf.where(\n            tf.reduce_any(mask, -1, keepdims=True),\n            tf.where(mask, logits, -1e4),\n            tf.zeros_like(logits),\n        )\n\n\n@tf.keras.utils.register_keras_serializable(package=\"nejimakidori\")\nclass PolicySummaries(tf.keras.layers.Layer):\n    def call(self, outputs):\n        riichi = tf.reshape(outputs[\"riichi_policy_logits\"], (-1, 2, 37))\n        response = outputs[\"response_policy_logits\"]\n        chii = tf.reshape(response[:, 1:112], (-1, 3, 37))\n        pon = tf.reshape(response[:, 112:149], (-1, 1, 37))\n        return {\n            \"riichi_action_logits\": tf.reduce_logsumexp(riichi, -1),\n            \"response_action_logits\": tf.stack(\n                [\n                    response[:, 0],\n                    tf.reduce_logsumexp(chii, (1, 2)),\n                    tf.reduce_logsumexp(pon, (1, 2)),\n                    response[:, 149],\n                ],\n                axis=-1,\n            ),\n            \"chi_pattern_logits\": tf.reduce_logsumexp(chii, -1),\n        }\n\n\n@tf.keras.utils.register_keras_serializable(package=\"nejimakidori\")\nclass CandidatePool(tf.keras.layers.Layer):\n    \"\"\"Attend to legal candidates using the private actor context.\"\"\"\n\n    def __init__(self, width=128, output_width=768, **kwargs):\n        kwargs.setdefault(\"dtype\", \"float32\")\n        super().__init__(**kwargs)\n        self.width = width\n        self.output_width = output_width\n        self.normalization = tf.keras.layers.LayerNormalization()\n        self.query_normalization = tf.keras.layers.LayerNormalization()\n        self.query = tf.keras.layers.Dense(width)\n        self.key = tf.keras.layers.Dense(width)\n        self.value = tf.keras.layers.Dense(width)\n        self.correction = tf.keras.layers.Dense(\n            output_width, kernel_initializer=\"zeros\", bias_initializer=\"zeros\"\n        )\n\n    def build(self, shape):\n        self.normalization.build(shape[0])\n        self.query_normalization.build(shape[2])\n        self.query.build(shape[2])\n        self.key.build(shape[0])\n        self.value.build(shape[0])\n        self.correction.build((None, self.width))\n        super().build(shape)\n\n    def get_config(self):\n        return {\n            **super().get_config(),\n            \"width\": self.width,\n            \"output_width\": self.output_width,\n        }\n\n    def call(self, values):\n        candidates, owners, context = values\n        batch_size = tf.shape(context)[0]\n        candidates = self.normalization(tf.stop_gradient(candidates))\n        logits = (\n            tf.reduce_sum(\n                self.key(candidates)\n                * tf.gather(\n                    self.query(self.query_normalization(context)), owners\n                ),\n                axis=-1,\n            )\n            / self.width**0.5\n        )\n        weights = tf.exp(\n            logits\n            - tf.gather(\n                tf.math.unsorted_segment_max(logits, owners, batch_size),\n                owners,\n            )\n        )\n        weights /= tf.gather(\n            tf.math.unsorted_segment_sum(weights, owners, batch_size), owners\n        )\n        pooled = tf.math.unsorted_segment_sum(\n            self.value(candidates) * weights[:, None], owners, batch_size\n        )\n        present = (\n            tf.math.unsorted_segment_sum(\n                tf.ones_like(owners), owners, batch_size\n            )[:, None]\n            > 0\n        )\n        return tf.where(present, self.correction(pooled), 0.0)\n\n\ndef build_policy_heads(inputs, context, candidates, selected, predictions):\n    \"\"\"Condition each local action on decision and candidate predictions.\"\"\"\n    outputs = {}\n    cut_evidence = [\n        tf.keras.ops.sigmoid(tf.keras.ops.stop_gradient(predictions[name]))\n        for name in (\"route_affinity_logits\", \"candidate_ron_logits\")\n    ]\n    final = FinalCandidates(dtype=\"float32\")(\n        [\n            tf.keras.layers.Concatenate(dtype=\"float32\")(\n                [candidates, *cut_evidence]\n            ),\n            context,\n            selected,\n        ]\n    )\n    final = tf.keras.layers.Dense(\n        512, activation=\"gelu\", dtype=\"float32\", name=\"final_pass\"\n    )(final)\n    final = tf.keras.layers.LayerNormalization(\n        center=False,\n        scale=False,\n        epsilon=1e-5,\n        dtype=\"float32\",\n        name=\"final_pass_normalized\",\n    )(final)\n    # Uncomputed actions are constant padding, not learned illegal logits.\n    # Only the legal candidate scores participate in policy training.\n    final = UnpackCandidates(dtype=\"float32\")(\n        [\n            tf.keras.layers.Dense(1, dtype=\"float32\", name=\"final_scores\")(\n                final\n            ),\n            selected,\n            context,\n        ]\n    )[:, :, 0]\n    for name, values in (\n        (\"discard_policy_logits\", final[:, :37]),\n        (\"riichi_policy_logits\", final[:, 37:111]),\n        (\"kan_action_logits\", final[:, 260:295]),\n    ):\n        outputs[name] = PolicyMask(name, name=name, dtype=\"float32\")(\n            [values, inputs]\n        )\n    return outputs\n\n\ndef build_board_heads(inputs, context):\n    win = tf.keras.layers.Dense(2, dtype=\"float32\", name=\"win_decision_logits\")(\n        context\n    )\n    win = PolicyMask(\n        \"win_decision_logits\", name=\"win_legality\", dtype=\"float32\"\n    )([win, inputs])\n    return {\n        \"win_decision_logits\": win,\n    }\n\n\ndef final_wall_safe_cuts(inputs, legal):\n    \"\"\"Return the forced uniform support, or an empty mask on free choices.\"\"\"\n    safe = legal & tf.gather(\n        tf.reduce_all(actions.guaranteed_safe_tiles(inputs), axis=1),\n        list(range(34)) + [4, 13, 22],\n        axis=1,\n    )\n    # Exact public river eligibility, including called discards, survives\n    # riichi safety expansion and the truncated opponent river encodings.\n    terminal_or_honor = tf.constant(\n        [i >= 27 or i % 9 in (0, 8) for i in range(34)] + [False] * 3\n    )\n    safe &= (inputs[\"nagashi_possible\"][:, :1] == 0) | terminal_or_honor[None]\n    return (\n        safe\n        & (inputs[\"live_wall_count\"] == 0)[:, None]\n        & ~tf.reduce_any(\n            legal & (inputs[\"discard_action_all_shanten\"] <= 1),\n            axis=-1,\n            keepdims=True,\n        )\n    )\n\n\ndef opening_discard_symmetry(logits, inputs, legal):\n    \"\"\"Pool equivalent legal cuts on the dealer’s first discard.\"\"\"\n    counts = inputs[\"candidate_hand_counts\"][:, 0]\n    suited = tf.reshape(counts[:, :27], (-1, 3, 9))\n    non_dora = ~tf.reduce_any(\n        tf.reshape(inputs[\"dora_multiplicity\"][:, :27] > 0, (-1, 3, 9)),\n        axis=-1,\n    )\n    terminals = tf.reshape(\n        tf.stack(\n            [\n                non_dora\n                & (suited[:, :, 0] == 1)\n                & tf.reduce_all(suited[:, :, 1:5] == 0, -1),\n                non_dora\n                & (suited[:, :, 8] == 1)\n                & tf.reduce_all(suited[:, :, 4:8] == 0, -1),\n            ],\n            axis=-1,\n        ),\n        (-1, 6),\n    )\n    floating = (\n        tf.linalg.matmul(\n            tf.cast(terminals, tf.float32),\n            tf.one_hot([0, 8, 9, 17, 18, 26], 37),\n        )\n        > 0\n    ) & legal\n    symmetric = (\n        non_dora\n        & (suited[:, :, 0] == 1)\n        & tf.reduce_all(suited == tf.reverse(suited, axis=[-1]), axis=-1)\n        & tf.reduce_all(suited[:, :, 1:3] == 0, axis=-1)\n        & ~tf.reduce_any(floating, axis=-1, keepdims=True)\n    )\n    winds = tf.constant([[0, 1, 2, 3]], dtype=tf.int8)\n    groups = (\n        tf.concat(\n            [\n                floating[:, None, :],\n                tf.pad(\n                    (counts[:, 31:34] == 1)\n                    & (inputs[\"dora_multiplicity\"][:, 31:34] == 0),\n                    [[0, 0], [31, 3]],\n                )[:, None, :],\n                tf.pad(\n                    (counts[:, 27:31] == 1)\n                    & (inputs[\"dora_multiplicity\"][:, 27:31] == 0)\n                    & (winds != inputs[\"seat_wind\"][:, 0, None])\n                    & (winds != inputs[\"seat_wind\"][:, 1, None])\n                    & (winds != inputs[\"prevailing_wind\"][:, None]),\n                    [[0, 0], [27, 6]],\n                )[:, None, :],\n                symmetric[:, :, None]\n                & tf.cast(\n                    tf.one_hot([0, 9, 18], 37) + tf.one_hot([8, 17, 26], 37),\n                    tf.bool,\n                )[None],\n            ],\n            axis=1,\n        )\n        & legal[:, None, :]\n    )\n    # Log-space arithmetic preserves tiny probabilities and group mass.\n    group_mean = tf.reduce_logsumexp(\n        tf.where(groups, logits[:, None, :], -1e9), axis=-1\n    ) - tf.math.log(\n        tf.maximum(1.0, tf.reduce_sum(tf.cast(groups, tf.float32), axis=-1))\n    )\n    pooled = tf.reduce_sum(\n        tf.where(groups, group_mean[:, :, None], 0.0), axis=1\n    )\n    return tf.where(tf.reduce_any(groups, axis=1), pooled, logits)\n\n\n@tf.keras.utils.register_keras_serializable(package=\"nejimakidori\")\nclass FinalCandidates(tf.keras.layers.Layer):\n    def call(self, values):\n        candidates, context, selected = values\n        return tf.concat(\n            [candidates, tf.gather(context, selected[:, 0])],\n            axis=-1,\n        )\n\n\ndef distribution(outputs, heads, legal):\n    \"\"\"Normalize over the exact native candidates used by the collector.\"\"\"\n    logits = tf.stack(\n        [\n            tf.pad(outputs[name], [[0, 0], [0, 150 - outputs[name].shape[-1]]])\n            for name in actions.TRAIN_POLICY_HEADS\n        ],\n        axis=1,\n    )\n    logits = tf.gather(logits, heads, batch_dims=1)\n    return tf.nn.log_softmax(tf.where(legal, logits, -1e9), axis=-1)\n\n\nclass CallPolicy(tf.keras.Model):\n    \"\"\"A call choice followed by the ordinary policy on accepted-call states.\"\"\"\n\n    def __init__(self, policy, hand_context, belief_layer):\n        super().__init__(autocast=False)\n        self.policy = policy\n        head_names = (\n            \"win_decision_logits\",\n            \"route_affinity_logits\",\n            \"route_constraint_loss\",\n            \"candidate_ron_logits\",\n            \"discard_policy_logits\",\n            \"riichi_policy_logits\",\n            \"kan_action_logits\",\n            \"constraint_loss\",\n        )\n        self.readout_inputs = (\n            \"candidate\",\n            \"selected\",\n            \"policy_context\",\n            \"opponent_wait_logits\",\n            \"ron_eligibility_logits\",\n            \"belief_constraint_loss\",\n            \"round_completion_yaku_logits_constraint_loss\",\n            \"round_completion_score_logits_constraint_loss\",\n        )\n        # Reapply the same head graph after pooling. The policy model owns\n        # its variables; this function introduces no second set of weights.\n        self.readout = tf.keras.Function(\n            [\n                policy.input,\n                {name: policy.output[name] for name in self.readout_inputs},\n            ],\n            {name: policy.output[name] for name in head_names},\n            name=\"candidate_readout\",\n        )\n        self.encode = tf.keras.Model(\n            policy.input,\n            {\n                name: value\n                for name, value in policy.output.items()\n                if name not in head_names\n            },\n            name=\"decision_encoding\",\n            autocast=False,\n        )\n        self.encode_called = tf.keras.Model(\n            policy.input,\n            {\n                name: policy.output[name]\n                for name in (\n                    \"board\",\n                    \"actor_board\",\n                    \"candidate\",\n                    \"selected\",\n                    \"structure\",\n                    \"critic_rivers\",\n                )\n            },\n            name=\"called_state_encoding\",\n            autocast=False,\n        )\n        self.condition_inputs = (\n            \"actor_board\",\n            *beliefs.BELIEF_HEADS,\n            *beliefs.COMPLETION_HEADS,\n            \"belief_constraint_loss\",\n            \"round_completion_yaku_logits_constraint_loss\",\n            \"round_completion_score_logits_constraint_loss\",\n        )\n        self.condition = tf.keras.Function(\n            {name: policy.output[name] for name in self.condition_inputs},\n            {\n                name: policy.output[name]\n                for name in (\n                    \"policy_context\",\n                    \"belief_context\",\n                    \"completion_context\",\n                )\n            },\n            name=\"belief_conditioning\",\n        )\n        self.beliefs = belief_layer\n        self.hand_context = hand_context\n        self.candidate_pool = CandidatePool(name=\"candidate_pool\")\n        self.call_choice = tf.keras.layers.Dense(\n            6,\n            kernel_initializer=\"zeros\",\n            bias_initializer=\"zeros\",\n            dtype=\"float32\",\n            name=\"call_choice\",\n        )\n        self.summaries = PolicySummaries(dtype=\"float32\")\n\n    def candidate_heads(self, features, outputs):\n        outputs.update(\n            self.readout(\n                [\n                    features,\n                    {name: outputs[name] for name in self.readout_inputs},\n                ]\n            )\n        )\n\n    def call(self, features, training=False):\n        current = call_states.base(features)\n        outputs = self.encode(current, training=training)\n        count = tf.shape(features[\"post_call_owner\"])[0]\n        capacity = tf.bitwise.left_shift(\n            1,\n            tf.cast(\n                tf.math.ceil(\n                    tf.math.log(tf.cast(tf.maximum(count, 1), tf.float32))\n                    / tf.math.log(2.0)\n                ),\n                tf.int32,\n            ),\n        )\n        # Bucket only device-side work; sparse transport remains unpadded.\n        # One unselected dummy keeps shared convolutions defined when C=0.\n        called_features = {\n            name: tf.gather(\n                tf.concat([value, current[name][:1]], axis=0),\n                tf.minimum(tf.range(capacity), count),\n            )\n            for name, value in call_states.post(features).items()\n        }\n        called = self.encode_called(called_features, training=training)\n        owners = tf.gather(\n            tf.concat([features[\"post_call_owner\"], [0]], axis=0),\n            tf.minimum(tf.range(capacity), count),\n        )\n        # Considering our own call adds no evidence about concealed opponents.\n        # Reuse the parent posterior; recompute completion potential on the\n        # changed board with that same posterior as detached evidence.\n        called.update(\n            self.beliefs(\n                inputs=called_features,\n                hidden=called[\"board\"],\n                rivers=called[\"critic_rivers\"],\n                opponents={\n                    name: tf.gather(outputs[name], owners)\n                    for name in (\n                        *beliefs.BELIEF_HEADS,\n                        \"belief_constraint_loss\",\n                    )\n                },\n            )\n        )\n        called.update(\n            {\n                name: tf.gather(outputs[name], owners)\n                for name in (\"opponent_wait_logits\", \"ron_eligibility_logits\")\n            }\n        )\n        called.update(\n            self.condition(\n                {name: called[name] for name in self.condition_inputs}\n            )\n        )\n        child_rows = tf.where(\n            (called[\"selected\"][:, 0] < count) & (called[\"selected\"][:, 1] < 37)\n        )[:, 0]\n        child_selected = tf.gather(called[\"selected\"], child_rows)\n        selected = tf.concat(\n            [\n                outputs[\"selected\"],\n                tf.stack(\n                    [\n                        tf.gather(\n                            features[\"post_call_owner\"], child_selected[:, 0]\n                        ),\n                        112\n                        + 37\n                        * tf.gather(\n                            features[\"post_call_option\"], child_selected[:, 0]\n                        )\n                        + child_selected[:, 1],\n                    ],\n                    axis=-1,\n                ),\n            ],\n            axis=0,\n        )\n        order = tf.argsort(selected[:, 0] * 295 + selected[:, 1], stable=True)\n        joint = tf.concat(\n            [outputs[\"candidate\"], tf.gather(called[\"candidate\"], child_rows)],\n            axis=0,\n        )\n        pooled = self.candidate_pool(\n            [joint, selected[:, 0], outputs[\"policy_context\"]]\n        )\n        outputs[\"policy_context\"] += pooled\n        called[\"policy_context\"] += tf.gather(pooled, owners)\n        self.candidate_heads(current, outputs)\n        self.candidate_heads(called_features, called)\n        conditional = tf.nn.log_softmax(\n            called[\"discard_policy_logits\"][:count], axis=-1\n        )\n        conditional = tf.tensor_scatter_nd_update(\n            tf.fill((tf.shape(outputs[\"board\"])[0], 4, 37), -1e4),\n            tf.stack(\n                [features[\"post_call_owner\"], features[\"post_call_option\"]],\n                axis=-1,\n            ),\n            conditional,\n        )\n        legal = actions.legal_choices(current)[\"response_policy_logits\"]\n        branch_legal = tf.stack(\n            [\n                tf.reduce_any(part, axis=-1)\n                for part in tf.split(legal, [1, 37, 37, 37, 37, 1], axis=-1)\n            ],\n            axis=-1,\n        )\n        choice = tf.nn.log_softmax(\n            tf.where(\n                branch_legal, self.call_choice(outputs[\"policy_context\"]), -1e9\n            ),\n            axis=-1,\n        )\n        response = tf.concat(\n            [\n                choice[:, :1],\n                tf.reshape(choice[:, 1:5, None] + conditional, (-1, 148)),\n                choice[:, 5:],\n            ],\n            axis=-1,\n        )\n        outputs[\"response_policy_logits\"] = tf.where(\n            tf.reduce_any(legal, axis=-1, keepdims=True),\n            tf.where(legal, response, -1e4),\n            tf.zeros_like(response),\n        )\n        # Shared neural and hand context follows the accepted-call state.\n        # Public event legality remains attached to the original call window.\n        for rows, local in ((current, outputs), (called_features, called)):\n            local[\"candidate_context\"] = tf.concat(\n                [\n                    tf.cast(local[\"candidate\"], tf.float32),\n                    tf.gather(local[\"belief_context\"], local[\"selected\"][:, 0]),\n                    tf.cast(\n                        tf.gather(local[\"board\"], local[\"selected\"][:, 0]),\n                        tf.float32,\n                    ),\n                    self.hand_context(\n                        [rows, local[\"selected\"], local[\"structure\"]]\n                    ),\n                ],\n                axis=-1,\n            )\n            local[\"candidate_completion\"] = tf.gather(\n                local[\"completion_context\"], local[\"selected\"][:, 0]\n            )\n        for name in (\n            \"candidate\",\n            \"structure\",\n            \"route_affinity_logits\",\n            \"candidate_ron_logits\",\n            \"candidate_context\",\n            \"candidate_completion\",\n        ):\n            outputs[name] = tf.gather(\n                tf.concat(\n                    [outputs[name], tf.gather(called[name], child_rows)], axis=0\n                ),\n                order,\n            )\n        outputs[\"selected\"] = tf.gather(selected, order)\n        outputs.update(self.summaries(outputs))\n        return outputs\n\n\ndef greedy_choices(log_probability, heads):\n    \"\"\"Marginal branch selection on device, with lowest-index tie breaks.\"\"\"\n    chosen = tf.argmax(log_probability, axis=1, output_type=tf.int32)\n    for head, sizes in (\n        (1, (37, 37)),\n        (2, (1, 37, 37, 37, 37, 1)),\n    ):\n        scores = log_probability[:, : sum(sizes)]\n        branch = tf.argmax(\n            tf.stack(\n                [\n                    tf.reduce_logsumexp(part, axis=1)\n                    for part in tf.split(scores, sizes, axis=1)\n                ],\n                axis=1,\n            ),\n            axis=1,\n            output_type=tf.int32,\n        )\n        scores = tf.where(\n            tf.repeat(tf.range(len(sizes)), sizes)[None] == branch[:, None],\n            scores,\n            -float(\"inf\"),\n        )\n        chosen = tf.where(\n            heads == head,\n            tf.argmax(scores, axis=1, output_type=tf.int32),\n            chosen,\n        )\n    return chosen\n\n\n@tf.keras.utils.register_keras_serializable(package=\"nejimakidori\")\nclass UnpackCandidates(tf.keras.layers.Layer):\n    def call(self, values):\n        packed, selected, board = values\n        return tf.scatter_nd(\n            selected,\n            packed,\n            (tf.shape(board)[0], 295, packed.shape[-1]),\n        )\n",
      "sha256": "66453b03a74b69decd5128d4240d8069645dd06cf46dfd0037718cf685bf0c36"
    },
    {
      "path": "model/beliefs.py",
      "text": "\"\"\"Opponent belief heads, constraints and supervision.\"\"\"\n\nimport math\n\nimport tensorflow as tf\n\nfrom model import actions, input_features, losses, payment_scoring\n\nTENPAI_UKEIRE_WEIGHT = 9.0\n\n\ndef held_count_context(inputs):\n    \"\"\"Known meld copies, unseen physical copies and concealed hand sizes.\"\"\"\n    tile = tf.cast(input_features.meld_tile_ids(inputs)[:, 1:], tf.int32)\n    red = tf.cast(input_features.meld_tile_red(inputs)[:, 1:], tf.bool)\n    code = tf.where(red, 34 + tile // 9, tile)\n    valid = tf.cast(input_features.meld_tile_valid(inputs)[:, 1:], tf.float32)\n    lower = tf.reduce_sum(tf.one_hot(code, 37) * valid[..., None], axis=(2, 3))\n    unseen = 4 - tf.cast(inputs[\"known_unavailable_counts\"], tf.float32)\n    unseen_red = (\n        1\n        - tf.cast(inputs[\"candidate_hand_red\"][:, 0], tf.float32)\n        - tf.cast(inputs[\"public_visible_red_counts\"], tf.float32)\n    )\n    correction = tf.linalg.matmul(unseen_red, tf.one_hot([4, 13, 22], 34))\n    available = tf.concat([unseen - correction, unseen_red], -1)\n    size = 13 - 3 * tf.reduce_sum(\n        tf.cast(\n            input_features.meld_tile_valid(inputs)[:, 1:, :, 0], tf.float32\n        ),\n        axis=-1,\n    )\n    return lower, available, size\n\n\n@tf.keras.utils.register_keras_serializable(package=\"nejimakidori\")\nclass HeldCountMask(tf.keras.layers.Layer):\n    def call(self, values):\n        logits, inputs = values\n        lower, available, _ = held_count_context(inputs)\n        upper = tf.minimum(4.0, lower + tf.maximum(0.0, available[:, None, :]))\n        classes = tf.cast(tf.range(5), tf.float32)\n        valid = (classes >= lower[..., None]) & (classes <= upper[..., None])\n        return tf.where(valid, logits, -1e4)\n\n\nclass StructuralWait(tf.keras.layers.Layer):\n    \"\"\"Joint tenpai-and-improving probability as stable tile-wise logits.\"\"\"\n\n    def call(self, outputs):\n        shanten_log = tf.nn.log_softmax(outputs[\"opponent_shanten_logits\"], -1)\n        improving = outputs[\"opponent_ukeire_by_shanten_logits\"][..., 0, :]\n        return (\n            shanten_log[..., 0, None]\n            - tf.nn.softplus(-improving)\n            - tf.reduce_logsumexp(\n                tf.stack(\n                    [\n                        shanten_log[..., 0, None] - tf.nn.softplus(improving),\n                        tf.broadcast_to(\n                            tf.reduce_logsumexp(shanten_log[..., 1:], -1)[\n                                ..., None\n                            ],\n                            tf.shape(improving),\n                        ),\n                    ],\n                    -1,\n                ),\n                -1,\n            )\n        )\n\n\nBELIEF_HEADS = (\n    \"opponent_shanten_logits\",\n    \"opponent_ukeire_by_shanten_logits\",\n    \"opponent_hand_count_logits\",\n)\n\n\nCOMPLETION_HEADS = (\n    \"round_completion_yaku_logits\",\n    \"round_completion_score_logits\",\n)\n\n\n# Immediate named prediction inputs in the forward graph. Each boundary\n# refers to the constrained value at that stage. Public features, learned\n# latents and raw logits internal to a belief's own refinement are outside\n# this contract. The joint response reads the accepted child's discard.\nBELIEF_INPUTS = {\n    \"opponent_wait_logits\": (\n        \"opponent_shanten_logits\",\n        \"opponent_ukeire_by_shanten_logits\",\n    ),\n    \"round_completion_yaku_logits\": (\"opponent_hand_count_logits\",),\n    \"round_completion_score_logits\": (\"round_completion_yaku_logits\",),\n    \"ron_eligibility_logits\": (\n        \"round_completion_yaku_logits\",\n        \"opponent_hand_count_logits\",\n    ),\n    \"candidate_ron_logits\": (\"opponent_wait_logits\", \"ron_eligibility_logits\"),\n    \"shanten_weighted_ukeire\": (\n        \"opponent_shanten_logits\",\n        \"opponent_ukeire_by_shanten_logits\",\n    ),\n    \"policy_context\": (\n        \"opponent_shanten_logits\",\n        \"shanten_weighted_ukeire\",\n        \"opponent_hand_count_logits\",\n        \"round_completion_yaku_logits\",\n        \"round_completion_score_logits\",\n    ),\n    \"discard_policy_logits\": (\n        \"policy_context\",\n        \"route_affinity_logits\",\n        \"candidate_ron_logits\",\n    ),\n    \"riichi_policy_logits\": (\n        \"policy_context\",\n        \"route_affinity_logits\",\n        \"candidate_ron_logits\",\n    ),\n    # The scorer is shared. On kan rows the ron input is fixed to zero by\n    # the discard-only mask, so its value cannot distinguish legal kans.\n    \"kan_action_logits\": (\n        \"policy_context\",\n        \"route_affinity_logits\",\n        \"candidate_ron_logits\",\n    ),\n    \"win_decision_logits\": (\"policy_context\",),\n    \"call_choice\": (\"policy_context\",),\n    \"response_policy_logits\": (\"call_choice\", \"discard_policy_logits\"),\n    \"critic_state\": (\n        \"opponent_shanten_logits\",\n        \"opponent_ukeire_by_shanten_logits\",\n        \"opponent_hand_count_logits\",\n        \"round_completion_yaku_logits\",\n        \"round_completion_score_logits\",\n        \"route_affinity_logits\",\n    ),\n}\n\n\nclass Probabilities(tf.keras.layers.Layer):\n    def call(self, logits):\n        return {\n            name: (\n                tf.sigmoid(logits[name])\n                if name in (BELIEF_HEADS[1], COMPLETION_HEADS[0])\n                else tf.nn.softmax(logits[name], axis=-1)\n            )\n            for name in BELIEF_HEADS + COMPLETION_HEADS\n        }\n\n\nclass TileAttention(tf.keras.layers.Layer):\n    \"\"\"Refine count and wait marginals jointly across all 34 tile types.\"\"\"\n\n    def __init__(self):\n        super().__init__(name=\"tile_attention\", dtype=\"float32\")\n        self.identity = tf.keras.layers.Embedding(34, 8, dtype=\"float32\")\n        self.context = tf.keras.layers.Dense(3 * 64, dtype=\"float32\")\n        # Keep variables and belief readouts in float32; attention activations\n        # use BF16 to reduce the training workspace without loss scaling.\n        self.tokens = tf.keras.layers.Dense(128, dtype=\"mixed_bfloat16\")\n        self.attention = [\n            tf.keras.layers.MultiHeadAttention(\n                num_heads=4, key_dim=32, dtype=\"mixed_bfloat16\"\n            )\n            for _ in range(2)\n        ]\n        self.attention_norm = [\n            tf.keras.layers.LayerNormalization(dtype=\"float32\")\n            for _ in range(2)\n        ]\n        self.feedforward_norm = [\n            tf.keras.layers.LayerNormalization(dtype=\"float32\")\n            for _ in range(2)\n        ]\n        self.feedforward = [\n            tf.keras.Sequential(\n                [\n                    tf.keras.layers.Dense(\n                        256, activation=\"gelu\", dtype=\"mixed_bfloat16\"\n                    ),\n                    tf.keras.layers.Dense(128, dtype=\"mixed_bfloat16\"),\n                ]\n            )\n            for _ in range(2)\n        ]\n        for layer in self.feedforward:\n            layer.dtype_policy = \"mixed_bfloat16\"\n        # Zero initialization preserves the base belief predictions.\n        self.correction = tf.keras.layers.Dense(\n            14,\n            kernel_initializer=\"zeros\",\n            bias_initializer=\"zeros\",\n            dtype=\"float32\",\n        )\n\n    def call(self, inputs, hidden, counts, waits, shanten):\n        lower, available, _ = held_count_context(inputs)\n        red_tiles = tf.one_hot([4, 13, 22], 34)\n        # Estimates used by the shared refinement are evidence. The residual\n        # paths below still train each base readout from its own labels.\n        count_probability = tf.nn.softmax(tf.stop_gradient(counts))\n        tile_features = tf.concat(\n            [\n                count_probability[:, :, :34],\n                tf.einsum(\n                    \"bsrc,rt->bstc\", count_probability[:, :, 34:], red_tiles\n                ),\n                tf.transpose(tf.sigmoid(tf.stop_gradient(waits)), [0, 1, 3, 2]),\n                lower[:, :, :34, None] / 4,\n                tf.einsum(\"bsr,rt->bst\", lower[:, :, 34:], red_tiles)[\n                    ..., None\n                ],\n                tf.broadcast_to(\n                    available[:, None, :34, None] / 4,\n                    tf.shape(lower[:, :, :34, None]),\n                ),\n                tf.broadcast_to(\n                    tf.einsum(\"br,rt->bt\", available[:, 34:], red_tiles)[\n                        :, None, :, None\n                    ],\n                    tf.shape(lower[:, :, :34, None]),\n                ),\n            ],\n            axis=-1,\n        )\n        values = self.tokens(\n            tf.concat(\n                [\n                    tile_features,\n                    tf.broadcast_to(\n                        self.identity(tf.range(34))[None, None],\n                        [tf.shape(counts)[0], 3, 34, 8],\n                    ),\n                    tf.broadcast_to(\n                        tf.reshape(self.context(hidden), [-1, 3, 1, 64]),\n                        [tf.shape(counts)[0], 3, 34, 64],\n                    ),\n                    tf.broadcast_to(\n                        tf.nn.softmax(tf.stop_gradient(shanten))[:, :, None],\n                        [tf.shape(counts)[0], 3, 34, 4],\n                    ),\n                ],\n                axis=-1,\n            )\n        )\n        values = tf.reshape(values, [-1, 34, 128])\n        for attention, attention_norm, feedforward, feedforward_norm in zip(\n            self.attention,\n            self.attention_norm,\n            self.feedforward,\n            self.feedforward_norm,\n        ):\n            normalized = attention_norm(values)\n            values = values + attention(normalized, normalized)\n            values = values + feedforward(feedforward_norm(values))\n        correction = tf.reshape(self.correction(values), [-1, 3, 34, 14])\n        return (\n            counts\n            + tf.concat(\n                [\n                    correction[..., :5],\n                    tf.gather(correction[..., 5:10], [4, 13, 22], axis=2),\n                ],\n                axis=2,\n            ),\n            waits + tf.transpose(correction[..., 10:], [0, 1, 3, 2]),\n        )\n\n\nclass OpponentShanten(tf.keras.layers.Layer):\n    \"\"\"One shared four-class readout conditioned on each opponent's evidence.\"\"\"\n\n    def __init__(self):\n        super().__init__(name=\"opponent_shanten\", dtype=\"float32\")\n        self.board = tf.keras.layers.Dense(48, use_bias=False, dtype=\"float32\")\n        self.observation = tf.keras.layers.Dense(48, dtype=\"float32\")\n        self.readout = tf.keras.layers.Dense(\n            4, kernel_initializer=\"zeros\", dtype=\"float32\"\n        )\n\n    def call(self, values):\n        hidden, inputs, rivers = values\n        observed = tf.concat(\n            [\n                tf.cast(rivers, tf.float32),\n                tf.one_hot(\n                    tf.reduce_sum(\n                        tf.cast(\n                            input_features.meld_tile_valid(inputs)[:, 1:, :, 0]\n                            > 0,\n                            tf.int32,\n                        ),\n                        -1,\n                    ),\n                    5,\n                ),\n                tf.cast(\n                    tf.range(1, 4)[None]\n                    == tf.cast(\n                        inputs[\"dealer_relative_seat\"][:, None], tf.int32\n                    ),\n                    tf.float32,\n                )[..., None],\n                tf.one_hot(tf.cast(inputs[\"riichi_state\"][:, 1:], tf.int32), 3),\n                tf.cast(\n                    inputs[\"opponent_discard_count\"][:, 1:, None], tf.float32\n                )\n                / 24,\n                tf.broadcast_to(\n                    tf.cast(\n                        inputs[\"live_wall_count\"][:, None, None], tf.float32\n                    )\n                    / 70,\n                    [tf.shape(hidden)[0], 3, 1],\n                ),\n                tf.one_hot(\n                    tf.cast(inputs[\"last_tedashi_tile_id\"][:, 1:], tf.int32), 37\n                ),\n                tf.cast(\n                    inputs[\"last_tedashi_tile_id\"][:, 1:, None] < 37, tf.float32\n                ),\n            ],\n            axis=-1,\n        )\n        return self.readout(\n            tf.nn.gelu(self.board(hidden)[:, None] + self.observation(observed))\n        )\n\n\nclass CompletionEvidence(tf.keras.layers.Layer):\n    \"\"\"Shared opponent yaku residual from observed and inferred tiles.\"\"\"\n\n    def __init__(self):\n        super().__init__(dtype=\"float32\", autocast=False)\n        self.hidden = tf.keras.layers.Dense(\n            64, activation=\"gelu\", dtype=\"float32\"\n        )\n        self.readout = tf.keras.layers.Dense(\n            math.prod(actions.ACTOR_OUTPUTS[COMPLETION_HEADS[0]][1:]),\n            kernel_initializer=\"zeros\",\n            dtype=\"float32\",\n        )\n\n    def evidence(self, inputs, counts):\n        # Physical code counts distinguish red fives from ordinary fives.\n        red = tf.cast(inputs[\"candidate_hand_red\"][:, 0], tf.float32)\n        own = tf.concat(\n            [\n                tf.cast(inputs[\"candidate_hand_counts\"][:, 0], tf.float32)\n                - tf.linalg.matmul(red, tf.one_hot([4, 13, 22], 34)),\n                red,\n            ],\n            -1,\n        )\n        _, available, _ = held_count_context(inputs)\n        expected = tf.reduce_sum(\n            tf.nn.softmax(tf.cast(counts, tf.float32), -1)\n            * tf.range(5, dtype=tf.float32),\n            -1,\n        )\n        physical = tf.concat([own[:, None], available[:, None], expected], 1)\n        base = tf.constant(list(range(34)) + [4, 13, 22])\n        suit = tf.one_hot(tf.minimum(base // 9, 3), 4)\n        summary = tf.concat(\n            [\n                tf.linalg.matmul(physical, suit) / 14.0,\n                tf.linalg.matmul(\n                    physical\n                    * tf.gather(\n                        tf.cast(inputs[\"dora_multiplicity\"], tf.float32),\n                        base,\n                        axis=-1,\n                    )[:, None],\n                    suit,\n                )\n                / 14.0,\n                physical[..., 34:],\n            ],\n            -1,\n        )\n        return tf.concat(\n            [\n                tf.broadcast_to(\n                    tf.reshape(summary[:, :2], [-1, 1, 22]),\n                    [tf.shape(counts)[0], 3, 22],\n                ),\n                summary[:, 2:],\n            ],\n            -1,\n        )\n\n    def call(self, inputs, counts, rivers):\n        hidden = self.hidden(\n            tf.concat(\n                [self.evidence(inputs, counts), tf.cast(rivers, tf.float32)],\n                -1,\n            )\n        )\n        return hidden, self.readout(hidden)\n\n\nclass Beliefs(tf.keras.Model):\n    \"\"\"Shared opponent and hand-completion beliefs from the board encoder.\"\"\"\n\n    def __init__(self):\n        super().__init__(name=\"beliefs\", autocast=False)\n        self.refinement = tf.keras.Sequential(\n            [\n                tf.keras.layers.LayerNormalization(dtype=\"float32\"),\n                tf.keras.layers.Dense(1152, activation=\"gelu\", dtype=\"float32\"),\n                tf.keras.layers.Dense(\n                    512, kernel_initializer=\"zeros\", dtype=\"float32\"\n                ),\n            ],\n            name=\"belief_refinement\",\n        )\n        self.refinement.dtype_policy = \"float32\"\n        self.heads = {\n            name: (\n                OpponentShanten()\n                if name == BELIEF_HEADS[0]\n                else tf.keras.layers.Dense(\n                    math.prod(actions.ACTOR_OUTPUTS[name]),\n                    dtype=\"float32\",\n                    name=name.removesuffix(\"_logits\") + \"_scores\",\n                )\n            )\n            for name in BELIEF_HEADS + COMPLETION_HEADS\n        }\n        self.tile_attention = TileAttention()\n        self.completion_evidence = CompletionEvidence()\n        self.completion_yaku_mask = payment_scoring.CompletionMask(\n            dtype=\"float32\"\n        )\n        self.completion_score_mask = payment_scoring.CompletionScoreMask(\n            dtype=\"float32\"\n        )\n        self.completion_coupling = payment_scoring.CompletionScoreCoupling(\n            dtype=\"float32\"\n        )\n        self.held_count_mask = HeldCountMask(dtype=\"float32\")\n        self.count_projection = CountProjection(dtype=\"float32\")\n\n    def call(self, inputs, hidden, rivers, opponents=None):\n        hidden = hidden + self.refinement(hidden)\n        if opponents is None:\n            outputs = {\n                name: tf.reshape(\n                    (\n                        self.heads[name]([hidden, inputs, rivers])\n                        if name == BELIEF_HEADS[0]\n                        else self.heads[name](hidden)\n                    ),\n                    [-1, *actions.ACTOR_OUTPUTS[name]],\n                )\n                for name in BELIEF_HEADS\n            }\n            outputs[BELIEF_HEADS[2]], outputs[BELIEF_HEADS[1]] = (\n                self.tile_attention(\n                    inputs=inputs,\n                    hidden=hidden,\n                    counts=outputs[BELIEF_HEADS[2]],\n                    waits=outputs[BELIEF_HEADS[1]],\n                    shanten=outputs[BELIEF_HEADS[0]],\n                )\n            )\n            raw_counts = outputs[BELIEF_HEADS[2]]\n            raw_shanten = outputs[BELIEF_HEADS[0]]\n            outputs[BELIEF_HEADS[0]] = tf.where(\n                (\n                    (inputs[\"riichi_state\"][:, 1:, None] > 0)\n                    | (\n                        tf.reduce_sum(\n                            tf.cast(\n                                input_features.meld_tile_valid(inputs)[\n                                    :, 1:, :, 0\n                                ]\n                                > 0,\n                                tf.int32,\n                            ),\n                            -1,\n                        )[..., None]\n                        == 4\n                    )\n                )\n                & (tf.range(4)[None, None] != 0),\n                -1e4,\n                raw_shanten,\n            )\n            outputs[BELIEF_HEADS[2]] = self.held_count_mask(\n                [outputs[BELIEF_HEADS[2]], inputs]\n            )\n            outputs[BELIEF_HEADS[2]] = self.count_projection(\n                [outputs[BELIEF_HEADS[2]], inputs]\n            )\n            outputs[\"belief_constraint_loss\"] = tf.reduce_mean(\n                losses.constraint_divergence(\n                    raw_counts, outputs[BELIEF_HEADS[2]]\n                ),\n                axis=(1, 2),\n            ) + tf.reduce_mean(\n                losses.constraint_divergence(\n                    raw_shanten, outputs[BELIEF_HEADS[0]]\n                ),\n                axis=1,\n            )\n        else:\n            outputs = dict(opponents)\n        outputs.update(\n            {\n                name: tf.reshape(\n                    self.heads[name](hidden), [-1, *actions.ACTOR_OUTPUTS[name]]\n                )\n                for name in COMPLETION_HEADS\n            }\n        )\n        for name in COMPLETION_HEADS:\n            raw = outputs[name]\n            if name == COMPLETION_HEADS[0]:\n                outputs[\"opponent_yaku_hidden\"], residual = (\n                    self.completion_evidence(\n                        inputs,\n                        tf.stop_gradient(outputs[BELIEF_HEADS[2]]),\n                        rivers,\n                    )\n                )\n                raw = tf.concat(\n                    [\n                        raw[:, :1],\n                        raw[:, 1:]\n                        + tf.reshape(\n                            residual,\n                            [-1, 3, *actions.ACTOR_OUTPUTS[name][1:]],\n                        ),\n                    ],\n                    axis=1,\n                )\n                values = self.completion_yaku_mask([raw, inputs])\n            else:\n                values = self.completion_coupling(\n                    [\n                        self.completion_score_mask([raw, inputs]),\n                        tf.stop_gradient(outputs[COMPLETION_HEADS[0]][:, :1]),\n                        inputs,\n                    ]\n                )\n            outputs[name] = values\n            outputs[name + \"_constraint_loss\"] = tf.reduce_mean(\n                losses.constraint_divergence(\n                    raw, values, binary=name == COMPLETION_HEADS[0]\n                ),\n                axis=(1, 2),\n            )\n        return outputs\n\n\ndef count_weights(features):\n    \"\"\"Shared strategic weights for count supervision and projection.\"\"\"\n    base = tf.constant(list(range(34)) + [4, 13, 22])\n    winds = tf.cast(features[\"seat_wind\"][:, 1:], tf.int32) + 27\n    prevailing = tf.cast(features[\"prevailing_wind\"], tf.int32) + 27\n    yakuhai = (\n        (base[None, None] >= 31)\n        | (base[None, None] == winds[..., None])\n        | (base[None, None] == prevailing[:, None, None])\n    )\n    return (\n        1\n        + 9\n        * tf.gather(\n            tf.cast(features[\"dora_multiplicity\"], tf.float32), base, axis=-1\n        )[:, None]\n        + 9 * tf.cast(tf.range(37) >= 34, tf.float32)\n        + 4 * tf.cast(yakuhai, tf.float32)\n    )\n\n\n@tf.keras.utils.register_keras_serializable(package=\"nejimakidori\")\nclass CountProjection(tf.keras.layers.Layer):\n    \"\"\"Weighted minimum-KL marginal projection using public constraints.\n\n    Input logits must already have HeldCountMask applied. This enforces\n    expected concealed sizes and shared physical copy limits, not a joint\n    distribution over legal hands. No hidden labels enter the projection.\n    \"\"\"\n\n    def call(self, values):\n        logits, features = values\n        lower, available, size = held_count_context(features)\n        classes = tf.range(5, dtype=tf.float32) - lower[..., None]\n        weights = count_weights(features)\n\n        def solve(logits):\n            def moments(alpha, beta):\n                probability = tf.nn.softmax(\n                    logits\n                    + classes\n                    * (alpha[..., None, None] + beta[:, None, :, None])\n                    / weights[..., None],\n                    -1,\n                )\n                mean = tf.reduce_sum(probability * classes, -1)\n                curvature = (\n                    tf.reduce_sum(\n                        probability * tf.square(classes - mean[..., None]), -1\n                    )\n                    / weights\n                )\n                return mean, curvature\n\n            def dual_step(residual, curvature):\n                # Counts span at most four and every KL weight is at least one.\n                # Thus |d log(curvature) / d dual| <= 4. Integrating this\n                # bound gives a Newton step that cannot overshoot its root.\n                newton = residual / tf.maximum(curvature, 1e-7)\n                return tf.sign(newton) * tf.math.log1p(4 * tf.abs(newton)) / 4\n\n            @tf.function(jit_compile=True)\n            def step(iteration, alpha, beta, error):\n                mean, curvature = moments(alpha, beta)\n                alpha += dual_step(\n                    size - tf.reduce_sum(mean, -1),\n                    tf.reduce_sum(curvature, -1),\n                )\n                mean, curvature = moments(alpha, beta)\n                beta = tf.minimum(\n                    0.0,\n                    beta\n                    + dual_step(\n                        available - tf.reduce_sum(mean, 1),\n                        tf.reduce_sum(curvature, 1),\n                    ),\n                )\n                mean, _ = moments(alpha, beta)\n                error = tf.maximum(\n                    tf.reduce_max(tf.abs(tf.reduce_sum(mean, -1) - size)),\n                    tf.reduce_max(\n                        tf.abs(\n                            tf.where(\n                                beta < 0,\n                                tf.reduce_sum(mean, 1) - available,\n                                tf.nn.relu(tf.reduce_sum(mean, 1) - available),\n                            )\n                        )\n                    ),\n                )\n                return iteration + 1, alpha, beta, error\n\n            _, alpha, beta, error = tf.while_loop(\n                lambda iteration, alpha, beta, error: (iteration < 2048)\n                & (error > 1e-5),\n                step,\n                (\n                    0,\n                    tf.zeros_like(size),\n                    tf.zeros_like(available),\n                    float(\"inf\"),\n                ),\n            )\n            return (\n                (\n                    logits\n                    + classes\n                    * (alpha[..., None, None] + beta[:, None, :, None])\n                    / weights[..., None]\n                ),\n                error,\n                beta,\n            )\n\n        @tf.custom_gradient\n        def projected(logits):\n            result, error, beta = tf.function(solve, jit_compile=True)(\n                tf.stop_gradient(logits)\n            )\n\n            @tf.function(jit_compile=True)\n            def gradient(upstream, error_gradient):\n                probability = tf.cast(tf.nn.softmax(result), tf.float64)\n                counts = tf.cast(classes, tf.float64)\n                weight = tf.cast(weights, tf.float64)\n                mean = tf.reduce_sum(probability * counts, -1)\n                curvature = (\n                    tf.reduce_sum(\n                        probability * tf.square(counts - mean[..., None]), -1\n                    )\n                    / weight\n                )\n                active = tf.cast(beta < 0, tf.float64)\n                cross = curvature * active[:, None]\n                column_curvature = tf.reduce_sum(cross, 1)\n                right = (\n                    tf.reduce_sum(tf.cast(upstream, tf.float64) * counts, -1)\n                    / weight\n                )\n                right_column = tf.reduce_sum(right, 1) * active\n                scaled = tf.math.divide_no_nan(cross, column_curvature[:, None])\n                # Eliminate tile multipliers; only a 3x3 hand system remains.\n                # Float64 protects cancellation in the Schur complement.\n                schur = tf.linalg.diag(tf.reduce_sum(curvature, -1)) - (\n                    scaled @ tf.transpose(cross, [0, 2, 1])\n                )\n                right_row = tf.reduce_sum(right, -1) - tf.reduce_sum(\n                    scaled * right_column[:, None], -1\n                )\n                eigenvalues, eigenvectors = tf.linalg.eigh(schur)\n                # Redundant physical constraints leave zero eigenvalues.\n                # Their pseudoinverse leaves projected probabilities unique.\n                inverse = tf.where(\n                    eigenvalues\n                    > tf.reduce_max(eigenvalues, -1, keepdims=True) * 1e-10,\n                    tf.math.divide_no_nan(\n                        tf.ones_like(eigenvalues), eigenvalues\n                    ),\n                    0.0,\n                )\n                row = tf.linalg.matvec(\n                    eigenvectors,\n                    inverse\n                    * tf.linalg.matvec(\n                        eigenvectors, right_row, transpose_a=True\n                    ),\n                )\n                column = tf.math.divide_no_nan(\n                    right_column - tf.reduce_sum(cross * row[..., None], 1),\n                    column_curvature,\n                )\n                return upstream - tf.cast(\n                    probability\n                    * (counts - mean[..., None])\n                    * (row[..., None, None] + column[:, None, :, None]),\n                    upstream.dtype,\n                )\n\n            return (result, error), gradient\n\n        result, error = projected(logits)\n        tf.debugging.assert_less_equal(\n            error, 1e-4, message=\"Count projection failed to converge\"\n        )\n        return result\n\n\ndef belief_loss_terms(features, labels, outputs, mean=losses.mean_valid):\n    \"\"\"Opponent supervision for joint training.\"\"\"\n    terms = {\n        \"opponent_shanten_loss\": losses.classification(\n            labels[\"opponent_shanten\"], outputs[BELIEF_HEADS[0]], mean=mean\n        ),\n    }\n    terms[\"opponent_ukeire_loss\"] = ukeire_loss(labels, outputs, mean=mean)\n    terms[\"opponent_hand_count_loss\"] = losses.classification(\n        labels[\"opponent_hand_counts\"],\n        outputs[BELIEF_HEADS[2]],\n        count_weights(features),\n        mean=mean,\n    )\n    return terms\n\n\ndef ukeire_loss(labels, outputs, mean=losses.mean_valid):\n    target = tf.cast(labels[\"opponent_ukeire\"], tf.float32)\n    distance = tf.cast(labels[\"opponent_shanten\"], tf.int32)\n    logits = tf.gather(\n        outputs[\"opponent_ukeire_by_shanten_logits\"],\n        tf.maximum(distance, 0),\n        axis=2,\n        batch_dims=2,\n    )\n    valid = (target >= 0) & (distance[..., None] >= 0)\n    tenpai = valid & (distance[..., None] == 0)\n    other = valid & (distance[..., None] > 0)\n    losses = tf.nn.sigmoid_cross_entropy_with_logits(\n        labels=tf.maximum(target, 0), logits=logits\n    )\n    tenpai_loss = mean(losses, tenpai)\n    other_loss = mean(losses, other)\n    return tf.math.divide_no_nan(\n        TENPAI_UKEIRE_WEIGHT * tenpai_loss + other_loss,\n        TENPAI_UKEIRE_WEIGHT * mean(tf.ones_like(target), tenpai)\n        + mean(tf.ones_like(target), other),\n    )\n\n\ndef completion_loss_terms(labels, outputs, mean=losses.mean_valid):\n    \"\"\"Masked supervised yaku and score completion likelihoods.\"\"\"\n    metrics = {}\n    metrics[\"completion_yaku_loss\"] = mean(\n        tf.nn.sigmoid_cross_entropy_with_logits(\n            labels=tf.maximum(\n                tf.cast(labels[\"round_completion_yaku\"], tf.float32), 0\n            ),\n            logits=outputs[\"round_completion_yaku_logits\"],\n        ),\n        labels[\"round_completion_yaku\"] >= 0,\n    )\n    metrics[\"completion_score_loss\"] = mean(\n        tf.nn.sparse_softmax_cross_entropy_with_logits(\n            labels=tf.maximum(\n                tf.cast(labels[\"round_completion_score\"][:, :1], tf.int32), 0\n            ),\n            logits=outputs[\"round_completion_score_logits\"],\n        ),\n        labels[\"round_completion_score\"][:, :1] >= 0,\n    )\n    return metrics\n",
      "sha256": "fd4344e550935dc25fc63994d1cb0a7d9b54ce24635518fde73f3ccf32c5de4e"
    },
    {
      "path": "model/candidate_predictions.py",
      "text": "\"\"\"Candidate route support and opponent ron liability predictions.\"\"\"\n\nimport tensorflow as tf\n\nfrom model import actions, input_features, losses, payment_scoring\n\n\ndef predict(*, inputs, candidates, selected, wait_logits, eligibility_logits):\n    \"\"\"Predict candidate targets once for each selected local action.\"\"\"\n    raw_route = tf.keras.layers.Dense(\n        3, dtype=\"float32\", name=\"route_affinity\"\n    )(candidates)\n    route = RouteMask(dtype=\"float32\")([raw_route, inputs, selected])\n    return {\n        \"route_affinity_logits\": route,\n        \"route_constraint_loss\": losses.ConstraintLoss(\n            binary=True, dtype=\"float32\"\n        )([raw_route, route, selected[:, 0]]),\n        \"candidate_ron_logits\": RonRisk(dtype=\"float32\")(\n            [eligibility_logits, wait_logits, inputs, selected]\n        ),\n    }\n\n\nclass RonRisk(tf.keras.layers.Layer):\n    \"\"\"Ron requires a structural wait on the discarded tile and eligibility.\"\"\"\n\n    def call(self, values):\n        eligibility, wait, inputs, selected = values\n        # Local discard, dama and declaration each index the same 37 cuts.\n        # Accepted-call children reach this head as local discard decisions.\n        tile = tf.gather(list(range(34)) + [4, 13, 22], selected[:, 1] % 37)\n        index = tf.stack([selected[:, 0], tile], axis=-1)\n        eligibility = tf.gather_nd(tf.transpose(eligibility, [0, 2, 1]), index)\n        wait = tf.gather_nd(\n            tf.transpose(tf.stop_gradient(wait), [0, 2, 1]), index\n        )\n        safe = tf.gather_nd(\n            tf.transpose(actions.guaranteed_safe_tiles(inputs), [0, 2, 1]),\n            index,\n        )\n        # logit(sigmoid(w) * sigmoid(e)) without a probability-space log.\n        logits = -tf.reduce_logsumexp(\n            tf.stack([-wait, -eligibility, -wait - eligibility]), axis=0\n        )\n        return tf.where(\n            actions.discard_decisions(inputs, selected)[:, None] & ~safe,\n            logits,\n            -1e4,\n        )\n\n\nclass RouteMask(tf.keras.layers.Layer):\n    def call(self, values):\n        logits, inputs, selected = values\n        hands = tf.stack(\n            [\n                selected[:, 0],\n                tf.cast(\n                    tf.gather_nd(\n                        actions.candidate_hand_indices(inputs),\n                        selected,\n                    ),\n                    tf.int32,\n                ),\n            ],\n            axis=1,\n        )\n        allowed = payment_scoring.support(\n            tf.gather_nd(\n                tf.cast(input_features.candidate_melds(inputs), tf.float32),\n                hands,\n            )\n        )\n        # Outside routes include sequence-free honroutou/chinroutou.\n        return tf.where(\n            tf.stack(\n                [\n                    allowed[..., 1],\n                    allowed[..., 18],\n                    allowed[..., 10] | allowed[..., 11],\n                ],\n                axis=-1,\n            ),\n            logits,\n            -1e9,\n        )\n\n\ndef ron_risk_labels(labels, selected, structure):\n    \"\"\"Legal discard ron, including unknown amounts but excluding triple ron.\"\"\"\n    legal = tf.gather_nd(\n        tf.transpose(labels[\"ron_legal\"], [0, 2, 1]),\n        tf.stack(\n            [\n                selected[:, 0],\n                tf.minimum(tf.cast(structure[:, -1], tf.int32), 36),\n            ],\n            axis=1,\n        ),\n    )\n    risk = legal == 1\n    return risk & ~tf.reduce_all(risk, axis=1)[:, None], legal >= 0\n\n\ndef loss_terms(features, labels, outputs, mean=losses.mean_valid):\n    selected = outputs[\"selected\"]\n    hand_indices = actions.candidate_hand_indices(features)\n    affinity = tf.cast(\n        tf.gather_nd(\n            labels[\"candidate_yaku_affinity\"],\n            tf.stack(\n                [\n                    selected[:, 0],\n                    tf.cast(tf.gather_nd(hand_indices, selected), tf.int32),\n                ],\n                axis=1,\n            ),\n        ),\n        tf.float32,\n    )\n    # Parent records have local-hand route labels only. Accepted-call child\n    # hands are not represented in that bank and must not inherit hand zero.\n    affinity = tf.where(\n        ((selected[:, 1] >= 112) & (selected[:, 1] < 260))[:, None],\n        -1.0,\n        affinity,\n    )\n    terms = {\n        \"route_affinity_loss\": losses.candidate_mean(\n            tf.nn.sigmoid_cross_entropy_with_logits(\n                labels=tf.maximum(affinity, 0.0),\n                logits=outputs[\"route_affinity_logits\"],\n            ),\n            affinity >= 0,\n            selected[:, 0],\n            mean=mean,\n        ),\n    }\n    risk, known = ron_risk_labels(labels, selected, outputs[\"structure\"])\n    terms[\"candidate_ron_loss\"] = losses.candidate_mean(\n        tf.nn.sigmoid_cross_entropy_with_logits(\n            labels=tf.cast(risk, tf.float32),\n            logits=outputs[\"candidate_ron_logits\"],\n        ),\n        known & actions.discard_decisions(features, selected)[:, None],\n        selected[:, 0],\n        mean=mean,\n    )\n    return terms\n",
      "sha256": "46913eef4d8bc4827f7ad40d783c269665e313af44f27428ec7a36609a0d5520"
    },
    {
      "path": "model/critic.py",
      "text": "\"\"\"Action-conditioned settlements and policy values.\"\"\"\n\nimport math\n\nimport numpy\nimport tensorflow as tf\n\nfrom log_dataset import scoring\nfrom model import (\n    actions,\n    beliefs,\n    encoder,\n    input_features,\n    joint_settlement,\n    losses,\n    outcomes,\n    payment_scoring,\n)\n\nSTATISTICS_CHUNK = 128\n# Frozen 2,048-row reference calibration: 5.3469339609 / 0.5389408991.\n# Units are nats per squared J, never raw mahjong points squared.\nQ_MSE_TO_NLL = 9.921187963468466\nEVENT_READOUTS = numpy.array(\n    [\n        [\n            float(\n                bool(event[2] & readout[2])\n                if event[0] == readout[0] == 4\n                else event == readout\n            )\n            for readout in joint_settlement.READOUT_EVENTS\n        ]\n        for event in joint_settlement.EVENTS\n    ],\n    numpy.float32,\n)\nBELIEF_SHAPES = tuple(\n    actions.ACTOR_OUTPUTS[name] for name in beliefs.BELIEF_HEADS\n)\nBELIEF_WIDTH = sum(math.prod(shape) for shape in BELIEF_SHAPES)\nROUTE_WIDTH = 3\nPREDICTED_TAIL_WIDTH = ROUTE_WIDTH + sum(\n    math.prod(actions.ACTOR_OUTPUTS[name]) for name in beliefs.COMPLETION_HEADS\n)\n\n\ndef meld_tile_counts(melds):\n    \"\"\"Expand chi starts, triplets and kans to their physical tile counts.\"\"\"\n    chi = melds[..., 0]\n    return (\n        chi\n        + tf.roll(chi, 1, axis=-1)\n        + tf.roll(chi, 2, axis=-1)\n        + 3 * melds[..., 1]\n        + 4 * tf.reduce_sum(melds[..., 2:5], axis=-1)\n    )\n\n\ndef public_inputs(features, selected=None):\n    \"\"\"Guaranteed scoring constraints given an attempted action.\n\n    Scores and the existing pot remain pre-action: settlement deposits account\n    for a declaration only after its discard survives ron.\n    \"\"\"\n    opened = tf.reduce_any(\n        (input_features.meld_tile_valid(features)[..., 0] > 0)\n        & (features[\"meld_type\"] != 4),\n        axis=-1,\n    )\n    public = {\n        \"opened\": opened,\n        \"nagashi_allowed\": tf.cast(features[\"nagashi_possible\"], tf.bool),\n        \"pao_payer\": tf.cast(features[\"pao_payer\"], tf.int32),\n        \"pao_trigger\": tf.zeros_like(features[\"pao_payer\"], tf.bool),\n        \"deposit_allowed\": ~opened\n        & (features[\"riichi_state\"] != 2)\n        & (\n            tf.gather(\n                features[\"scores\"],\n                tf.cast(features[\"seat_wind\"], tf.int32),\n                batch_dims=1,\n            )\n            >= 1000\n        ),\n        \"deposit_required\": features[\"riichi_state\"] == 1,\n        \"riichi_required\": features[\"riichi_state\"] > 0,\n        \"tenpai_required\": (features[\"riichi_state\"] > 0)\n        | (\n            tf.reduce_sum(\n                tf.cast(\n                    input_features.meld_tile_valid(features)[..., 0] > 0,\n                    tf.int32,\n                ),\n                -1,\n            )\n            == 4\n        ),\n        \"action_tile\": tf.fill(tf.shape(features[\"dealer_relative_seat\"]), 37),\n        \"ending_draw_kind\": tf.zeros_like(features[\"dealer_relative_seat\"]),\n        \"ending_tenpai\": tf.fill(tf.shape(features[\"riichi_state\"]), -1),\n        \"ending_safe\": tf.zeros_like(features[\"riichi_state\"][:, 1:], tf.bool),\n        \"dealer\": features[\"dealer_relative_seat\"],\n        \"public_fu\": payment_scoring.fixed_meld_fu(features),\n        \"public_bonus\": tf.cast(features[\"public_bonus\"], tf.int32),\n        \"yakuman_allowed\": payment_scoring.support(\n            payment_scoring.public_melds(features)\n        )[..., -1],\n    }\n    if selected is None:\n        return public\n    public = {\n        name: tf.gather(value, selected[:, 0]) for name, value in public.items()\n    }\n    response = tf.gather(features[\"decision_phase\"], selected[:, 0]) == 1\n    hands = tf.stack(\n        [\n            selected[:, 0],\n            tf.cast(\n                tf.gather_nd(\n                    actions.candidate_hand_indices(features), selected\n                ),\n                tf.int32,\n            ),\n        ],\n        axis=1,\n    )\n    # Float32 keeps both gathers and slices on device; these small integer\n    # counts are exact. TensorFlow's int32 StridedSlice uses host memory.\n    melds = tf.gather_nd(\n        tf.cast(input_features.candidate_melds(features), tf.float32), hands\n    )\n    own_opened = tf.reduce_any(\n        tf.gather(melds, [0, 1, 2, 4], axis=2) > 0, axis=(1, 2)\n    )\n    declaration = (selected[:, 1] >= 74) & (selected[:, 1] < 111)\n    own = tf.stack(\n        [\n            tf.range(tf.shape(selected)[0]),\n            tf.zeros(tf.shape(selected)[0], tf.int32),\n        ],\n        axis=1,\n    )\n    public[\"opened\"] = tf.tensor_scatter_nd_update(\n        public[\"opened\"],\n        own,\n        tf.where(response, public[\"opened\"][:, 0], own_opened),\n    )\n    candidate_bonus = tf.reduce_sum(\n        meld_tile_counts(melds)\n        * tf.gather(\n            tf.cast(features[\"dora_multiplicity\"], tf.float32), selected[:, 0]\n        )\n        + melds[..., 5],\n        axis=1,\n    )\n    for name, values in (\n        (\n            \"public_fu\",\n            tf.gather_nd(tf.cast(features[\"candidate_fu\"], tf.float32), hands),\n        ),\n        (\"public_bonus\", candidate_bonus),\n    ):\n        public[name] = tf.tensor_scatter_nd_update(\n            public[name],\n            own,\n            tf.where(response, public[name][:, 0], tf.cast(values, tf.int32)),\n        )\n    public[\"yakuman_allowed\"] = tf.tensor_scatter_nd_update(\n        public[\"yakuman_allowed\"],\n        own,\n        tf.where(\n            response,\n            public[\"yakuman_allowed\"][:, 0],\n            payment_scoring.support(melds)[..., -1],\n        ),\n    )\n    trigger = tf.cast(\n        tf.gather(features[\"trigger_tile_id\"], selected[:, 0]), tf.int32\n    )\n    completes_pao = (\n        response\n        & (selected[:, 1] >= 112)\n        & (\n            (\n                (trigger >= 31)\n                & (trigger < 34)\n                & (tf.reduce_sum(melds[:, 31:34, 1:5], (1, 2)) == 3)\n            )\n            | (\n                (trigger >= 27)\n                & (trigger < 31)\n                & (tf.reduce_sum(melds[:, 27:31, 1:5], (1, 2)) == 4)\n            )\n        )\n    )\n    public[\"pao_payer\"] = tf.tensor_scatter_nd_update(\n        public[\"pao_payer\"],\n        own,\n        tf.where(\n            completes_pao & (public[\"pao_payer\"][:, 0] < 0),\n            tf.cast(\n                tf.gather(features[\"trigger_source\"], selected[:, 0]),\n                tf.int32,\n            ),\n            public[\"pao_payer\"][:, 0],\n        ),\n    )\n    public[\"deposit_allowed\"] &= ~public[\"opened\"]\n    for name in (\"deposit_required\", \"riichi_required\"):\n        public[name] = tf.tensor_scatter_nd_update(\n            public[name], own, public[name][:, 0] | declaration\n        )\n        # A competing ron can end the hand before a pending declaration\n        # is accepted. Hypothetical call features remain in learned context.\n        public[name] &= ~(\n            response[:, None]\n            & (tf.gather(features[\"riichi_state\"], selected[:, 0]) == 1)\n        )\n    # Only an unconditional own discard can force a draw at this boundary.\n    # Response passes still await opponents' claims, including last-tile ron.\n    discard = actions.discard_decisions(features, selected) & ~response\n    public[\"tenpai_required\"] |= public[\"riichi_required\"]\n    public[\"tenpai_required\"] = tf.tensor_scatter_nd_update(\n        public[\"tenpai_required\"],\n        own,\n        public[\"tenpai_required\"][:, 0]\n        | (~response & (tf.reduce_sum(melds[:, :, :5], (1, 2)) == 4)),\n    )\n    public[\"action_tile\"] = tf.where(\n        selected[:, 1] < 111,\n        selected[:, 1] % 37,\n        tf.where(\n            (selected[:, 1] >= 112) & (selected[:, 1] < 260),\n            (selected[:, 1] - 112) % 37,\n            tf.where(selected[:, 1] >= 261, selected[:, 1] - 261, 37),\n        ),\n    )\n    tile = tf.where(selected[:, 1] < 111, selected[:, 1] % 37, 0)\n    abort = (\n        tf.gather_nd(\n            features[\"discard_abort\"],\n            tf.stack(\n                [selected[:, 0], tf.cast(declaration, tf.int32), tile],\n                axis=1,\n            ),\n        )\n        > 0\n    )\n    public[\"ending_safe\"] = tf.gather_nd(\n        tf.transpose(actions.guaranteed_safe_tiles(features), [0, 2, 1]),\n        tf.stack(\n            [\n                selected[:, 0],\n                tf.where(tile < 34, tile, 4 + 9 * (tile - 34)),\n            ],\n            axis=1,\n        ),\n    )\n    fixed_groups = tf.reduce_sum(\n        tf.gather(payment_scoring.public_melds(features), selected[:, 0])[\n            ..., 1:5\n        ],\n        axis=-1,\n    )\n    public[\"pao_trigger\"] = (\n        discard[:, None]\n        & (tf.range(4)[None] != 0)\n        & ~public[\"riichi_required\"]\n        & (public[\"pao_payer\"] < 0)\n        & (\n            tf.gather(fixed_groups, tf.minimum(tile, 33), axis=2, batch_dims=1)\n            == 0\n        )\n        & (\n            ((tile >= 31) & (tile < 34))[:, None]\n            & (tf.reduce_sum(fixed_groups[..., 31:34], -1) == 2)\n            | ((tile >= 27) & (tile < 31))[:, None]\n            & (tf.reduce_sum(fixed_groups[..., 27:31], -1) == 3)\n        )\n    )\n    public[\"nagashi_allowed\"] = tf.tensor_scatter_nd_update(\n        public[\"nagashi_allowed\"],\n        own,\n        public[\"nagashi_allowed\"][:, 0]\n        & (\n            ~discard\n            | ((tile < 34) & ((tile >= 27) | (tile % 9 == 0) | (tile % 9 == 8)))\n        ),\n    )\n    called_source = tf.stack(\n        [\n            tf.range(tf.shape(selected)[0]),\n            tf.cast(\n                tf.gather(features[\"trigger_source\"], selected[:, 0]),\n                tf.int32,\n            ),\n        ],\n        axis=1,\n    )\n    public[\"nagashi_allowed\"] = tf.tensor_scatter_nd_update(\n        public[\"nagashi_allowed\"],\n        called_source,\n        tf.gather_nd(public[\"nagashi_allowed\"], called_source)\n        & ~(response & (selected[:, 1] >= 112)),\n    )\n    public[\"ending_draw_kind\"] = tf.where(\n        discard & abort,\n        2,\n        tf.where(\n            discard\n            & (tf.gather(features[\"live_wall_count\"], selected[:, 0]) == 0),\n            1,\n            0,\n        ),\n    )\n    public[\"ending_tenpai\"] = tf.concat(\n        [\n            tf.cast(\n                tf.gather_nd(\n                    features[\"discard_action_all_shanten\"],\n                    tf.stack([selected[:, 0], tile], axis=1),\n                )\n                == 1,\n                tf.int32,\n            )[:, None],\n            tf.where(public[\"tenpai_required\"][:, 1:], 1, -1),\n        ],\n        axis=1,\n    )\n    return public\n\n\nclass PublicContext(tf.keras.layers.Layer):\n    def call(self, values):\n        inputs, selected, structural = values\n        tiles = tf.cast(structural[:, -1], tf.int32)\n        # Code 37 denotes an action without a tile. Red fives retain their\n        # identity in the one-hot feature, but share public safety with fives.\n        base = tf.where(\n            tiles == 37, 0, tf.where(tiles < 34, tiles, 4 + 9 * (tiles - 34))\n        )\n        tile_indices = tf.stack([selected[:, 0], base], axis=-1)\n        has_tile = tf.cast(tiles != 37, tf.float32)[:, None]\n        # Eighteen two-sided wait lines: 14, 25, 36, 47, 58, 69 in each suit.\n        # Genbutsu at either endpoint rules out that entire ryanmen line.\n        lower = tf.constant(\n            [9 * suit + rank for suit in range(3) for rank in range(6)]\n        )\n        live_lines = ~(\n            tf.gather(inputs[\"genbutsu_to_seat\"], lower, axis=2) > 0\n        ) & ~(tf.gather(inputs[\"genbutsu_to_seat\"], lower + 3, axis=2) > 0)\n        remaining = tf.gather(\n            tf.reduce_sum(tf.cast(live_lines, tf.float32), axis=2),\n            selected[:, 0],\n        )\n        tile_lines = (\n            tf.reduce_sum(\n                tf.cast(tf.gather(live_lines, selected[:, 0]), tf.float32)\n                * tf.cast(\n                    (base[:, None] == lower) | (base[:, None] == lower + 3),\n                    tf.float32,\n                )[:, None],\n                axis=2,\n            )\n            * has_tile\n        )\n        return tf.concat(\n            [\n                tf.one_hot(tiles, 38),\n                tf.one_hot(\n                    tf.searchsorted(\n                        [37, 74, 111, 112, 223, 260, 261],\n                        selected[:, 1],\n                        side=\"right\",\n                    ),\n                    8,\n                ),\n                tf.cast(\n                    tf.gather(inputs[\"riichi_state\"], selected[:, 0]),\n                    tf.float32,\n                )\n                / 2,\n                tf.cast(\n                    tf.gather(inputs[\"ippatsu_alive\"], selected[:, 0]),\n                    tf.float32,\n                ),\n                tf.cast(\n                    tf.gather(\n                        inputs[\"opponent_called_tile_count\"], selected[:, 0]\n                    ),\n                    tf.float32,\n                )\n                / 16,\n                tf.cast(\n                    tf.gather(inputs[\"opponent_discard_count\"], selected[:, 0]),\n                    tf.float32,\n                )\n                / 24,\n                tf.one_hot(\n                    tf.cast(\n                        tf.gather(\n                            inputs[\"dealer_relative_seat\"], selected[:, 0]\n                        ),\n                        tf.int32,\n                    ),\n                    4,\n                ),\n                *[\n                    tf.cast(\n                        tf.gather_nd(\n                            tf.transpose(inputs[name], [0, 2, 1]), tile_indices\n                        ),\n                        tf.float32,\n                    )\n                    * has_tile\n                    / scale\n                    for name, scale in (\n                        (\"genbutsu_to_seat\", 1),\n                        (\"sotogawa_earliest_turn_to_seat\", 6),\n                    )\n                ],\n                tf.cast(\n                    tf.gather_nd(\n                        input_features.blocker_counts(inputs), tile_indices\n                    ),\n                    tf.float32,\n                )\n                * has_tile\n                / 4,\n                *[\n                    tf.cast(\n                        tf.gather_nd(inputs[name], tile_indices), tf.float32\n                    )[:, None]\n                    * has_tile\n                    / 4\n                    for name in (\n                        \"known_unavailable_counts\",\n                        \"dora_multiplicity\",\n                    )\n                ],\n                remaining / 18,\n                tile_lines / 2,\n                tf.math.divide_no_nan(tile_lines, remaining),\n                tf.cast(\n                    tf.gather_nd(\n                        tf.transpose(\n                            inputs[\"passed_unchanged_to_seat\"], [0, 2, 1]\n                        ),\n                        tile_indices,\n                    ),\n                    tf.float32,\n                )\n                * has_tile,\n                tf.reshape(\n                    tf.cast(\n                        tf.gather(inputs[\"riichi_push_count\"], selected[:, 0]),\n                        tf.float32,\n                    ),\n                    (-1, 16),\n                )\n                / 24,\n            ],\n            axis=-1,\n        )\n\n\nclass HandContext(tf.keras.layers.Layer):\n\n    def call(self, values):\n        inputs, selected, structural = values\n        hands = tf.stack(\n            [\n                selected[:, 0],\n                tf.cast(\n                    tf.gather_nd(\n                        actions.candidate_hand_indices(inputs),\n                        selected,\n                    ),\n                    tf.int32,\n                ),\n            ],\n            axis=1,\n        )\n        melds = tf.gather_nd(\n            tf.cast(input_features.candidate_melds(inputs), tf.float32), hands\n        )\n        red = tf.reduce_sum(\n            tf.gather_nd(\n                tf.cast(inputs[\"candidate_hand_red\"], tf.float32), hands\n            ),\n            axis=-1,\n        ) + tf.reduce_sum(melds[:, :, 5], axis=-1)\n        counts = tf.gather_nd(\n            tf.cast(inputs[\"candidate_hand_counts\"], tf.float32), hands\n        ) + meld_tile_counts(melds)\n        dora = (\n            tf.reduce_sum(\n                counts\n                * tf.cast(\n                    tf.gather(inputs[\"dora_multiplicity\"], selected[:, 0]),\n                    tf.float32,\n                ),\n                axis=-1,\n            )\n            + red\n        )\n        return tf.concat(\n            [\n                tf.stack(\n                    [\n                        dora,\n                        red,\n                        tf.cast(\n                            tf.gather(\n                                inputs[\"live_wall_count\"], selected[:, 0]\n                            ),\n                            tf.float32,\n                        )\n                        / 70,\n                        tf.reduce_sum(\n                            4\n                            - tf.cast(\n                                tf.gather(\n                                    inputs[\"known_unavailable_counts\"],\n                                    selected[:, 0],\n                                ),\n                                tf.float32,\n                            ),\n                            axis=-1,\n                        )\n                        / 136,\n                    ],\n                    axis=-1,\n                ),\n                tf.math.asinh(tf.cast(structural[:, :-1], tf.float32)),\n            ],\n            axis=-1,\n        )\n\n\nclass PlayerContext(tf.keras.layers.Layer):\n    \"\"\"Public player descriptors, without learned opponent-slot predictions.\"\"\"\n\n    def call(self, values):\n        inputs, rivers, selected = values\n        players = tf.concat(\n            [\n                tf.broadcast_to(\n                    tf.constant([1.0, 0.0, 0.0, 0.0])[None, :, None],\n                    (tf.shape(rivers)[0], 4, 1),\n                ),\n                tf.concat(\n                    [tf.zeros_like(rivers[:, :1]), tf.cast(rivers, tf.float32)],\n                    axis=1,\n                ),\n                tf.concat(\n                    [\n                        tf.gather(\n                            input_features.field_features(\n                                name, inputs[name], inputs\n                            ),\n                            tf.cast(inputs[\"seat_wind\"], tf.int32),\n                            batch_dims=1,\n                        )\n                        for name in (\"scores\", \"ranks\")\n                    ],\n                    axis=-1,\n                ),\n                # Wind identity is not a player ID. Expose its scoring and\n                # tile-availability consequences instead.\n                tf.stack(\n                    [\n                        tf.cast(inputs[\"seat_wind\"] == 0, tf.float32),\n                        tf.cast(\n                            inputs[\"seat_wind\"]\n                            == inputs[\"prevailing_wind\"][:, None],\n                            tf.float32,\n                        ),\n                        *[\n                            tf.cast(\n                                tf.gather(\n                                    inputs[name],\n                                    tf.cast(inputs[\"seat_wind\"], tf.int32) + 27,\n                                    axis=1,\n                                    batch_dims=1,\n                                ),\n                                tf.float32,\n                            )\n                            / scale\n                            for name, scale in (\n                                (\"known_unavailable_counts\", 4),\n                                (\"dora_multiplicity\", 5),\n                            )\n                        ],\n                    ],\n                    axis=-1,\n                ),\n                *[\n                    tf.cast(inputs[name], tf.float32)[..., None] / scale\n                    for name, scale in (\n                        (\"riichi_state\", 2),\n                        (\"ippatsu_alive\", 1),\n                        (\"opponent_called_tile_count\", 16),\n                        (\"opponent_discard_count\", 24),\n                    )\n                ],\n                tf.math.asinh(\n                    tf.cast(\n                        input_features.last_tedashi_tile(inputs), tf.float32\n                    )\n                ),\n                *[\n                    tf.math.asinh(tf.cast(inputs[name], tf.float32))\n                    for name in (\n                        \"open_opponent_yaku_possibility\",\n                        \"genbutsu_to_seat\",\n                        \"passed_unchanged_to_seat\",\n                        \"sotogawa_earliest_turn_to_seat\",\n                        \"meld_type\",\n                    )\n                ],\n                tf.reduce_sum(\n                    tf.one_hot(\n                        tf.cast(input_features.meld_tile_ids(inputs), tf.int32),\n                        34,\n                    )\n                    * tf.cast(\n                        input_features.meld_tile_valid(inputs), tf.float32\n                    )[..., None],\n                    axis=(2, 3),\n                )\n                / 4,\n                tf.reduce_sum(\n                    tf.cast(input_features.meld_tile_red(inputs), tf.float32)\n                    * tf.cast(\n                        input_features.meld_tile_valid(inputs), tf.float32\n                    ),\n                    axis=(2, 3),\n                )[..., None]\n                / 3,\n            ],\n            axis=-1,\n        )\n        response = tf.gather(inputs[\"decision_phase\"], selected[:, 0]) == 1\n        source = tf.where(\n            response,\n            tf.cast(\n                tf.gather(inputs[\"trigger_source\"], selected[:, 0]), tf.int32\n            ),\n            0,\n        )\n        active_discard = response | actions.discard_decisions(inputs, selected)\n        return tf.concat(\n            [\n                tf.gather(players, selected[:, 0]),\n                encoder.projected_draws(inputs, selected)[..., :1] / 18,\n                tf.cast(\n                    active_discard[:, None]\n                    & (\n                        tf.gather(inputs[\"live_wall_count\"], selected[:, 0]) > 0\n                    )[:, None]\n                    & (tf.range(4)[None] == (source[:, None] + 1) % 4)\n                    & (tf.gather(inputs[\"riichi_state\"], selected[:, 0]) == 0),\n                    tf.float32,\n                )[..., None],\n                tf.cast(\n                    active_discard[:, None]\n                    & (tf.range(4)[None] == source[:, None]),\n                    tf.float32,\n                )[..., None],\n            ],\n            axis=-1,\n        )\n\n\nclass BeliefContext(tf.keras.layers.Layer):\n    \"\"\"Small shared residual from an opponent token and belief moments.\"\"\"\n\n    def __init__(self, belief_offset):\n        super().__init__(name=\"belief_context\", dtype=\"float32\", autocast=False)\n        self.belief_offset = belief_offset\n        self.hidden = tf.keras.layers.Dense(\n            128, activation=\"gelu\", dtype=\"float32\"\n        )\n        self.projection = tf.keras.layers.Dense(\n            96, kernel_initializer=\"zeros\", dtype=\"float32\"\n        )\n\n    def moments(self, probability):\n        probability = tf.cast(probability, tf.float32)\n        shanten, ukeire, counts = [\n            tf.reshape(value, [-1, *shape])\n            for value, shape in zip(\n                tf.split(\n                    probability,\n                    [math.prod(shape) for shape in BELIEF_SHAPES],\n                    -1,\n                ),\n                BELIEF_SHAPES,\n            )\n        ]\n        classes = tf.cast(tf.range(BELIEF_SHAPES[2][-1]), tf.float32)\n        mean = tf.reduce_sum(counts * classes, -1)\n        variance = tf.maximum(\n            0.0,\n            tf.reduce_sum(counts * tf.square(classes), -1) - tf.square(mean),\n        )\n        return tf.concat(\n            [\n                shanten,\n                shanten[..., :1] * ukeire[:, :, 0],\n                tf.reduce_sum(shanten[..., None] * ukeire, axis=2),\n                mean / 4,\n                variance / 4,\n                -tf.reduce_sum(\n                    tf.math.xlogy(shanten, tf.maximum(shanten, 1e-6)),\n                    -1,\n                    keepdims=True,\n                )\n                / tf.math.log(float(BELIEF_SHAPES[0][-1])),\n            ],\n            axis=-1,\n        )\n\n    def call(self, values):\n        state, tokens = values\n        probability = state[\n            :, self.belief_offset : self.belief_offset + BELIEF_WIDTH\n        ]\n        return self.projection(\n            self.hidden(\n                tf.concat(\n                    [tf.cast(tokens, tf.float32), self.moments(probability)], -1\n                )\n            )\n        )\n\n\n@tf.keras.utils.register_keras_serializable(package=\"nejimakidori\")\nclass ResultAttention(tf.keras.layers.Layer):\n    \"\"\"Refine whole-event hypotheses within each candidate independently.\"\"\"\n\n    def __init__(self, **kwargs):\n        super().__init__(**kwargs)\n        self.normalization = tf.keras.layers.LayerNormalization(\n            dtype=self.dtype_policy\n        )\n        self.attention = tf.keras.layers.MultiHeadAttention(\n            num_heads=4, key_dim=16, dtype=self.dtype_policy\n        )\n        self.correction = tf.keras.layers.Dense(\n            32,\n            use_bias=False,\n            kernel_initializer=\"zeros\",\n            dtype=self.dtype_policy,\n        )\n\n    def build(self, input_shape):\n        self.normalization.build(input_shape)\n        self.attention.build(input_shape, input_shape)\n        self.correction.build(input_shape)\n        super().build(input_shape)\n\n    def call(self, events):\n        tokens = self.normalization(events)\n        return events + self.correction(self.attention(tokens, tokens))\n\n\nclass PaymentCritic(tf.keras.Model):\n    \"\"\"Predict action-conditioned hand events, scores and deposits.\"\"\"\n\n    def __init__(self, belief_offset, player_width):\n        super().__init__(dtype=\"float32\", autocast=False)\n        self.player_width = player_width\n        self.state = tf.keras.layers.Dense(\n            384, activation=\"gelu\", dtype=\"float32\"\n        )\n        self.refinement = [\n            tf.keras.Sequential(\n                [\n                    tf.keras.layers.LayerNormalization(dtype=\"float32\"),\n                    tf.keras.layers.Dense(\n                        480, activation=\"gelu\", dtype=\"float32\"\n                    ),\n                    tf.keras.layers.Dense(\n                        384, kernel_initializer=\"zeros\", dtype=\"float32\"\n                    ),\n                ],\n                name=f\"critic_refinement_{block}\",\n            )\n            for block in range(6)\n        ]\n        for layer in self.refinement:\n            layer.dtype_policy = \"float32\"\n        self.belief_context = BeliefContext(belief_offset)\n        self.self_player = tf.keras.layers.Dense(\n            96, activation=\"gelu\", dtype=\"float32\"\n        )\n        self.opponent_players = tf.keras.layers.Dense(\n            96, activation=\"gelu\", dtype=\"float32\"\n        )\n        self.cell_state = tf.keras.layers.Dense(\n            96, activation=\"gelu\", dtype=\"float32\"\n        )\n        self.event_context = tf.keras.layers.Dense(32, dtype=\"float32\")\n        self.event_roles = [\n            tf.keras.layers.Dense(32, dtype=\"float32\") for _ in range(3)\n        ]\n        self.event_kind = tf.keras.layers.Embedding(5, 32, dtype=\"float32\")\n        self.event_kind.build((len(joint_settlement.READOUT_EVENTS),))\n        self.result_attention = ResultAttention(\n            name=\"result_attention\", dtype=\"float32\"\n        )\n        self.event = tf.keras.layers.Dense(1, dtype=\"float32\")\n        self.deposit_context = tf.keras.layers.Dense(8, dtype=\"float32\")\n        self.deposit_players = tf.keras.layers.Dense(8, dtype=\"float32\")\n        self.deposit_roles = tf.keras.layers.Dense(8, dtype=\"float32\")\n        self.deposit = tf.keras.layers.Dense(1, dtype=\"float32\")\n        self.pao_claim = tf.keras.layers.Dense(16, dtype=\"float32\")\n        self.pao_players = tf.keras.layers.Dense(16, dtype=\"float32\")\n        self.pao_roles = tf.keras.layers.Dense(16, dtype=\"float32\")\n        self.pao = tf.keras.layers.Dense(1, dtype=\"float32\")\n        self.total_score = tf.keras.layers.Dense(\n            len(payment_scoring.SCORES), dtype=\"float32\", name=\"total_score\"\n        )\n\n    def context(self, state):\n        state = tf.cast(state, tf.float32)\n        hidden = self.state(state[:, : -4 * self.player_width])\n        for layer in self.refinement:\n            hidden = hidden + layer(hidden)\n        descriptors = tf.concat(\n            [\n                tf.reshape(\n                    state[:, -4 * self.player_width :],\n                    (-1, 4, self.player_width),\n                ),\n                tf.broadcast_to(\n                    hidden[:, None], (tf.shape(state)[0], 4, self.state.units)\n                ),\n            ],\n            axis=-1,\n        )\n        opponents = self.opponent_players(descriptors[:, 1:])\n        players = tf.concat(\n            [\n                self.self_player(descriptors[:, :1]),\n                opponents + self.belief_context([state, opponents]),\n            ],\n            axis=1,\n        )\n        return hidden, players\n\n    def event_contexts(self, hidden, players):\n        # Joint masks remain whole events. Shared role pooling is followed by\n        # a nonlinearity, not a product of independent player probabilities.\n        roles = tf.constant(\n            [\n                [\n                    [\n                        float(bool(winners & (1 << seat))),\n                        float(kind < 2 and source == seat),\n                        float(\n                            ready if kind == 4 else bool(ready & (1 << seat))\n                        ),\n                    ]\n                    for seat in range(4)\n                ]\n                for kind, source, winners, ready in joint_settlement.READOUT_EVENTS\n            ],\n            tf.float32,\n        )\n        events = tf.nn.gelu(\n            self.event_context(hidden)[:, None]\n            + tf.linalg.matmul(\n                tf.one_hot(\n                    [row[0] for row in joint_settlement.READOUT_EVENTS], 5\n                ),\n                self.event_kind.embeddings,\n            )[None]\n            + tf.add_n(\n                [\n                    tf.einsum(\n                        \"es,nsh->neh\",\n                        roles[..., role],\n                        projection(players),\n                    )\n                    for role, projection in enumerate(self.event_roles)\n                ]\n            )\n        )\n        return self.result_attention(events), roles\n\n    def event_logits(self, state):\n        hidden, players = self.context(state)\n        event, _ = self.event_contexts(hidden, players)\n        return tf.linalg.matmul(\n            self.event(event)[..., 0],\n            tf.constant(EVENT_READOUTS),\n            transpose_b=True,\n        )\n\n    def distributions(self, inputs):\n        \"\"\"Scored ron/tsumo events, exhaustive masks, abort and bank deposits.\n\n        Twelve ron claimant slots plus four tsumo winners. All three tsumo\n        payer shares use exactly the same total han/fu distribution.\n        \"\"\"\n        hidden, players = self.context(inputs[\"state\"])\n        shares = [\n            cell if cell < 12 else 12 + row[2]\n            for cell, row in enumerate(scoring.CELLS[:24])\n        ]\n        cells = self.cell_state(\n            tf.concat(\n                [\n                    tf.gather(\n                        players,\n                        [\n                            scoring.CELLS[cell][2]\n                            for cell in joint_settlement.SCORE_HEADS\n                        ],\n                        axis=1,\n                    ),\n                    tf.gather(\n                        players,\n                        [\n                            scoring.CELLS[cell][1]\n                            for cell in joint_settlement.SCORE_HEADS\n                        ],\n                        axis=1,\n                    )\n                    * tf.constant(\n                        [cell < 12 for cell in joint_settlement.SCORE_HEADS],\n                        tf.float32,\n                    )[None, :, None],\n                    *[\n                        tf.gather(\n                            tf.cast(inputs[name], tf.float32),\n                            [\n                                scoring.CELLS[cell][2]\n                                for cell in joint_settlement.SCORE_HEADS\n                            ],\n                            axis=1,\n                        )[..., None]\n                        / scale\n                        for name, scale in (\n                            (\"public_fu\", 128),\n                            (\"public_bonus\", 5),\n                            (\"opened\", 1),\n                            (\"riichi_required\", 1),\n                        )\n                    ],\n                    tf.broadcast_to(\n                        tf.one_hot(\n                            [\n                                scoring.CELLS[cell][0]\n                                for cell in joint_settlement.SCORE_HEADS\n                            ],\n                            2,\n                        )[None],\n                        (tf.shape(players)[0], 16, 2),\n                    ),\n                ],\n                axis=-1,\n            )\n        )\n        # One total han/fu distribution per claim; tsumo payer shares use\n        # the same winning-hand prediction and exact payment conversion.\n        raw_score = tf.gather(self.total_score(cells), shares, axis=1)\n        score_logits = payment_scoring.masked_score_logits(\n            logits=raw_score,\n            dealer=inputs[\"dealer\"],\n            meld_fu=inputs[\"public_fu\"],\n            opened=inputs[\"opened\"],\n            riichi_required=inputs[\"riichi_required\"],\n            bonus=inputs[\"public_bonus\"],\n            yakuman=inputs[\"yakuman_allowed\"],\n        )\n        score_logits = tf.where(\n            (\n                tf.gather(\n                    inputs[\"pao_payer\"],\n                    [cell[2] for cell in scoring.CELLS[:24]],\n                    axis=1,\n                )\n                < 0\n            )[..., None]\n            | tf.constant(payment_scoring.SCORE_HAN == 0)[None, None],\n            score_logits,\n            -1e9,\n        )\n        event, roles = self.event_contexts(hidden, players)\n        # Four nagashi readouts generate all nonempty qualifier masks.\n        # Sum log-odds; pooled contexts only condition the shared bank law.\n        event_logits = tf.linalg.matmul(\n            self.event(event)[..., 0],\n            tf.constant(EVENT_READOUTS),\n            transpose_b=True,\n        )\n        event = tf.einsum(\n            \"er,nrh->neh\",\n            tf.constant(EVENT_READOUTS / EVENT_READOUTS.sum(-1, keepdims=True)),\n            event,\n        )\n        roles = tf.einsum(\"er,rsd->esd\", tf.constant(EVENT_READOUTS), roles)\n        deposit = tf.nn.gelu(\n            self.deposit_context(event)[:, :, None]\n            + tf.einsum(\n                \"ds,nsh->ndh\",\n                tf.constant(joint_settlement.DEPOSITS),\n                self.deposit_players(players),\n            )[:, None]\n            + self.deposit_roles(\n                tf.einsum(\n                    \"ds,esr->edr\", tf.constant(joint_settlement.DEPOSITS), roles\n                )\n            )[None]\n        )\n        pao_roles = tf.constant(\n            [\n                [\n                    [\n                        float(seat == scoring.CELLS[cell][2]),\n                        float(cell < 12 and seat == scoring.CELLS[cell][1]),\n                    ]\n                    for seat in range(4)\n                ]\n                for cell in joint_settlement.SCORE_HEADS\n            ],\n            tf.float32,\n        )\n        pao_logits = self.pao(\n            tf.nn.gelu(\n                self.pao_claim(cells)[:, :, None]\n                + self.pao_players(players)[:, None]\n                + self.pao_roles(\n                    tf.concat(\n                        [\n                            tf.broadcast_to(\n                                pao_roles[None],\n                                [tf.shape(cells)[0], 16, 4, 2],\n                            ),\n                            tf.cast(\n                                tf.gather(\n                                    inputs[\"pao_trigger\"],\n                                    [\n                                        scoring.CELLS[cell][2]\n                                        for cell in joint_settlement.SCORE_HEADS\n                                    ],\n                                    axis=1,\n                                )[..., None]\n                                & (tf.range(4)[None, None] == 0),\n                                tf.float32,\n                            )[..., None],\n                        ],\n                        axis=-1,\n                    )\n                )\n            )\n        )[..., 0]\n        # Winner-as-payer denotes ordinary allocation. Established public\n        # liability is deterministic; only future responsibility is learned.\n        known_payer = tf.gather(\n            inputs[\"pao_payer\"],\n            [scoring.CELLS[cell][2] for cell in joint_settlement.SCORE_HEADS],\n            axis=1,\n        )\n        pao_logits = tf.where(\n            tf.where(\n                (known_payer >= 0)[..., None],\n                known_payer[..., None] == tf.range(4)[None, None],\n                (pao_roles[None, ..., 0] > 0)\n                | ~tf.gather(\n                    inputs[\"riichi_required\"],\n                    [\n                        scoring.CELLS[cell][2]\n                        for cell in joint_settlement.SCORE_HEADS\n                    ],\n                    axis=1,\n                )[..., None],\n            ),\n            pao_logits,\n            -1e9,\n        )\n        result = {\n            \"pao_logits\": pao_logits,\n            \"score_logits\": score_logits,\n            \"score_probability\": tf.nn.softmax(score_logits),\n            \"event_logits\": event_logits,\n            \"deposit_logits\": self.deposit(deposit)[..., 0],\n        }\n\n        _, _, legal = joint_settlement.event_probabilities({**inputs, **result})\n        possible = tf.reduce_any(legal, -1)\n        result[\"critic_constraint_loss\"] = (\n            tf.reduce_mean(\n                losses.constraint_divergence(raw_score, score_logits), -1\n            )\n            + losses.constraint_divergence(\n                result[\"event_logits\"],\n                tf.where(possible, result[\"event_logits\"], -1e9),\n            )\n            + tf.math.divide_no_nan(\n                tf.reduce_sum(\n                    losses.constraint_divergence(\n                        result[\"deposit_logits\"],\n                        tf.where(legal, result[\"deposit_logits\"], -1e9),\n                    )\n                    * tf.cast(possible, tf.float32),\n                    -1,\n                ),\n                tf.reduce_sum(tf.cast(possible, tf.float32), -1),\n            )\n        )\n        return result\n\n    def joint_distributions(self, inputs):\n        factors = self.distributions(inputs)\n        result = {**factors, **joint_settlement.decode({**inputs, **factors})}\n        result[\"payment_probability\"] = joint_settlement.marginals(result)\n        return result\n\n    def candidate_chunk(self, inputs, payoff, weights, integer_fields):\n        \"\"\"Bounded, detached forecasts for actor objectives.\"\"\"\n        inputs = {\n            name: (\n                tf.bitcast(value, tf.int32) if name in integer_fields else value\n            )\n            for name, value in inputs.items()\n        }\n        with tf.keras.StatelessScope(\n            state_mapping=zip(self.trainable_variables, weights)\n        ):\n            outputs = PaymentCritic.distributions(self, inputs)\n            probability, _ = joint_settlement.probabilities(\n                {**inputs, **outputs}\n            )\n        return tf.stop_gradient(\n            joint_settlement.expectation(probability, payoff)\n        )\n\n    def chunk_statistics(self, inputs, labels, weights=None):\n        # Inline the differentiable body into the chunk compilation. Nested\n        # compiled gradients can specialize on forward tensor values.\n        if weights is None:\n            outputs = PaymentCritic.distributions(self, inputs)\n        else:\n            with tf.keras.StatelessScope(\n                state_mapping=zip(self.trainable_variables, weights)\n            ):\n                outputs = PaymentCritic.distributions(self, inputs)\n\n        def mean(values, mask):\n            return losses.masked_totals(\n                values,\n                mask,\n                tf.reshape(\n                    labels[\"valid\"], [-1] + [1] * (values.shape.rank - 1)\n                ),\n            )\n\n        support = {\n            name.removeprefix(\"support_\"): value\n            for name, value in labels.items()\n            if name.startswith(\"support_\")\n        }\n        support[\"selected\"] = tf.constant(joint_settlement.EVENT_CLAIMS)\n        metrics = joint_settlement.observed_terms(\n            labels, {**inputs, **outputs}, mean=mean, support=support\n        )\n        probability, _ = joint_settlement.probabilities({**inputs, **outputs})\n        metrics[\"q_mse\"] = mean(\n            tf.square(\n                joint_settlement.expectation(probability, labels[\"q_payoff\"])\n                - labels[\"q_target\"]\n            ),\n            labels[\"q_identified\"],\n        )\n        metrics[\"q_target_coverage\"] = mean(\n            tf.cast(labels[\"q_identified\"], tf.float32),\n            tf.ones_like(labels[\"q_identified\"]),\n        )\n        metrics[\"critic_constraint_loss\"] = mean(\n            outputs[\"critic_constraint_loss\"],\n            tf.ones_like(outputs[\"critic_constraint_loss\"]),\n        )\n        return tf.stack([metrics[name] for name in CRITIC_METRICS])\n\n    def chunk_gradients(self, inputs, labels, weights, upstream, gradients):\n        \"\"\"Keep recomputation, differentiation and accumulation together.\"\"\"\n        with tf.GradientTape() as tape:\n            tape.watch([inputs[\"state\"], *weights])\n            statistics = PaymentCritic.chunk_statistics(\n                self, inputs, labels, weights\n            )\n        values = tape.gradient(\n            statistics,\n            [inputs[\"state\"], *weights],\n            output_gradients=upstream,\n        )\n        return (\n            values[0],\n            [total + value for total, value in zip(gradients, values[1:])],\n        )\n\n    def supervised_statistics(self, inputs, labels, valid=None):\n        labels = {\n            **labels,\n            \"valid\": (\n                tf.ones(tf.shape(inputs[\"state\"])[0])\n                if valid is None\n                else tf.cast(valid, tf.float32)\n            ),\n        }\n\n        rows = tf.shape(inputs[\"state\"])[0]\n        indices = tf.range(\n            (rows + STATISTICS_CHUNK - 1) // STATISTICS_CHUNK * STATISTICS_CHUNK\n        )\n        inputs = {\n            name: tf.gather(value, tf.minimum(indices, rows - 1))\n            for name, value in inputs.items()\n        }\n        labels = {\n            **{\n                name: tf.gather(value, tf.minimum(indices, rows - 1))\n                for name, value in labels.items()\n            },\n            \"valid\": tf.gather(labels[\"valid\"], tf.minimum(indices, rows - 1))\n            * tf.cast(indices < rows, tf.float32),\n        }\n\n        labels = joint_settlement.prepare_supervision(inputs, labels)\n\n        # Retain only loss sufficient statistics. Recompute one chunk at a\n        # time in the backward pass instead of retaining every settlement.\n        # Explicit weight tensors preserve the local replica's dependency;\n        # implicit custom-gradient variable capture can select replica zero.\n        @tf.custom_gradient\n        def summarize(state, *weights):\n            statistics = tf.zeros((len(CRITIC_METRICS), 2))\n            for begin in tf.range(0, tf.shape(state)[0], STATISTICS_CHUNK):\n                tf.autograph.experimental.set_loop_options(\n                    parallel_iterations=1\n                )\n                statistics += self.chunk_statistics(\n                    {\n                        **{\n                            name: value[begin : begin + STATISTICS_CHUNK]\n                            for name, value in inputs.items()\n                        },\n                        \"state\": state[begin : begin + STATISTICS_CHUNK],\n                    },\n                    {\n                        name: value[begin : begin + STATISTICS_CHUNK]\n                        for name, value in labels.items()\n                    },\n                    weights,\n                )\n\n            @tf.function\n            def backward(upstream):\n                state_gradients = tf.TensorArray(\n                    tf.float32, size=0, dynamic_size=True\n                )\n                gradients = [tf.zeros_like(value) for value in weights]\n                for begin in tf.range(0, tf.shape(state)[0], STATISTICS_CHUNK):\n                    tf.autograph.experimental.set_loop_options(\n                        parallel_iterations=1\n                    )\n                    values = self.chunk_gradients(\n                        inputs={\n                            **{\n                                name: value[begin : begin + STATISTICS_CHUNK]\n                                for name, value in inputs.items()\n                            },\n                            \"state\": state[begin : begin + STATISTICS_CHUNK],\n                        },\n                        labels={\n                            name: value[begin : begin + STATISTICS_CHUNK]\n                            for name, value in labels.items()\n                        },\n                        weights=weights,\n                        upstream=upstream,\n                        gradients=gradients,\n                    )\n                    state_gradients = state_gradients.write(\n                        begin // STATISTICS_CHUNK, values[0]\n                    )\n                    gradients = values[1]\n                return (\n                    state_gradients.concat(),\n                    *gradients,\n                )\n\n            return statistics, backward\n\n        statistics = summarize(\n            inputs[\"state\"],\n            *[value.value.read_value() for value in self.trainable_variables],\n        )\n        # XLA ignores Assert ops: verify targets after compiled aggregation.\n        # These denominators count supported and Q-identifiable valid rows.\n        with tf.control_dependencies(\n            [\n                tf.debugging.assert_equal(\n                    statistics[CRITIC_METRICS.index(\"payment_nll\"), 1],\n                    tf.reduce_sum(labels[\"valid\"]),\n                    message=\"Unsupported valid settlement targets\",\n                ),\n                tf.debugging.assert_equal(\n                    statistics[CRITIC_METRICS.index(\"q_mse\"), 1],\n                    tf.reduce_sum(labels[\"valid\"]),\n                    message=\"Unidentified valid Q targets\",\n                ),\n            ]\n        ):\n            return tf.identity(statistics)\n\n    def call(self, inputs):\n        return self.joint_distributions(inputs)\n\n\nCRITIC_METRICS = (\n    \"payment_nll\",\n    \"q_mse\",\n    \"q_target_coverage\",\n    \"nagashi_loss\",\n    \"critic_constraint_loss\",\n)\n\n\ndef metrics_from_statistics(statistics):\n    \"\"\"Reduce globally before deriving RMSE in the original J units.\"\"\"\n    metrics = dict(\n        zip(CRITIC_METRICS, tf.unstack(losses.packed_means(statistics)))\n    )\n    return {\n        **metrics,\n        \"q_rmse\": tf.sqrt(metrics[\"q_mse\"]),\n        \"critic_nll_component\": 0.5 * metrics[\"payment_nll\"],\n        \"critic_q_component\": 0.5 * Q_MSE_TO_NLL * metrics[\"q_mse\"],\n    }\n\n\ndef settlement_objective(metrics):\n    \"\"\"Equal calibrated likelihood/value fit, plus direct constraints.\"\"\"\n    return (\n        0.5 * metrics[\"payment_nll\"]\n        + 0.5 * Q_MSE_TO_NLL * metrics[\"q_mse\"]\n        + metrics[\"nagashi_loss\"]\n        + metrics[\"critic_constraint_loss\"]\n    )\n\n\ndef chosen_actions(features, labels):\n    return tf.where(\n        features[\"decision_phase\"] == 4,\n        260,\n        tf.where(\n            labels[\"discard_policy_logits\"] >= 0,\n            tf.cast(labels[\"discard_policy_logits\"], tf.int32),\n            tf.where(\n                labels[\"riichi_policy_logits\"] >= 0,\n                37 + tf.cast(labels[\"riichi_policy_logits\"], tf.int32),\n                tf.where(\n                    labels[\"response_policy_logits\"] >= 0,\n                    tf.where(\n                        labels[\"response_policy_logits\"] == 149,\n                        261 + tf.cast(features[\"trigger_tile_id\"], tf.int32),\n                        111\n                        + tf.cast(labels[\"response_policy_logits\"], tf.int32),\n                    ),\n                    260 + tf.cast(labels[\"kan_action_logits\"], tf.int32),\n                ),\n            ),\n        ),\n    )\n\n\ndef active_candidates(features, selected):\n    phase = tf.gather(features[\"decision_phase\"], selected[:, 0])\n    action = selected[:, 1]\n    return (\n        ((phase == 0) & (action < 37))\n        | ((phase == 3) & (action >= 37) & (action < 111))\n        | (\n            (phase == 1)\n            & (\n                ((action >= 111) & (action < 260))\n                | (\n                    action\n                    == 261\n                    + tf.cast(\n                        tf.gather(features[\"trigger_tile_id\"], selected[:, 0]),\n                        tf.int32,\n                    )\n                )\n            )\n        )\n        | ((phase == 2) & (action >= 260))\n        | ((phase == 4) & (action == 260))\n    )\n\n\ndef candidate_probabilities(features, outputs):\n    probability = {\n        name: tf.nn.softmax(outputs[name])\n        * tf.cast(features[\"decision_phase\"][:, None] == phase, tf.float32)\n        for name, phase in (\n            (\"discard_policy_logits\", 0),\n            (\"riichi_policy_logits\", 3),\n            (\"response_policy_logits\", 1),\n            (\"kan_action_logits\", 2),\n        )\n    }\n    # Response daiminkan shares a candidate with the trigger tile's kan.\n    probability = tf.tensor_scatter_nd_add(\n        tf.concat(\n            [\n                probability[\"discard_policy_logits\"],\n                probability[\"riichi_policy_logits\"],\n                probability[\"response_policy_logits\"][:, :149],\n                probability[\"kan_action_logits\"],\n            ],\n            axis=1,\n        ),\n        tf.stack(\n            [\n                tf.range(tf.shape(features[\"decision_phase\"])[0]),\n                261 + tf.cast(features[\"trigger_tile_id\"], tf.int32),\n            ],\n            axis=1,\n        ),\n        probability[\"response_policy_logits\"][:, 149],\n    )\n    # Win/pass exposes a current-hand forecast, not a fabricated\n    # action-conditioned forecast.\n    return tf.where(\n        (features[\"decision_phase\"] == 4)[:, None],\n        tf.one_hot(260, 295),\n        probability,\n    )\n",
      "sha256": "ebe4b763ee91e083cb181cd929405f83a463f8f6c3df08e051a9bde0d38cc340"
    },
    {
      "path": "model/encoder.py",
      "text": "\"\"\"Shared board, hand and river representations.\"\"\"\n\nimport math\n\nimport tensorflow as tf\n\nfrom log_dataset import _native_collection\nfrom model import actions, input_features, river_attention\n\nHAND_BATCH_BUCKET = 512\n# Deterministic scoring constraints bypass learned projections.\nSCORING_INPUTS = frozenset(\n    {\n        \"public_bonus\",\n        \"candidate_fu\",\n    }\n)\nCANDIDATE_SCORING_INPUTS = frozenset(\n    {\n        \"action_win_value_range\",\n        \"action_win_value_valid\",\n        \"action_value_eligible\",\n        \"action_open_yaku_restricted\",\n    }\n)\nTILE_CONTEXT_INPUTS = (\n    \"dora_multiplicity\",\n    \"known_unavailable_counts\",\n    \"blocker_counts\",\n    \"genbutsu_to_seat\",\n    \"passed_unchanged_to_seat\",\n    \"sotogawa_earliest_turn_to_seat\",\n)\nTABLE_INPUTS = {\n    name: spec\n    for name, spec in input_features.NEURAL_INPUTS.items()\n    if name not in SCORING_INPUTS\n    and name not in CANDIDATE_SCORING_INPUTS\n    and not name.startswith(\"river_\")\n    and not name.startswith((\"candidate_\", \"discard_\", \"call_\", \"kan_\"))\n    and name not in TILE_CONTEXT_INPUTS\n    and name\n    not in {\n        \"riichi_legal_mask\",\n        \"riichi_discard_legal_mask\",\n        \"response_legal_mask\",\n    }\n}\n\n\n@tf.keras.utils.register_keras_serializable(package=\"nejimakidori\")\nclass TableContext(tf.keras.layers.Layer):\n    \"\"\"Encode shared fields and river summaries once before hand fusion.\"\"\"\n\n    def __init__(self, **kwargs):\n        super().__init__(**kwargs)\n        groups = {}\n        offset = 384\n        for name, spec in TABLE_INPUTS.items():\n            size = math.prod(spec[\"shape\"]) * input_features.field_width(name)\n            if name.endswith((\"yaku_possibility\",)):\n                groups.setdefault(spec[\"shape\"][-1], []).extend(\n                    range(offset, offset + size)\n                )\n            offset += size\n        selected = {index for indices in groups.values() for index in indices}\n        self.retained = [\n            index for index in range(offset) if index not in selected\n        ]\n        self.indices = list(groups.values())\n        self.widths = list(groups)\n        self.bases = [\n            tf.keras.layers.Dense(\n                max(4, width // 2), use_bias=False, dtype=self.dtype_policy\n            )\n            for width in self.widths\n        ]\n        self.project = tf.keras.Sequential(\n            [\n                tf.keras.layers.Dense(\n                    384, use_bias=False, dtype=self.dtype_policy\n                ),\n                tf.keras.layers.Dense(\n                    512, activation=\"gelu\", dtype=self.dtype_policy\n                ),\n            ],\n            name=\"table_readout\",\n        )\n        self.project.dtype_policy = self.dtype_policy\n\n    def build(self, input_shape):\n        for width, basis in zip(self.widths, self.bases):\n            basis.build((None, width))\n        self.project.build(\n            (\n                None,\n                len(self.retained)\n                + sum(\n                    len(indices) // width * basis.units\n                    for width, indices, basis in zip(\n                        self.widths, self.indices, self.bases\n                    )\n                ),\n            )\n        )\n        super().build(input_shape)\n\n    def call(self, values):\n        encoded = [tf.gather(values, self.retained, axis=-1)]\n        for width, indices, basis in zip(self.widths, self.indices, self.bases):\n            encoded.append(\n                tf.reshape(\n                    basis(\n                        tf.reshape(\n                            tf.gather(values, indices, axis=-1),\n                            (-1, len(indices) // width, width),\n                        )\n                    ),\n                    (-1, len(indices) // width * basis.units),\n                )\n            )\n        return self.project(tf.concat(encoded, -1))\n\n\ndef semantic_features(values):\n    \"\"\"Flatten already encoded field coordinates in schema order.\"\"\"\n    return tf.keras.ops.concatenate(\n        [\n            tf.keras.ops.reshape(value, (-1, math.prod(value.shape[1:])))\n            for value in values.values()\n        ],\n        axis=-1,\n    )\n\n\n@tf.keras.utils.register_keras_serializable(package=\"nejimakidori\")\nclass SuitResidual(tf.keras.layers.Layer):\n    def __init__(self, dilation, **kwargs):\n        super().__init__(**kwargs)\n        self.dilation = dilation\n        self.first = tf.keras.layers.Conv1D(\n            filters=128,\n            kernel_size=3,\n            padding=\"same\",\n            dilation_rate=dilation,\n            dtype=self.dtype_policy,\n            activation=\"gelu\",\n        )\n        self.second = tf.keras.layers.Conv1D(\n            filters=128,\n            kernel_size=3,\n            padding=\"same\",\n            dilation_rate=dilation,\n            dtype=self.dtype_policy,\n        )\n        self.normalization = tf.keras.layers.LayerNormalization(\n            dtype=self.dtype_policy\n        )\n\n    def build(self, input_shape):\n        self.first.build(input_shape)\n        self.second.build((*input_shape[:-1], 128))\n        self.normalization.build((*input_shape[:-1], 128))\n        super().build(input_shape)\n\n    def call(self, values):\n        return tf.nn.gelu(\n            self.normalization(values + self.second(self.first(values)))\n        )\n\n    def get_config(self):\n        return {**super().get_config(), \"dilation\": self.dilation}\n\n\n@tf.keras.utils.register_keras_serializable(package=\"nejimakidori\")\nclass HandBank(tf.keras.layers.Layer):\n    \"\"\"Encode occupied candidate hands with shared, suit-local convolutions.\"\"\"\n\n    def __init__(self, **kwargs):\n        super().__init__(**{**kwargs, \"autocast\": False})\n        self.context = tf.keras.layers.Dense(\n            128, use_bias=False, dtype=self.dtype_policy\n        )\n        self.tiles = tf.keras.layers.Dense(\n            128,\n            activation=None,\n            dtype=self.dtype_policy,\n        )\n        self.suits = [\n            SuitResidual(dilation, dtype=self.dtype_policy)\n            for dilation in (1, 2, 4)\n        ]\n        self.honors = tf.keras.layers.Dense(\n            128, activation=\"gelu\", dtype=self.dtype_policy\n        )\n        self.projection = tf.keras.Sequential(\n            [\n                tf.keras.layers.Dense(\n                    384, use_bias=False, dtype=self.dtype_policy\n                ),\n                tf.keras.layers.Dense(\n                    512, activation=\"gelu\", dtype=self.dtype_policy\n                ),\n            ],\n            name=\"hand_readout\",\n        )\n        self.projection.dtype_policy = self.dtype_policy\n        self.normalization = tf.keras.layers.LayerNormalization(\n            dtype=self.dtype_policy\n        )\n\n    def build(self, input_shape):\n        self.tiles.build((None, 34, 31 + input_features.TILE_WIDTH))\n        self.context.build(input_shape[1])\n        for block in self.suits:\n            block.build((None, 9, 128))\n        self.honors.build((None, 7, 128))\n        self.projection.build((None, 34 * 128 + 19))\n        self.normalization.build((None, 512))\n        super().build(input_shape)\n\n    def call(self, values):\n        inputs, context = values\n        selected = tf.where(inputs[\"candidate_hand_valid\"] > 0)\n        # GatherNd has no int8 GPU kernel. Cast before selecting so the\n        # full candidate bank does not take a round trip through the host.\n        counts = tf.gather_nd(\n            tf.cast(inputs[\"candidate_hand_counts\"], tf.int32), selected\n        )\n        red = tf.linalg.matmul(\n            tf.gather_nd(\n                tf.cast(inputs[\"candidate_hand_red\"], self.compute_dtype),\n                selected,\n            ),\n            tf.one_hot([4, 13, 22], 34, dtype=self.compute_dtype),\n        )\n        melds = tf.gather_nd(\n            tf.cast(inputs[\"candidate_melds\"], tf.int32), selected\n        )\n        # Exact raw keys include suit identity: tile embeddings differ by suit.\n        # Only the integer deduplication runs on CPU; encodings stay on device.\n        with tf.device(\"/CPU:0\"):\n            keys = tf.reshape(\n                tf.concat(\n                    [\n                        tf.cast(counts[:, :27, None], tf.int32),\n                        tf.cast(red[:, :27, None], tf.int32),\n                        tf.cast(melds[:, :27], tf.int32),\n                    ],\n                    axis=-1,\n                ),\n                (-1, 72),\n            )\n            keys = tf.concat(\n                [keys, tf.tile(tf.range(3), [tf.shape(counts)[0]])[:, None]],\n                axis=-1,\n            )\n            # Board-conditioned suits can only share within one board.\n            keys = tf.concat(\n                [\n                    keys,\n                    tf.repeat(tf.cast(selected[:, 0], tf.int32), 3)[:, None],\n                ],\n                axis=-1,\n            )\n            unique, inverse = tf.raw_ops.UniqueV2(x=keys, axis=[0])\n            first = tf.math.unsorted_segment_min(\n                tf.range(tf.shape(keys)[0]), inverse, tf.shape(unique)[0]\n            )\n        values = tf.concat(\n            [\n                tf.one_hot(\n                    tf.cast(counts, tf.int32), 5, dtype=self.compute_dtype\n                ),\n                red[..., None],\n                tf.cast(melds, self.compute_dtype),\n                tf.broadcast_to(\n                    tf.cast(inputs[\"tile_identity\"], self.compute_dtype)[None],\n                    (tf.shape(selected)[0], 34, input_features.TILE_WIDTH),\n                ),\n            ],\n            axis=-1,\n        )\n        values = tf.concat(\n            [\n                values,\n                tf.gather(\n                    tf.cast(\n                        tf.concat(\n                            [\n                                input_features.field_features(\n                                    name, inputs[name], inputs\n                                )\n                                for name in (\n                                    \"dora_multiplicity\",\n                                    \"known_unavailable_counts\",\n                                )\n                            ]\n                            + [\n                                tf.math.asinh(\n                                    tf.cast(\n                                        inputs[\"blocker_counts\"], tf.float32\n                                    )\n                                ),\n                                *[\n                                    tf.transpose(\n                                        input_features.field_features(\n                                            name, inputs[name], inputs\n                                        )[..., 0],\n                                        (0, 2, 1),\n                                    )\n                                    for name in (\n                                        \"genbutsu_to_seat\",\n                                        \"passed_unchanged_to_seat\",\n                                        \"sotogawa_earliest_turn_to_seat\",\n                                    )\n                                ],\n                            ],\n                            axis=-1,\n                        ),\n                        self.compute_dtype,\n                    ),\n                    selected[:, 0],\n                ),\n            ],\n            axis=-1,\n        )\n        # Keep convolution batch shapes stable as occupied hand counts vary.\n        # Small inference requests use smaller buckets to limit padding cost.\n        size = tf.shape(selected)[0]\n        multiple = tf.where(size > 128, HAND_BATCH_BUCKET, 16)\n        values = tf.pad(values, ((0, (-size) % multiple), (0, 0), (0, 0)))\n        values = self.tiles(values)\n        # Every hand reads the same observed context. Only hand zero feeds\n        # the board; hypothetical hands are consumed by candidate scoring.\n        values = tf.nn.gelu(\n            values\n            + tf.pad(\n                tf.gather(self.context(context), selected[:, 0])[:, None],\n                ((0, (-size) % multiple), (0, 0), (0, 0)),\n            )\n        )\n        suits = tf.gather(tf.reshape(values[:size, :27], (-1, 9, 128)), first)\n        suit_size = tf.shape(suits)[0]\n        # Coarser suit padding reduces compiled convolution shape variants.\n        suit_multiple = tf.where(\n            suit_size <= 128,\n            16,\n            tf.where(\n                suit_size <= 512, 512, tf.where(suit_size <= 1024, 1024, 4096)\n            ),\n        )\n        suits = tf.pad(\n            suits, ((0, (-suit_size) % suit_multiple), (0, 0), (0, 0))\n        )\n        for block in self.suits:\n            suits = block(suits)\n        # A leading batch axis makes Gather's gradient dense, so repeated\n        # suits sum in float32 before the cast back to the compute dtype.\n        suits = tf.reshape(\n            tf.cast(\n                tf.gather(tf.cast(suits, tf.float32)[None], inverse, axis=1)[0],\n                suits.dtype,\n            ),\n            (-1, 27, 128),\n        )\n        suits = tf.pad(suits, ((0, (-size) % multiple), (0, 0), (0, 0)))\n        values = tf.concat([suits, self.honors(values[:, 27:])], axis=1)\n        values = self.normalization(\n            self.projection(\n                tf.concat(\n                    [\n                        tf.reshape(values, (-1, 34 * 128)),\n                        tf.pad(\n                            tf.gather_nd(\n                                tf.cast(\n                                    inputs[\"candidate_hand_yaku_possibility\"],\n                                    self.compute_dtype,\n                                ),\n                                selected,\n                            ),\n                            ((0, (-size) % multiple), (0, 0)),\n                        ),\n                    ],\n                    axis=-1,\n                )\n            )\n        )\n        return tf.scatter_nd(\n            selected,\n            values[:size],\n            tf.cast(\n                (tf.shape(inputs[\"candidate_hand_valid\"])[0], 16, 512), tf.int64\n            ),\n        )\n\n\n@tf.keras.utils.register_keras_serializable(package=\"nejimakidori\")\nclass RiverEncoding(tf.keras.layers.Layer):\n    \"\"\"Encode separately padded pre/post-riichi rivers with shared weights.\"\"\"\n\n    def __init__(self, **kwargs):\n        super().__init__(**{**kwargs, \"autocast\": False})\n        self.event_attention = river_attention.RiverAttention(\n            dtype=self.dtype_policy\n        )\n        self.fields = tuple(\n            name.removeprefix(\"river_pre_\")\n            for name in input_features.NEURAL_INPUTS\n            if name.startswith(\"river_pre_\")\n            and name not in (\"river_pre_tile_id\", \"river_pre_valid\")\n        )\n        self.metadata_features = input_features.SemanticFields(\n            [\"river_pre_\" + name for name in self.fields],\n            dtype=self.dtype_policy,\n        )\n        self.tokens = tf.keras.layers.Dense(\n            64, activation=\"gelu\", dtype=self.dtype_policy\n        )\n        self.convolutions = [\n            tf.keras.layers.Conv1D(\n                filters=64,\n                kernel_size=3,\n                padding=\"same\",\n                dilation_rate=dilation,\n                dtype=self.dtype_policy,\n            )\n            for dilation in (1, 2, 4)\n        ]\n        self.normalizations = [\n            tf.keras.layers.LayerNormalization(dtype=self.dtype_policy)\n            for _ in self.convolutions\n        ]\n        self.projection = tf.keras.layers.Dense(\n            64, activation=\"gelu\", dtype=self.dtype_policy\n        )\n\n    def build(self, input_shape):\n        self.event_attention.build((None, 32, 64))\n        self.tokens.build(\n            (\n                None,\n                32,\n                input_features.TILE_WIDTH\n                + sum(\n                    input_features.field_width(\"river_pre_\" + name)\n                    for name in self.fields\n                ),\n            )\n        )\n        for convolution, normalization in zip(\n            self.convolutions, self.normalizations\n        ):\n            convolution.build((None, 32, 64))\n            normalization.build((None, 32, 64))\n        self.projection.build((None, 33 * 64))\n        super().build(input_shape)\n\n    def call(self, inputs):\n        return self.encode(\n            {\n                name: value\n                for name, value in inputs.items()\n                if name.startswith((\"river_pre_\", \"river_post_\"))\n                or name == \"tile_identity\"\n            }\n        )\n\n    def encode(self, inputs):\n        rivers = {\n            name: tf.stack(\n                [\n                    inputs[\"river_pre_\" + name],\n                    (\n                        tf.zeros_like(inputs[\"river_pre_riichi\"])\n                        if name == \"riichi\"\n                        else inputs[\"river_post_\" + name]\n                    ),\n                ],\n                axis=2,\n            )\n            for name in (\"tile_id\", \"valid\", *self.fields)\n        }\n        mask = tf.reshape(\n            tf.cast(rivers[\"valid\"], self.compute_dtype), (-1, 32, 1)\n        )\n        metadata = tf.concat(\n            list(\n                self.metadata_features(\n                    {\n                        \"river_pre_\" + name: value\n                        for name, value in rivers.items()\n                    }\n                ).values()\n            ),\n            -1,\n        )\n        values = tf.reshape(\n            tf.concat(\n                [\n                    tf.cast(\n                        input_features.tile_features(\n                            rivers[\"tile_id\"], inputs[\"tile_identity\"]\n                        ),\n                        self.compute_dtype,\n                    ),\n                    tf.cast(metadata, self.compute_dtype),\n                ],\n                axis=-1,\n            ),\n            (\n                -1,\n                32,\n                input_features.TILE_WIDTH\n                + sum(\n                    input_features.field_width(\"river_pre_\" + name)\n                    for name in self.fields\n                ),\n            ),\n        )\n        values = self.tokens(values) * mask\n        # All positions are already observed. Mask every block so padding\n        # cannot feed activations back into the observed river boundary.\n        for convolution, normalization in zip(\n            self.convolutions, self.normalizations\n        ):\n            values = (\n                tf.nn.gelu(normalization(values + convolution(values))) * mask\n            )\n        values = self.event_attention(values, mask)\n        # Shared summaries retain each opponent's pre/post-riichi history.\n        # Empty rivers remain identical regardless of their storage slot.\n        occupied = tf.reduce_any(mask > 0, axis=1)\n        maximum = tf.where(\n            occupied,\n            tf.reduce_max(tf.where(mask > 0, values, -1e4), axis=1),\n            tf.zeros_like(values[:, 0]),\n        )\n        local = tf.concat(\n            [\n                tf.math.divide_no_nan(\n                    tf.reduce_sum(values, axis=1),\n                    tf.reduce_sum(mask, axis=1),\n                ),\n                maximum,\n            ],\n            axis=-1,\n        )\n        encoded = self.projection(\n            tf.concat([tf.reshape(values, (-1, 32 * 64)), maximum], axis=-1)\n        ) * tf.cast(occupied, self.compute_dtype)\n        return (\n            tf.reshape(encoded, (-1, 384)),\n            tf.reshape(local, (-1, 3, 256)),\n        )\n\n\ndef projected_draws(inputs, selected):\n    \"\"\"Ordinary draw counts and last drawer if this action takes effect.\"\"\"\n    remaining = tf.cast(\n        tf.gather(inputs[\"live_wall_count\"], selected[:, 0]), tf.int32\n    ) - tf.cast(selected[:, 1] >= 261, tf.int32)\n    source = tf.where(\n        (tf.gather(inputs[\"decision_phase\"], selected[:, 0]) == 1)\n        & (selected[:, 1] == 111),\n        tf.cast(tf.gather(inputs[\"trigger_source\"], selected[:, 0]), tf.int32),\n        0,\n    )\n    return tf.stack(\n        [\n            tf.cast(\n                (\n                    remaining[:, None]\n                    + 3\n                    - (tf.range(4)[None] - source[:, None] - 1) % 4\n                )\n                // 4,\n                tf.float32,\n            ),\n            tf.one_hot((source + remaining) % 4, 4)\n            * tf.cast(remaining > 0, tf.float32)[:, None],\n        ],\n        axis=-1,\n    )\n\n\ndef last_draw_context(inputs, selected):\n    \"\"\"Current last-tile flags and projected seats without further calls.\n\n    Seat projections describe ordinary live-wall draws, excluding rinshan.\n    A kan consumes one live-wall tile for its replacement draw. A response\n    pass continues after the discarder; our chii/pon continues after us.\n    \"\"\"\n    wall = tf.cast(\n        tf.gather(inputs[\"live_wall_count\"], selected[:, 0]), tf.int32\n    )\n    response = tf.gather(inputs[\"decision_phase\"], selected[:, 0]) == 1\n    source = tf.cast(\n        tf.gather(inputs[\"trigger_source\"], selected[:, 0]), tf.int32\n    )\n    return tf.concat(\n        [\n            tf.cast(\n                tf.stack(\n                    [\n                        (wall == 0)\n                        & (\n                            tf.gather(\n                                inputs[\"current_draw_valid\"], selected[:, 0]\n                            )\n                            > 0\n                        )\n                        & (\n                            tf.gather(inputs[\"rinshan_state\"], selected[:, 0])\n                            == 0\n                        ),\n                        (wall == 0) & response,\n                    ],\n                    axis=-1,\n                ),\n                tf.float32,\n            ),\n            tf.one_hot((tf.where(response, source, 0) + wall) % 4, 4)\n            * tf.cast(wall > 0, tf.float32)[:, None],\n            projected_draws(inputs, selected)[..., 1],\n        ],\n        axis=-1,\n    )\n\n\n@tf.keras.utils.register_keras_serializable(package=\"nejimakidori\")\nclass DecisionCandidates(tf.keras.layers.Layer):\n    \"\"\"Local discard/riichi, pass and kan candidates in joint action IDs.\"\"\"\n\n    def __init__(self, **kwargs):\n        super().__init__(**{**kwargs, \"autocast\": False})\n        self.context = tf.keras.layers.Dense(\n            192, activation=\"gelu\", dtype=self.dtype_policy\n        )\n        self.projection = tf.keras.layers.Dense(\n            384, activation=\"gelu\", dtype=self.dtype_policy\n        )\n\n    def build(self, input_shape):\n        self.context.build(input_shape[2])\n        self.projection.build(\n            (None, input_shape[1][-1] + 241 + input_features.TILE_WIDTH)\n        )\n        super().build(input_shape)\n\n    def call(self, values):\n        inputs, bank, board = values\n        batch = tf.shape(board)[0]\n        local_ids = tf.constant(list(range(112)) + list(range(260, 295)))\n        indices = tf.gather(\n            actions.candidate_hand_indices(inputs), local_ids, axis=1\n        )\n        cuts = tf.broadcast_to(tf.range(37)[None], (batch, 37))\n        tiles = tf.concat(\n            [\n                cuts,\n                cuts,\n                cuts,\n                tf.fill((batch, 1), 37),\n                tf.fill((batch, 1), 37),\n                tf.broadcast_to(tf.range(34)[None], (batch, 34)),\n            ],\n            axis=1,\n        )\n        discard_values = tf.concat(\n            [\n                tf.cast(\n                    inputs[\"discard_action_all_shanten\"][..., None], tf.float32\n                ),\n                tf.cast(\n                    inputs[\"discard_action_all_ukeire_count\"][..., None],\n                    tf.float32,\n                ),\n            ],\n            axis=-1,\n        )\n        structural = tf.pad(\n            tf.tile(discard_values, [1, 3, 1]), [[0, 0], [0, 36], [0, 0]]\n        )\n        # Local action kind and declaration flag; no call-discard slots.\n        flags = tf.constant(\n            [[0, 0]] * 37\n            + [[1, declare] for declare in range(2) for _ in range(37)]\n            + [[2, 0]]\n            + [[6, 0]]\n            + [[5, 0]] * 34,\n            dtype=tf.float32,\n        )\n        scoring_rows = tf.constant(list(range(37)) + list(range(110)))\n        local_open = (inputs[\"candidate_meld_tiles\"] < 34) & (\n            inputs[\"candidate_meld_types\"] != 3\n        )\n        opened = tf.gather(\n            tf.reduce_any(local_open, axis=-1),\n            tf.cast(indices, tf.int32),\n            batch_dims=1,\n        )\n        open_axis = tf.one_hot(tf.cast(opened, tf.int32), 2)\n        structural = tf.concat(\n            [\n                structural,\n                tf.reshape(\n                    tf.gather(\n                        inputs[\"action_win_value_range\"], scoring_rows, axis=1\n                    )[:, :, None]\n                    * open_axis[..., None, None],\n                    (batch, 147, 8),\n                ),\n                tf.cast(\n                    tf.reshape(\n                        tf.gather(\n                            inputs[\"action_win_value_valid\"],\n                            scoring_rows,\n                            axis=1,\n                        )[:, :, None]\n                        * tf.cast(open_axis[..., None], tf.int8),\n                        (batch, 147, 4),\n                    ),\n                    tf.float32,\n                ),\n                tf.cast(\n                    tf.gather(\n                        inputs[\"action_value_eligible\"], scoring_rows, axis=1\n                    )[..., None],\n                    tf.float32,\n                ),\n                tf.cast(\n                    tf.gather(\n                        inputs[\"action_open_yaku_restricted\"],\n                        scoring_rows,\n                        axis=1,\n                    ),\n                    tf.float32,\n                ),\n            ],\n            axis=-1,\n        )\n        # Action analysis belongs to each alternative, not observed-state\n        # inference. Calls read these fields from their accepted child state.\n        discard_analysis = tf.math.asinh(\n            tf.concat(\n                [\n                    tf.cast(inputs[name], tf.float32)[..., None]\n                    for name in (\n                        \"discard_action_normal_shanten\",\n                        \"discard_action_normal_ukeire_count\",\n                    )\n                ]\n                + [tf.cast(inputs[\"discard_retained_genbutsu\"], tf.float32)],\n                axis=-1,\n            )\n        )\n        action_analysis = tf.concat(\n            [\n                tf.pad(\n                    tf.tile(discard_analysis, [1, 3, 1]),\n                    [[0, 0], [0, 36], [0, 0]],\n                ),\n                tf.pad(inputs[\"kan_efficiency\"], [[0, 0], [113, 0], [0, 0]]),\n                tf.cast(\n                    tf.concat(\n                        [\n                            inputs[\"discard_abort\"][:, 0],\n                            tf.reshape(inputs[\"discard_abort\"], (batch, 74)),\n                            tf.zeros((batch, 36), tf.int8),\n                        ],\n                        1,\n                    ),\n                    tf.float32,\n                )[..., None],\n            ],\n            -1,\n        )\n        masks = actions.legal_choices(inputs)\n        local_selected = tf.cast(\n            tf.where(\n                tf.concat(\n                    [\n                        masks[\"discard_policy_logits\"],\n                        masks[\"riichi_policy_logits\"],\n                        masks[\"response_policy_logits\"][:, :1],\n                        masks[\"kan_action_logits\"],\n                    ],\n                    axis=1,\n                )\n            ),\n            tf.int32,\n        )\n        selected = tf.stack(\n            [local_selected[:, 0], tf.gather(local_ids, local_selected[:, 1])],\n            axis=1,\n        )\n        hands = tf.stack(\n            [\n                selected[:, 0],\n                tf.cast(tf.gather_nd(indices, local_selected), tf.int32),\n            ],\n            axis=1,\n        )\n        return (\n            self.projection(\n                tf.concat(\n                    [\n                        tf.cast(value, self.compute_dtype)\n                        for value in [\n                            tf.gather_nd(bank, hands),\n                            tf.math.asinh(\n                                tf.cast(\n                                    tf.gather_nd(\n                                        inputs[\"candidate_yaku_shanten\"], hands\n                                    ),\n                                    tf.float32,\n                                )\n                            ),\n                            tf.gather_nd(action_analysis, local_selected),\n                            input_features.tile_features(\n                                tf.gather_nd(tiles, local_selected),\n                                inputs[\"tile_identity\"],\n                            ),\n                            tf.cast(\n                                (tf.gather_nd(tiles, local_selected) >= 34)\n                                & (tf.gather_nd(tiles, local_selected) < 37),\n                                tf.float32,\n                            )[:, None],\n                            tf.math.asinh(\n                                tf.gather_nd(\n                                    structural[..., :10], local_selected\n                                )\n                            ),\n                            tf.gather_nd(structural[..., 10:], local_selected),\n                            tf.one_hot(\n                                tf.cast(\n                                    tf.gather(\n                                        flags[:, 0], local_selected[:, 1]\n                                    ),\n                                    tf.int32,\n                                ),\n                                7,\n                            ),\n                            tf.gather(flags[:, 1:2], local_selected[:, 1]),\n                            last_draw_context(inputs, selected),\n                            tf.gather(self.context(board), selected[:, 0]),\n                        ]\n                    ],\n                    axis=-1,\n                )\n            ),\n            selected,\n            tf.concat(\n                [\n                    tf.gather_nd(structural, local_selected),\n                    tf.cast(tf.gather_nd(tiles, local_selected), tf.float32)[\n                        :, None\n                    ],\n                ],\n                axis=-1,\n            ),\n        )\n\n\ndef board_stack(hidden, prefix):\n    \"\"\"Independent upper board representation over shared lower encodings.\"\"\"\n    hidden = tf.keras.layers.Dense(\n        512, activation=\"gelu\", name=f\"{prefix}_fusion\", dtype=\"mixed_bfloat16\"\n    )(hidden)\n    for block in range(3):\n        residual = tf.keras.layers.LayerNormalization(\n            name=f\"{prefix}_block_{block}_norm\", dtype=\"mixed_bfloat16\"\n        )(hidden)\n        residual = tf.keras.layers.Dense(\n            576,\n            activation=\"gelu\",\n            name=f\"{prefix}_block_{block}_expand\",\n            dtype=\"mixed_bfloat16\",\n        )(residual)\n        residual = tf.keras.layers.Dense(\n            576,\n            activation=\"gelu\",\n            name=f\"{prefix}_block_{block}_hidden\",\n            dtype=\"mixed_bfloat16\",\n        )(residual)\n        residual = tf.keras.layers.Dense(\n            512, name=f\"{prefix}_block_{block}_contract\", dtype=\"mixed_bfloat16\"\n        )(residual)\n        hidden = tf.keras.layers.Add(\n            name=f\"{prefix}_block_{block}_add\", dtype=\"mixed_bfloat16\"\n        )([hidden, residual])\n    hidden = tf.keras.layers.Dense(\n        512, activation=\"gelu\", name=f\"{prefix}_state\", dtype=\"mixed_bfloat16\"\n    )(hidden)\n    hidden = tf.keras.layers.LayerNormalization(\n        center=False,\n        scale=False,\n        epsilon=1e-5,\n        dtype=\"float32\",\n        name=f\"{prefix}_state_normalized\",\n    )(hidden)\n    return hidden\n\n\ndef encode_inputs():\n    inputs = {\n        name: tf.keras.Input(\n            shape=definition[\"shape\"], dtype=definition[\"dtype\"], name=name\n        )\n        for name, definition in _native_collection.INPUTS.items()\n    }\n    neural = input_features.NeuralFeatures(\n        name=\"neural_features\", dtype=\"float32\"\n    )(inputs)\n    rivers, critic_rivers = RiverEncoding(\n        name=\"river_encoder\", dtype=\"mixed_bfloat16\"\n    )(neural)\n    context = TableContext(name=\"table_context\", dtype=\"mixed_bfloat16\")(\n        tf.keras.layers.Concatenate(dtype=\"mixed_bfloat16\")(\n            [\n                rivers,\n                semantic_features(\n                    input_features.SemanticFields(\n                        TABLE_INPUTS,\n                        dtype=\"mixed_bfloat16\",\n                        name=\"table_features\",\n                    )(neural)\n                ),\n            ]\n        )\n    )\n    bank = HandBank(name=\"hand_bank\", dtype=\"mixed_bfloat16\")([neural, context])\n    joint = tf.keras.layers.Concatenate(dtype=\"mixed_bfloat16\")(\n        [context, bank[:, 0]]\n    )\n    actor_board = board_stack(tf.keras.ops.stop_gradient(joint), \"actor_board\")\n    hidden = board_stack(joint, \"board\")\n    candidates, selected, structure = DecisionCandidates(\n        name=\"decision_candidates\", dtype=\"mixed_bfloat16\"\n    )([neural, bank, hidden])\n    candidates = tf.keras.layers.LayerNormalization(\n        center=False,\n        scale=False,\n        epsilon=1e-5,\n        dtype=\"float32\",\n        name=\"candidate_state_normalized\",\n    )(candidates)\n    return (\n        inputs,\n        actor_board,\n        hidden,\n        candidates,\n        selected,\n        structure,\n        critic_rivers,\n    )\n",
      "sha256": "147cc852149c8a392e7479a5de524ac7ae1f764cc3de9c31261705b25efe44ff"
    },
    {
      "path": "model/export.py",
      "text": "\"\"\"Export the joint actor, board heads and action payment critic.\"\"\"\n\nimport argparse\nimport hashlib\nimport json\nimport pathlib\nimport shutil\n\nimport numpy\nimport tensorflow as tf\n\nfrom log_dataset import call_states, scoring, training_data\nfrom model import actions, critic, joint_settlement\nfrom model import network as joint_network\nfrom model import outcomes\n\n\nclass ServingModel(tf.Module):\n    def __init__(self, network):\n        super().__init__()\n        # Track weights without exporting Keras' training-only call signatures.\n        self.network = self._no_dependency(network)\n        self.parameters = [variable.value for variable in network.variables]\n\n    @tf.function\n    def policy(self, **features):\n        outputs = self.network.actor(features, training=False)\n        return {name: outputs[name] for name in actions.TRAIN_POLICY_HEADS}\n\n    @tf.function\n    def serve(self, **features):\n        chunk_size = 4\n        outputs = self.network.actor(features, training=False)\n        state = self.network.candidate_context(features, outputs)\n        active = critic.active_candidates(features, outputs[\"selected\"])\n        selected = tf.boolean_mask(outputs[\"selected\"], active)\n        state = tf.boolean_mask(state, active)\n        public = joint_settlement.public_inputs(features)\n        candidate_public = critic.public_inputs(features, selected)\n        probability = tf.TensorArray(\n            tf.float32,\n            size=0,\n            dynamic_size=True,\n            element_shape=[\n                None,\n                len(scoring.CELLS),\n                len(outcomes.PAYMENT_VALUES) + 4,\n            ],\n        )\n        review_outcomes = tf.TensorArray(\n            tf.float32, size=0, dynamic_size=True, element_shape=[None, 7]\n        )\n        final_ranks = tf.TensorArray(\n            tf.float32, size=0, dynamic_size=True, element_shape=[None, 4]\n        )\n        points = tf.TensorArray(\n            tf.float32, size=0, dynamic_size=True, element_shape=[None, 4]\n        )\n        settlement = tf.TensorArray(\n            tf.float32, size=0, dynamic_size=True, element_shape=[None, 2, 5]\n        )\n        for begin in tf.range(0, tf.shape(selected)[0], chunk_size):\n            rows = selected[begin : begin + chunk_size, 0]\n            inputs = {\n                \"state\": state[begin : begin + chunk_size],\n                **{\n                    name: tf.gather(value, rows)\n                    for name, value in public.items()\n                },\n            }\n            inputs.update(\n                {\n                    name: value[begin : begin + chunk_size]\n                    for name, value in candidate_public.items()\n                }\n            )\n            forecast = self.network.critic.joint_distributions(inputs)\n            _, final_probability = joint_settlement.continuation_forecast(\n                scores=forecast[\"joint_scores\"],\n                ranks=forecast[\"joint_ranks\"],\n                support=forecast[\"joint_support\"],\n                dealer=inputs[\"dealer\"],\n                hand_number=inputs[\"hand_number\"],\n                pot=inputs[\"pot\"],\n            )\n            # Mutually exclusive endings from the actor's perspective.\n            categories = tf.constant(\n                [\n                    (\n                        6\n                        if kind == 3 or (kind == 0 and mask.bit_count() == 3)\n                        else (\n                            2\n                            if kind == 2 and draw & 1\n                            else (\n                                3\n                                if kind == 2\n                                else (\n                                    1\n                                    if mask & 1\n                                    else (\n                                        0\n                                        if kind == 0 and payer == 0\n                                        else 4 if kind == 1 else 5\n                                    )\n                                )\n                            )\n                        )\n                    )\n                    for kind, payer, mask, draw in joint_settlement.EVENTS\n                ]\n            )\n            review_outcomes = review_outcomes.write(\n                begin // chunk_size,\n                tf.einsum(\n                    \"ns,nsc->nc\",\n                    tf.reduce_sum(forecast[\"joint_probability\"], axis=-1),\n                    tf.one_hot(\n                        tf.gather(\n                            categories, forecast[\"joint_support\"][..., 5]\n                        ),\n                        7,\n                    ),\n                ),\n            )\n            probability = probability.write(\n                begin // chunk_size, forecast[\"payment_probability\"]\n            )\n            final_ranks = final_ranks.write(\n                begin // chunk_size,\n                joint_settlement.expectation(\n                    forecast[\"joint_probability\"], final_probability\n                ),\n            )\n            points = points.write(\n                begin // chunk_size,\n                joint_settlement.expectation(\n                    forecast[\"joint_probability\"],\n                    forecast[\"joint_scores\"] - inputs[\"scores\"][:, None, None],\n                ),\n            )\n            settlement = settlement.write(\n                begin // chunk_size,\n                tf.stack(joint_settlement.settlement_moments(forecast), axis=1),\n            )\n        probability = probability.concat()\n        weights = tf.gather_nd(\n            critic.candidate_probabilities(features, outputs), selected\n        )\n        count = tf.shape(features[\"decision_phase\"])[0]\n        tf.debugging.assert_near(\n            tf.math.unsorted_segment_sum(weights, selected[:, 0], count),\n            tf.ones(count),\n            atol=1e-5,\n        )\n        mixture = tf.math.unsorted_segment_sum(\n            probability * weights[:, None, None], selected[:, 0], count\n        )\n        moments = tf.math.unsorted_segment_sum(\n            settlement.concat() * weights[:, None, None], selected[:, 0], count\n        )\n        return {\n            **{name: outputs[name] for name in actions.SERVING_ACTOR_OUTPUTS},\n            \"payment_values\": joint_settlement.payment_values(public),\n            \"final_placement_probabilities\": tf.math.unsorted_segment_sum(\n                final_ranks.concat() * weights[:, None], selected[:, 0], count\n            ),\n            \"review_outcome_probabilities\": tf.math.unsorted_segment_sum(\n                review_outcomes.concat() * weights[:, None],\n                selected[:, 0],\n                count,\n            ),\n            \"settlement_mean\": moments[:, 0],\n            \"settlement_variance\": tf.maximum(\n                moments[:, 1] - moments[:, 0] ** 2, 0\n            ),\n            \"critic_expected_points\": points.concat(),\n            \"terminal_payment_probabilities\": tf.einsum(\n                \"ncv,ctpr->ntprv\",\n                mixture,\n                tf.constant(\n                    numpy.eye(64, dtype=numpy.float32)[\n                        numpy.ravel_multi_index(\n                            numpy.array(scoring.CELLS).T, (4, 4, 4)\n                        )\n                    ].reshape(-1, 4, 4, 4)\n                ),\n            )\n            + tf.cast(~tf.constant(outcomes.PAYMENT_CELLS), tf.float32)[\n                None, ..., None\n            ]\n            * tf.one_hot(1, len(outcomes.PAYMENT_VALUES) + 4),\n            \"critic_action_indices\": selected,\n        }\n\n\ndef build_network(inputs):\n    \"\"\"Build every actor and critic variable before strict weight loading.\"\"\"\n    network = joint_network.JointPolicyPayment()\n    outputs = network.actor(inputs, training=False)\n    state = network.candidate_context(inputs, outputs)\n    network.critic.joint_distributions(\n        {\n            **{\n                name: tf.gather(value, outputs[\"selected\"][:1, 0])\n                for name, value in joint_settlement.public_inputs(\n                    inputs\n                ).items()\n            },\n            \"state\": state[:1],\n            **critic.public_inputs(inputs, outputs[\"selected\"][:1]),\n        }\n    )\n    network.built = True\n    return network\n\n\ndef load_network(weights, inputs):\n    network = build_network(inputs)\n    network.load_weights(weights)\n    network.compile_training()\n    return network\n\n\ndef run(args):\n    from training import frozen_policy, self_play\n\n    for device in tf.config.list_physical_devices(\"GPU\"):\n        tf.config.experimental.set_memory_growth(device, True)\n    if args.data is None:\n        inputs = self_play.initial_features(args.self_play_seed)\n    else:\n        inputs = training_data.parse_batch(\n            next(\n                iter(\n                    training_data.dataset(\n                        root=args.data,\n                        partition=\"train\",\n                        batch_size=8,\n                    )\n                )\n            )\n        )[0]\n    network = load_network(args.weights, inputs)\n    module = ServingModel(network)\n    signature = module.serve.get_concrete_function(**call_states.input_specs())\n    root = pathlib.Path(args.output)\n    pending = root.with_name(root.name + \".pending\")\n    if pending.exists():\n        shutil.rmtree(pending)\n    pending.mkdir(parents=True)\n    tf.saved_model.save(\n        module,\n        str(pending / \"saved_model\"),\n        signatures={\n            \"serving_default\": signature,\n            \"policy\": module.policy.get_concrete_function(\n                **signature.structured_input_signature[1]\n            ),\n        },\n    )\n    loaded = tf.saved_model.load(str(pending / \"saved_model\"))\n    actual = loaded.signatures[\"serving_default\"](**inputs)\n    expected = module.serve(**inputs)\n    policy = loaded.signatures[\"policy\"](**inputs)\n    for name, value in policy.items():\n        numpy.testing.assert_allclose(value, actual[name], rtol=1e-5, atol=1e-5)\n    errors = {}\n    for name in expected:\n        numpy.testing.assert_allclose(\n            actual[name], expected[name], rtol=1e-5, atol=1e-5\n        )\n        errors[name] = float(\n            tf.reduce_max(tf.abs(actual[name] - expected[name]))\n        )\n    for name in (\n        \"terminal_payment_probabilities\",\n        \"review_outcome_probabilities\",\n        \"final_placement_probabilities\",\n    ):\n        numpy.testing.assert_allclose(\n            tf.reduce_sum(actual[name], -1), 1, rtol=1e-4, atol=1e-5\n        )\n    for value in actual.values():\n        assert numpy.isfinite(value.numpy()).all()\n    with pathlib.Path(args.weights).open(\"rb\") as stream:\n        weight_hash = hashlib.file_digest(stream, \"sha256\").hexdigest()\n    (pending / \"export-verification.json\").write_text(\n        json.dumps(\n            {\n                \"passed\": True,\n                \"weights\": pathlib.Path(args.weights).name,\n                \"weight_sha256\": weight_hash,\n                \"output_max_errors\": errors,\n                \"critic_candidates\": int(\n                    tf.shape(actual[\"critic_action_indices\"])[0]\n                ),\n                \"payment_forecast\": \"active_policy_mixture_honba_free\",\n                \"policy_signature_matches_full_export\": True,\n            },\n            indent=2,\n        )\n        + \"\\n\"\n    )\n\n    for name in (\"model\", \"training\", \"log_dataset\"):\n        frozen_policy.freeze_source(\n            pathlib.Path(__file__).parents[1] / name,\n            pending / \"source\" / name,\n        )\n    shutil.copy2(\n        pathlib.Path(__file__).parents[1] / \"requirements.txt\",\n        pending / \"source/requirements.txt\",\n    )\n    pending.rename(root)\n\n\ndef main():\n    parser = argparse.ArgumentParser(description=__doc__)\n    parser.add_argument(\"--weights\", required=True)\n    source = parser.add_mutually_exclusive_group(required=True)\n    source.add_argument(\"--data\")\n    source.add_argument(\"--self-play-seed\", type=int)\n    parser.add_argument(\"--output\", required=True)\n    run(parser.parse_args())\n\n\nif __name__ == \"__main__\":\n    main()\n",
      "sha256": "b2ae959aed0336803b7fc05ac59cae3a9b1ba14dbd93ab231fb1190e81d4134c"
    },
    {
      "path": "model/inference.py",
      "text": "\"\"\"Strict SavedModel loading and batched inference.\"\"\"\n\nimport dataclasses\nimport hashlib\nimport pathlib\nimport time\n\nimport numpy\nimport tensorflow as tf\n\nfrom log_dataset import call_states, scoring, shanten\nfrom model import actions, outcomes\n\n\n@dataclasses.dataclass\nclass Inference:\n    predictions: list\n    latency_ms: float\n    metadata: dict\n    outputs: dict\n\n    def as_dict(self):\n        return {\n            \"predictions\": self.predictions,\n            \"latency_ms\": self.latency_ms,\n            \"metadata\": self.metadata,\n        }\n\n\nclass Predictor:\n    max_batch_size = 256\n\n    def __init__(self, saved_model):\n        self.model_path = pathlib.Path(saved_model)\n        self.module = tf.saved_model.load(str(saved_model))\n        self.function = self.module.signatures[\"serving_default\"]\n        self.input_specs = {\n            name: (tuple(value[\"shape\"]), value[\"dtype\"])\n            for name, value in call_states.INPUTS.items()\n        }\n        signature = self.function.structured_input_signature[1]\n        if signature != call_states.input_specs():\n            raise ValueError(\"SavedModel inputs do not match feature producer\")\n        self.output_specs = self.function.structured_outputs\n        expected = {\n            **actions.SERVING_ACTOR_OUTPUTS,\n            \"terminal_payment_probabilities\": [\n                4,\n                4,\n                4,\n                len(outcomes.PAYMENT_VALUES) + 4,\n            ],\n            \"payment_values\": [len(outcomes.PAYMENT_VALUES) + 4],\n            \"final_placement_probabilities\": [4],\n            \"review_outcome_probabilities\": [7],\n            \"settlement_mean\": [5],\n            \"settlement_variance\": [5],\n            \"critic_expected_points\": [4],\n            \"critic_action_indices\": [2],\n        }\n        if self.output_specs.keys() != expected.keys():\n            raise ValueError(\"SavedModel must include joint actor and critic\")\n        for name, shape in expected.items():\n            dtype = tf.int32 if name == \"critic_action_indices\" else tf.float32\n            if (\n                self.output_specs[name].shape.as_list() != [None, *shape]\n                or self.output_specs[name].dtype != dtype\n            ):\n                raise ValueError(f\"Incorrect serving output contract: {name}\")\n        digest = hashlib.sha256()\n        for path in sorted(self.model_path.rglob(\"*\")):\n            if path.is_file():\n                digest.update(str(path.relative_to(self.model_path)).encode())\n                with path.open(\"rb\") as source:\n                    while block := source.read(1024 * 1024):\n                        digest.update(block)\n        self.metadata = {\n            \"revision\": digest.hexdigest(),\n            \"model_contract\": \"joint_policy_payment_critic\",\n            \"payment_forecast\": \"active_policy_mixture_honba_free\",\n            \"payment_events\": \"coexisting_ron_claims_tsumo_exhaustive_abort\",\n            \"bank_payment\": \"accepted_deposits_and_priority_pot_award\",\n            \"critic_action_ranges\": {\n                \"discard\": [0, 37],\n                \"riichi\": [37, 111],\n                \"response_without_daiminkan\": [111, 260],\n                \"kan\": [260, 295],\n            },\n            \"daiminkan_action\": \"261 + trigger_tile_id\",\n            \"payment_types\": list(outcomes.PAYMENT_TYPES),\n            \"tile_names\": list(shanten.TILE_NAMES),\n            \"completion_yaku_names\": list(scoring.NAMES),\n            \"completion_modes\": [\"ron\", \"tsumo\"],\n            \"completion_score_states\": list(outcomes.SCORE_STATES),\n            \"completion_score_seats\": [\"self\"],\n            \"opponent_tile_target\": \"structural_ukeire_by_shanten\",\n            \"opponent_shanten_classes\": [0, 1, 2, \"3+\"],\n            \"opponent_wait_target\": \"joint_tenpai_and_structural_wait\",\n        }\n\n    def tensors(self, instances):\n        if (\n            not isinstance(instances, list)\n            or not 1 <= len(instances) <= self.max_batch_size\n        ):\n            raise ValueError(\n                f\"instances must contain 1 to {self.max_batch_size} \"\n                \"feature objects\"\n            )\n        rows = []\n        for instance in instances:\n            if (\n                not isinstance(instance, dict)\n                or instance.keys() != self.input_specs.keys()\n            ):\n                raise ValueError(\"feature keys do not match model contract\")\n            count = len(instance[\"post_call_option\"])\n            row = {}\n            for name, (shape, dtype) in self.input_specs.items():\n                expected = tuple(\n                    count if size is None else size for size in shape\n                )\n                row[name] = numpy.asarray(instance[name], dtype=dtype)\n                # Empty JSON arrays carry no trailing dimension information.\n                if name.startswith(\"post_call_\") and count == 0:\n                    row[name] = row[name].reshape(expected)\n                if row[name].shape != expected:\n                    raise ValueError(\n                        f\"incorrect shape for {name}: expected {expected}\"\n                    )\n            if (\n                numpy.any(row[\"post_call_owner\"] != 0)\n                or numpy.any(\n                    (row[\"post_call_option\"] < 0)\n                    | (row[\"post_call_option\"] > 3)\n                )\n                or len(numpy.unique(row[\"post_call_option\"])) != count\n            ):\n                raise ValueError(\"invalid per-instance call branches\")\n            if int(instance[\"decision_phase\"]) not in (0, 1, 2, 3, 4):\n                raise ValueError(\"Inference requires a discretionary decision\")\n            rows.append(row)\n        return {\n            name: tf.convert_to_tensor(value, dtype=self.input_specs[name][1])\n            for name, value in call_states.batch(rows).items()\n        }\n\n    def predict(self, **features):\n        return self.function(**features)\n\n    def infer(self, instances):\n        start = time.perf_counter()\n        outputs = self.predict(**self.tensors(instances))\n        probabilities = {}\n        for name, logits in outputs.items():\n            if not name.endswith(\"logits\"):\n                continue\n            probabilities[name.replace(\"logits\", \"probabilities\")] = (\n                tf.nn.softmax(logits, -1).numpy()\n            )\n        probabilities[\"terminal_payment_probabilities\"] = outputs[\n            \"terminal_payment_probabilities\"\n        ].numpy()\n        probabilities[\"final_placement_probabilities\"] = outputs[\n            \"final_placement_probabilities\"\n        ].numpy()\n        probabilities[\"review_outcome_probabilities\"] = outputs[\n            \"review_outcome_probabilities\"\n        ].numpy()\n        payment_values = outputs[\"payment_values\"].numpy()\n        action_points = outputs[\"critic_expected_points\"].numpy()\n        selected = outputs[\"critic_action_indices\"].numpy()\n        settlement_mean = outputs[\"settlement_mean\"].numpy()\n        settlement_variance = outputs[\"settlement_variance\"].numpy()\n        predictions = []\n        for index in range(len(instances)):\n            row = {\n                name: values[index].tolist()\n                for name, values in probabilities.items()\n            }\n            row[\"action_values\"] = [\n                {\n                    \"action\": int(selected[action, 1]),\n                    \"expected_points\": action_points[action].tolist(),\n                }\n                for action in numpy.flatnonzero(selected[:, 0] == index)\n            ]\n            row[\"structured_outcome\"] = {\n                \"format\": \"typed_payments\",\n                \"conditioning\": \"active_policy_mixture\",\n                \"honba_included\": False,\n                \"types\": list(outcomes.PAYMENT_TYPES),\n                \"probabilities\": row[\"terminal_payment_probabilities\"],\n                \"values\": payment_values[index].tolist(),\n                \"settlement_mean\": settlement_mean[index].tolist(),\n                \"settlement_stddev\": numpy.sqrt(\n                    settlement_variance[index]\n                ).tolist(),\n                \"uncertainty\": \"joint hand settlement\",\n            }\n            predictions.append(row)\n        return Inference(\n            predictions,\n            (time.perf_counter() - start) * 1000,\n            self.metadata,\n            outputs,\n        )\n",
      "sha256": "354feb0b2a2f7fb19715cd2302a5e13958c3647ee6207f4dfb8e5c143e82a573"
    },
    {
      "path": "model/input_features.py",
      "text": "\"\"\"Lossless semantic expansion of compact model inputs.\"\"\"\n\nimport tensorflow as tf\n\nfrom log_dataset import _native_collection\n\nTILE_WIDTH = 8\n\n# Projection axes retain their semantic order independently of wire packing.\nNEURAL_INPUTS = {}\nfor name, spec in _native_collection.INPUTS.items():\n    if name == \"candidate_meld_tiles\":\n        NEURAL_INPUTS[\"candidate_melds\"] = {\n            \"shape\": [16, 34, 6],\n            \"dtype\": \"int8\",\n        }\n    elif name in (\n        \"candidate_meld_types\",\n        \"candidate_meld_red\",\n        \"nagashi_possible\",\n        \"pao_payer\",\n    ):\n        continue\n    elif name == \"last_tedashi_tile_id\":\n        NEURAL_INPUTS[name] = spec\n        NEURAL_INPUTS[\"last_tedashi_is_red\"] = {\"shape\": [4], \"dtype\": \"int8\"}\n    elif name == \"meld_tiles\":\n        for field in (\"meld_tile_ids\", \"meld_tile_red\", \"meld_tile_valid\"):\n            NEURAL_INPUTS[field] = {\"shape\": [4, 4, 4], \"dtype\": \"int8\"}\n    else:\n        NEURAL_INPUTS[name] = spec\n    if name == \"passed_unchanged_to_seat\":\n        NEURAL_INPUTS[\"blocker_counts\"] = {\"shape\": [34, 5], \"dtype\": \"int8\"}\n\n\ndef candidate_melds(inputs):\n    groups = tf.reduce_sum(\n        tf.one_hot(tf.cast(inputs[\"candidate_meld_tiles\"], tf.int32), 34)[\n            ..., None\n        ]\n        * tf.one_hot(tf.cast(inputs[\"candidate_meld_types\"], tf.int32), 5)[\n            ..., None, :\n        ],\n        axis=-3,\n    )\n    red = tf.linalg.matmul(\n        tf.cast(inputs[\"candidate_meld_red\"], tf.float32),\n        tf.one_hot([4, 13, 22], 34),\n    )\n    return tf.cast(tf.concat([groups, red[..., None]], -1), tf.int8)\n\n\ndef meld_tile_ids(inputs):\n    codes = tf.cast(inputs[\"meld_tiles\"], tf.int32)\n    return tf.cast(\n        tf.where(\n            codes < 37, tf.where(codes < 34, codes, 4 + 9 * (codes - 34)), 0\n        ),\n        tf.int8,\n    )\n\n\ndef meld_tile_red(inputs):\n    return tf.cast(\n        (inputs[\"meld_tiles\"] >= 34) & (inputs[\"meld_tiles\"] < 37), tf.int8\n    )\n\n\ndef meld_tile_valid(inputs):\n    return tf.cast(inputs[\"meld_tiles\"] < 37, tf.int8)\n\n\ndef last_tedashi_tile(inputs):\n    return tf.cast(\n        tf.one_hot(tf.cast(inputs[\"last_tedashi_tile_id\"], tf.int32), 37),\n        tf.int8,\n    )\n\n\ndef blocker_counts(inputs):\n    outside = ((), (0,), (0, 1), (1, 2), (2, 6), (6, 7), (7, 8), (8,), ())\n    return tf.cast(\n        tf.einsum(\n            \"st,bsc->btc\",\n            tf.constant(\n                [\n                    [\n                        float(\n                            source < 27\n                            and target // 9 == source // 9\n                            and target % 9 in outside[source % 9]\n                        )\n                        for target in range(34)\n                    ]\n                    for source in range(34)\n                ]\n            ),\n            tf.one_hot(\n                4 - tf.cast(inputs[\"known_unavailable_counts\"], tf.int32), 5\n            ),\n        ),\n        tf.int8,\n    )\n\n\ndef neural_features(inputs):\n    return {\n        **inputs,\n        \"candidate_melds\": candidate_melds(inputs),\n        \"last_tedashi_is_red\": tf.cast(\n            (inputs[\"last_tedashi_tile_id\"] >= 34)\n            & (inputs[\"last_tedashi_tile_id\"] < 37),\n            tf.int8,\n        ),\n        \"meld_tile_ids\": meld_tile_ids(inputs),\n        \"meld_tile_red\": meld_tile_red(inputs),\n        \"meld_tile_valid\": meld_tile_valid(inputs),\n        \"blocker_counts\": blocker_counts(inputs),\n    }\n\n\n@tf.keras.utils.register_keras_serializable(package=\"nejimakidori\")\nclass NeuralFeatures(tf.keras.layers.Layer):\n    \"\"\"Expand compact fields and project one shared one-hot tile vocabulary.\"\"\"\n\n    def __init__(self, **kwargs):\n        super().__init__(**{**kwargs, \"autocast\": False})\n        self.tile_projection = tf.keras.layers.Dense(\n            TILE_WIDTH, use_bias=False, dtype=\"float32\", name=\"tile_projection\"\n        )\n\n    def build(self, input_shape):\n        self.tile_projection.build((None, 34))\n        super().build(input_shape)\n\n    def call(self, inputs):\n        return {\n            **neural_features(inputs),\n            \"tile_identity\": self.tile_projection(tf.eye(34)),\n        }\n\n\ndef tile_features(codes, identity):\n    \"\"\"Project base-34 one-hot identity; red codes share their five's row.\"\"\"\n    codes = tf.cast(codes, tf.int32)\n    base = tf.where(codes < 34, codes, 4 + 9 * (codes - 34))\n    return tf.linalg.matmul(\n        tf.one_hot(tf.where(codes < 37, base, 34), 34, dtype=identity.dtype),\n        identity,\n    )\n\n\n# Categorical coordinates have no meaningful numeric distance. Tile identity\n# uses a shared learned vector for every base tile; red flags remain separate.\nRIVER_CATEGORIES = {\n    \"origin\": 6,  # Padding, dealer start, draw, hand, chii, pon.\n    \"caller\": 6,  # No caller, pending, then four actor-relative seats.\n    \"call_resolution\": 6,  # Padding, pending, no call, chii, pon, open kan.\n}\nCATEGORIES = {\n    \"prevailing_wind\": 4,\n    \"dealer_relative_seat\": 4,\n    \"seat_wind\": 4,\n    \"win_kind\": 3,\n    \"decision_phase\": 5,\n    \"trigger_source\": 4,\n    \"riichi_state\": 3,\n    \"meld_type\": 6,\n    \"meld_source\": 5,\n    **{\n        f\"river_{phase}_{field}\": width\n        for phase in (\"pre\", \"post\")\n        for field, width in RIVER_CATEGORIES.items()\n    },\n}\nTILE_FIELDS = frozenset(\n    {\n        \"current_draw_tile_id\",\n        \"trigger_tile_id\",\n        \"meld_tile_ids\",\n        \"last_tedashi_tile_id\",\n    }\n)\nBINARY_FIELDS = frozenset(\n    {\n        \"candidate_hand_valid\",\n        \"meld_tile_valid\",\n        \"meld_tile_red\",\n        \"current_draw_valid\",\n        \"current_draw_is_red\",\n        \"closed_hand\",\n        \"candidate_hand_yaku_possibility\",\n        \"open_opponent_yaku_possibility\",\n        \"ippatsu_alive\",\n        \"rinshan_state\",\n        \"genbutsu_to_seat\",\n        \"passed_unchanged_to_seat\",\n        \"last_tedashi_is_red\",\n        \"trigger_valid\",\n        \"trigger_is_red\",\n        \"riichi_legal_mask\",\n        \"riichi_discard_legal_mask\",\n        \"response_legal_mask\",\n        \"call_discard_legal\",\n        \"kan_legal_mask\",\n        \"discard_abort\",\n        \"discard_action_legal\",\n        \"discard_tedashi_legal\",\n        \"river_pre_riichi\",\n        *[\n            f\"river_{phase}_{field}\"\n            for phase in (\"pre\", \"post\")\n            for field in (\"is_red\", \"tsumogiri\", \"valid\")\n        ],\n    }\n)\nSCALED_FIELDS = frozenset(\n    {\n        \"self_efficiency\",\n        \"call_efficiency\",\n        \"kan_efficiency\",\n        \"meld_call_age\",\n        \"meld_upgrade_age\",\n        *[\n            f\"river_{phase}_{field}\"\n            for phase in (\"pre\", \"post\")\n            for field in (\"event_age\", \"own_gap\", \"live_wall\")\n        ],\n    }\n)\n\n\ndef field_width(name):\n    if name in TILE_FIELDS:\n        return TILE_WIDTH\n    if name.startswith(\"river_\") and name in CATEGORIES:\n        return 2\n    return CATEGORIES[name] if name in CATEGORIES else 1\n\n\ndef field_features(name, value, inputs):\n    \"\"\"Encode learned evidence; deterministic consumers retain native values.\"\"\"\n    ops = tf.keras.ops\n    value = ops.cast(value, \"float32\")\n    if name == \"scores\":\n        encoded = value[..., None] / 100000\n    elif name == \"ranks\":\n        encoded = value[..., None] / 4\n    elif name in CATEGORIES:\n        encoded = ops.one_hot(ops.cast(value, \"int32\"), CATEGORIES[name])\n    elif name in BINARY_FIELDS or name in SCALED_FIELDS:\n        encoded = value[..., None]\n    else:\n        encoded = ops.arcsinh(value)[..., None]\n    if name.startswith(\"river_\"):\n        encoded = encoded * ops.cast(\n            inputs[\"river_\" + name.split(\"_\")[1] + \"_valid\"][..., None],\n            \"float32\",\n        )\n    elif name in (\"trigger_source\", \"trigger_is_red\"):\n        encoded = encoded * ops.cast(\n            inputs[\"trigger_valid\"][..., None], \"float32\"\n        )\n    elif name == \"current_draw_is_red\":\n        encoded = encoded * ops.cast(\n            inputs[\"current_draw_valid\"][..., None], \"float32\"\n        )\n    elif name.startswith(\"meld_\"):\n        valid = inputs[\"meld_tile_valid\"][..., 0]\n        while len(valid.shape) < len(value.shape):\n            valid = valid[..., None]\n        encoded = encoded * ops.cast(valid[..., None], \"float32\")\n    return encoded\n\n\nclass SemanticFields(tf.keras.layers.Layer):\n    \"\"\"Shared categorical embeddings, masks, and compressed numeric evidence.\"\"\"\n\n    def __init__(self, names, **kwargs):\n        super().__init__(**{**kwargs, \"autocast\": False})\n        self.names = tuple(names)\n        self.river_categories = {\n            field: tf.keras.layers.Embedding(width, 2, dtype=self.dtype_policy)\n            for field, width in RIVER_CATEGORIES.items()\n            if any(name.endswith(\"_\" + field) for name in self.names)\n        }\n\n    def call(self, inputs):\n        encoded = {}\n        for name in self.names:\n            if name in TILE_FIELDS:\n                valid = (\n                    inputs[name] < 37\n                    if name == \"last_tedashi_tile_id\"\n                    else inputs[\n                        (\n                            \"meld_tile_valid\"\n                            if name == \"meld_tile_ids\"\n                            else name.removesuffix(\"_tile_id\") + \"_valid\"\n                        )\n                    ]\n                )\n                encoded[name] = tf.cast(\n                    tile_features(inputs[name], inputs[\"tile_identity\"]),\n                    self.compute_dtype,\n                ) * tf.cast(valid[..., None], self.compute_dtype)\n            elif name.startswith(\"river_\") and name in CATEGORIES:\n                field = name.split(\"_\", 2)[2]\n                encoded[name] = self.river_categories[field](\n                    tf.cast(inputs[name], tf.int32)\n                ) * tf.cast(\n                    inputs[\"river_\" + name.split(\"_\")[1] + \"_valid\"][..., None],\n                    self.compute_dtype,\n                )\n            else:\n                encoded[name] = tf.cast(\n                    field_features(name, inputs[name], inputs),\n                    self.compute_dtype,\n                )\n        return encoded\n",
      "sha256": "d1742e6a43a5d2da414ecf8d58b10a0827024197226a9f4f0047c45ce35e231a"
    },
    {
      "path": "model/joint_settlement.py",
      "text": "\"\"\"Scored hand endings and bank transitions, with coexisting ron claims.\n\nThe learned tensor describes events and hand scores. Monetary transfers are\ncomputed by rules, including double ron, dealer repeats and deposit priority.\n\"\"\"\n\nimport itertools\n\nimport numpy\nimport tensorflow as tf\n\nfrom log_dataset import scoring\nfrom model import losses, outcomes, payment_scoring\n\nDEPOSITS = numpy.array(\n    [[(mask >> seat) & 1 for seat in range(4)] for mask in range(16)],\n    numpy.float32,\n)\n# kind, discarder (or tsumo winner), absolute winner bits, draw mask.\n# Single and double ron claims; triple ron shares the general abort event.\nREADOUT_EVENTS = (\n    tuple(\n        (\n            0,\n            payer,\n            sum(\n                1 << ((payer + offset + 1) % 4)\n                for offset in range(3)\n                if mask & (1 << offset)\n            ),\n            0,\n        )\n        for payer in range(4)\n        for mask in range(1, 7)\n    )\n    + tuple((1, seat, 1 << seat, 0) for seat in range(4))\n    + tuple((2, -1, 0, mask) for mask in range(16))\n    + ((3, -1, 0, 16),)\n    + tuple((4, seat, 1 << seat, 0) for seat in range(4))\n)\nEVENTS = READOUT_EVENTS[:45] + tuple((4, -1, mask, 0) for mask in range(1, 16))\nDRAW_EVENTS = numpy.array([i for i, row in enumerate(EVENTS) if row[0] == 2])\nBASE_VALUES = numpy.array(\n    sorted(\n        {\n            8000 * fu if han == 0 else outcomes.basic_points(han, fu)\n            for han, fu in payment_scoring.SCORES\n        }\n    ),\n    numpy.int32,\n)\nSCORE_TO_BASE = numpy.array(\n    [\n        BASE_VALUES\n        == (8000 * fu if han == 0 else outcomes.basic_points(han, fu))\n        for han, fu in payment_scoring.SCORES\n    ],\n    numpy.float32,\n)\n\n\n# Each claim has ordinary base values plus full-stack Tenhou pao atoms.\nTSUMO_CELLS = tuple(\n    tuple(\n        index\n        for index, cell in enumerate(scoring.CELLS[:24])\n        if cell[0] == 1 and cell[2] == winner\n    )\n    for winner in range(4)\n)\nSCORE_HEADS = tuple(range(12)) + tuple(cells[0] for cells in TSUMO_CELLS)\nEVENT_CLAIMS = numpy.array(\n    [\n        [\n            kind == scoring.CELLS[head][0]\n            and bool(winners & (1 << scoring.CELLS[head][2]))\n            and (kind == 1 or payer == scoring.CELLS[head][1])\n            for head in SCORE_HEADS\n        ]\n        for kind, payer, winners, _ in EVENTS\n    ]\n)\nCLAIM_CELLS = numpy.array(\n    [\n        [\n            index\n            for index, cell in enumerate(scoring.CELLS[:24])\n            if cell[0] == scoring.CELLS[head][0]\n            and cell[2] == scoring.CELLS[head][2]\n        ]\n        for head in SCORE_HEADS\n    ]\n)\nCLAIM_VALUES = numpy.r_[BASE_VALUES, numpy.tile(8000 * numpy.arange(1, 5), 3)]\nCLAIM_PAYERS = numpy.array(\n    [\n        [scoring.CELLS[head][2]] * len(BASE_VALUES)\n        + [\n            seat\n            for seat in range(4)\n            if seat != scoring.CELLS[head][2]\n            for _ in range(4)\n        ]\n        for head in SCORE_HEADS\n    ]\n)\n\nORDINARY_ALLOCATION = numpy.array(\n    [\n        [\n            seat == scoring.CELLS[head][2]\n            or (scoring.CELLS[head][0] == 0 and seat == scoring.CELLS[head][1])\n            for seat in range(4)\n        ]\n        for head in SCORE_HEADS\n    ]\n)\n\n\ndef claim_transfers():\n    transfers = numpy.zeros((4, 16, len(CLAIM_VALUES), 36), numpy.int32)\n    honba = numpy.zeros_like(transfers)\n    for dealer, claim, atom in itertools.product(\n        range(4), range(16), range(len(CLAIM_VALUES))\n    ):\n        kind, source, winner = scoring.CELLS[SCORE_HEADS[claim]]\n        liable = CLAIM_PAYERS[claim, atom]\n        value = CLAIM_VALUES[atom]\n        for cell in CLAIM_CELLS[claim]:\n            payer = scoring.CELLS[cell][1]\n            if liable == winner:\n                factor = (\n                    (6 if winner == dealer else 4)\n                    if kind == 0\n                    else (2 if winner == dealer or payer == dealer else 1)\n                )\n                active = kind == 1 or payer == source\n                transfers[dealer, claim, atom, cell] = (\n                    active * 100 * ((factor * value + 99) // 100)\n                )\n                honba[dealer, claim, atom, cell] = active * (\n                    300 if kind == 0 else 100\n                )\n            else:\n                total = value * (6 if winner == dealer else 4)\n                transfers[dealer, claim, atom, cell] = (\n                    total * (payer == liable)\n                    if kind == 1\n                    else total // 2 * ((payer == liable) + int(payer == source))\n                )\n                honba[dealer, claim, atom, cell] = 300 * (payer == liable)\n    return transfers, honba\n\n\nCLAIM_TRANSFERS, CLAIM_HONBA = claim_transfers()\n\n\ndef settlement_support():\n    \"\"\"Enumerate score/allocation atoms, with deposits on a separate axis.\"\"\"\n    rows, transfers, selectors, honba = [], [], [], []\n    for dealer in range(4):\n        for event_id, (kind, payer, mask, draw) in enumerate(EVENTS):\n            winners = [seat for seat in range(4) if mask & (1 << seat)]\n            collector = (\n                min(winners, key=lambda seat: (seat - payer) % 4)\n                if kind < 2\n                else -1\n            )\n            heads = [\n                SCORE_HEADS.index(\n                    next(\n                        index\n                        for index, cell in enumerate(scoring.CELLS[:24])\n                        if cell[0] == kind\n                        and cell[2] == winner\n                        and (kind == 1 or cell[1] == payer)\n                    )\n                )\n                for winner in winners\n                if kind < 2\n            ]\n            for values in itertools.product(\n                *[\n                    [\n                        atom\n                        for atom in range(len(CLAIM_VALUES))\n                        if atom < len(BASE_VALUES)\n                        or not ORDINARY_ALLOCATION[\n                            head, CLAIM_PAYERS[head, atom]\n                        ]\n                    ]\n                    for head in heads\n                ]\n            ):\n                payment = numpy.zeros(36, numpy.int32)\n                bonus = numpy.zeros(36, numpy.int32)\n                for winner, head, value in zip(winners, heads, values):\n                    payment += CLAIM_TRANSFERS[dealer, head, value]\n                    if winner == collector:\n                        bonus += CLAIM_HONBA[dealer, head, value]\n                if kind == 2:\n                    count = int(DEPOSITS[draw].sum())\n                    if 0 < count < 4:\n                        for cell, (mode, source, winner) in enumerate(\n                            scoring.CELLS[:36]\n                        ):\n                            if (\n                                mode == 2\n                                and not DEPOSITS[draw, source]\n                                and DEPOSITS[draw, winner]\n                            ):\n                                payment[cell] = 3000 // (count * (4 - count))\n                elif kind == 4:\n                    for cell, (mode, source, winner) in enumerate(\n                        scoring.CELLS[:36]\n                    ):\n                        if mode == 2 and winner in winners:\n                            payment[cell] = (\n                                4000\n                                if winner == dealer or source == dealer\n                                else 2000\n                            )\n                for repeat in (range(2) if kind == 4 else (draw,)):\n                    rows.append(\n                        (dealer, kind, collector, repeat, mask, event_id)\n                    )\n                    transfers.append(payment)\n                    honba.append(bonus)\n                    selectors.append(\n                        list(zip(heads, values)) + [(-1, 0)] * (2 - len(heads))\n                    )\n    return tuple(\n        numpy.array(values, numpy.int32)\n        for values in (rows, transfers, selectors, honba)\n    )\n\n\nSUPPORT, TRANSFERS, SELECTORS, HONBA = settlement_support()\nCLASSES = outcomes.payment_classes(TRANSFERS)\nCOEFFICIENTS = numpy.array(\n    [\n        [int(recipient == seat) - int(payer == seat) for seat in range(4)]\n        for _, payer, recipient in scoring.CELLS[:36]\n    ],\n    numpy.float32,\n)\nEVENT_ROWS = numpy.array(\n    [\n        numpy.flatnonzero((SUPPORT[:, 0] == 0) & (SUPPORT[:, 5] == event))[0]\n        for event in range(len(EVENTS))\n    ]\n)\n\n\ndef dealer_indices(dealer):\n    \"\"\"Select the contiguous settlement block for each position's dealer.\"\"\"\n    return (\n        tf.cast(dealer, tf.int32)[:, None] * (len(SUPPORT) // 4)\n        + tf.range(len(SUPPORT) // 4)[None]\n    )\n\n\ndef bank_transfers(collectors, pot):\n    \"\"\"Bank movement for every position, settlement and deposit mask.\"\"\"\n    return (\n        tf.one_hot(collectors, 4)[:, :, None]\n        * (\n            pot[:, None, None, None]\n            + 1000\n            * tf.reduce_sum(tf.constant(DEPOSITS), -1)[None, None, :, None]\n        )\n        - 1000 * tf.constant(DEPOSITS)[None, None]\n    )\n\n\ndef claim_probabilities(inputs):\n    \"\"\"Only true yakuman can redirect a claim through responsibility.\"\"\"\n    score = tf.gather(inputs[\"score_probability\"], SCORE_HEADS, axis=1)\n    allocation = tf.nn.softmax(inputs[\"pao_logits\"])\n    # Responsibility assigned to the ron discarder is the ordinary transfer.\n    ordinary = tf.reduce_sum(\n        allocation * tf.constant(ORDINARY_ALLOCATION, tf.float32)[None],\n        -1,\n    )\n    base = tf.linalg.matmul(\n        score\n        * tf.where(\n            tf.constant(payment_scoring.SCORE_HAN == 0)[None, None],\n            ordinary[..., None],\n            1.0,\n        ),\n        tf.constant(SCORE_TO_BASE),\n    )\n    liable = tf.reduce_sum(\n        (allocation * tf.constant(~ORDINARY_ALLOCATION, tf.float32)[None])[\n            :, :, None\n        ]\n        * tf.one_hot(CLAIM_PAYERS[:, len(BASE_VALUES) :: 4], 4)[None],\n        -1,\n    )\n    return tf.concat(\n        [\n            base,\n            tf.reshape(\n                score[..., None, -4:] * liable[..., :, None],\n                [tf.shape(score)[0], 16, 12],\n            ),\n        ],\n        -1,\n    )\n\n\ndef public_inputs(features):\n    return {\n        \"scores\": tf.gather(\n            tf.cast(features[\"scores\"], tf.float32),\n            tf.cast(features[\"seat_wind\"], tf.int32),\n            batch_dims=1,\n        ),\n        \"honba\": tf.cast(features[\"honba\"], tf.float32),\n        \"pot\": tf.cast(features[\"riichi_sticks\"], tf.float32) * 1000,\n        \"first_dealer\": (\n            tf.cast(features[\"dealer_relative_seat\"], tf.int32)\n            - ((7 - tf.cast(features[\"hands_remaining\"], tf.int32)) % 4)\n        )\n        % 4,\n        \"hand_number\": 7 - tf.cast(features[\"hands_remaining\"], tf.int32),\n    }\n\n\ndef settlement_states(inputs):\n    \"\"\"Rule-derived outcomes depend only on the position, not its actions.\"\"\"\n    indices = dealer_indices(inputs[\"dealer\"])\n    classes = tf.gather(tf.constant(CLASSES, tf.int64), indices)\n    support = tf.gather(tf.constant(SUPPORT, tf.int64), indices)\n    bank = bank_transfers(support[:, :, 2], inputs[\"pot\"])\n    # Physical point transfers must not pass through reduced-precision GEMM.\n    delta = tf.gather(\n        tf.constant(TRANSFERS @ COEFFICIENTS, tf.float32), indices\n    ) + inputs[\"honba\"][:, None, None] * tf.gather(\n        tf.constant(HONBA @ COEFFICIENTS, tf.float32), indices\n    )\n    scores = inputs[\"scores\"][:, None, None] + delta[:, :, None] + bank\n    priority = (tf.range(4)[None] - inputs[\"first_dealer\"][:, None]) % 4\n    ranks = tf.reduce_sum(\n        tf.cast(\n            (scores[..., None, :] > scores[..., :, None])\n            | (\n                (scores[..., None, :] == scores[..., :, None])\n                & (\n                    priority[:, None, None, None, :]\n                    < priority[:, None, None, :, None]\n                )\n            ),\n            tf.int64,\n        ),\n        -1,\n    )\n    return {\n        \"joint_classes\": classes,\n        \"joint_bank\": bank,\n        \"joint_scores\": scores,\n        \"joint_ranks\": ranks,\n        \"joint_support\": support,\n    }\n\n\ndef event_legal(inputs):\n    \"\"\"Shared event/bank support, including deterministic last-discard facts.\"\"\"\n    kind = tf.constant([event[0] for event in EVENTS])\n    payer = tf.constant([event[1] for event in EVENTS])\n    ready = tf.constant(\n        [\n            [bool(mask & (1 << seat)) for seat in range(4)]\n            for _, _, _, mask in EVENTS\n        ]\n    )\n    claims = tf.constant(\n        [\n            [bool(mask & (1 << seat)) for seat in range(4)]\n            for _, _, mask, _ in EVENTS\n        ]\n    )\n    deposits = tf.constant(DEPOSITS, tf.bool)\n    # A pending declarer's deal-in may precede acceptance or occur later.\n    # Other endings require acceptance. Already paid sticks are in scores/pot.\n    preempted = (kind[:, None] == 0) & (payer[:, None] == tf.range(4)[None])\n    legal = tf.reduce_all(\n        (~deposits[None, None] | inputs[\"deposit_allowed\"][:, None, None])\n        & (\n            deposits[None, None]\n            | ~inputs[\"deposit_required\"][:, None, None]\n            | preempted[None, :, None]\n        ),\n        -1,\n    )\n    legal &= tf.reduce_all(\n        (kind != 2)[None, :, None, None]\n        | ready[None, :, None]\n        | ~(inputs[\"tenpai_required\"][:, None, None] | deposits[None, None]),\n        -1,\n    )\n    boundary = inputs[\"ending_draw_kind\"] > 0\n    ron = (kind == 0) & (payer == 0)\n    allowed = ron[None] | tf.where(\n        inputs[\"ending_draw_kind\"][:, None] == 1,\n        (kind[None] == 2) | (kind[None] == 4),\n        kind[None] == 3,\n    )\n    allowed &= ~ron[None] | ~tf.reduce_any(\n        claims[None, :, 1:] & inputs[\"ending_safe\"][:, None], -1\n    )\n    allowed &= (kind != 2)[None] | tf.reduce_all(\n        (inputs[\"ending_tenpai\"][:, None] < 0)\n        | (tf.cast(ready, tf.int32)[None] == inputs[\"ending_tenpai\"][:, None]),\n        -1,\n    )\n    # No further declarations can occur once this discard ends the hand.\n    boundary_deposits = inputs[\"deposit_required\"][:, None] & ~preempted[None]\n    legal &= ~boundary[:, None, None] | (\n        allowed[..., None]\n        & tf.reduce_all(\n            deposits[None, None] == boundary_deposits[:, :, None], -1\n        )\n    )\n    # The merged abort retains the bank support of triple ron: exactly\n    # one pending declarer's discard may end before accepting their stick.\n    triple_preempted = tf.eye(4, dtype=tf.bool)\n    triple_legal = tf.reduce_all(\n        (~deposits[None, None] | inputs[\"deposit_allowed\"][:, None, None])\n        & (\n            deposits[None, None]\n            | ~inputs[\"deposit_required\"][:, None, None]\n            | triple_preempted[None, :, None]\n        ),\n        -1,\n    )\n    triple_legal &= ~boundary[:, None, None] | (\n        (tf.range(4)[None, :, None] == 0)\n        & ~tf.reduce_any(inputs[\"ending_safe\"], -1)[:, None, None]\n        & tf.reduce_all(\n            deposits[None, None]\n            == (inputs[\"deposit_required\"][:, None] & ~triple_preempted[None])[\n                :, :, None\n            ],\n            -1,\n        )\n    )\n    legal |= (kind == 3)[None, :, None] & tf.reduce_any(triple_legal, axis=1)[\n        :, None\n    ]\n    legal &= (kind != 4)[None, :, None] | tf.reduce_all(\n        ~claims[None] | inputs[\"nagashi_allowed\"][:, None], -1\n    )[..., None]\n    # Nagashi inherits the same feasible readiness/deposit combinations.\n    legal &= (kind != 4)[None, :, None] | tf.reduce_any(\n        tf.gather(legal, DRAW_EVENTS, axis=1), axis=1\n    )[:, None]\n    return legal\n\n\ndef event_probabilities(inputs):\n    legal = event_legal(inputs)\n    deposit = tf.nn.softmax(\n        tf.where(legal, inputs[\"deposit_logits\"], -1e9)\n    ) * tf.cast(legal, tf.float32)\n    event = tf.nn.softmax(\n        tf.where(tf.reduce_any(legal, -1), inputs[\"event_logits\"], -1e9)\n    )\n    return event, deposit, legal\n\n\ndef dealer_repeat_probability(inputs, legal):\n    \"\"\"Nagashi repeat law from legal exhaustive readiness and deposits.\"\"\"\n    draw_legal = tf.gather(legal, DRAW_EVENTS, axis=1)\n    readiness = tf.nn.softmax(\n        tf.where(\n            draw_legal,\n            tf.gather(inputs[\"event_logits\"], DRAW_EVENTS, axis=1)[..., None],\n            -1e9,\n        ),\n        axis=1,\n    ) * tf.cast(draw_legal, tf.float32)\n    dealer_ready = tf.gather(\n        tf.constant(DEPOSITS), tf.cast(inputs[\"dealer\"], tf.int32), axis=1\n    )\n    return tf.reduce_sum(\n        readiness * tf.transpose(dealer_ready)[:, :, None], axis=1\n    )\n\n\ndef probabilities(inputs):\n    \"\"\"Exact categorical law, without ranks or payment marginals.\"\"\"\n    indices = dealer_indices(inputs[\"dealer\"])\n    support = tf.gather(tf.constant(SUPPORT, tf.int64), indices)\n    selectors = tf.gather(tf.constant(SELECTORS, tf.int32), indices)\n    amount = tf.gather(\n        tf.reshape(\n            claim_probabilities(inputs), (tf.shape(inputs[\"dealer\"])[0], -1)\n        ),\n        tf.maximum(selectors[..., 0], 0) * len(CLAIM_VALUES)\n        + selectors[..., 1],\n        axis=1,\n        batch_dims=1,\n    )\n    amount = tf.reduce_prod(tf.where(selectors[..., 0] >= 0, amount, 1.0), -1)\n    event, deposit, legal = event_probabilities(inputs)\n    probability = (\n        tf.gather(event, support[:, :, 5], axis=1, batch_dims=1) * amount\n    )[..., None] * tf.gather(deposit, support[:, :, 5], axis=1, batch_dims=1)\n    repeat = dealer_repeat_probability(inputs, legal)\n    probability *= tf.where(\n        support[:, :, 1, None] == 4,\n        tf.where(\n            support[:, :, 3, None] == 1, repeat[:, None], 1.0 - repeat[:, None]\n        ),\n        1.0,\n    )\n    legal = tf.gather(legal, support[:, :, 5], axis=1, batch_dims=1)\n    return probability, legal\n\n\ndef decode(inputs):\n    \"\"\"Rule-derived transfers, ranks and diagnostics for serving.\"\"\"\n    probability, _ = probabilities(inputs)\n    return {\n        \"joint_probability\": probability,\n        **settlement_states(inputs),\n    }\n\n\ndef observed_support(labels, inputs):\n    \"\"\"Label-compatible score atoms and public event/deposit support.\"\"\"\n    legal = event_legal(inputs)\n    amounts = tf.gather(\n        tf.constant(outcomes.PAYMENT_VALUES, tf.int32),\n        tf.maximum(labels[\"payment\"][:, :24], 0),\n    )\n    targets = tf.gather(amounts, CLAIM_CELLS, axis=1)\n    unknown = tf.gather(labels[\"payment\"][:, :24] < 0, CLAIM_CELLS, axis=1)\n    claim_transfers = numpy.take_along_axis(\n        CLAIM_TRANSFERS, CLAIM_CELLS[None, :, None], axis=-1\n    )\n    transfers = tf.gather(\n        tf.constant(claim_transfers), tf.cast(inputs[\"dealer\"], tf.int32)\n    )\n    score_match = tf.reduce_all(\n        tf.where(\n            unknown[:, :, None],\n            transfers != 0,\n            transfers == targets[:, :, None],\n        ),\n        -1,\n    )\n    selected = EVENT_CLAIMS\n    active = numpy.array(\n        [\n            [\n                kind == cell[0] and bool(winners & (1 << cell[2]))\n                for cell in scoring.CELLS[:24]\n            ]\n            for kind, _, winners, _ in EVENTS\n        ]\n    )\n    compatible = tf.reduce_all(\n        (labels[\"payment\"][:, None, :24] == 1) | tf.constant(active)[None], -1\n    )\n    compatible &= tf.reduce_all(\n        labels[\"payment\"][:, None, 24:36]\n        == tf.gather(\n            tf.constant(CLASSES[:, 24:36], tf.int32),\n            tf.cast(inputs[\"dealer\"], tf.int32)[:, None] * (len(SUPPORT) // 4)\n            + tf.constant(EVENT_ROWS, tf.int32)[None],\n        ),\n        -1,\n    )\n    compatible &= tf.reduce_all(\n        ~tf.constant(selected)[None] | tf.reduce_any(score_match, -1)[:, None],\n        -1,\n    )\n    kinds = tf.constant([event[0] for event in EVENTS], tf.int32)\n    compatible &= (\n        kinds[None] == tf.cast(labels[\"round_end_kind\"], tf.int32)[:, None]\n    )\n    compatible &= (kinds != 0)[None] | (\n        tf.constant([event[1] for event in EVENTS], tf.int32)[None]\n        == tf.cast(labels[\"round_end_source\"], tf.int32)[:, None]\n    )\n    readiness = tf.reduce_sum(\n        tf.cast(labels[\"round_end_tenpai\"], tf.int32)\n        * tf.constant([1, 2, 4, 8]),\n        -1,\n    )\n    compatible &= (kinds != 2)[None] | (\n        tf.constant([event[3] for event in EVENTS])[None] == readiness[:, None]\n    )\n    bank = bank_transfers(\n        tf.constant(SUPPORT[EVENT_ROWS, 2])[None], inputs[\"pot\"]\n    )\n    actual_bank = tf.gather(\n        payment_values(labels), labels[\"payment\"][:, 36:], axis=1, batch_dims=1\n    )\n    bank_match = tf.reduce_all(bank == actual_bank[:, None, None], -1)\n    return {\n        \"score_match\": score_match,\n        \"selected\": tf.constant(selected),\n        \"compatible\": compatible,\n        \"matches\": compatible[..., None]\n        & bank_match\n        & legal\n        & (\n            (kinds != 4)[None, :, None]\n            | tf.gather(\n                tf.gather(legal, DRAW_EVENTS, axis=1),\n                readiness,\n                axis=1,\n                batch_dims=1,\n            )[:, None]\n        ),\n        \"legal\": legal,\n    }\n\n\ndef observed_terms(labels, inputs, mean=losses.mean_valid, support=None):\n    \"\"\"Observed categorical likelihood without a score Cartesian product.\n\n    Recorded ending kind and readiness distinguish zero-payment draws and\n    aborts. Responsibility and joint nagashi use the same law as action Q.\n    \"\"\"\n    if support is None:\n        support = observed_support(labels, inputs)\n    event, deposit, _ = event_probabilities(inputs)\n    score = tf.reduce_sum(\n        claim_probabilities(inputs)\n        * tf.cast(support[\"score_match\"], tf.float32),\n        -1,\n    )\n    event_score_likelihood = tf.reduce_prod(\n        tf.where(support[\"selected\"][None], score[:, None], 1.0), -1\n    )\n    probability = (event * event_score_likelihood)[..., None] * deposit\n    repeat = dealer_repeat_probability(inputs, support[\"legal\"])\n    probability *= tf.where(\n        tf.constant([row[0] == 4 for row in EVENTS])[None, :, None],\n        tf.where(\n            tf.gather(\n                tf.cast(labels[\"round_end_tenpai\"], tf.bool),\n                tf.cast(inputs[\"dealer\"], tf.int32),\n                axis=1,\n                batch_dims=1,\n            )[:, None],\n            repeat,\n            1.0 - repeat,\n        )[:, None],\n        1.0,\n    )\n    supported = tf.reduce_any(support[\"matches\"], axis=(1, 2))\n    likelihood = tf.reduce_sum(\n        tf.where(support[\"matches\"], probability, 0.0), (1, 2)\n    )\n    nagashi = tf.constant(\n        [\n            [kind == 4 and bool(winners & (1 << seat)) for seat in range(4)]\n            for kind, _, winners, _ in EVENTS\n        ]\n    )\n    targets = tf.reduce_any(\n        support[\"compatible\"][..., None] & nagashi[None], axis=1\n    )\n    logits = tf.where(\n        tf.reduce_any(support[\"legal\"], -1), inputs[\"event_logits\"], -1e9\n    )\n    nagashi_loss = tf.reduce_logsumexp(logits, -1)[\n        :, None\n    ] - tf.reduce_logsumexp(\n        tf.where(nagashi[None] == targets[:, None], logits[..., None], -1e9),\n        axis=1,\n    )\n    return {\n        \"nagashi_loss\": mean(tf.reduce_mean(nagashi_loss, -1), supported),\n        \"payment_nll\": mean(\n            -tf.math.log(tf.maximum(likelihood, 1e-30)), supported\n        ),\n    }\n\n\ndef observed_payoff(labels, inputs, payoff, support=None):\n    \"\"\"Exact J only when every label-compatible settlement agrees.\n\n    Recorded ending labels resolve continuation ambiguity. Unknown payment\n    amounts retain NLL supervision without an invented squared-error target.\n    \"\"\"\n    observed = observed_support(labels, inputs) if support is None else support\n    indices = dealer_indices(inputs[\"dealer\"])\n    support = tf.gather(tf.constant(SUPPORT, tf.int32), indices)\n    selectors = tf.gather(tf.constant(SELECTORS, tf.int32), indices)\n    matched_scores = tf.gather(\n        tf.reshape(\n            observed[\"score_match\"], [tf.shape(inputs[\"dealer\"])[0], -1]\n        ),\n        tf.maximum(selectors[..., 0], 0) * len(CLAIM_VALUES)\n        + selectors[..., 1],\n        axis=1,\n        batch_dims=1,\n    )\n    matches = (\n        tf.gather(observed[\"matches\"], support[:, :, 5], axis=1, batch_dims=1)\n        & tf.reduce_all((selectors[..., 0] < 0) | matched_scores, -1)[..., None]\n    )\n    matches &= (support[:, :, 1, None] != 4) | (\n        support[:, :, 3, None]\n        == tf.gather(\n            tf.cast(labels[\"round_end_tenpai\"], tf.int32),\n            tf.cast(inputs[\"dealer\"], tf.int32),\n            axis=1,\n            batch_dims=1,\n        )[:, None, None]\n    )\n    minimum = tf.reduce_min(tf.where(matches, payoff, float(\"inf\")), (1, 2))\n    maximum = tf.reduce_max(tf.where(matches, payoff, -float(\"inf\")), (1, 2))\n    identifiable = (\n        tf.reduce_all(labels[\"payment\"] >= 0, -1)\n        & tf.reduce_any(matches, (1, 2))\n        & (maximum - minimum <= 1e-6)\n    )\n    return tf.stop_gradient(tf.where(identifiable, minimum, 0.0)), identifiable\n\n\ndef expectation(probability, values):\n    \"\"\"Sum deposits before scored events to avoid long FP32 channel sums.\"\"\"\n    if values.shape.rank == 4:\n        probability = probability[..., None]\n    return tf.reduce_sum(tf.reduce_sum(probability * values, axis=2), axis=1)\n\n\n@tf.function(jit_compile=True)\ndef position_payoffs(inputs):\n    \"\"\"Project settlement states to normalized J once per position.\"\"\"\n    states = settlement_states(inputs)\n    st3, probability = continuation_forecast(\n        scores=states[\"joint_scores\"],\n        ranks=states[\"joint_ranks\"],\n        support=states[\"joint_support\"],\n        dealer=inputs[\"dealer\"],\n        hand_number=inputs[\"hand_number\"],\n        pot=inputs[\"pot\"],\n    )\n    return policy_objective(st3, probability)\n\n\n@tf.function(jit_compile=True)\ndef supervision_chunk(inputs, labels):\n    \"\"\"Fuse fixed support, payoff projection and target matching once.\"\"\"\n    support = observed_support(labels, inputs)\n    payoff = position_payoffs(inputs)\n    target, identified = observed_payoff(\n        labels, inputs, payoff, support=support\n    )\n    return {\n        \"q_payoff\": tf.stop_gradient(payoff),\n        \"q_target\": target,\n        \"q_identified\": identified,\n        **{\n            \"support_\" + name: value\n            for name, value in support.items()\n            if name != \"selected\"\n        },\n    }\n\n\ndef prepare_supervision(inputs, labels):\n    \"\"\"Cache fixed supervision in bounded, fused 32-row chunks.\"\"\"\n    prepared = {\n        name: tf.TensorArray(\n            value.dtype,\n            size=0,\n            dynamic_size=True,\n            element_shape=[None, *value.shape[1:]],\n        ).write(0, value)\n        for name, value in supervision_chunk(\n            {name: value[:32] for name, value in inputs.items()},\n            {name: value[:32] for name, value in labels.items()},\n        ).items()\n    }\n    for chunk_index in tf.range(1, (tf.shape(inputs[\"dealer\"])[0] + 31) // 32):\n        tf.autograph.experimental.set_loop_options(parallel_iterations=1)\n        begin = chunk_index * 32\n        chunk = supervision_chunk(\n            {name: value[begin : begin + 32] for name, value in inputs.items()},\n            {name: value[begin : begin + 32] for name, value in labels.items()},\n        )\n        prepared = {\n            name: array.write(chunk_index, chunk[name])\n            for name, array in prepared.items()\n        }\n    return {\n        **labels,\n        **{name: array.concat() for name, array in prepared.items()},\n    }\n\n\ndef gather_position_payoffs(inputs, positions):\n    \"\"\"Project each requested position once in bounded, fixed-size chunks.\"\"\"\n    shape = [len(SUPPORT) // 4, 16]\n    payoffs = tf.TensorArray(\n        tf.float32,\n        size=(tf.shape(positions)[0] + 31) // 32,\n        element_shape=[32, *shape],\n    )\n    for begin in tf.range(0, tf.shape(positions)[0], 32):\n        rows = tf.gather(\n            positions,\n            tf.minimum(tf.range(begin, begin + 32), tf.shape(positions)[0] - 1),\n        )\n        payoffs = payoffs.write(\n            begin // 32,\n            position_payoffs(\n                {\n                    name: tf.gather(value, rows)\n                    for name, value in inputs.items()\n                },\n            ),\n        )\n    return tf.reshape(payoffs.stack(), [-1, *shape])[: tf.shape(positions)[0]]\n\n\n@tf.function(jit_compile=True)\ndef continuation_forecast(scores, ranks, support, dealer, hand_number, pot):\n    \"\"\"Public-state payoff of each settlement, shared by every action.\"\"\"\n    dealer = tf.cast(dealer, tf.int64)\n    tenpai = tf.gather(\n        tf.constant(DEPOSITS, tf.bool), tf.minimum(support[:, :, 3], 15)\n    )\n    repeat = (\n        (\n            tf.bitwise.bitwise_and(\n                support[:, :, 4],\n                tf.bitwise.left_shift(tf.ones_like(dealer), dealer)[:, None],\n            )\n            > 0\n        )\n        & (support[:, :, 1] < 2)\n        | (support[:, :, 1] == 3)\n        | ((support[:, :, 1] == 4) & (support[:, :, 3] == 1))\n        | (\n            (support[:, :, 1] == 2)\n            & tf.gather(tenpai, dealer, axis=2, batch_dims=1)\n        )\n    )\n    dealer_rank = tf.gather(ranks, dealer, axis=3, batch_dims=1)\n    terminal = (\n        tf.reduce_any(scores < 0, -1)\n        | (\n            (hand_number[:, None, None] >= 7)\n            & (support[:, :, 1, None] != 3)\n            & (tf.reduce_max(scores, -1) >= 30000)\n            & (~repeat[:, :, None] | (dealer_rank == 0))\n        )\n        | ((hand_number[:, None, None] >= 11) & ~repeat[:, :, None])\n    )\n    phase = hand_number[:, None] + tf.cast(~repeat, tf.int32)\n    next_dealer = (dealer[:, None] + tf.cast(~repeat, tf.int64)) % 4\n    terminal_bank = tf.where(\n        support[:, :, 1, None] < 2,\n        0.0,\n        pot[:, None, None]\n        + 1000 * tf.reduce_sum(tf.constant(DEPOSITS), -1)[None, None],\n    )\n    return post_hand_forecast(\n        scores=scores,\n        ranks=ranks,\n        next_dealer=next_dealer[:, :, None],\n        next_hand=phase[:, :, None],\n        terminal=terminal,\n        pot=terminal_bank,\n    )\n\n\ndef policy_objective(st3, probability):\n    \"\"\"Normalized ST3 plus first-place reward and fourth-place penalty.\"\"\"\n    return (\n        st3 / outcomes.OBJECTIVE_ST3_SCALE\n        + probability[..., 0]\n        - probability[..., 3]\n    )\n\n\ndef post_hand_forecast(scores, ranks, next_dealer, next_hand, terminal, pot):\n    \"\"\"Forecast match outcomes from a post-hand state.\"\"\"\n    rounds = tf.cast(tf.maximum(8 - next_hand, 0), tf.float32)\n    future = tf.range(8, dtype=tf.int64)\n    dealerships = tf.reduce_sum(\n        tf.cast(\n            (tf.cast(future, tf.float32) < rounds[..., None])[..., None]\n            & (\n                ((next_dealer[..., None] + future) % 4)[..., None]\n                == tf.range(4, dtype=tf.int64)\n            ),\n            tf.float32,\n        ),\n        axis=-2,\n    )\n    smooth, probability = continuation_values(scores, rounds, dealerships)\n    offsets = tf.constant(outcomes.SAINT3_JADE_SOUTH_OFFSETS, tf.float32)\n    terminal_points = scores[..., 0] + tf.where(ranks[..., 0] == 0, pot, 0.0)\n    exact = tf.math.ceil(\n        (terminal_points - 25000) / 1000 + tf.gather(offsets, ranks[..., 0])\n    )\n    return tf.where(terminal, exact, smooth), tf.where(\n        terminal[..., None], tf.one_hot(ranks[..., 0], 4), probability\n    )\n\n\ndef continuation_values(scores, rounds, dealerships):\n    \"\"\"Fixed Gumbel continuation with time-dependent score variance.\n\n    Scores use 10,000-point units. Positive dealership drift and a positive\n    quadratic variance in remaining hands preserve directional consistency.\n    The calibrated coefficients are fixed during policy and critic training.\n    \"\"\"\n    coefficient = tf.nn.softplus(\n        tf.constant(\n            [-2.9851044578, -2.9903753151, -2.0806273807, -4.2473072284],\n            tf.float32,\n        )\n    )\n    location = scores / 10000 + coefficient[0] * (\n        dealerships - tf.reduce_mean(dealerships, -1, keepdims=True)\n    )\n    noise = tf.sqrt(\n        coefficient[1]\n        + coefficient[2] * rounds\n        + coefficient[3] * tf.square(rounds)\n    )\n    probability = placement_prior(location, 0, noise[..., None])\n    return (\n        location[..., 0] * 10\n        - 25\n        + 0.5\n        + tf.reduce_sum(\n            probability\n            * tf.constant(outcomes.SAINT3_JADE_SOUTH_OFFSETS, tf.float32),\n            -1,\n        )\n    ), probability\n\n\ndef marginals(outputs):\n    \"\"\"Class marginals; four state-dependent atoms encode the bank exactly.\"\"\"\n    probability = outputs[\"joint_probability\"]\n    batch = tf.shape(probability)[0]\n    count = len(outcomes.PAYMENT_VALUES) + 4\n    base = tf.reduce_sum(probability, -1)\n    transfers = tf.reshape(\n        tf.math.unsorted_segment_sum(\n            tf.reshape(\n                tf.broadcast_to(\n                    base[..., None], tf.shape(outputs[\"joint_classes\"])\n                ),\n                [-1],\n            ),\n            tf.reshape(\n                tf.cast(\n                    tf.range(batch)[:, None, None] * 36\n                    + tf.range(36)[None, None],\n                    tf.int64,\n                )\n                * count\n                + outputs[\"joint_classes\"],\n                [-1],\n            ),\n            batch * 36 * count,\n        ),\n        (batch, 36, count),\n    )\n    # Sum by pot collector first, avoiding a long scatter-add for every\n    # score combination that has the same bank movement.\n    # Tree reductions avoid the long float32 dot-product accumulation that\n    # can move bank probability mass outside the export tolerance on GPU.\n    bank_probability = tf.stack(\n        [\n            tf.reduce_sum(\n                tf.where(\n                    outputs[\"joint_support\"][:, :, 2, None] == seat,\n                    probability,\n                    0.0,\n                ),\n                axis=1,\n            )\n            for seat in range(-1, 4)\n        ],\n        axis=1,\n    )\n    winner = tf.one_hot(tf.range(5) - 1, 4, dtype=tf.int32)\n    deposits = tf.constant(DEPOSITS, tf.int32)\n    bank_classes = tf.where(\n        winner[:, None] > 0,\n        len(outcomes.PAYMENT_VALUES)\n        + tf.reduce_sum(deposits, -1)[None, :, None]\n        - deposits[None],\n        1 - deposits[None],\n    )\n    bank = tf.reduce_sum(\n        tf.where(\n            bank_classes[..., None] == tf.range(count),\n            bank_probability[..., None, None],\n            0.0,\n        ),\n        axis=(1, 2),\n    )\n    # Almost every transfer is zero. Recover its complement instead of\n    # accumulating thousands of tiny zero-class masses in arbitrary order.\n    nonzero = transfers * (1 - tf.one_hot(1, count))\n    transfers = nonzero + tf.maximum(\n        0.0, 1 - tf.reduce_sum(nonzero, -1, keepdims=True)\n    ) * tf.one_hot(1, count)\n    return tf.concat([transfers, bank], axis=1)\n\n\ndef payment_values(inputs):\n    return tf.concat(\n        [\n            tf.broadcast_to(\n                tf.constant(outcomes.PAYMENT_VALUES, tf.float32),\n                [tf.shape(inputs[\"pot\"])[0], len(outcomes.PAYMENT_VALUES)],\n            ),\n            inputs[\"pot\"][:, None] + 1000 * tf.range(4, dtype=tf.float32)[None],\n        ],\n        -1,\n    )\n\n\ndef payment_labels(\n    points, public, *, ending_kind, ending_tenpai, ending_source\n):\n    \"\"\"Map transfers; -1 denotes a known win with unknown payment amount.\"\"\"\n    matches = (\n        tf.cast(points[..., None], tf.float32)\n        == payment_values(public)[:, None]\n    )\n    tf.debugging.Assert(\n        tf.reduce_all(tf.reduce_any(matches, -1) | (points == -1)),\n        [\n            \"Unsupported payment targets (row, cell), points, public pots:\",\n            tf.where(~tf.reduce_any(matches, -1)),\n            tf.boolean_mask(points, ~tf.reduce_any(matches, -1)),\n            tf.boolean_mask(\n                public[\"pot\"], ~tf.reduce_all(tf.reduce_any(matches, -1), -1)\n            ),\n        ],\n    )\n    # Exact 0/1 floats keep ArgMax on the GPU instead of copying matches.\n    return {\n        \"payment\": tf.where(\n            points == -1,\n            -1,\n            tf.argmax(tf.cast(matches, tf.float32), -1, output_type=tf.int32),\n        ),\n        \"pot\": public[\"pot\"],\n        \"round_end_kind\": tf.cast(ending_kind, tf.int32),\n        \"round_end_source\": tf.cast(ending_source, tf.int32),\n        \"round_end_tenpai\": tf.cast(ending_tenpai, tf.int32),\n    }\n\n\ndef settlement_moments(outputs):\n    \"\"\"Exact honba-free player/bank moments, retaining transfer covariance.\"\"\"\n    net = (\n        tf.linalg.matmul(\n            tf.gather(\n                tf.constant(outcomes.PAYMENT_VALUES, tf.float32),\n                outputs[\"joint_classes\"],\n            ),\n            tf.constant(COEFFICIENTS),\n        )[:, :, None]\n        + outputs[\"joint_bank\"]\n    )\n    net = tf.concat([net, -tf.reduce_sum(net, -1, keepdims=True)], -1)\n    mean = expectation(outputs[\"joint_probability\"], net)\n    second = expectation(outputs[\"joint_probability\"], net**2)\n    return mean, second\n\n\ndef placement_prior(scores, remaining, scale=0.0472):\n    \"\"\"Coherent actor rank probabilities from a Gumbel future-score prior.\n\n    Scores and scale must share units; leading batch dimensions broadcast.\n    Enumerate only opponent orders, avoiding the 24-permutation score tensor.\n    \"\"\"\n    remaining = tf.clip_by_value(tf.cast(remaining, tf.float32), 0.0, 7.0)\n    scores = tf.cast(scores, tf.float32)\n    location = (scores - scores[..., :1]) / (\n        scale * tf.sqrt(remaining[..., None] + 1)\n    )\n    total = tf.reduce_logsumexp(location, axis=-1)\n    first = tf.exp(-total)\n    second = tf.zeros_like(first)\n    fourth = tf.zeros_like(first)\n    for seat in (1, 2, 3):\n        after_first = tf.reduce_logsumexp(\n            tf.gather(location, [i for i in range(4) if i != seat], axis=-1),\n            axis=-1,\n        )\n        second += tf.exp(location[..., seat] - total - after_first)\n        for other in (i for i in (1, 2, 3) if i != seat):\n            last = 6 - seat - other\n            fourth += tf.exp(\n                tf.reduce_sum(location[..., 1:], axis=-1)\n                - total\n                - after_first\n                - tf.nn.softplus(location[..., last])\n            )\n    probability = tf.stack(\n        [first, second, tf.maximum(1 - first - second - fourth, 0), fourth],\n        axis=-1,\n    )\n    return probability / tf.reduce_sum(probability, axis=-1, keepdims=True)\n",
      "sha256": "0e37cd56f1c6afaf5190eef77ef254402ae0a95e67cda79edef202eb17ed5485"
    },
    {
      "path": "model/losses.py",
      "text": "\"\"\"Masked loss reductions shared across components and replicas.\"\"\"\n\nimport tensorflow as tf\n\n\ndef constraint_divergence(raw, constrained, binary=False):\n    \"\"\"Teach raw predictions the projection, without moving its target.\"\"\"\n    constrained = tf.stop_gradient(tf.cast(constrained, tf.float32))\n    raw = tf.cast(raw, tf.float32)\n    if binary:\n        target = tf.sigmoid(constrained)\n        divergence = tf.nn.sigmoid_cross_entropy_with_logits(\n            labels=target, logits=raw\n        ) - tf.nn.sigmoid_cross_entropy_with_logits(\n            labels=target, logits=constrained\n        )\n        return tf.reduce_mean(divergence, -1)\n    target = tf.nn.log_softmax(constrained)\n    return tf.reduce_sum(tf.exp(target) * (target - tf.nn.log_softmax(raw)), -1)\n\n\n@tf.keras.utils.register_keras_serializable(package=\"nejimakidori\")\nclass ConstraintLoss(tf.keras.layers.Layer):\n    def __init__(self, binary=False, **kwargs):\n        super().__init__(**kwargs)\n        self.binary = binary\n\n    def get_config(self):\n        return {**super().get_config(), \"binary\": self.binary}\n\n    def call(self, values):\n        penalty = constraint_divergence(*values[:2], binary=self.binary)\n        penalty = tf.reduce_mean(\n            penalty, axis=tuple(range(1, penalty.shape.rank))\n        )\n        if len(values) == 3:\n            # Sparse candidate outputs contribute equal mass per decision.\n            return tf.math.divide_no_nan(\n                tf.math.segment_sum(penalty, values[2]),\n                tf.math.segment_sum(tf.ones_like(penalty), values[2]),\n            )\n        return penalty\n\n\ndef masked_totals(loss, mask, weight=None):\n    mask = tf.cast(mask, tf.float32)\n    if weight is not None:\n        mask *= tf.cast(weight, tf.float32)\n    return tf.stack(\n        [tf.reduce_sum(tf.cast(loss, tf.float32) * mask), tf.reduce_sum(mask)]\n    )\n\n\ndef mean_valid(loss, mask, weight=None):\n    numerator, denominator = tf.unstack(masked_totals(loss, mask, weight))\n    replica = tf.distribute.get_replica_context()\n    if replica is not None:\n        numerator = replica.all_reduce(tf.distribute.ReduceOp.SUM, numerator)\n        denominator = replica.all_reduce(\n            tf.distribute.ReduceOp.SUM, denominator\n        )\n    return tf.math.divide_no_nan(numerator, denominator)\n\n\ndef candidate_mean(loss, mask, rows, mean=mean_valid):\n    \"\"\"Equal decision mass over valid candidate/head entries.\n\n    Rows are the sorted decision IDs returned by DecisionCandidates. Unknown\n    candidates contribute neither loss nor normalization mass.\n    \"\"\"\n    mask = tf.cast(mask, tf.float32)\n    totals = tf.math.segment_sum(\n        tf.stack(\n            [\n                tf.reduce_sum(tf.cast(loss, tf.float32) * mask, axis=-1),\n                tf.reduce_sum(mask, axis=-1),\n            ],\n            axis=-1,\n        ),\n        rows,\n    )\n    return mean(\n        tf.math.divide_no_nan(totals[:, 0], totals[:, 1]), totals[:, 1] > 0\n    )\n\n\ndef packed_means(statistics):\n    \"\"\"Reduce masked statistics using TensorFlow's distributed autodiff.\"\"\"\n    replica = tf.distribute.get_replica_context()\n    if replica is not None:\n        statistics = replica.all_reduce(tf.distribute.ReduceOp.SUM, statistics)\n    return tf.math.divide_no_nan(statistics[:, 0], statistics[:, 1])\n\n\nclass MaskedMeans:\n    \"\"\"Collect independent masked means into one replica reduction.\"\"\"\n\n    def __init__(self):\n        self.statistics = []\n\n    def collect(self, loss, mask, weight=None):\n        self.statistics.append(masked_totals(loss, mask, weight))\n        return tf.constant(0.0)\n\n    def reduce(self):\n        self.values = iter(tf.unstack(packed_means(tf.stack(self.statistics))))\n\n    def read(self, loss, mask, weight=None):\n        return next(self.values)\n\n\ndef classification(labels, logits, weight=None, mean=mean_valid):\n    labels = tf.cast(labels, tf.int32)\n    return mean(\n        tf.nn.sparse_softmax_cross_entropy_with_logits(\n            labels=tf.maximum(labels, 0), logits=tf.cast(logits, tf.float32)\n        ),\n        labels >= 0,\n        weight,\n    )\n",
      "sha256": "bddb7d19e8772d4b95037e4fbcdd4c7cb03fee93e278465ee428aee6c54f2044"
    },
    {
      "path": "model/network.py",
      "text": "\"\"\"Assembly of the shared actor, beliefs and payment critic.\"\"\"\n\nimport tensorflow as tf\n\nfrom model import actor as actor_layers\nfrom model import (\n    beliefs,\n    candidate_predictions,\n    critic,\n    encoder,\n    joint_settlement,\n)\n\n\nclass JointPolicyPayment(tf.keras.Model):\n    \"\"\"Shared policy, beliefs, auxiliaries and payment critic.\"\"\"\n\n    def __init__(self):\n        super().__init__(autocast=False)\n        (\n            inputs,\n            actor_board,\n            board,\n            candidates,\n            selected,\n            structure,\n            critic_rivers,\n        ) = encoder.encode_inputs()\n        self.beliefs = beliefs.Beliefs()\n        belief_logits = self.beliefs(inputs, hidden=board, rivers=critic_rivers)\n        # Downstream heads read these probabilities as fixed evidence. The\n        # original logits retain gradients for each head's supervised loss.\n        belief_probability = {\n            name: tf.keras.ops.stop_gradient(value)\n            for name, value in beliefs.Probabilities(dtype=\"float32\")(\n                {\n                    name: belief_logits[name]\n                    for name in beliefs.BELIEF_HEADS + beliefs.COMPLETION_HEADS\n                }\n            ).items()\n        }\n        wait = beliefs.StructuralWait(dtype=\"float32\")(belief_logits)\n        eligibility = tf.keras.layers.Dense(\n            34, dtype=\"float32\", name=\"candidate_ron\"\n        )(\n            tf.keras.layers.Dense(\n                128,\n                activation=\"gelu\",\n                dtype=\"float32\",\n                name=\"ron_eligibility_hidden\",\n            )(\n                tf.keras.layers.Concatenate(dtype=\"float32\")(\n                    [\n                        tf.keras.layers.RepeatVector(3)(board),\n                        belief_logits[\"opponent_yaku_hidden\"],\n                        belief_probability[\"round_completion_yaku_logits\"][\n                            :, 1:, 0\n                        ],\n                    ]\n                )\n            )\n        )\n        # Policy evidence weights improving-tile slices by their shanten mass.\n        shanten, improving, counts = (\n            belief_probability[name] for name in beliefs.BELIEF_HEADS\n        )\n        flatten = tf.keras.layers.Flatten(dtype=\"float32\")\n        concatenate = tf.keras.layers.Concatenate(dtype=\"float32\")\n        completion = concatenate(\n            [\n                flatten(belief_probability[name])\n                for name in beliefs.COMPLETION_HEADS\n            ]\n        )\n        predicted = tf.keras.layers.Dense(\n            256, activation=\"gelu\", dtype=\"float32\", name=\"policy_evidence\"\n        )(\n            concatenate(\n                [\n                    actor_board,\n                    flatten(shanten),\n                    flatten(\n                        tf.keras.layers.Multiply(\n                            name=\"shanten_weighted_ukeire\", dtype=\"float32\"\n                        )([shanten[..., None], improving])\n                    ),\n                    flatten(counts),\n                    completion,\n                ]\n            )\n        )\n        context = concatenate([actor_board, predicted])\n        for block in range(2):\n            context = tf.keras.layers.Add(dtype=\"float32\")(\n                [\n                    context,\n                    tf.keras.Sequential(\n                        [\n                            tf.keras.layers.LayerNormalization(dtype=\"float32\"),\n                            tf.keras.layers.Dense(\n                                384, activation=\"gelu\", dtype=\"float32\"\n                            ),\n                            tf.keras.layers.Dense(\n                                768, kernel_initializer=\"zeros\", dtype=\"float32\"\n                            ),\n                        ],\n                        name=(\n                            \"actor_refinement\"\n                            if block == 0\n                            else \"actor_refinement_1\"\n                        ),\n                    )(context),\n                ]\n            )\n        # Critic and belief losses retain their direct encoder paths.\n        # The private actor stack learns above detached lower encodings.\n        encoded = {\n            \"candidate\": candidates,\n            \"board\": board,\n            \"actor_board\": actor_board,\n            \"selected\": selected,\n            \"structure\": structure,\n            \"critic_rivers\": critic_rivers,\n            **belief_logits,\n            \"opponent_wait_logits\": wait,\n            \"ron_eligibility_logits\": eligibility,\n            \"belief_context\": concatenate(\n                [flatten(shanten), flatten(improving), flatten(counts)]\n            ),\n            \"completion_context\": completion,\n            \"policy_context\": context,\n        }\n        self.context = critic.HandContext(dtype=\"float32\")\n        self.public = critic.PublicContext(dtype=\"float32\")\n        self.player_context = critic.PlayerContext(dtype=\"float32\")\n        self.critic = critic.PaymentCritic(\n            belief_offset=candidates.shape[-1],\n            player_width=self.player_context(\n                [inputs, critic_rivers, selected]\n            ).shape[-1],\n        )\n\n        predictions = candidate_predictions.predict(\n            inputs=inputs,\n            candidates=candidates,\n            selected=selected,\n            wait_logits=wait,\n            eligibility_logits=eligibility,\n        )\n        outputs = {\n            **predictions,\n            **actor_layers.build_board_heads(inputs, context),\n            **actor_layers.build_policy_heads(\n                inputs=inputs,\n                context=context,\n                candidates=tf.keras.ops.stop_gradient(candidates),\n                selected=selected,\n                predictions=predictions,\n            ),\n        }\n        outputs[\"constraint_loss\"] = tf.keras.layers.Add(dtype=\"float32\")(\n            [\n                encoded[\"belief_constraint_loss\"],\n                outputs[\"route_constraint_loss\"],\n                encoded[\"round_completion_yaku_logits_constraint_loss\"],\n                encoded[\"round_completion_score_logits_constraint_loss\"],\n            ]\n        )\n        # Auxiliary heads have visible-route and hindsight targets.\n        # Only predictions enter the actor; labels stay in the trainer.\n        self.actor = actor_layers.CallPolicy(\n            tf.keras.Model(inputs, {**outputs, **encoded}, autocast=False),\n            self.context,\n            self.beliefs,\n        )\n        # Both paths reuse the same local/accepted-call encodings. Unused\n        # final policy readouts have no path to the critic objective.\n        self.encoder = self.actor\n\n    def compile_training(self):\n        \"\"\"Call after initialization so tracing binds live Keras variables.\"\"\"\n        self.critic.distributions = tf.function(\n            self.critic.distributions, jit_compile=True\n        )\n        self.critic.joint_distributions = tf.function(\n            self.critic.joint_distributions, jit_compile=True\n        )\n        self.critic.chunk_statistics = tf.function(\n            self.critic.chunk_statistics, jit_compile=True\n        )\n        self.critic.chunk_gradients = tf.function(\n            self.critic.chunk_gradients, jit_compile=True\n        )\n        self.critic.candidate_chunk = tf.function(\n            self.critic.candidate_chunk, jit_compile=True\n        )\n        self.critic.supervised_statistics = tf.function(\n            self.critic.supervised_statistics\n        )\n\n    def candidate_context(self, features, encoded):\n        return tf.concat(\n            [\n                encoded[\"candidate_context\"],\n                self.public(\n                    [features, encoded[\"selected\"], encoded[\"structure\"]]\n                ),\n                tf.sigmoid(tf.stop_gradient(encoded[\"route_affinity_logits\"])),\n                encoded[\"candidate_completion\"],\n                tf.reshape(\n                    self.player_context(\n                        [\n                            features,\n                            encoded[\"critic_rivers\"],\n                            encoded[\"selected\"],\n                        ]\n                    ),\n                    (-1, 4 * self.critic.player_width),\n                ),\n            ],\n            axis=-1,\n        )\n\n    def call(self, inputs):\n        outputs = self.actor(inputs[0])\n        # Reuse the actor encoder output for critic supervision.\n        state = self.candidate_context(inputs[0], outputs)\n        return {\n            **outputs,\n            **self.supervised_outputs(inputs, outputs, state),\n        }\n\n    def chosen_inputs(self, features, encoded, state, chosen):\n        \"\"\"One observed action per row, with the shared transition contract.\"\"\"\n        recorded = (\n            tf.gather(chosen, encoded[\"selected\"][:, 0])\n            == encoded[\"selected\"][:, 1]\n        )\n        selected = tf.boolean_mask(encoded[\"selected\"], recorded)\n        return {\n            **joint_settlement.public_inputs(features),\n            \"state\": tf.boolean_mask(state, recorded),\n            **critic.public_inputs(features, selected),\n        }\n\n    def supervised_outputs(self, inputs, encoded, state):\n        features, labels, _ = inputs\n        recorded_inputs = self.chosen_inputs(\n            features, encoded, state, critic.chosen_actions(features, labels)\n        )\n        if not self.critic.built:\n            self.critic(\n                {name: value[:1] for name, value in recorded_inputs.items()}\n            )\n        return {\n            \"critic_statistics\": self.critic.supervised_statistics(\n                recorded_inputs, inputs[2]\n            )\n        }\n",
      "sha256": "50bf67de5d6c5337b407bd39fd377e7723d1946a6e2214488b3a5519ecd45c2f"
    },
    {
      "path": "model/outcomes.py",
      "text": "\"\"\"Stable hand payments, score conservation and initial-dealer tie priority.\"\"\"\n\nimport numpy\n\nPAYMENT_TYPES = (\"ron\", \"tsumo\", \"draw\", \"bank\")\nSAINT3_JADE_SOUTH_OFFSETS = (125, 60, -5, -255)\nOBJECTIVE_ST3_SCALE = 100.0\nPAYMENT_CELLS = numpy.array(\n    [\n        [\n            [\n                payer == recipient if kind == \"bank\" else payer != recipient\n                for recipient in range(4)\n            ]\n            for payer in range(4)\n        ]\n        for kind in PAYMENT_TYPES\n    ]\n)\n\n\n# Scoring states are hand values, never payer-specific point amounts.\n# 20/25 fu require at least two han; sub-mangan hands stop at 110 fu.\n# Fu-capped mangan (3 han 70+ fu, 4 han 40+ fu) shares the limit tier.\n# Limit hands use representative han: mangan, haneman, baiman, sanbaiman,\n# kazoe. Named yakuman count once; at most four distinct families can stack\n# in the native four-player rules (double-value variants are normalized).\nSCORE_STATES = (\n    tuple(\n        (han, fu)\n        for han in range(1, 5)\n        for fu in (20, 25, *range(30, 111, 10))\n        if (han >= 2 or fu >= 30) and fu * 2 ** (han + 2) < 2000\n    )\n    + tuple((han, 0) for han in (5, 6, 8, 11, 13))\n    + tuple((0, count) for count in range(1, 5))\n)\n\n\ndef basic_points(han, fu):\n    if han >= 13:\n        return 8000\n    if han >= 11:\n        return 6000\n    if han >= 8:\n        return 4000\n    if han >= 6:\n        return 3000\n    if han >= 5:\n        return 2000\n    return min(2000, fu * 2 ** (han + 2))\n\n\n# Derived monetary alphabet, including exhaustive draws and pao shares.\n# Bank awards also have four public-state atoms; records store raw amounts.\nPAYMENT_VALUES = numpy.array(\n    sorted(\n        {-1000, 0, 750, 1000, 1500, 3000}\n        | {\n            4000 * count * factor\n            for count in range(1, 5)\n            for factor in (1, 2, 3, 4, 6, 8, 12)\n        }\n        | {\n            100\n            * (\n                (\n                    factor * (8000 * fu if han == 0 else basic_points(han, fu))\n                    + 99\n                )\n                // 100\n            )\n            for han, fu in SCORE_STATES\n            for factor in (1, 2, 4, 6)\n        }\n    ),\n    dtype=numpy.int32,\n)\n\n\ndef saint3_jade_south(scores, ranks):\n    \"\"\"Final ST3 return, with one-based ranks and scores in table points.\"\"\"\n    return numpy.ceil(\n        (numpy.asarray(scores) - 25000) / 1000\n        + numpy.asarray(SAINT3_JADE_SOUTH_OFFSETS)[numpy.asarray(ranks) - 1]\n    ).astype(numpy.int32)\n\n\ndef normalize_draw_payments(events):\n    \"\"\"Remove native draw deltas' already-paid riichi deposits.\n\n    Nagashi and zero-transfer exhaustive draws can retain the per-seat\n    deposit delta. MJAI reach_accepted already accounts for that payment.\n    Accept only the observed, conservation-checked native defect.\n    \"\"\"\n    for event in events:\n        if event[\"type\"] == \"start_kyoku\":\n            deposits = [0] * 4\n        elif event[\"type\"] == \"reach_accepted\":\n            deposits[event[\"actor\"]] += 1000\n        elif event[\"type\"] == \"ryukyoku\" and sum(event[\"deltas\"]):\n            corrected = [\n                delta + deposit\n                for delta, deposit in zip(event[\"deltas\"], deposits)\n            ]\n            if sum(corrected) or not (\n                event[\"reason\"] == \"nagashimangan\"\n                or (\n                    event[\"reason\"] == \"exhaustive_draw\"\n                    and corrected == [0] * 4\n                )\n            ):\n                raise ValueError(f\"Invalid native draw payment: {event}\")\n            event[\"deltas\"] = corrected\n\n\ndef normalize_recorded_endings(events):\n    \"\"\"Recover omitted fourth-riichi acceptance from next-round accounting.\n\n    Annotate the existing terminal event, preserving every decision index.\n    A triple ron on the fourth declaration retains its unpaid deposit.\n    \"\"\"\n    start = None\n    for index, event in enumerate(events):\n        if event[\"type\"] not in (\"start_kyoku\", \"end_game\"):\n            continue\n        if start is not None:\n            hand = events[start:index]\n            declared = {\n                row[\"actor\"]\n                for row in hand\n                if row[\"type\"] in (\"reach\", \"reach_accepted\")\n            }\n            accepted = {\n                row[\"actor\"] for row in hand if row[\"type\"] == \"reach_accepted\"\n            }\n            ending = next(\n                row\n                for row in reversed(hand)\n                if row[\"type\"] in (\"hora\", \"ryukyoku\")\n            )\n            if (\n                ending[\"type\"] == \"ryukyoku\"\n                and len(declared) == 4\n                and len(accepted) == 3\n            ):\n                if \"scores\" not in event:\n                    raise ValueError(\"Missing fourth-riichi score evidence\")\n                change = numpy.array(event[\"scores\"]) - hand[0][\"scores\"]\n                paid = numpy.array([seat in accepted for seat in range(4)])\n                if numpy.array_equal(change, [-1000] * 4):\n                    if event[\"type\"] == \"start_kyoku\":\n                        assert event[\"kyotaku\"] == hand[0][\"kyotaku\"] + 4\n                    assert ending[\"deltas\"] == [0] * 4\n                    if \"reason\" in ending:\n                        assert ending[\"reason\"] == \"suucha_riichi\"\n                    ending[\"reason\"] = \"suucha_riichi\"\n                elif numpy.array_equal(change, -1000 * paid):\n                    if event[\"type\"] == \"start_kyoku\":\n                        assert event[\"kyotaku\"] == hand[0][\"kyotaku\"] + 3\n                else:\n                    raise ValueError(\"Inconsistent fourth-riichi accounting\")\n        start = index if event[\"type\"] == \"start_kyoku\" else None\n\n\ndef terminal_payments(events):\n    \"\"\"Typed ron/tsumo/draw/bank transfers, without honba, including pao.\"\"\"\n    result = numpy.zeros((len(PAYMENT_TYPES), 4, 4), dtype=numpy.int32)\n    honba = 0\n    for event in events:\n        if event[\"type\"] == \"start_kyoku\":\n            hand_start = event\n            live_wall = 70\n            nagashi = [True] * 4\n            declarations = set()\n            accepted = set()\n            honba = event.get(\"honba\", 0)\n        elif event[\"type\"] == \"tsumo\":\n            live_wall -= 1\n        elif event[\"type\"] == \"dahai\":\n            nagashi[event[\"actor\"]] &= (\n                len(event[\"pai\"]) == 1 or event[\"pai\"][0] in \"19\"\n            )\n        elif event[\"type\"] in (\"chi\", \"pon\", \"daiminkan\"):\n            nagashi[event[\"target\"]] = False\n        elif event[\"type\"] == \"reach\":\n            declarations.add(event[\"actor\"])\n        elif event[\"type\"] == \"reach_accepted\":\n            declarations.add(event[\"actor\"])\n            accepted.add(event[\"actor\"])\n            result[3, event[\"actor\"], event[\"actor\"]] -= 1000\n        elif event[\"type\"] == \"hora\":\n            winner = event[\"actor\"]\n            delta = event[\"deltas\"]\n            payers = [seat for seat in range(4) if delta[seat] < 0]\n            for payer in payers:\n                if event[\"target\"] == winner:\n                    # Tenhou pao tsumo charges one seat all three shares.\n                    bonus = 300 * honba // len(payers)\n                else:\n                    # Split pao ron charges honba only to the liable seat,\n                    # which is the payer other than the discarder.\n                    bonus = (\n                        300\n                        * honba\n                        * (len(payers) == 1 or payer != event[\"target\"])\n                    )\n                result[int(event[\"target\"] == winner), payer, winner] += (\n                    -delta[payer] - bonus\n                )\n            result[3, winner, winner] += sum(delta)\n            honba = 0\n        elif event[\"type\"] == \"ryukyoku\":\n            if event.get(\"reason\") == \"suucha_riichi\":\n                assert len(declarations) == 4\n                for actor in declarations - accepted:\n                    result[3, actor, actor] -= 1000\n            delta = numpy.array(event[\"deltas\"])\n            if numpy.any(numpy.abs(delta) > 3000) and (\n                event.get(\"reason\") not in (None, \"nagashimangan\")\n                or (\"reason\" not in event and live_wall != 0)\n            ):\n                raise ValueError(f\"Invalid non-nagashi draw payment: {event}\")\n            if event.get(\"reason\") == \"nagashimangan\" or (\n                \"reason\" not in event\n                and (\n                    numpy.any(numpy.abs(delta) > 3000)\n                    or (live_wall == 0 and all(nagashi))\n                )\n            ):\n                # Native deltas net simultaneous mangan transfers. Preserve\n                # their gross directed payments, including winner-to-winner\n                # transfers; equal splitting corrupts dealer/nondealer wins.\n                payment = (\n                    ((delta > 0) | numpy.all(delta == 0))[None]\n                    * (1 - numpy.eye(4, dtype=numpy.int32))\n                    * numpy.where(\n                        (numpy.arange(4)[:, None] == hand_start[\"oya\"])\n                        | (numpy.arange(4)[None] == hand_start[\"oya\"]),\n                        4000,\n                        2000,\n                    )\n                )\n                if not numpy.array_equal(\n                    payment.sum(0) - payment.sum(1), delta\n                ):\n                    raise ValueError(f\"Invalid nagashi payment: {event}\")\n                result[2] += payment\n                continue\n            losers = numpy.flatnonzero(delta < 0)\n            winners = numpy.flatnonzero(delta > 0)\n            for loser in losers:\n                for winner in winners:\n                    result[2, loser, winner] += -delta[loser] // len(winners)\n    return result\n\n\ndef terminal_ending(events):\n    \"\"\"Observed ending kind, ron source and draw readiness for one hand.\n\n    Kinds are ron, tsumo, exhaustive draw, abort and nagashi (0 through 4).\n    Input draw deltas must already be normalized by normalize_draw_payments.\n    Only final concealed tile counts are reconstructed; no decisions replay.\n    \"\"\"\n    from log_dataset import shanten\n\n    ending = next(\n        event\n        for event in reversed(events)\n        if event[\"type\"] in (\"hora\", \"ryukyoku\")\n    )\n    if ending[\"type\"] == \"hora\":\n        kind = int(ending[\"actor\"] == ending[\"target\"])\n    elif \"reason\" not in ending:\n        kan_actors = [\n            event[\"actor\"]\n            for event in events\n            if event[\"type\"] in (\"ankan\", \"kakan\", \"daiminkan\")\n        ]\n        # Abort rules take precedence even when the fourth kan/riichi\n        # coincides with the last wall draw. Archives omit the draw reason.\n        if (len(kan_actors) >= 4 and len(set(kan_actors)) > 1) or sum(\n            event[\"type\"] == \"reach_accepted\" for event in events\n        ) == 4:\n            kind = 3\n        elif terminal_payments(events)[2].sum() > 3000:\n            kind = 4\n        else:\n            kind = (\n                2\n                if sum(event[\"type\"] == \"tsumo\" for event in events) == 70\n                else 3\n            )\n    elif ending[\"reason\"] == \"nagashimangan\":\n        kind = 4\n    else:\n        kind = 2 if ending[\"reason\"] == \"exhaustive_draw\" else 3\n    if kind == 0:\n        assert all(\n            event[\"target\"] == ending[\"target\"]\n            and event[\"actor\"] != event[\"target\"]\n            for event in events\n            if event[\"type\"] == \"hora\"\n        ), \"Ron winners must share the actual discarder\"\n    if kind in (2, 4):\n        for event in events:\n            if event[\"type\"] == \"start_kyoku\":\n                counts = numpy.array(\n                    [\n                        numpy.bincount(\n                            [shanten.base_id(tile) for tile in hand],\n                            minlength=34,\n                        )\n                        for hand in event[\"tehais\"]\n                    ]\n                )\n            elif event[\"type\"] == \"tsumo\":\n                counts[event[\"actor\"], shanten.base_id(event[\"pai\"])] += 1\n            elif event[\"type\"] == \"dahai\":\n                counts[event[\"actor\"], shanten.base_id(event[\"pai\"])] -= 1\n            elif event[\"type\"] in (\"chi\", \"pon\", \"daiminkan\", \"ankan\"):\n                for tile in event[\"consumed\"]:\n                    counts[event[\"actor\"], shanten.base_id(tile)] -= 1\n            elif event[\"type\"] == \"kakan\":\n                counts[event[\"actor\"], shanten.base_id(event[\"pai\"])] -= 1\n        ready = numpy.array(\n            [shanten.calculate_shanten(hand) == 0 for hand in counts],\n            numpy.int8,\n        )\n    else:\n        ready = numpy.zeros(4, numpy.int8)\n    return {\n        \"round_end_kind\": numpy.int8(kind),\n        \"round_end_source\": numpy.int8(ending[\"target\"] if kind == 0 else -1),\n        \"round_end_tenpai\": ready,\n    }\n\n\ndef settlement(payments):\n    payments = numpy.asarray(payments).sum(axis=0)\n    diagonal = numpy.diag(payments)\n    return numpy.r_[\n        payments.sum(0) - payments.sum(1) + diagonal, -diagonal.sum()\n    ]\n\n\ndef relative_payments(payments, actor, accepted_riichi):\n    order = [(actor + offset) % 4 for offset in range(4)]\n    result = numpy.asarray(payments)[:, order][:, :, order].copy()\n    result[3] += numpy.diag(numpy.asarray(accepted_riichi)[order]) * 1000\n    return result\n\n\ndef payment_classes(payments):\n    values = numpy.asarray(payments)\n    matches = values[..., None] == PAYMENT_VALUES\n    if not matches.any(-1).all():\n        raise ValueError(\n            \"payment is outside the declared classes: \"\n            f\"{numpy.unique(values[~matches.any(-1)]).tolist()}\"\n        )\n    return matches.argmax(-1)\n",
      "sha256": "54de3960334008145429a475619791635f78ffb47c8dce86e6c937807d9caa5d"
    },
    {
      "path": "model/payment_scoring.py",
      "text": "\"\"\"Public yaku constraints and joint han/fu payment scoring.\"\"\"\n\nimport numpy\nimport tensorflow as tf\n\nfrom log_dataset import scoring\nfrom model import input_features, outcomes\n\n# Unlisted pairs may coexist; yakuman replaces ordinary scored yaku.\nEXCLUSIVE = numpy.zeros((len(scoring.NAMES), len(scoring.NAMES)), bool)\nfor name, others in {\n    \"pinfu\": (\n        \"haku hatsu chun seat_wind round_wind honroutou toitoi sanankou \"\n        \"sankantsu sanshoku_doukou chiitoitsu shousangen\"\n    ),\n    \"tanyao\": (\n        \"haku hatsu chun seat_wind round_wind chanta honroutou shousangen \"\n        \"honitsu junchan\"\n    ),\n    \"iipeikou\": (\n        \"toitoi sanankou sankantsu sanshoku_doukou chiitoitsu ryanpeikou \"\n        \"honroutou\"\n    ),\n    \"sanshoku_doujun\": (\n        \"ittsuu honroutou toitoi sanankou sankantsu sanshoku_doukou \"\n        \"chiitoitsu shousangen honitsu chinitsu ryanpeikou\"\n    ),\n    \"ittsuu\": (\n        \"chanta honroutou toitoi sanankou sankantsu sanshoku_doukou \"\n        \"chiitoitsu shousangen junchan ryanpeikou\"\n    ),\n    \"chanta\": (\"honroutou toitoi chiitoitsu junchan chinitsu\"),\n    \"honroutou\": \"junchan ryanpeikou chinitsu\",\n    \"toitoi\": \"chiitoitsu junchan ryanpeikou\",\n    \"sanankou\": \"chiitoitsu ryanpeikou\",\n    \"sankantsu\": \"chiitoitsu ryanpeikou\",\n    \"sanshoku_doukou\": \"chiitoitsu shousangen honitsu chinitsu ryanpeikou\",\n    \"chiitoitsu\": \"shousangen ryanpeikou haku hatsu chun seat_wind round_wind\",\n    \"shousangen\": \"junchan chinitsu ryanpeikou\",\n    \"honitsu\": \"junchan chinitsu\",\n    \"junchan\": \"haku hatsu chun seat_wind round_wind\",\n    \"ryanpeikou\": \"haku hatsu chun seat_wind round_wind\",\n    \"chinitsu\": \"haku hatsu chun seat_wind round_wind\",\n    \"yakuman\": \" \".join(scoring.NAMES[:-1]),\n}.items():\n    for other in others.split():\n        EXCLUSIVE[scoring.NAMES.index(name), scoring.NAMES.index(other)] = True\n        EXCLUSIVE[scoring.NAMES.index(other), scoring.NAMES.index(name)] = True\n\n\ndef exclusive_cliques(\n    group=(),\n    candidates=frozenset(range(len(scoring.NAMES))),\n    excluded=frozenset(),\n):\n    \"\"\"Maximal exclusive sets, built once from the scored-yaku graph.\"\"\"\n    if not candidates and not excluded:\n        yield group\n    while candidates:\n        vertex = min(candidates)\n        neighbors = frozenset(numpy.flatnonzero(EXCLUSIVE[vertex]))\n        yield from exclusive_cliques(\n            group + (vertex,), candidates & neighbors, excluded & neighbors\n        )\n        candidates = candidates - {vertex}\n        excluded = excluded | {vertex}\n\n\nEXCLUSIVE_CLIQUES = numpy.array(\n    [\n        [index in group for index in range(len(scoring.NAMES))]\n        for group in exclusive_cliques()\n    ],\n    numpy.float32,\n)\n\n\ndef support(melds):\n    \"\"\"Twenty-three named-yaku masks; concealed future tiles stay unknown.\"\"\"\n    melds = tf.cast(melds, tf.float32)\n    tiles = tf.range(34)\n    sequence = melds[..., 0] > 0\n    triplet = tf.reduce_any(melds[..., 1:5] > 0, axis=-1)\n    used = sequence | triplet\n    any_meld = tf.reduce_any(used, axis=-1)\n    opened = tf.reduce_any(\n        tf.gather(melds, [0, 1, 2, 4], axis=-1) > 0, axis=(-1, -2)\n    )\n    no_sequence = ~tf.reduce_any(sequence, axis=-1)\n    terminal = (tiles >= 27) | (tiles % 9 == 0) | (tiles % 9 == 8)\n    simple = ~tf.reduce_any(\n        (triplet & terminal)\n        | (sequence & ((tiles % 9 == 0) | (tiles % 9 == 6))),\n        axis=-1,\n    )\n    outside = ~tf.reduce_any(\n        (triplet & ~terminal)\n        | (sequence & (tiles % 9 != 0) & (tiles % 9 != 6)),\n        axis=-1,\n    )\n    honor = tf.reduce_any(used[..., 27:], axis=-1)\n    suits = tf.reduce_sum(\n        tf.cast(\n            tf.reduce_any(\n                tf.reshape(\n                    used[..., :27], tf.concat([tf.shape(used)[:-1], [3, 9]], 0)\n                ),\n                axis=-1,\n            ),\n            tf.int32,\n        ),\n        axis=-1,\n    )\n    flush = suits <= 1\n    groups = tf.reduce_sum(melds[..., :5], axis=(-1, -2))\n    dragons = tf.reduce_sum(melds[..., 31:34, 1:5], axis=(-1, -2))\n    winds = tf.reduce_sum(melds[..., 27:31, 1:5], axis=(-1, -2))\n    green = tf.reduce_all(~sequence | (tiles == 19), axis=-1) & tf.reduce_all(\n        ~triplet\n        | tf.reduce_any(tiles[:, None] == [19, 20, 21, 23, 25, 32], -1),\n        axis=-1,\n    )\n    yakuman = (\n        ~opened  # Suuankou; no-meld hands also retain kokushi/chuuren.\n        | (groups - dragons <= 1)  # Daisangen.\n        | (groups - winds <= 1)  # Shousuushii/daisuushii.\n        | green\n        | no_sequence  # Four kans remain possible by upgrading pons.\n    )\n    # A three-group yaku must fit its missing groups in the unfixed slots.\n    sanshoku = tf.reduce_any(\n        tf.reduce_sum(\n            tf.cast(\n                tf.gather(\n                    sequence, [[i, i + 9, i + 18] for i in range(7)], axis=-1\n                ),\n                tf.float32,\n            ),\n            -1,\n        )\n        + (4 - groups[..., None])\n        >= 3,\n        -1,\n    )\n    ittsuu = tf.reduce_any(\n        tf.reduce_sum(\n            tf.cast(\n                tf.gather(\n                    sequence, [[i, i + 3, i + 6] for i in (0, 9, 18)], axis=-1\n                ),\n                tf.float32,\n            ),\n            -1,\n        )\n        + (4 - groups[..., None])\n        >= 3,\n        -1,\n    )\n    doukou = tf.reduce_any(\n        tf.reduce_sum(\n            tf.cast(\n                tf.gather(\n                    triplet, [[i, i + 9, i + 18] for i in range(9)], axis=-1\n                ),\n                tf.float32,\n            ),\n            -1,\n        )\n        + (4 - groups[..., None])\n        >= 3,\n        -1,\n    )\n    return tf.stack(\n        [\n            ~opened & ~tf.reduce_any(triplet, -1),  # Pinfu.\n            simple,\n            ~opened & (groups <= 2),\n            triplet[..., 31] | (groups < 4),\n            triplet[..., 32] | (groups < 4),\n            triplet[..., 33] | (groups < 4),\n            (winds > 0) | (groups < 4),\n            (winds > 0) | (groups < 4),\n            sanshoku,\n            ittsuu,\n            outside & (~no_sequence | (groups < 4)),\n            outside & no_sequence,\n            no_sequence,\n            tf.reduce_sum(tf.gather(melds, [0, 1, 2, 4], axis=-1), (-1, -2))\n            <= 1,\n            tf.reduce_sum(melds[..., 0], -1) <= 1,\n            doukou,\n            ~any_meld,\n            (dragons <= 2) & (groups - dragons <= 2),\n            flush,\n            outside & ~honor & (~no_sequence | (groups < 4)),\n            ~any_meld,\n            flush & ~honor,\n            yakuman,\n        ],\n        axis=-1,\n    )\n\n\ndef public_melds(inputs):\n    \"\"\"Public groups in the same start-tile encoding as candidate melds.\"\"\"\n    starts = tf.reduce_min(\n        tf.where(\n            input_features.meld_tile_valid(inputs) > 0,\n            input_features.meld_tile_ids(inputs),\n            34,\n        ),\n        axis=-1,\n    )\n    return tf.reduce_sum(\n        tf.one_hot(starts, 34)[..., None]\n        * tf.one_hot(tf.cast(inputs[\"meld_type\"], tf.int32) - 1, 5)[\n            ..., None, :\n        ],\n        axis=2,\n    )\n\n\ndef fixed_meld_fu(inputs):\n    \"\"\"Self candidate-zero fu and opponent fu from fixed public melds.\"\"\"\n    tiles = tf.range(34)\n    outside = (tiles >= 27) | (tiles % 9 == 0) | (tiles % 9 == 8)\n    opponents = tf.reduce_sum(\n        public_melds(inputs)[:, 1:]\n        * tf.constant([0.0, 2.0, 8.0, 16.0, 8.0])\n        * (1 + tf.cast(outside, tf.float32))[:, None],\n        axis=(-1, -2),\n    )\n    return tf.concat(\n        [\n            tf.cast(inputs[\"candidate_fu\"][:, :1], tf.int32),\n            tf.cast(opponents, tf.int32),\n        ],\n        axis=1,\n    )\n\n\nclass CompletionMask(tf.keras.layers.Layer):\n    def call(self, values):\n        logits, inputs = values\n        melds = public_melds(inputs)\n        allowed = support(melds)\n        # Concealed tiles can still be discarded and claimed later. Only\n        # publicly unavailable copies rule out a future yakuhai triplet.\n        available = (\n            4\n            - tf.cast(inputs[\"known_unavailable_counts\"], tf.float32)[:, None]\n            + tf.cast(inputs[\"candidate_hand_counts\"][:, 0], tf.float32)[\n                :, None\n            ]\n            + tf.reduce_sum(\n                tf.one_hot(input_features.meld_tile_ids(inputs), 34)\n                * tf.cast(input_features.meld_tile_valid(inputs), tf.float32)[\n                    ..., None\n                ],\n                axis=(2, 3),\n            )\n        )\n        # The offered discard is still claimable, except by its discarder.\n        available += (\n            tf.one_hot(inputs[\"trigger_tile_id\"], 34)[:, None]\n            * tf.cast(inputs[\"trigger_valid\"], tf.float32)[:, None, None]\n            * tf.cast(\n                tf.range(4)[None]\n                != tf.cast(inputs[\"trigger_source\"], tf.int32)[:, None],\n                tf.float32,\n            )[..., None]\n        )\n        triplets = tf.reduce_any(melds[..., 1:] > 0, axis=-1) | (\n            (available >= 3)\n            & (tf.reduce_sum(melds, axis=(-1, -2)) < 4)[..., None]\n        )\n        yakuhai = tf.concat(\n            [\n                triplets[..., 31:34],\n                tf.gather(\n                    triplets,\n                    tf.cast(inputs[\"seat_wind\"], tf.int32) + 27,\n                    axis=2,\n                    batch_dims=2,\n                )[..., None],\n                tf.gather(\n                    triplets,\n                    tf.cast(inputs[\"prevailing_wind\"], tf.int32) + 27,\n                    axis=2,\n                    batch_dims=1,\n                )[..., None],\n            ],\n            axis=-1,\n        )\n        allowed = tf.concat([allowed[..., :3], yakuhai, allowed[..., 8:]], -1)\n        logits = tf.where(allowed[:, :, None], logits, -1e9)\n        # Each connected conflict is a scored-yaku exclusion, not a route.\n        # For yaku i, competing alternatives contribute to its complement.\n        # Thus every mutually exclusive clique has total probability <= 1.\n        competing = tf.where(tf.constant(EXCLUSIVE), logits[..., None, :], -1e9)\n        complement = tf.reduce_logsumexp(\n            tf.concat([tf.zeros_like(logits[..., None]), competing], -1), -1\n        )\n        return logits - complement\n\n\nSCORES = outcomes.SCORE_STATES\n\n\ndef score_class(han, fu, yakuman):\n    if yakuman:\n        return SCORES.index((0, han // 13))\n    if han >= 5:\n        return SCORES.index(\n            (max(tier for tier in (5, 6, 8, 11, 13) if tier <= han), 0)\n        )\n    return SCORES.index(\n        (5, 0) if outcomes.basic_points(han, fu) == 2000 else (han, fu)\n    )\n\n\n# Settlement factors: nondealer tsumo share, dealer tsumo share, ordinary\n# ron, dealer ron. True yakuman states encode their multiplicity.\nCELLS = numpy.argwhere(outcomes.PAYMENT_CELLS)[:24]\nPAYMENT_ENVIRONMENTS = numpy.where(\n    CELLS[:, 0] == 0,\n    2 + (CELLS[:, 2] == numpy.arange(4)[:, None]),\n    (CELLS[:, 1] == numpy.arange(4)[:, None])\n    | (CELLS[:, 2] == numpy.arange(4)[:, None]),\n)\nSCORE_HAN, SCORE_FU = numpy.array(SCORES).T\n# Limit tiers include every han value up to the next threshold.\nSCORE_MAX_HAN = numpy.array(\n    [{6: 7, 8: 10, 11: 12, 13: numpy.inf}.get(han, han) for han in SCORE_HAN]\n)\nPAYMENTS_BY_FACTOR = numpy.where(\n    SCORE_HAN == 0,\n    8000 * SCORE_FU * numpy.array([1, 2, 4, 6])[:, None],\n    100\n    * (\n        (\n            numpy.array([1, 2, 4, 6])[:, None]\n            * numpy.array(\n                [outcomes.basic_points(han, fu) for han, fu in SCORES]\n            )\n            + 99\n        )\n        // 100\n    ),\n)\n\n# Fu is bounded by four exposed concealed terminal/honor kans (4 * 32).\n# Axis order: settlement environment, public fu, scoring mode, score state.\n# Modes are open, closed, and true-yakuman-only.\nPUBLIC_FU = numpy.arange(129)[None, :, None, None]\nRON = numpy.array([False, False, True, True])[:, None, None, None]\nCLOSED = numpy.array([False, True, False])[None, None, :, None]\nLEGAL_SCORE_STATES = (\n    (\n        (\n            (\n                (SCORE_HAN >= 5)\n                | (\n                    (SCORE_FU >= 30)\n                    & (\n                        SCORE_FU\n                        >= 20 + PUBLIC_FU + 10 * (RON & CLOSED) + 2 * ~RON\n                    )\n                )\n                | (\n                    (SCORE_FU == 25)\n                    & CLOSED\n                    & (PUBLIC_FU == 0)\n                    & (SCORE_HAN >= numpy.where(RON, 2, 3))\n                )\n                | (\n                    (SCORE_FU == 20)\n                    & ~RON\n                    & CLOSED\n                    & (PUBLIC_FU == 0)\n                    & (SCORE_HAN >= 2)\n                )\n            )\n            & (numpy.arange(3)[None, None, :, None] != 2)\n        )\n        | (SCORE_HAN == 0)\n    )\n    & (RON | (SCORE_HAN != 1) | (SCORE_FU != 110))\n    & (PAYMENTS_BY_FACTOR[..., None] == outcomes.PAYMENT_VALUES).any(-1)[\n        :, None, None\n    ]\n).reshape(-1, 3, len(SCORES))\n\n\ndef payment_amounts():\n    return PAYMENTS_BY_FACTOR[PAYMENT_ENVIRONMENTS]\n\n\ndef minimum_han_mask(minimum, bonus=0):\n    # Tier states represent intervals: e.g. haneman includes 6 and 7 han.\n    return (tf.constant(SCORE_HAN) == 0) | (\n        tf.constant(SCORE_MAX_HAN, tf.float32)\n        >= tf.cast(bonus, tf.float32)[..., None]\n        + tf.maximum(\n            1.0,\n            tf.cast(minimum[..., None], tf.float32)\n            + tf.constant(\n                numpy.where(SCORE_FU == 25, 2, SCORE_FU == 20), tf.float32\n            ),\n        )\n    )\n\n\ndef masked_score_logits(\n    logits, dealer, meld_fu, opened, riichi_required, bonus, yakuman\n):\n    indices = tf.gather(\n        tf.constant(PAYMENT_ENVIRONMENTS, tf.int32),\n        tf.cast(dealer, tf.int32),\n    ) * 129 + tf.gather(meld_fu, CELLS[:, 2], axis=1)\n    valid = tf.gather(tf.constant(LEGAL_SCORE_STATES), indices)\n    public_bonus = tf.gather(bonus, CELLS[:, 2], axis=1)\n    required = tf.gather(riichi_required, CELLS[:, 2], axis=1)\n    # Before riichi a closed hand can still open. Future bonuses are learned\n    # within the total score distribution; only public minima constrain it.\n    open_valid = (\n        valid[:, :, 0]\n        & ~required[..., None]\n        & minimum_han_mask(tf.zeros_like(public_bonus), bonus=public_bonus)\n    )\n    closed_valid = (\n        valid[:, :, 1]\n        & ~tf.gather(opened, CELLS[:, 2], axis=1)[..., None]\n        & minimum_han_mask(\n            tf.cast(required, tf.int32)\n            + tf.constant(CELLS[:, 0] == 1, tf.int32)[None],\n            bonus=public_bonus,\n        )\n    )\n    return tf.where(\n        (open_valid | closed_valid)\n        & (\n            (tf.constant(SCORE_HAN) != 0)\n            | tf.gather(yakuman, CELLS[:, 2], axis=1)[..., None]\n        ),\n        logits,\n        -1e9,\n    )\n\n\nclass CompletionScoreMask(tf.keras.layers.Layer):\n    def call(self, values):\n        logits, inputs = values\n        fu = fixed_meld_fu(inputs)[:, : logits.shape[1]]\n        opened = tf.reduce_any(\n            (input_features.meld_tile_valid(inputs)[..., 0] > 0)\n            & (inputs[\"meld_type\"] != 4),\n            -1,\n        )[:, : logits.shape[1]]\n        required = inputs[\"riichi_state\"][:, : logits.shape[1]] > 0\n        table = tf.constant(LEGAL_SCORE_STATES.reshape(4, 129, 3, -1))\n        modes = []\n        for environment in (2, 0):\n            allowed = tf.gather(table[environment], fu)\n            modes.append(\n                (\n                    allowed[..., 0, :]\n                    & ~required[..., None]\n                    & minimum_han_mask(\n                        tf.zeros_like(fu),\n                        bonus=tf.cast(\n                            inputs[\"public_bonus\"][:, : logits.shape[1]],\n                            tf.int32,\n                        ),\n                    )\n                )\n                | (\n                    allowed[..., 1, :]\n                    & ~opened[..., None]\n                    & minimum_han_mask(\n                        tf.cast(required, tf.int32) + int(environment == 0),\n                        bonus=tf.cast(\n                            inputs[\"public_bonus\"][:, : logits.shape[1]],\n                            tf.int32,\n                        ),\n                    )\n                )\n            )\n        allowed = tf.stack(modes, axis=2)\n        allowed &= (\n            (tf.constant(SCORE_HAN) != 0)\n            | support(public_melds(inputs))[:, : logits.shape[1], -1, None]\n        )[:, :, None]\n        return tf.where(allowed, logits, -1e9)\n\n\nclass CompletionScoreCoupling(tf.keras.layers.Layer):\n    \"\"\"Lift score tails to the lower bounds implied by the same completion.\n\n    Compatible yaku marginals are never added as if independent. Exclusive\n    alternatives can be summed; the strongest exclusive-set bound wins.\n    \"\"\"\n\n    def call(self, values):\n        logits, yaku_logits, inputs = values\n        yaku = tf.sigmoid(yaku_logits)\n        # Current closed hands may open later. Only declared riichi and\n        # closed-only yaku guarantee closed han and menzen-tsumo bonuses.\n        required = inputs[\"riichi_state\"][:, : logits.shape[1]] > 0\n        closed_only = tf.constant(\n            [\n                True,\n                False,\n                True,\n                False,\n                False,\n                False,\n                False,\n                False,\n                False,\n                False,\n                False,\n                False,\n                False,\n                False,\n                False,\n                False,\n                True,\n                False,\n                False,\n                False,\n                True,\n                False,\n                False,\n            ]\n        )\n        closed = required[..., None] | closed_only\n        # Shousangen also guarantees two dragon triplets (four han total).\n        minimum = (\n            tf.cast(inputs[\"public_bonus\"][:, : logits.shape[1]], tf.int32)[\n                ..., None\n            ]\n            + tf.cast(required[..., None], tf.int32)\n            + tf.where(\n                closed,\n                tf.constant(\n                    [\n                        1,\n                        1,\n                        1,\n                        1,\n                        1,\n                        1,\n                        1,\n                        1,\n                        2,\n                        2,\n                        2,\n                        2,\n                        2,\n                        2,\n                        2,\n                        2,\n                        2,\n                        4,\n                        3,\n                        3,\n                        3,\n                        6,\n                        0,\n                    ]\n                ),\n                tf.constant(\n                    [\n                        1,\n                        1,\n                        1,\n                        1,\n                        1,\n                        1,\n                        1,\n                        1,\n                        1,\n                        1,\n                        1,\n                        2,\n                        2,\n                        2,\n                        2,\n                        2,\n                        2,\n                        4,\n                        2,\n                        2,\n                        3,\n                        5,\n                        0,\n                    ]\n                ),\n            )\n        )[:, :, None] + (\n            tf.cast(closed, tf.int32)[:, :, None]\n            * tf.constant([0, 1])[None, None, :, None]\n        )\n        levels = tf.constant(\n            [(1, 2, 3, 4, 5, 6, 8, 11, 13, 0).index(han) for han in SCORE_HAN],\n            dtype=tf.float32,\n        )\n        # Collapsed haneman/baiman/sanbaiman states include 7/10/12 han.\n        normal = tf.constant(SCORE_HAN > 0)\n        possible = (\n            (logits[..., None, :] > -1e8)\n            & normal\n            & (\n                tf.constant(SCORE_MAX_HAN, tf.float32)\n                >= tf.cast(minimum[..., None], tf.float32)\n            )\n        )\n        # The yakuman label denotes a true yakuman, not counted yakuman.\n        possible = tf.where(\n            tf.range(23)[:, None] == 22,\n            (logits[..., None, :] > -1e8) & ~normal,\n            possible,\n        )\n        floor = tf.reduce_min(tf.where(possible, levels, 9), -1)\n        required_tail = tf.minimum(\n            1.0,\n            tf.reduce_max(\n                tf.einsum(\n                    \"...yt,cy->...ct\",\n                    yaku[..., None]\n                    * tf.cast(\n                        floor[..., None] > tf.range(9, dtype=tf.float32),\n                        tf.float32,\n                    ),\n                    tf.constant(EXCLUSIVE_CLIQUES),\n                ),\n                axis=-2,\n            ),\n        )\n        # Keep true-yakuman mass identical across heads. Project the\n        # remaining conditional distribution from low thresholds to high;\n        # raising a later tail cannot undo any earlier lower bound.\n        conditional_tail = tf.clip_by_value(\n            tf.math.divide_no_nan(\n                required_tail - yaku[..., -1:], 1 - yaku[..., -1:]\n            ),\n            0.0,\n            1.0,\n        )\n        ordinary = tf.where(normal, logits, -1e9)\n        for boundary in range(8):\n            below = normal & (levels <= boundary)\n            above = normal & (levels > boundary)\n            lower = tf.reduce_logsumexp(tf.where(below, ordinary, -1e9), -1)\n            upper = tf.reduce_logsumexp(tf.where(above, ordinary, -1e9), -1)\n            bound = conditional_tail[..., boundary]\n            # Log-space rescaling retains every feasible score when the\n            # bound is below one, even if its starting mass underflows.\n            adjustment = tf.where(\n                below,\n                (tf.math.log(tf.maximum(1 - bound, 1e-30)) - lower)[..., None],\n                (tf.math.log(tf.maximum(bound, 1e-30)) - upper)[..., None],\n            )\n            ordinary = tf.where(\n                normal & (logits > -1e8),\n                tf.where(\n                    (bound > tf.sigmoid(upper - lower))[..., None],\n                    ordinary + adjustment,\n                    ordinary,\n                ),\n                -1e9,\n            )\n        mass = tf.where(normal, 1 - yaku[..., -1:], yaku[..., -1:])\n        conditional = tf.where(\n            normal,\n            tf.nn.log_softmax(ordinary),\n            tf.nn.log_softmax(tf.where(~normal, logits, -1e9)),\n        )\n        return tf.where(\n            (mass > 0) & (logits > -1e8),\n            conditional + tf.math.log(tf.maximum(mass, 1e-30)),\n            -1e9,\n        )\n",
      "sha256": "e880bce05c78c86a39402e11b0126a4945c7825e73bed55a0282f3bc875e31c9"
    },
    {
      "path": "model/river_attention.py",
      "text": "\"\"\"Observed-event attention across opponent seats and riichi segments.\"\"\"\n\nimport tensorflow as tf\n\n\n@tf.keras.utils.register_keras_serializable(package=\"nejimakidori\")\nclass RiverAttention(tf.keras.layers.Layer):\n    def __init__(self, **kwargs):\n        super().__init__(**kwargs)\n        self.position = tf.keras.layers.Embedding(\n            64, 64, dtype=self.dtype_policy\n        )\n        self.seat = tf.keras.layers.Embedding(3, 64, dtype=self.dtype_policy)\n        self.attention = tf.keras.layers.MultiHeadAttention(\n            num_heads=4, key_dim=16, dtype=self.dtype_policy\n        )\n        self.correction = tf.keras.layers.Dense(\n            64,\n            use_bias=False,\n            kernel_initializer=\"zeros\",\n            dtype=self.dtype_policy,\n        )\n\n    def build(self, input_shape):\n        self.position.build((192,))\n        self.seat.build((192,))\n        self.attention.build((None, 192, 64), (None, 192, 64))\n        self.correction.build((None, 192, 64))\n        super().build(input_shape)\n\n    def call(self, values, mask):\n        events = tf.reshape(values, (-1, 192, 64))\n        observed = tf.reshape(mask > 0, (-1, 192))\n        tokens = (\n            events\n            + self.position(tf.range(192) % 64)[None]\n            + self.seat(tf.range(192) // 64)[None]\n        )\n        update = self.attention(\n            tokens,\n            tokens,\n            attention_mask=observed[:, :, None] & observed[:, None, :],\n        )\n        return values + tf.reshape(self.correction(update), (-1, 32, 64)) * mask\n",
      "sha256": "2df91bc717bce63007e8ff6ae01f42269780eb5cdbddaf0f77e7d9c6c6aebb01"
    },
    {
      "path": "training/EVALUATION.md",
      "text": "# Export and evaluation\n\n## Export weights\n\n```sh\npython -m model.export \\\n  --weights /path/to/run/final.weights.h5 \\\n  --data /path/to/dataset --output /path/to/export\n```\n\nTo export without a corpus, replace `--data` with `--self-play-seed 941`.\nExport validates finite outputs, normalized distributions and numerical parity\nbefore and after saving.\n\n| Output | Purpose |\n| --- | --- |\n| `saved_model/` | TensorFlow prediction signatures |\n| `source/` | Matching feature and policy source |\n| `export-verification.json` | Weight identity and validation results |\n\nKeep the model and source together. The `policy` signature returns five action\nheads; the full signature returns the\n[serving tensors](../model/ARCHITECTURE.md#savedmodel-interface). Local applications\ncan use `model.inference.Predictor`.\n\n## Recorded-action agreement\n\nCompare a policy with both the human action and Mortal's recorded greedy action\non the reserved validation set:\n\n```sh\npython -m training.evaluate_imitation \\\n  --model /path/to/export/saved_model \\\n  --data /path/to/expert-data \\\n  --output /path/to/agreement.json\n```\n\nUse `--weights /path/to/checkpoint.weights.h5` instead of `--model` to evaluate\nweights with matching source. The evaluator snapshots the checkpoint before\nloading it and records its hash. `--max-decisions` limits evaluation to a\nrepeatable prefix of the validation sample.\n\nThe report contains exact match counts, disagreements, top-1 agreement and\nsupported-target NLL, overall and by decision type. Call agreement includes\nthe follow-up discard; branch agreement and discard agreement conditional on\nthe target's chi/pon are also reported. Use the same cohort when comparing\ncheckpoints. A small prefix may underrepresent uncommon decisions.\n\n## Compare two models\n\n```sh\npython -m training.evaluate \\\n  --new /path/to/export/saved_model \\\n  --old /path/to/opponent/saved_model \\\n  --output /path/to/match \\\n  --games 10000 --seed 941 --workers 1 --devices -1\n```\n\nEach policy loads its own frozen feature and action source. Every wall seed\nrotates the candidate through all four seats, so the game count must be a\npositive multiple of four. Tile-copy aliases and exact policy ties use seeded\nrandomness keyed by wall, seat, event and decision phase. Neural outputs may\nstill differ slightly with inference batch shape.\n\nRepeating an unchanged command resumes completed games. Changed model files\nor settings require a new output directory. Use independent seeds for later\ncheckpoint comparisons.\n\n| Output | Contents |\n| --- | --- |\n| `evaluation.json` | Model identities, rule format and seed range |\n| `games.jsonl` and `replays/` | Completed game results and MJAI replays |\n| `summary.json` | Placements, scores, ST3 points and paired bootstrap intervals |\n| `metrics.jsonl` | Timestamped progress and comparison metrics |\n\nSummaries include complete four-seat groups only. `new` identifies the\ncandidate and `old` its opponents. Metric rows use stage `evaluation` and\ncompleted games as their step. Lower training loss or higher action agreement alone does not\nestablish stronger play.\n\n### Distributed match collection\n\nAssign disjoint seed ranges to workers and keep each seed's four rotations\ntogether. Use identical model, opponent and adapter files throughout.\n`evaluate.merge_parts()` combines complete result lines from the worker\noutputs. Finalization checks every requested seed/seat and replay, then copies\nthe replays into the merged match directory for training.\n\n## Mortal opponent\n\nThe evaluator also accepts a Mortal checkpoint (`.pth`, or a ZIP containing\none checkpoint):\n\n```sh\npython -m training.evaluate \\\n  --new /path/to/export/saved_model \\\n  --old /path/to/mortal-checkpoint.zip \\\n  --mortal-source /path/to/Mortal \\\n  --output /path/to/mortal-match \\\n  --games 4 --seed 941 --workers 1 --devices -1\n```\n\nInstall PyTorch in the evaluation environment. The adapter uses Mortal commit\n`0cff2b52982be5b1163aa9a62fb01f03ce91e0d2` and its matching `libriichi` extension.\nBuild with the same Python interpreter:\n\n```sh\ngit clone https://github.com/Equim-chan/Mortal.git /path/to/Mortal\ngit -C /path/to/Mortal checkout 0cff2b52982be5b1163aa9a62fb01f03ce91e0d2\ncd /path/to/Mortal\nPYO3_PYTHON=\"$(command -v python)\" cargo build --release --locked -p libriichi\npython - <<'PY'\nimport pathlib\nimport shutil\nimport sysconfig\n\nshutil.copy2(\n    \"target/release/libriichi.so\",\n    pathlib.Path(sysconfig.get_paths()[\"platlib\"]) / \"libriichi.so\",\n)\nPY\n```\n\nMortal receives each seat's private MJAI event stream, loads its checkpoint\nstrictly and uses greedy legal-action selection with the upstream win guard.\nMortal's source and weights remain external dependencies with their own\nlicenses. The match output records their identities for reproducibility.\n\nMortal matches use standard Tenhou South rules, recorded as\n`riichienv_standard_south`. Model-versus-model matches use\n`riichienv_duplicate_south`: per-seat draw queues, shared replacement draws and\n14 tiles reserved at exhaustion. The rule formats are reported separately\nand cannot be combined in one summary.\n\nStart with four games. CPU inference uses `--devices -1`; a comma-separated\nGPU UUID list selects GPU workers. `--batch-games` controls concurrent games.\nMeasure full-game throughput and memory before increasing concurrency.\n\n## Evaluate a training checkpoint\n\n`python -m training.checkpoint_match` exports the checkpoint under\n`OUTPUT/policy/` and runs its comparison under `OUTPUT/matches/`. An existing\nexport must match the checkpoint hash. The\n[training runner](corrections/README.md#run) accepts this command as a JSON\nargument list.\n",
      "sha256": "81da26eb64a724951264198843168b6671eb30eaf5ab2e88ad553c97f097aefa"
    },
    {
      "path": "training/MATCH_RECORDS.md",
      "text": "# Match records\n\nMatch records convert completed games into all-seat settlement and belief\nsupervision, together with the fixed reference probabilities used by MMD.\n\n## Build\n\n```sh\nCUDA_VISIBLE_DEVICES=-1 python -m training.match_records \\\n  --matches /path/to/evaluation/matches \\\n  --reference /path/to/reference/saved_model \\\n  --output /path/to/new-match-records --workers 4\n```\n\nThe input `games.jsonl` and `evaluation.json` identify the complete game set.\nThe output directory must be new. Conversion writes compressed TFRecord shards\nand `dataset.json` with game counts, position counts and reference identities.\nKeep generated records outside the source repository.\n\nThe reference export must include its matching frozen native feature producer.\nConversion replays each original event stream through that producer and stores\nmasked log probabilities for the active policy head. Reference inputs are\nnever reconstructed from the learner's feature tensors.\n\n## Targets\n\nRecords include recoverable decisions from all four seats. Recorded actions\nidentify the observed settlement target; they are not MMD imitation targets.\nUnrecorded losing claims are excluded rather than interpreted as passes.\n\nCurrent-hand payments include accepted riichi deposits and use actor-relative\nseats. Final-game outcomes are not targets. The seven belief targets are\nreconstructed from each decision and its observed continuation; unavailable\ntargets remain masked. The trainer excludes forced decisions and riichi-locked\ndiscards according to the [shared eligibility rule](OBJECTIVE.md#decision-eligibility).\n\n## Batches\n\n`match_records.batches(output, batch_size, seed)` makes one shuffled pass and\nretains the final partial batch.\n\n| Field | Meaning |\n| --- | --- |\n| `features` | Decision-time model inputs |\n| `labels` | Seven supervised belief targets |\n| `chosen` | Canonical critic action ID |\n| `head`, `legal` | Active policy head and legal action mask |\n| `reference_log_probability` | Frozen reference log probabilities, float32 `[150]` |\n| `payment_points` | Observed actor-relative payments |\n\nRoot continuations use the same targets and reference probabilities. Their\ncompressed rollout shards retain every root and descendant decision. The\n[runner](corrections/README.md) owns shuffling, padding and optimizer state.\n",
      "sha256": "0148d49df01c2e3c605b88c324aa6cd471efe20a18f38bcb417198f2bf543cad"
    },
    {
      "path": "training/OBJECTIVE.md",
      "text": "# Training objective\n\nThe model learns from observed current-hand outcomes and recorded decisions.\nIts actor and settlement critic share lower encodings with seven supervised\nbelief predictions. [Training](README.md) describes the commands;\n[model constraints](../model/CONSTRAINTS.md) describe legal support.\n\n## Decision eligibility\n\nPadding, single-legal-action rows and discards committed by riichi contribute\nzero loss. Voluntary riichi/dama decisions and the ordinary discard after\nstaying dama are eligible. Unknown belief targets are masked per coordinate.\nAn entirely excluded global batch does not update optimizer state.\n\nA policy target must also lie within the actor's effective support. A legal\nteacher discard excluded by the final-wall safe-cut rule receives no policy\ncross-entropy or normalization mass, while its known predictive targets\nremain eligible. `policy_target_coverage` reports this fraction. Q-weight\ncalibration uses all eligible rows.\n\n## Expert initialization\n\nThe initializer has exactly three corpus-sized passes of Q-weighted\ncross-entropy against the recorded human action. Each pass uses a fresh\noptimizer at learning rate `1e-5`.\n\nEvery pass also fits the calibrated settlement objective below, with\nunit-weight critic constraints and all seven supervised beliefs. The settlement target\nbelongs to the human action actually played. Unplayed Mortal actions receive\nno copied human outcome labels. Human CE has no MMD penalty.\n\nSettlement sufficient statistics and their gradients use 128-row chunks,\nwith one loop iteration in flight to bound the settlement workspace.\nPadding has zero valid mass; chunk totals are reduced over the original\neligible rows. The backward pass recomputes each chunk instead of retaining\nall settlement distributions. Fixed payoff tables and observed support/targets\nare prepared once, outside the gradient recomputation, and reused by both\npasses. Fixed payoff, support and target preparation is fused into one\ncompiled operation per 32-row block.\nSettlement kernels use XLA compilation. Encoder blocks use ordinary\nTensorFlow graph execution to avoid large nested compilation workspaces and\nrepeated shape-specialization costs.\n\nBefore each human exposure batch, select focused roots paired one-for-one\nwith unfiltered roots from the natural-source half of the batch. Collect\nand fit their Monte Carlo outcomes together at each 16-batch window boundary\nand at pass end. The six categories are Q disagreement, tenpai with threat,\nkeiten, strictly shanten-advancing calls, riichi/dama and future defensive\nsakigiri, using the [shared category rules](corrections/README.md#root-selection).\nEvery advancing\nlegal call-plus-discard is included with pass, regardless of the policy's\npreferred action. Sakigiri includes every qualifying earlier alternative and\nthe recorded cut. Other categories contribute their existing action pair;\noverlapping actions and categories at a position are deduplicated.\n\nEach 16-batch collection window targets one actual simulated decision per\nhuman exposure. Every requested decision across all seats counts, including\nforced roots and descendants not retained for training. Padding and scoring\nrecorded human candidates do not count.\n\nEach human batch selects balanced focused/normal seed pairs using an estimate\nof decisions per continuation: initially 32, then the latest consumed window's actual\nglobal decisions divided by its continuations. Pair selection stops when its\nestimated cost reaches the batch's human count. Eligibility, selected actions\nand category rules are unchanged by lazy scoring: visit all\neligible positions in a seeded random order, score them in small chunks, and\nstop once enough qualifying pairs have been selected. Restricting a uniform\nrandom order to qualifying positions preserves uniform targeted selection;\nthere is no fixed search cap. Score normal partners together after selection.\nSeed policy and discard-Q scoring share one actor encoding. Root affinities\nreuse the recorded labels for the unchanged observed human state.\nCompact metadata, selected actions, wall seeds and root affinities are retained;\nfull human batches are\nnot buffered. Human fitting continues each batch. At the configured interval\n(default 16 batches), and at a short final pass window, accumulated\ncontinuations enter a one-window\nbackground buffer with a configurable active-stream limit per learner\n(default 512). Frozen-reference inference batch size is independently\nconfigurable (default 64); both affect throughput and memory, not the total\nsimulation budget. Ready CPU workers share inference without an all-worker\nbarrier. Collection overlaps\nthe next human window; its root labels are fitted at the following boundary.\nThe final buffer is drained before ending the pass. Each action runs once.\nStarted hands finish. Actual\ncounts can differ from the estimate; there is no debt or repayment. Root\nstarts remain 50/50, with no placement-based sampling or passes.\n\nSeed choices use the live learner at selection time. After the forced root\naction, initializer continuations use the fixed reference policy with its own\nfrozen replay feature producer. They estimate settlement under reference\ncontinuation, not under the changing learner. The buffer delays their critic\nand MMD updates by one human window. Collection can run ahead because its\ncontinuation policy is immutable; the match/root improvement loop continues\nto use learner self-play.\n\nFocused alternatives share one wall seed; normal roots draw two policy actions\nwith replacement and independent walls. The reference plays all seats\nafter the forced root action. Original opponent hands remain fixed; unseen wall tiles, including\nunrevealed indicators, are reshuffled. Human roots load directly from saved\nsimulator states whose features were verified during dataset preparation.\nHeld-out games are rejected. A batch with no eligible natural-source partner\ndoes not collect an unbalanced focused-only set.\n\nEach continuation supplies its own root settlement and eligible belief labels.\nRoot likelihoods are averaged over valid samples. Mean payments are never treated as a settlement.\nOnly roots are retained for initializer updates; descendants are used to\nproduce outcomes and labels. These critic/belief updates share the stage's\noptimizer with human updates. They do not train policy CE or turn forced\nactions into imitation labels. Human expert updates compute Q weights from\nthe learner at that update, including prior collection-window updates. All three initializer passes use this\ncollection/fitting sequence; their human exposure budgets remain unchanged.\n\nEach MC window then trains the actor with the same MMD objective as the\nmain loop: detached expected Q, previous-policy KL 0.3, fixed-reference KL\n0.3, actor structural constraints 0.01, and all seven direct belief losses at\nunit weight. Snapshot the learner actor immediately before fitting that\nwindow's critic targets; keep this mirror fixed through both fits. The magnet\nuses the immutable reference model and its own frozen replay features at the\nroot before any forced action. Reference inference batches independent roots\ntogether; alternatives at the same root share its reference distribution.\nMMD has its own optimizer at 1e-5, fresh each initializer pass and retained\nacross windows within that pass. All collected root rows receive one critic\npass followed by one actor pass. Forced actions are not imitation labels.\n\nFor the expert passes, both action values come from the current learner:\n\n```text\ngap = stop_gradient(Q(human) - Q(Mortal))\nraw_weight = min(20, exp(gap / beta))\nweight = raw_weight / mean_valid(raw_weight)\nloss = mean_valid(weight * human_cross_entropy)\n     + critic_loss\n```\n\nEach global batch calibrates beta in `[0.0001, 1.28]` to target 75% effective\nsample size. The solver chooses the highest-beta crossing; when the target\nis unattainable, it reports the closest grid value. Weights are detached and\napply only to policy cross-entropy. Recorded Mortal choices come from the\nprepared corpus and are mapped into the critic's candidate-action space.\n\nEach pass draws 50% natural and 50% focused records, with\nreplacement. Its total exposure budget equals the number of training records;\nvalidation remains natural and disjoint. Focused sampling emphasizes calls,\nyaku routes, visible threats and late decisions. No placement-based sampling\nstratum or pass remains. Sampling priorities are metadata, not model inputs; their\nrules are defined in [focus_sampling.py](../log_dataset/focus_sampling.py).\nEach learner shard must contain positive focused mass. Initializer MC and\nmain-loop root collection both pair focused and unfiltered normal starts\n50/50. This is a root-start balance: all generated eligible training rows\nremain supervised, so differing action counts or trajectory lengths need not\nproduce equal loss-row counts.\n\n## Current-hand critic\n\n```text\nJ = projected_ST3 / 100 + P(first) - P(fourth)\nQ(action) = sum(settlement_probability * J)\nq_mse = mean_identified((Q(played_action) - observed_J)^2)\ncritic_loss = 0.5 * payment_nll + 0.5 * Q_MSE_TO_NLL * q_mse\n              + nagashi_loss + critic_constraint_loss + sum(belief_losses)\n```\n\nThe critic fits observed payments for the action played, including forced\nalternatives with their own simulated outcomes.\nThe Q target uses the same fixed continuation mapping as predicted Q. It is\neligible only when all payment amounts are known and every compatible legal\nsettlement has the same J (within 1e-6). Required actor-relative\n`round_end_source` records the actual ron discarder, shared by all winners\nin multi-ron; non-ron endings use -1. It distinguishes discarder and liable\npayer in split pao payments, fixing the honba allocation in both NLL and Q.\nRequired `round_end_kind` and actor-relative `round_end_tenpai` labels\ndistinguish nobody-tenpai,\nall-tenpai and abort even when every payment is zero. Nagashi readiness\nidentifies the actual dealer continuation. These are supervision labels,\nnever prediction inputs. Every valid training row must identify its Q target;\nunknown amounts or ambiguous settlements fail training rather than silently\ndropping Q supervision. Zero-mass padding is exempt. Support and Q-target\nchecks run outside XLA after aggregation. `q_target_coverage` remains an\ninternal eligibility diagnostic.\nThe same exact ending labels constrain NLL; its value is not directly\ncomparable to earlier payment-only marginalized NLL.\n\n`Q_MSE_TO_NLL = 9.921187963468466` is a fixed reference-sample NLL/MSE ratio,\nin nats per J squared. Calibration used 2,048 held-out, balanced\nnatural/focused positions: NLL 5.3469339609 nats, MSE 0.5389408991 J squared,\nand 100% identifiable Q targets. These are fixed reference risks,\nnot target loss values or per-batch normalizers.\nThus the two terms receive equal weight on their calibrated scales while\npreserving the prior aggregate critic scale relative to the direct auxiliary\nlosses. The constant does not adapt to current batches or receive gradients.\nRaw `q_mse` remains in J squared and `q_rmse` in J; weighted components are\nreported separately. Equal calibrated losses do not imply equal gradients.\nThe expectation differentiates through settlement probabilities, while the\npayoff table and observed target are fixed and cached once per batch.\nCritic recomputation uses 128-row chunks; fixed payoff preparation uses 32.\nFor event contributions `Q = sum_e p_e * E[J | e]`, every event receives the\nsame scalar residual `2 * (Q - target)`. Conditional score/deposit factors\nalso receive gradients. Squaring separate event errors would change the\nobjective and is not used.\nThe nagashi term is unit-weight binary cross-entropy averaged across four\nplayers, using qualifier marginals of the constrained settlement distribution\nand observed ending labels. Multiple qualifiers receive simultaneous positive\nlabels. This loss trains the critic in imitation and rollout critic fits;\nMMD policy improvement consumes detached Q as before. Alternatives without an\nobserved or simulated outcome receive no settlement target. Each possible\nsettlement passes through the fixed match-continuation mapping before taking\nits expectation. Terminal\nvalues use realized placement and rounded ST3; nonterminal values use\ncalibrated placement probabilities. Final-match returns are not targets.\n\nThe likelihood marginalizes compatible total han/fu outcomes. Public scoring\nevidence conditions the score network; future bonuses are learned within its\nsingle total-score distribution, with no separate added-han prediction.\nBelief and critic losses train their own readouts and shared representations.\nA call candidate includes its contingent discard; settlement forecasts account\nfor the possibility that another player preempts the attempted call.\n\n## Magnetic mirror descent\n\nEach match/root phase fits the critic once, then trains the actor once:\n\n```text\nactor_loss = -sum((P(current) - P(previous)) * stop_gradient(Q))\n           + 0.3 * KL(current || previous)\n           + 0.3 * KL(current || fixed_reference)\n           + 0.01 * structural_constraint_loss\n           + sum(belief_losses)\n```\n\nThe previous policy is frozen at the start of each phase, before critic\nfitting. The fixed reference remains unchanged throughout the run. Both\nreferences and Q values are detached. All legal actions enter the objective;\nforcing an action at a rollout root does not make it an imitation target.\nThe previous-policy value term is a constant baseline.\n\nReference probabilities are evaluated with the reference export's own frozen\nfeature producer, then stored with each training decision. The actor and critic\nuse separate AdamW optimizers at `1e-5`. Optimizer state persists across the\nmatch/root phases. Gradients are summed globally, clipped per variable at norm\n1, and checked for finite values before an update.\n\n## Gradient ownership\n\n| Objective | Shared representation | Own prediction layers | Actor layers |\n| --- | --- | --- | --- |\n| Direct belief supervision | Yes | Yes | No |\n| Settlement likelihood and critic constraints | Yes | Yes | No |\n| Policy cross-entropy, Q improvement and KL | No | No | Yes |\n\nEvery consumed belief prediction is detached, including predictions consumed\nby another belief. The private actor upper encoder consumes detached lower\nhand/public encodings and remains trainable through policy losses. Shared\ncandidate evidence also stays detached at its policy consumer. Critic and\nbelief losses train the other upper encoder and shared lower encodings,\nwithout updating the private actor branch. Consequently, shared features\ncan change during an MMD actor pass through direct belief supervision, while\nQ itself remains outside the actor's gradient path.\n\nMonitor likelihood, supervised belief losses, KL penalties and gradient\nnorms alongside [independent match results](EVALUATION.md). J includes placement\nbonuses, so multiplying it by 100 does not recover ST3. Lower training loss\nalone does not establish stronger play.\n",
      "sha256": "b3b2339ef22e85fa0c96a35ccf8ee2e71e9366d965a23e26215995af9e245783"
    },
    {
      "path": "training/README.md",
      "text": "# Training\n\nTraining starts with three expert passes, then improves the policy through\nmatches and self-play continuations. See [setup](../SETUP.md) for dependencies\nand [dataset preparation](../log_dataset/README.md) for training records.\n\n## Initialize from expert logs\n\nThe initializer runs three Q-weighted expert imitation passes. Each pass\nsamples one corpus-sized budget with 50% natural and 50% focused\nexamples. There is no placement-based sampling stratum. Validation\nrecords are excluded. Each pass starts a fresh AdamW optimizer at `1e-5`.\n\nAll three passes train a half NLL / half calibrated Q-MSE settlement critic,\nplus unit-weight direct nagashi, critic constraints and seven supervised beliefs.\nSee [loss units and target eligibility](OBJECTIVE.md#current-hand-critic). Human settlement targets belong to the recorded\nhuman action. Recorded Mortal choices supply the Q-weight comparator. Targeted\nalternatives also receive one simulated root settlement each. Compact balanced\nseeds accumulate while human training continues each batch. Every configured collection interval (default 16 human\nbatches, or at pass end), their continuations enter a single-window background\nbuffer. The next human window overlaps collection. At the next boundary,\ncompleted root labels fit the critic, followed by an MMD actor pass; the final\nwindow is drained before the pass completes. Starts are 50/50 focused/natural. The simulated-decision\ntarget matches the window's human exposures, estimated using the previous\nconsumed window's decisions per continuation (initially 32). Started hands finish;\nthere is no debt or repayment. Each selected action is simulated once.\nThe six shared categories\nare Q disagreement, tenpai with threat, keiten, improving calls, riichi/dama,\nand future defensive sakigiri; all shanten-advancing calls include pass. Rollout\nactions do not become imitation labels. Policy losses train the private actor upper encoder and policy layers. Critic\nand belief losses train their own upper encoder and the shared lower\nrepresentations; the actor reads those lower representations detached.\nThe [objective reference](OBJECTIVE.md) defines the losses and gradient rules.\n\nPrepare an [evaluation command](corrections/README.md#run), then run:\n\n```sh\npython -m training.expert \\\n  --data /path/to/expert-data \\\n  --initial /path/to/initial.weights.h5 \\\n  --reference /path/to/fixed-reference/saved_model \\\n  --output /path/to/new-initializer \\\n  --evaluation-command evaluation-command.json \\\n  --batch-size 512 --rollout-batch-size 512 \\\n  --collection-streams 512 --reference-batch-size 64 \\\n  --collection-interval-batches 16 --seed 941\n```\n\nPrepare the dataset's [persistent root states](../log_dataset/README.md#prepare-human-root-states)\nbefore starting initialization. The collector loads verified simulator snapshots\ndirectly; source archives are needed only during preparation. One wall seed\nis shared across competing focused actions; normal branches use independent\nwalls. After the forced root action, the fixed reference plays every seat\nusing its own frozen feature producer. These settlement targets describe\nreference-policy continuations, not current-learner continuations. Root\nselection still uses the live learner. The match/root improvement loop retains\nlearner self-play.\nIndependent action streams share inference batches. `--collection-streams`\nlimits active hand continuations per learner (default 512), divided exactly\namong its four CPU workers. `--reference-batch-size` controls frozen-reference\nGPU inference batches (default 64). `--collection-interval-batches` controls\nhow many human batches supply each window (default 16). Doubling the interval\ndoubles both the window's human budget and its estimated simulation target;\nit does not double the total simulation budget per human position. Benchmark them with overlapping human updates and\nMC fitting, since larger inference batches also consume device memory.\nFour persistent CPU processes per learner advance continuations and\nbuild labels; ready workers share reference GPU inference without waiting\nfor every worker. A bounded collection thread overlaps reference inference\nand simulation with human training. Workers\nhave no visible GPUs and retain their processes across collection windows.\nOnly root rows are retained; future-tenpai scoring stops once each\nrequested decision has its first witness. Each stream retains its own RNG and\noutcome labels. Visible candidate yaku-affinity labels reuse the recorded\nhuman-state labels and are shared across its actions and walls; future-hand and settlement labels\nremain specific to each continuation.\nCollection is additional work beyond the corpus-sized human exposure budget.\n\nThe output includes per-rank `imitation-rollouts/pass-N/window-*-rank-N/`\ndirectories containing `roots.json`, `statistics.json` and, when eligible\nroots exist, `outcomes.npz`. Receipts record original position identities,\nhead-local actions, targeted/normal kind, categories and per-action wall seeds. Outcome shards contain packed\nroot features, global critic actions, one settlement per selected action\nand directly supervised belief labels. Collection receipts and metric reports\ninclude total collection time and the remaining foreground wait. Store run\noutputs on artifact storage.\n\nThe output also includes a checkpoint for each pass, `final.weights.h5`, progress\nJSON and `metrics.jsonl`. `training-complete.json` marks successful\ncompletion. Use the final checkpoint as `--initial` for the\n[match/root training command](corrections/README.md#run). Its first match is\nthe first post-initialization evaluation; no match runs between expert passes.\n\n## Improve through matches\n\nThe [MMD runner](corrections/README.md) alternates a Mortal match, critic and\nactor fitting, and self-play continuations from selected positions. Every\nphase trains on eligible decisions from all four seats. The final match\nmeasures the final checkpoint and is not trained afterward.\n\nCreate a `STOP` file in a run's output directory to stop at the next safe\nboundary. Training commands require a new output directory and start fresh\noptimizers. Evaluation commands can resume unchanged matches.\n\n## Eligibility and monitoring\n\nSingle-legal-action decisions and discards committed by riichi do not train\npolicy, critic or beliefs. Voluntary riichi/dama decisions and the ordinary\ndiscard after staying dama remain eligible. Unknown belief targets are masked\nindependently. An entirely excluded batch leaves optimizer state unchanged.\n\n`exposures` counts sampled records; `actor_exposures` and `critic_exposures`\ncount eligible positions processed by their respective phases. Progress files\ninclude the `imitation-rollout` critic phase: its samples increase\n`critic_exposures`, while `actor_exposures` and corpus `exposures` count human\nrecords only. Fresh optimizer state is shared by both update types within\neach pass. Replica padding contributes no loss, including ranks with no roots.\nJSON metric reports include losses, policy agreement, gradient norms and\nthroughput. Each human batch reports `expert_top1` and `expert_top3` from\nthe pre-update policy, averaged over valid, supported expert targets without\nQ weighting. These training match rates are not held-out evaluation scores.\n[Independent evaluation](EVALUATION.md) measures playing strength separately.\n\nUse one visible GPU per learner process. Leave `TF_DETERMINISTIC_OPS` unset\nor set it to `0` for normal GPU execution; data and game seeds are controlled\nseparately. [Distributed execution](corrections/README.md#multiple-workers)\nuses global loss normalization and synchronized updates.\n\nTo pause an active fitting stage, create `PAUSE` in its candidate output\ndirectory. All learners pause together at the next optimizer-step boundary;\n`pause.json` acknowledges when they are parked. Remove `PAUSE` to resume\nthe same in-memory weights and optimizers. `STOP` also works while paused.\nInitializer elapsed time excludes acknowledged pauses. Keep learner and\nsupervisor processes running: freezing or suspending them also stops the\ndistributed heartbeats and can fail the run when resumed.\n\n| Guide | Purpose |\n| --- | --- |\n| [Objectives](OBJECTIVE.md) | Supervision, values and gradient boundaries |\n| [Match/root workflow](corrections/README.md) | Improvement loop and command-line setup |\n| [Match records](MATCH_RECORDS.md) | Recorded decisions and training targets |\n| [Evaluation](EVALUATION.md) | Export, action agreement and matches |\n\n\n## Metric reporting\n\nEach trainer writes `metrics.jsonl` in its output directory. Each line is one\ncomplete observation containing Unix `time`, numeric `step`, `stage`, and a\n`metrics` object mapping metric names to scalar values. Initializer records\ninclude `pass`; self-play records include `round`. The format supports any\nnumber of imitation passes followed by self-play, including no initializer.\nThe selected training recipe still determines the actual number of passes.\n\n`step` is a shared chronological training-position clock. Each human batch\nadvances it once by its global position count. Each targeted-rollout critic\nfit and MMD actor update then advances it by the positions trained, in actual\nexecution order. Collection itself does not advance it. The complete cycle\nbelongs to the imitation pass, so matching metrics can be interleaved on one\nposition axis. Self-play uses cumulative actor plus critic fitting positions.\nThe clock starts at zero for each training invocation; `reporting_positions`\nin status/progress JSON records the same value. Existing human, actor and\ncritic exposure counters retain their original meanings.\n\nMatch reports use completed games. Stage and pass or round identify phase\nboundaries within the timeline; consumers must not interpolate across them.\nEmpty metric objects mark stage changes. Missing measurements are absent,\nnot zero. On evaluation resume,\nan incomplete trailing JSON line is removed before the next append; complete\nrecords are preserved.\n\nRun settings and constants, including learning rates and loss coefficients,\nlive in `plan.json` and belong in configuration panels. Learning rates are not\nrepeated as scalar curves. `status.json` and `progress.jsonl` retain controller\nprogress, counters and state. The reporting service owns chart retention;\ntraining checkpoints and source artifacts are not pruned by the writer.\n\nPer-update reporting retains supervised losses, top-1/top-3 agreement,\nweighted/unweighted CE, policy target coverage, nagashi loss, Q-MSE/RMSE,\nQ-target coverage, the two weighted critic components, MMD value/KL\nterms, structural constraints, total objectives and the checked gradient norm.\nReporting-only ESS/Q-gap summaries, entropy, normalized weight means,\nmulti-ron frequency, duplicated critic totals and belief calibration/count\ndiagnostics are no longer computed. ESS calibration still determines expert\nweights; all seven belief losses and their masks are unchanged.\n\nSelected-rule settlement support includes ordinary and responsible-payer\nwins, all nagashi qualifier combinations, exhaustive draws and aborts. A\nunit-weight four-player nagashi classification loss accompanies observed\nsettlement NLL. Required ending-kind/readiness labels distinguish zero-payment\ndraws and supervise nagashi dealer continuation without adding a head.\nUnsupported valid labels fail outside compiled chunks using\nthe existing NLL denominator; the constant coverage metric is removed.\n\nRegenerate prepared records for the two new public constraint fields\n(`nagashi_possible`, `pao_payer`) and corrected multiple-nagashi targets.\nEarlier checkpoints need explicit transfer for the added critic layers.\nThe exact Q table has 12,863 states per dealer versus 7,313 previously;\nbenchmark memory before restarting training with this architecture.\n",
      "sha256": "8c9380f9ba9ba8eafad4022db2d5e1a7a32485205f8b4dd274e4c4598e6d66af"
    },
    {
      "path": "training/__init__.py",
      "text": "\"\"\"Supervised initialization, policy improvement and evaluation.\"\"\"\n",
      "sha256": "a3ef93f51c0d2d4e881d376a3d5947a43aa133cb27cf42152f69e9a529650c89"
    },
    {
      "path": "training/auxiliary.py",
      "text": "\"\"\"Supervise learned predictions on eligible decisions and known targets.\"\"\"\n\nimport tensorflow as tf\n\nfrom model import beliefs, candidate_predictions, losses\n\nLABELS = (\n    \"opponent_shanten\",\n    \"opponent_ukeire\",\n    \"opponent_hand_counts\",\n    \"round_completion_yaku\",\n    \"round_completion_score\",\n    \"candidate_yaku_affinity\",\n    \"ron_legal\",\n)\n\n\ndef reduce_terms(*, features, labels, outputs, valid, terms):\n    \"\"\"Reduce row metrics and the seven supervised heads in one collective.\"\"\"\n    means = losses.MaskedMeans()\n\n    def evaluate(reduce_mean):\n        def mean(value, mask, weight=None):\n            row_mask = tf.reshape(\n                tf.cast(valid, tf.float32), [-1] + [1] * (mask.shape.rank - 1)\n            )\n            return reduce_mean(\n                value, row_mask * tf.cast(mask, tf.float32), weight\n            )\n\n        metrics = {\n            name: mean(value, mask) for name, (value, mask) in terms.items()\n        }\n        supervised = beliefs.belief_loss_terms(\n            features, labels, outputs, mean=mean\n        )\n        supervised.update(beliefs.completion_loss_terms(labels, outputs, mean))\n        supervised.update(\n            candidate_predictions.loss_terms(features, labels, outputs, mean)\n        )\n        return metrics, supervised\n\n    evaluate(means.collect)\n    means.reduce()\n    return evaluate(means.read)\n",
      "sha256": "40d4a09a36b9213151e26483de0feddbebeebe3b73534806cd53976ce1052607"
    },
    {
      "path": "training/checkpoint_match.py",
      "text": "\"\"\"Export one phase and compare it against the incumbent.\"\"\"\n\nimport argparse\nimport hashlib\nimport json\nimport pathlib\nimport subprocess\nimport sys\n\n\ndef export_policy(weights, output):\n    \"\"\"Retain the full serving export used by evaluation and promotion.\"\"\"\n    root = pathlib.Path(output)\n    if (root / \"policy\").exists():\n        verification = json.loads(\n            (root / \"policy\" / \"export-verification.json\").read_text()\n        )\n        if (\n            verification[\"weight_sha256\"]\n            != hashlib.sha256(pathlib.Path(weights).read_bytes()).hexdigest()\n        ):\n            raise ValueError(\n                \"Existing evaluation export uses different weights\"\n            )\n    else:\n        subprocess.run(\n            [\n                sys.executable,\n                \"-m\",\n                \"model.export\",\n                \"--weights\",\n                str(weights),\n                \"--self-play-seed\",\n                \"941\",\n                \"--output\",\n                str(root / \"policy\"),\n            ],\n            check=True,\n        )\n\n\ndef run(args):\n    if args.games <= 0 or args.games % 4:\n        raise ValueError(\"Evaluation needs complete four-game seed groups\")\n    root = pathlib.Path(args.output)\n    export_policy(args.weights, root)\n    subprocess.run(\n        [\n            sys.executable,\n            \"-m\",\n            \"training.evaluate\",\n            \"--new\",\n            str(root / \"policy\" / \"saved_model\"),\n            \"--old\",\n            args.opponent,\n            \"--output\",\n            str(root / \"matches\"),\n            \"--games\",\n            str(args.games),\n            \"--seed\",\n            str(args.seed),\n            \"--workers\",\n            str(args.workers),\n            \"--devices\",\n            args.devices,\n            \"--batch-games\",\n            str(args.batch_games),\n            *(\n                [\"--mortal-source\", args.mortal_source]\n                if args.mortal_source\n                else []\n            ),\n        ],\n        check=True,\n    )\n\n\ndef main():\n    parser = argparse.ArgumentParser(description=__doc__)\n    for name in (\"weights\", \"opponent\", \"output\"):\n        parser.add_argument(\"--\" + name, required=True)\n    parser.add_argument(\"--mortal-source\")\n    parser.add_argument(\"--seed\", type=int, required=True)\n    parser.add_argument(\"--games\", type=int, default=512)\n    parser.add_argument(\"--workers\", type=int, default=1)\n    parser.add_argument(\"--batch-games\", type=int, default=8)\n    parser.add_argument(\"--devices\", default=\"-1\")\n    run(parser.parse_args())\n\n\nif __name__ == \"__main__\":\n    main()\n",
      "sha256": "ab6f7c6da6465445b46f948819ea4853125158217d9cac5cce7dbc09a1661fb7"
    },
    {
      "path": "training/collection_workers.py",
      "text": "\"\"\"Persistent CPU continuations sharing ready-request policy inference.\"\"\"\n\nimport itertools\nimport multiprocessing\nimport multiprocessing.connection\n\nimport numpy\nimport tensorflow as tf\n\nfrom log_dataset import _native_collection, call_states\nfrom training import fixed_reference, self_play\n\n\ndef concatenate_reference(batches):\n    \"\"\"Batch immutable policy features without learner post-call expansion.\"\"\"\n    return {\n        name: numpy.concatenate([batch[name] for batch in batches])\n        for name in batches[0]\n    }\n\n\ndef work(connection, max_active, reference):\n    tf.config.set_visible_devices([], \"GPU\")\n    tf.config.threading.set_intra_op_parallelism_threads(1)\n    tf.config.threading.set_inter_op_parallelism_threads(1)\n    producer = (\n        None\n        if reference is None\n        else fixed_reference.FeatureProducer(*reference)\n    )\n\n    def predict(features):\n        connection.send((\"features\", features))\n        return connection.recv()\n\n    def streams(jobs):\n        for job in jobs:\n            root = _native_collection.NativeRoot.loads(job[\"root\"])\n            for action, seed in zip(job[\"actions\"], job[\"wall_seeds\"]):\n                yield self_play.collection_steps(\n                    games=1,\n                    seed=seed,\n                    collector=root.fork(1, seed, until_hand_end=True),\n                    forced_root=(root.decision, action),\n                    with_labels=True,\n                    root_only=True,\n                    root_affinity=job[\"affinity\"],\n                    policy_features=(\n                        None if producer is None else producer.stream()\n                    ),\n                )\n\n    connection.send((\"ready\", None))\n    while (jobs := connection.recv()) is not None:\n        connection.send(\n            (\n                \"complete\",\n                self_play.collect_streams(\n                    predict,\n                    streams(jobs),\n                    max_active=max_active,\n                    concatenate=(\n                        call_states.concatenate\n                        if producer is None\n                        else concatenate_reference\n                    ),\n                ),\n            )\n        )\n    connection.close()\n\n\nclass CollectionWorkers:\n    \"\"\"Advance groups on CPU; keep inference and output ordering in parent.\"\"\"\n\n    def __init__(self, workers=4, reference=None, streams=512):\n        if workers <= 0 or streams < workers:\n            raise ValueError(\"Collection needs at least one stream per worker\")\n        self.workers = workers\n        self.reference = reference\n        self.streams = streams\n        self.connections = []\n        self.processes = []\n\n    def __enter__(self):\n        context = multiprocessing.get_context(\"spawn\")\n        for worker_ix in range(self.workers):\n            parent, child = context.Pipe()\n            process = context.Process(\n                target=work,\n                args=(\n                    child,\n                    self.streams // self.workers\n                    + int(worker_ix < self.streams % self.workers),\n                    self.reference,\n                ),\n            )\n            process.start()\n            child.close()\n            self.connections.append(parent)\n            self.processes.append(process)\n        for connection in self.connections:\n            assert connection.recv()[0] == \"ready\"\n        return self\n\n    def __exit__(self, error_type, error, traceback):\n        for connection, process in zip(self.connections, self.processes):\n            if process.is_alive():\n                if error_type is None:\n                    connection.send(None)\n                else:\n                    process.terminate()\n            connection.close()\n        for process in self.processes:\n            process.join()\n\n    def collect(self, predict, jobs):\n        for connection, indices in zip(\n            self.connections,\n            numpy.array_split(numpy.arange(len(jobs)), self.workers),\n        ):\n            connection.send([jobs[index] for index in indices])\n        pending = dict(enumerate(self.connections))\n        results = {}\n        while pending:\n            requests = {}\n            ready = multiprocessing.connection.wait(list(pending.values()))\n            for index, connection in list(pending.items()):\n                if connection not in ready:\n                    continue\n                kind, value = connection.recv()\n                if kind == \"complete\":\n                    results[index] = value\n                    del pending[index]\n                else:\n                    requests[index] = value\n            if requests:\n                outputs = predict(\n                    (\n                        call_states.concatenate\n                        if self.reference is None\n                        else concatenate_reference\n                    )(list(requests.values()))\n                )\n                offset = 0\n                for index, features in requests.items():\n                    count = len(features[\"decision_phase\"])\n                    pending[index].send(\n                        {\n                            name: value[offset : offset + count]\n                            for name, value in outputs.items()\n                        }\n                    )\n                    offset += count\n        return list(\n            itertools.chain.from_iterable(\n                results[index] for index in range(self.workers)\n            )\n        )\n",
      "sha256": "0c845334d30507596baa99acc50c04dfec834aeebac0cf735d45f2b54078c4c8"
    },
    {
      "path": "training/corrections/README.md",
      "text": "# Match and root magnetic mirror descent\n\nThis workflow improves an initialized policy using recorded outcomes from\nMortal matches and self-play continuations. See the\n[training objective](../OBJECTIVE.md) for losses and gradient ownership.\n\n## Training sequence\n\n1. Play 10,000 standard South games against Mortal: 2,500 wall seeds, each\n   rotated through all four learner seats.\n2. Fit the critic once on eligible decisions from all four seats, then run\n   one MMD actor pass over the same decisions.\n3. Select targeted positions and an equal number of uniformly sampled normal\n   positions from those games. Generate two self-play continuations per root.\n4. Fit the critic once on eligible roots and descendants, then run one MMD\n   actor pass over the same decisions.\n5. Play a fresh 10,000-game Mortal match. It supplies the next iteration;\n   the final match is not trained afterward.\n\nThe initializer's final checkpoint starts the first match. Mortal actions are\nobserved experience, not policy imitation labels. Their outcomes reflect the\noriginal policies; the self-play continuations provide additional outcomes\nunder the learner. Continuations stop at the current hand's settlement.\n\nThe previous-policy reference refreshes before each critic/actor phase. The\nfixed reference never refreshes. Both optimizers persist across phases.\n\n## Root selection\n\nEach source game is assigned a category before its positions are inspected:\n\n| Category | Comparison |\n| --- | --- |\n| Q disagreement | Policy discard versus max-Q discard, with at least 0.0025 J gap |\n| Tenpai with threat | Keep versus break the minimum-shanten route while facing a historical visible threat |\n| Keiten | The same comparison within one shanten and 16 live tiles |\n| Calls | Strictly shanten-improving call or kan versus declining |\n| Riichi | Declare versus dama, preferring the same discard |\n| Sakigiri | Earlier safe cuts before a future genbutsu/non-genbutsu dilemma at best shanten |\n\nEligible positions are sampled uniformly within each category. Q disagreement\nscores a reservoir of up to eight proposals. Sakigiri evidence selects starts\nonly; its ordering never supervises the actor.\n\nThe visible-threat rule is shared with focused corpus sampling: riichi, at\nleast three open melds, at least two open melds after nine opponent discards,\nor a public value estimate of at least three han. The value estimate counts\nexposed yakuhai, visible/red dora, and a supported flush signal. Closed kans\ndo not count as open melds. Hidden readiness is not required.\n\nSakigiri finds the first pre-own-riichi decision where a threatening opponent\nhas both genbutsu and non-genbutsu legal cuts tied for the best immediate\nshanten. It searches backward for earlier opportunities to cut those future\nnon-genbutsu tiles. The early alternative and recorded cut must both avoid\nimmediate ron and leave exactly equal immediate shanten. Endpoints are never\ntraining roots. Calls and kans may intervene; later hands and waits may differ.\nAll qualifying alternatives are stored, followed by the recorded cut. Main-loop\npaired roots sample one alternative uniformly with the controlled seed;\ninitializer MC evaluates all stored alternatives. Witnesses select roots only\nand never become imitation labels.\n\nEach targeted root is paired with an unfiltered normal root from the same\ngame. Targeted alternatives share an unseen wall; normal roots sample their\ninitial actions and independent walls from the frozen policy. Subsequent\nchoices use that policy in all seats. Hidden opponent hands remain fixed\nwithin each continuation. No root selection uses the new outcomes.\n\nThe 50/50 balance applies to root starts, not descendant counts. All eligible\ndecisions train once per phase; longer continuations contribute more rows.\n\n## Run\n\nSave an evaluation argument list as `evaluation-command.json`. It must include\n`--games 10000`, `--seed`, `--mortal-source`, and the `{weights}` / `{output}`\nplaceholders:\n\n```json\n[\"python\", \"-m\", \"training.checkpoint_match\",\n \"--weights\", \"{weights}\", \"--output\", \"{output}\",\n \"--opponent\", \"/path/to/mortal-checkpoint.zip\",\n \"--mortal-source\", \"/path/to/Mortal\",\n \"--games\", \"10000\", \"--seed\", \"941\",\n \"--workers\", \"1\", \"--devices\", \"-1\"]\n```\n\n```sh\npython -m training.corrections \\\n  --initial /path/to/initializer/final.weights.h5 \\\n  --reference /path/to/fixed-reference/saved_model \\\n  --output /path/to/new-run \\\n  --evaluation-command evaluation-command.json \\\n  --rounds 5 --root-games 10000 --workers 4 --seed 941 \\\n  --critic-batch-size 512 --actor-batch-size 512 --root-batch-size 512\n```\n\nChoose batch sizes and collector concurrency for the available hardware.\n`--root-games` limits the source games inspected for roots; match training\nalways consumes the full match. Each evaluation advances its base seed by\n2,500. Each training invocation requires a new output directory.\n\nOutputs include checkpoints, match replays, training records, root-selection\nreceipts, rollout shards, progress JSON and `metrics.jsonl` observations. Create `STOP`\nto stop after the current collection chunk or update batch. Completed outputs\nand the latest trained weights are preserved. Match results describe the\ncheckpoint evaluated before learning from that match.\nMetric `step` is cumulative actor plus critic fitting positions, preserving\nthe execution order on a shared timeline. Status/progress JSON also expose\nthis count as `reporting_positions`; individual exposure counters are retained.\n\n## Multiple workers\n\nSet `TF_CONFIG` to the same worker list in every process, with distinct worker\nindices. Select one GPU per process using `CUDA_VISIBLE_DEVICES`. Worker 0\ncoordinates collection, checkpoints and progress; all workers participate in\nsynchronized learner updates.\n\nBatch-size arguments are global row budgets. Replica padding carries no loss\nmass, and losses and gradients are normalized globally. Each worker decodes\nonly its assigned records. Set `--gpu-memory-mb` when an explicit allocator\nlimit is needed.\n\nFor separate filesystems, `--sync-command` names a JSON argument list using\n`{root}` and `{stage}` placeholders. The command copies the stage inputs and\npublishes `{stage}-ready.pending.json` as `{stage}-ready.json` on each worker\nonly after all inputs arrive. Worker output roots may differ.\n\n| Stage | Inputs to synchronize |\n| --- | --- |\n| `round-N-match` | `round-N-match-data/` |\n| `round-N-roots` | `round-N-*-rollouts.npz` and `round-N-rollouts.json` |\n| `complete` | Ready marker only |\n\nA marker with `stopped: true` needs no data transfer. The launcher must stop\nall peers if a worker fails.\n\n## Source layout\n\n| Module | Responsibility |\n| --- | --- |\n| [run.py](run.py) | Stage sequence and checkpoints |\n| [collection.py](collection.py) | Root selection and continuations |\n| [matches.py](matches.py) | Recorded-match discovery |\n| [rollouts.py](rollouts.py) | Rollout storage and batches |\n| [trainer.py](trainer.py) | MMD updates |\n| [distributed.py](distributed.py) | Replica coordination |\n",
      "sha256": "f3345f69a88268be5fd07921222bb222501cc017abe34d0c8bb6c31cc6345366"
    },
    {
      "path": "training/corrections/__init__.py",
      "text": "\"\"\"MMD on all-seat matches and balanced targeted-root reruns.\"\"\"\n",
      "sha256": "dc44dcd23baa23643d49f6b4b15486c2f9b2550c05ffc444980587474e6eb9bb"
    },
    {
      "path": "training/corrections/__main__.py",
      "text": "\"\"\"Run match-then-root magnetic mirror descent.\"\"\"\n\nimport argparse\nimport json\nimport os\nimport pathlib\nimport sys\nimport time\n\nfrom training import monitor\n\n\ndef main():\n    parser = argparse.ArgumentParser(description=__doc__)\n    for name in (\"initial\", \"reference\", \"output\", \"evaluation-command\"):\n        parser.add_argument(\"--\" + name, required=True)\n    parser.add_argument(\"--rounds\", type=int, default=5)\n    parser.add_argument(\"--root-games\", type=int, default=10000)\n    parser.add_argument(\"--critic-batch-size\", type=int, default=18432)\n    parser.add_argument(\"--actor-batch-size\", type=int, default=16384)\n    parser.add_argument(\"--root-batch-size\", type=int, default=4096)\n    parser.add_argument(\"--workers\", type=int, default=16)\n    parser.add_argument(\"--gpu-memory-mb\", type=int)\n    parser.add_argument(\"--seed\", type=int, required=True)\n    parser.add_argument(\"--sync-command\")\n    args = parser.parse_args()\n\n    from training.corrections import run\n\n    existing_output = pathlib.Path(args.output).exists()\n    try:\n        run.run(args)\n    finally:\n        path = pathlib.Path(args.output) / \"status.json\"\n        if (\n            (\n                \"TF_CONFIG\" not in os.environ\n                or json.loads(os.environ[\"TF_CONFIG\"])[\"task\"][\"index\"] == 0\n            )\n            and not existing_output\n            and sys.exception() is not None\n            and path.exists()\n        ):\n            status = json.loads(path.read_text())\n            status.update(\n                stage=\"failed\",\n                error=str(sys.exception()),\n                updated_at=time.time(),\n            )\n            monitor.write_json(path, status)\n\n\nif __name__ == \"__main__\":\n    main()\n",
      "sha256": "5d7faf6972933d429d3a4593f21f3630cd0b4ead6d2ce86a67154ad90fe31ae0"
    },
    {
      "path": "training/corrections/collection.py",
      "text": "\"\"\"Paired current-hand outcomes at selected frozen-policy decisions.\"\"\"\n\nimport numpy\nimport tensorflow as tf\n\nfrom log_dataset import (\n    _native_collection,\n    call_states,\n    focus_sampling,\n    training_data,\n)\nfrom model import actions\nfrom model import actor as actor_layers\nfrom model import critic, outcomes\nfrom training import self_play, trainer\n\nCATEGORIES = (\n    \"disagreement\",\n    \"tenpai_threat\",\n    \"keiten\",\n    \"calls\",\n    \"riichi\",\n    \"sakigiri\",\n)\n\n\ndef root_scorer(network, with_policy=False):\n    \"\"\"Return discard Q values and optionally reuse the policy encoding.\"\"\"\n    specs = {\n        name: tf.TensorSpec([None, *spec[\"shape\"]], spec[\"dtype\"])\n        for name, spec in _native_collection.INPUTS.items()\n    }\n    packing = training_data.PackedBatch(specs)\n\n    @tf.function(reduce_retracing=True)\n    def predict(inputs):\n        features = call_states.unpack(inputs, packing)\n        outputs = network.actor(features, training=False)\n        state = network.candidate_context(features, outputs)\n        selected = critic.active_candidates(features, outputs[\"selected\"])\n        selected &= outputs[\"selected\"][:, 1] < 37\n        values = trainer.action_values(\n            network=network,\n            features=features,\n            selected=tf.boolean_mask(outputs[\"selected\"], selected),\n            state=tf.boolean_mask(state, selected),\n            chunk_size=32,\n        )[:, :37]\n        values = tf.where(\n            tf.cast(features[\"discard_action_legal\"], tf.bool),\n            values,\n            -float(\"inf\"),\n        )\n        return (\n            tf.concat(\n                [outputs[name] for name in actions.TRAIN_POLICY_HEADS]\n                + [values],\n                axis=1,\n            )\n            if with_policy\n            else values\n        )\n\n    def evaluate(features):\n        # Stable encoder shapes avoid recompiling for each sampled root count.\n        count = len(features[\"decision_phase\"])\n        # Small self-play requests need small buckets, not 64 padded roots.\n        chunk_size = min(64, 1 << (count - 1).bit_length())\n        outputs = []\n        for begin in range(0, count, chunk_size):\n            indices = numpy.minimum(\n                numpy.arange(begin, begin + chunk_size), count - 1\n            )\n            with tf.device(\"/CPU:0\"):\n                inputs = tf.nest.map_structure(\n                    tf.convert_to_tensor,\n                    call_states.pack_numpy(\n                        call_states.select(features, indices), packing\n                    ),\n                )\n            outputs.append(\n                predict(inputs).numpy()[: min(chunk_size, count - begin)]\n            )\n        output = numpy.concatenate(outputs)\n        if with_policy:\n            return (\n                dict(\n                    zip(\n                        actions.TRAIN_POLICY_HEADS,\n                        numpy.split(\n                            output[:, :-37],\n                            numpy.cumsum(\n                                [\n                                    actions.ACTOR_OUTPUTS[name][0]\n                                    for name in actions.TRAIN_POLICY_HEADS\n                                ]\n                            )[:-1],\n                            axis=1,\n                        ),\n                    )\n                ),\n                output[:, -37:],\n            )\n        return output\n\n    return evaluate\n\n\ndef action_pair(features, head, legal, policy, category, preferred):\n    \"\"\"Compare the policy choice with a publicly identifiable alternative.\"\"\"\n    codes = numpy.flatnonzero(legal)\n    if category == \"calls\":\n        if head not in (2, 3):\n            return None\n        improving = self_play.improving_call_choices(features)[head - 2]\n        alternatives = codes[improving[codes]]\n        if preferred != 0 and not improving[preferred]:\n            return None\n        if preferred != 0:\n            return preferred, 0\n    elif head not in (0, 1):\n        return None\n    elif category == \"disagreement\":\n        # The discard-only critic scorer resolves this proposal after mining.\n        return (preferred, -1) if head == 0 else None\n    elif category in (\"tenpai_threat\", \"keiten\"):\n        distance = min(\n            int(features[name])\n            for name in (\n                \"normal_self_shanten\",\n                \"chiitoitsu_self_shanten\",\n                \"kokushi_self_shanten\",\n            )\n        )\n        if category == \"tenpai_threat\" and (\n            distance > 1\n            or not any(\n                focus_sampling.visible_threat(features, seat)\n                for seat in range(1, 4)\n            )\n        ):\n            return None\n        if category == \"keiten\" and (\n            distance > 2 or features[\"live_wall_count\"] > 16\n        ):\n            return None\n        shanten = features[\"discard_action_all_shanten\"][codes % 37]\n        keep = shanten == shanten.min()\n        alternatives = codes[keep != keep[codes == preferred][0]]\n    elif category == \"riichi\":\n        if head != 1:\n            return None\n        alternatives = codes[(codes >= 37) != (preferred >= 37)]\n        counterpart = preferred + (37 if preferred < 37 else -37)\n        if counterpart in alternatives:\n            return preferred, counterpart\n    else:\n        raise ValueError(f\"Unknown correction category: {category}\")\n    if not len(alternatives):\n        return None\n    return preferred, int(alternatives[policy[alternatives].argmax()])\n\n\ndef snapshot(collector, batch, row, actions):\n    \"\"\"Own the decision buffers retained beyond the current collector step.\"\"\"\n    return {\n        \"snapshot\": collector.snapshot(row),\n        \"features\": call_states.select(batch[\"features\"], [row]),\n        \"head\": int(batch[\"head\"][row]),\n        \"legal\": batch[\"legal\"][row].copy(),\n        \"actions\": actions,\n        \"source\": batch[\"indices\"][row].copy(),\n    }\n\n\ndef targeted_actions(\n    *, features, head, legal, policy, preferred, values, sakigiri_actions\n):\n    \"\"\"Union existing categories, exhaustively retaining advancing calls.\"\"\"\n    selected = set()\n    categories = []\n    for category in CATEGORIES:\n        if category == \"calls\":\n            if head not in (2, 3):\n                continue\n            improving = self_play.improving_call_choices(features)[head - 2]\n            codes = numpy.flatnonzero(legal)\n            alternatives = codes[improving[codes]]\n            pair = [0, *alternatives] if len(alternatives) else None\n        elif category == \"sakigiri\":\n            pair = (\n                sakigiri_actions\n                if head == 0 and len(sakigiri_actions)\n                else None\n            )\n        elif category == \"disagreement\":\n            if head != 0:\n                continue\n            best = int(values.argmax())\n            pair = (\n                (preferred, best)\n                if best != preferred\n                and values[best] - values[preferred]\n                >= 0.25 / outcomes.OBJECTIVE_ST3_SCALE\n                else None\n            )\n        else:\n            pair = action_pair(\n                features=features,\n                head=head,\n                legal=legal,\n                policy=policy,\n                category=category,\n                preferred=preferred,\n            )\n        if pair is not None:\n            assert legal[list(pair)].all()\n            selected.update(int(action) for action in pair)\n            categories.append(category)\n    return sorted(selected), categories\n\n\ndef collect(\n    predict, root_evaluate, games, seed, *, retain, discover, reference_policy\n):\n    \"\"\"Balance targeted starts with uniform normal starts from the same games.\n\n    A category is assigned before mining. Normal reservoirs include every\n    recoverable decision from all four seats, regardless of its category.\n    Each targeted root has one normal root from the same game. Both get two\n    continuations, and every rollout decision contributes to MMD.\n    \"\"\"\n    generator = numpy.random.default_rng(seed + 1000000000)\n    categories = (numpy.arange(games) + seed) % len(CATEGORIES)\n    generator.shuffle(categories)\n    proposals = {}\n    normal = {}\n    ordinary_seen = numpy.zeros(games, numpy.int64)\n    seen = numpy.zeros(games, numpy.int64)\n\n    def capture(collector, batch):\n        with tf.device(\"/CPU:0\"):\n            preferred = actor_layers.greedy_choices(\n                batch[\"behavior\"], batch[\"head\"]\n            ).numpy()\n        for row, game in enumerate(batch[\"indices\"][:, 0]):\n            ordinary_seen[game] += 1\n            if generator.integers(ordinary_seen[game]) == 0:\n                legal = numpy.flatnonzero(batch[\"legal\"][row])\n                probability = numpy.exp(\n                    batch[\"behavior\"][row, legal].astype(numpy.float64)\n                )\n                normal[int(game)] = snapshot(\n                    collector,\n                    batch,\n                    row,\n                    generator.choice(\n                        legal, size=2, p=probability / probability.sum()\n                    ),\n                )\n            if CATEGORIES[categories[game]] == \"sakigiri\":\n                actions = batch[\"sakigiri_actions\"][row]\n                if batch[\"head\"][row] != 0 or not len(actions):\n                    continue\n                pair = (int(generator.choice(actions[:-1])), int(actions[-1]))\n                assert batch[\"legal\"][row, list(pair)].all()\n            else:\n                pair = action_pair(\n                    features={\n                        name: value[row]\n                        for name, value in call_states.base(\n                            batch[\"features\"]\n                        ).items()\n                    },\n                    head=int(batch[\"head\"][row]),\n                    legal=batch[\"legal\"][row],\n                    policy=batch[\"behavior\"][row],\n                    category=CATEGORIES[categories[game]],\n                    preferred=int(preferred[row]),\n                )\n            if pair is None:\n                continue\n            seen[game] += 1\n            capacity = 8 if categories[game] == 0 else 1\n            slot = (\n                int(seen[game]) - 1\n                if seen[game] <= capacity\n                else int(generator.integers(seen[game]))\n            )\n            if slot >= capacity:\n                continue\n            root = snapshot(collector, batch, row, pair)\n            retained = proposals.setdefault(int(game), [])\n            if slot == len(retained):\n                retained.append(root)\n            else:\n                retained[slot] = root\n\n    statistics = discover(capture)\n    roots = {\n        game: retained[0]\n        for game, retained in proposals.items()\n        if categories[game] != 0\n    }\n    disagreement = [\n        (game, root)\n        for game in sorted(proposals)\n        if categories[game] == 0\n        for root in proposals[game]\n    ]\n    qualified = numpy.zeros(games, numpy.int64)\n    if disagreement:\n        features = call_states.concatenate(\n            [root[\"features\"] for _, root in disagreement]\n        )\n        values = root_evaluate(features)\n        for row, (game, root) in enumerate(disagreement):\n            preferred = root[\"actions\"][0]\n            best = int(values[row].argmax())\n            gap = values[row, best] - values[row, preferred]\n            if best == preferred or gap < 0.25 / outcomes.OBJECTIVE_ST3_SCALE:\n                continue\n            assert root[\"legal\"][[preferred, best]].all()\n            qualified[game] += 1\n            if generator.integers(qualified[game]) == 0:\n                root[\"actions\"] = (preferred, best)\n                roots[game] = root\n    statistics[\"disagreement_scored\"] = len(disagreement)\n    statistics[\"disagreement_qualifying\"] = int(qualified.sum())\n\n    selected = sorted(roots)\n    starts = [\n        (game, kind, root)\n        for game in selected\n        for kind, root in ((\"targeted\", roots[game]), (\"normal\", normal[game]))\n    ]\n    streams = []\n    for game, kind, root in starts:\n        for branch, action in enumerate(root[\"actions\"]):\n            # Targeted alternatives share a wall. Normal starts are independent\n            # policy samples, including when they choose the same root action.\n            continuation_seed = (\n                seed\n                + 1000000000\n                + game\n                + (games * (branch + 1) if kind == \"normal\" else 0)\n            )\n            streams.append(\n                self_play.collection_steps(\n                    games=1,\n                    seed=continuation_seed,\n                    collector=root[\"snapshot\"].fork(\n                        1, continuation_seed, until_hand_end=True\n                    ),\n                    forced_root=(\n                        root[\"snapshot\"].decision,\n                        int(action),\n                    ),\n                    with_labels=True,\n                    reference_policy=reference_policy,\n                )\n            )\n    payments = []\n    reference_probabilities = []\n    for branch, (batch, _) in enumerate(\n        self_play.collect_streams(predict, streams)\n    ):\n        row = numpy.flatnonzero(batch[\"paired_root\"])\n        assert len(row) == 1\n        _, kind, root = starts[branch // 2]\n        assert batch[\"chosen\"][row[0]] == root[\"actions\"][branch % 2]\n        assert batch[\"head\"][row[0]] == root[\"head\"]\n        retain(batch, kind)\n        payments.append(batch[\"payment_points\"][row[0]])\n        if branch % 2 == 0:\n            reference_probabilities.append(\n                batch[\"reference_log_probability\"][row[0]]\n            )\n\n    features = call_states.concatenate(\n        [root[\"features\"] for _, _, root in starts]\n    )\n    for category, name in enumerate(CATEGORIES):\n        statistics[f\"assigned/{name}\"] = int((categories == category).sum())\n        statistics[f\"eligible/{name}\"] = int(seen[categories == category].sum())\n        statistics[f\"selected/{name}\"] = int(\n            sum(categories[game] == category for game in selected)\n        )\n    statistics[\"selected_roots\"] = len(starts)\n    statistics[\"targeted_roots\"] = len(selected)\n    statistics[\"normal_roots\"] = len(selected)\n    statistics[\"root_continuations\"] = 2 * len(starts)\n    return {\n        \"features\": features,\n        \"head\": numpy.array(\n            [root[\"head\"] for _, _, root in starts], dtype=numpy.int32\n        ),\n        \"reference_log_probability\": numpy.asarray(\n            reference_probabilities, numpy.float32\n        ).reshape(-1, 150),\n        \"legal\": numpy.array(\n            [root[\"legal\"] for _, _, root in starts], dtype=bool\n        ).reshape(-1, 150),\n        \"actions\": numpy.array(\n            [root[\"actions\"] for _, _, root in starts], dtype=numpy.int32\n        ).reshape(-1, 2),\n        \"payment_points\": numpy.array(payments, dtype=numpy.int32).reshape(\n            -1, 2, int(outcomes.PAYMENT_CELLS.sum())\n        ),\n        \"category\": numpy.array(\n            [\n                categories[game] if kind == \"targeted\" else -1\n                for game, kind, _ in starts\n            ],\n            dtype=numpy.int8,\n        ),\n        \"source\": numpy.array(\n            [root[\"source\"] for _, _, root in starts], dtype=numpy.int64\n        ).reshape(-1, 4),\n    }, statistics\n",
      "sha256": "8efd7499c8e93e83e14f3b3cf41bda009a57ba0311a5889b47fb8c14fe5a9218"
    },
    {
      "path": "training/corrections/distributed.py",
      "text": "\"\"\"Persistent synchronized learner replicas with one global row budget.\"\"\"\n\nimport json\nimport os\nimport pathlib\nimport subprocess\nimport time\n\nimport tensorflow as tf\n\nfrom log_dataset import call_states\nfrom training import match_records, monitor, restoration\n\n\ndef publish_stage(args, group, root, stage):\n    \"\"\"Release workers after generated files reach their output roots.\"\"\"\n    path = root / f\"{stage}-ready.json\"\n    if group.chief:\n        pending = path.with_suffix(\".pending.json\")\n        monitor.write_json(pending, {\"stopped\": (root / \"STOP\").exists()})\n        if args.sync_command:\n            command = json.loads(pathlib.Path(args.sync_command).read_text())\n            subprocess.run(\n                [\n                    value.format(root=str(root), stage=stage)\n                    for value in command\n                ],\n                check=True,\n            )\n        pending.replace(path)\n    else:\n        while not path.exists():\n            time.sleep(1)\n    group.barrier()\n    return json.loads(path.read_text())[\"stopped\"]\n\n\nclass LearnerGroup:\n    \"\"\"One process per GPU; chief owns collection and completed artifacts.\"\"\"\n\n    def __init__(self):\n        self.chief = True\n        self.rank = 0\n        self.paused_seconds = 0.0\n        if \"TF_CONFIG\" in os.environ:\n            self.rank = json.loads(os.environ[\"TF_CONFIG\"])[\"task\"][\"index\"]\n            self.chief = self.rank == 0\n            self.strategy = tf.distribute.MultiWorkerMirroredStrategy(\n                communication_options=(\n                    tf.distribute.experimental.CommunicationOptions(\n                        implementation=\"NCCL\"\n                    )\n                )\n            )\n        else:\n            self.strategy = tf.distribute.get_strategy()\n\n        @tf.function\n        def synchronize(value):\n            values = self.strategy.run(\n                lambda: tf.distribute.get_replica_context().all_reduce(\n                    tf.distribute.ReduceOp.SUM, tf.cast(value, tf.float64)\n                )\n            )\n            # GPU collectives require floating-point inputs. Float64 keeps\n            # the integer stop flags and row counts exact during reduction.\n            return tf.cast(\n                self.strategy.experimental_local_results(values)[0], tf.int32\n            )\n\n        self.sum_counts = synchronize\n\n        @tf.function(input_signature=[tf.TensorSpec([], tf.int32)])\n        def maximum(value):\n            values = self.strategy.run(\n                lambda: tf.reduce_max(\n                    tf.distribute.get_replica_context().all_gather(\n                        tf.cast(value[None], tf.float32), axis=0\n                    )\n                )\n            )\n            return tf.cast(\n                self.strategy.experimental_local_results(values)[0], tf.int32\n            )\n\n        self.maximum = maximum\n\n    @property\n    def replicas(self):\n        return self.strategy.num_replicas_in_sync\n\n    def barrier(self):\n        self.sum_counts(tf.zeros(2, tf.int32)).numpy()\n\n    def configure(self, packing, batch_size):\n        self.set_batch_size(batch_size)\n        self.packing = packing\n        self._pack = tf.function(\n            lambda features: call_states.pack(features, self.packing),\n            input_signature=[call_states.input_specs()],\n        )\n\n    def bind(self, learner, critic_learner, batch_size):\n        self.configure(critic_learner.feature_packing, batch_size)\n        self._updates = {\n            \"critic\": self._make_update(\n                critic_learner.critic_update.python_function, actor=False\n            ),\n            \"actor\": self._make_update(\n                learner.update.python_function, actor=True\n            ),\n        }\n\n    def bind_expert(self, learner, rollout_actor, batch_size):\n        self.configure(learner.feature_packing, batch_size)\n        self._updates = {\n            \"imitation\": self._make_update(\n                learner.update.python_function, actor=True\n            ),\n            \"imitation-rollout\": self._make_update(\n                learner.critic_update.python_function, actor=False\n            ),\n            \"imitation-mmd\": self._make_update(\n                rollout_actor.update.python_function, actor=True\n            ),\n        }\n\n    def set_batch_size(self, batch_size):\n        self.local_batch = (batch_size + self.replicas - 1) // self.replicas\n\n    def _make_update(self, operation, actor):\n        def step(batch, valid):\n            if actor:\n                batch = {\n                    **batch,\n                    \"features\": call_states.unpack(\n                        batch[\"features\"], self.packing\n                    ),\n                }\n            return operation(batch, valid)\n\n        @tf.function(reduce_retracing=True)\n        def update(batch, valid):\n            metrics = self.strategy.run(step, args=(batch, valid))\n            names = tuple(metrics)\n            packed = self.strategy.run(\n                lambda values: tf.stack([values[name] for name in names]),\n                args=(metrics,),\n            )\n            # Trainers already reduce masked statistics and gradients globally.\n            # Re-reducing identical metrics adds another collective per update.\n            values = self.strategy.experimental_local_results(packed)[0]\n            return dict(zip(names, tf.unstack(values)))\n\n        return update\n\n    def _indices(self, count):\n        begin = self.rank * self.local_batch\n        return (\n            tf.minimum(begin + tf.range(self.local_batch), count - 1),\n            tf.clip_by_value(count - begin, 0, self.local_batch),\n        )\n\n    def decode_records(self, raw):\n        \"\"\"Decode only this rank's rows from the unchanged global raw batch.\"\"\"\n        count = tf.shape(raw)[0]\n        indices, local_count = self._indices(count)\n        return {\n            **match_records.decode_records(tf.gather(raw, indices)),\n            \"local_count\": local_count,\n            \"global_count\": count,\n        }\n\n    def localize(self, batch):\n        \"\"\"Partition packed root rows and remap their sparse call owners.\"\"\"\n        with tf.device(\"/CPU:0\"):\n            count = tf.shape(batch[\"chosen\"])[0]\n            indices, local_count = self._indices(count)\n            return {\n                \"features\": call_states.tensor_packed_select(\n                    batch[\"features\"], indices\n                ),\n                **{\n                    name: tf.nest.map_structure(\n                        lambda value: tf.gather(value, indices), values\n                    )\n                    for name, values in batch.items()\n                    if name != \"features\"\n                },\n                \"local_count\": local_count,\n                \"global_count\": count,\n            }\n\n    def update(self, update, batch, root):\n        \"\"\"Coordinate pause/stop requests before starting an optimizer step.\"\"\"\n        with tf.device(\"/CPU:0\"):\n            valid = restoration.trainable_decisions(\n                batch[\"features\"], batch[\"head\"], batch[\"legal\"]\n            ) & (tf.range(tf.size(batch[\"head\"])) < batch[\"local_count\"])\n            control = tf.stack(\n                [\n                    int(self.chief and (root / \"STOP\").exists()),\n                    int(self.chief and (root / \"PAUSE\").exists()),\n                    tf.reduce_sum(tf.cast(valid, tf.int32)),\n                ]\n            )\n        if self.replicas > 1:\n            control = self.sum_counts(control)\n        stopped, paused, trained = control.numpy()\n        if paused and not stopped:\n            started = time.monotonic()\n            if self.chief:\n                monitor.write_json(\n                    root / \"pause.json\",\n                    {\n                        \"paused\": True,\n                        \"updated_at\": time.time(),\n                        \"paused_seconds\": self.paused_seconds,\n                    },\n                )\n            while paused and not stopped:\n                time.sleep(1)\n                control = tf.constant(\n                    [\n                        int(self.chief and (root / \"STOP\").exists()),\n                        int(self.chief and (root / \"PAUSE\").exists()),\n                        0,\n                    ],\n                    tf.int32,\n                )\n                if self.replicas > 1:\n                    control = self.sum_counts(control)\n                stopped, paused, _ = control.numpy()\n            self.paused_seconds += time.monotonic() - started\n            if self.chief:\n                monitor.write_json(\n                    root / \"pause.json\",\n                    {\n                        \"paused\": False,\n                        \"updated_at\": time.time(),\n                        \"paused_seconds\": self.paused_seconds,\n                    },\n                )\n        if stopped:\n            return None\n        if not trained:\n            # Skip both Adam moments and decoupled weight decay. Every rank\n            # takes this branch together, including ranks with only padding.\n            return {\"trained_positions\": 0}\n        with tf.device(\"/CPU:0\"):\n            rows = {\n                \"features\": self._pack(batch[\"features\"]),\n                **{\n                    name: tf.nest.map_structure(tf.convert_to_tensor, values)\n                    for name, values in batch.items()\n                    if name not in (\"features\", \"local_count\", \"global_count\")\n                },\n            }\n            rows, valid = (\n                self.strategy.experimental_distribute_values_from_function(\n                    lambda ctx: (rows, valid)\n                )\n            )\n        metrics = self._updates[update](rows, valid)\n        # One device-to-host transfer instead of one scalar read per metric.\n        values = tf.stack(list(metrics.values())).numpy()\n        return {**dict(zip(metrics, values)), \"trained_positions\": int(trained)}\n",
      "sha256": "c774696696ae434bd353ee443138de4d502b2139e0544fa27ae8110d5b6d9eba"
    },
    {
      "path": "training/corrections/matches.py",
      "text": "\"\"\"Mine all-seat Mortal match trajectories with a frozen scoring policy.\"\"\"\n\nimport gzip\nimport json\nimport pathlib\n\nimport numpy\n\nfrom log_dataset import _native_collection, call_states, sakigiri_regret\nfrom training import self_play\n\n\ndef sources(directory):\n    \"\"\"Index a complete standard-South Mortal match for all-seat replay.\"\"\"\n    directory = pathlib.Path(directory).resolve()\n    manifest = json.loads((directory / \"evaluation.json\").read_text())\n    if (\n        manifest[\"format\"] != \"riichienv_standard_south\"\n        or not manifest[\"mortal\"]\n    ):\n        raise ValueError(\"Root selection requires a standard Mortal match\")\n    games = [\n        json.loads(line)\n        for line in (directory / \"games.jsonl\").read_text().splitlines()\n    ]\n    if len(games) != manifest[\"games\"] or len(games) != 10000:\n        raise ValueError(\"Root selection requires all 10,000 match games\")\n    if len({game[\"replay\"] for game in games}) != len(games):\n        raise ValueError(\"Match contains duplicate replay paths\")\n    return [\n        {\n            \"path\": str(directory / game[\"replay\"]),\n            \"seed\": game[\"seed\"],\n            \"new_seats\": game[\"new_seats\"],\n        }\n        for game in sorted(games, key=lambda game: game[\"replay\"])\n    ]\n\n\ndef discover(predict, games, capture):\n    \"\"\"Replay seeded matches, verifying generated events against every log.\n\n    Recorded choices advance discovery only. Root comparisons and subsequent\n    counterfactual continuations use the supplied frozen policy instead.\n    \"\"\"\n    collectors = {}\n    order_actions = []\n    for game, game_record in enumerate(games):\n        with gzip.open(game_record[\"path\"], \"rt\") as stream:\n            events = [json.loads(line) for line in stream]\n        collectors[game] = _native_collection.NativeCollector.from_match(\n            json.dumps(events), game_record[\"seed\"], False\n        )\n        starts = [\n            index\n            for index, event in enumerate(events)\n            if event[\"type\"] == \"start_kyoku\"\n        ]\n        order_actions.append(\n            {\n                (start + index, events[start + index][\"actor\"]): actions\n                for start, end in zip(starts, starts[1:] + [len(events)])\n                for index, (actions, _) in sakigiri_regret.round_pairs(\n                    str(game), events[start:end]\n                ).items()\n            }\n        )\n    statistics = self_play.collection_counts()\n    while collectors:\n        requests = {}\n        for game, collector in list(collectors.items()):\n            request = collector.next()\n            if request is None:\n                for name, value in collector.finish()[1].items():\n                    statistics[name] += value\n                del collectors[game]\n            else:\n                requests[game] = request\n        if not requests:\n            break\n        features = call_states.concatenate(\n            [call_states.from_request(request) for request in requests.values()]\n        )\n        outputs = predict(features)\n        start = 0\n        for game, request in requests.items():\n            count = len(request[\"head\"])\n            batch = self_play.request_batch(request)\n            batch[\"indices\"][:, 0] = game\n            capture(\n                collectors[game],\n                {\n                    **batch,\n                    \"sakigiri_actions\": [\n                        numpy.asarray(\n                            order_actions[game].get((event, seat), ()),\n                            dtype=numpy.int32,\n                        )\n                        for event, seat in zip(\n                            request[\"event\"], request[\"seat\"]\n                        )\n                    ],\n                    \"behavior\": self_play.policy_log_probabilities(\n                        {\n                            name: value[start : start + count]\n                            for name, value in outputs.items()\n                        },\n                        batch[\"head\"],\n                        batch[\"legal\"],\n                    ),\n                },\n            )\n            collectors[game].submit_recorded()\n            start += count\n    return {**statistics, \"logged_games\": len(games)}\n",
      "sha256": "ee985c7f5d64e4532bad527db600f715a2e3722fbd8b8114d9508e43e0aa108d"
    },
    {
      "path": "training/corrections/rollouts.py",
      "text": "\"\"\"Collect balanced root reruns and read their packed training shards.\"\"\"\n\nimport numpy\nimport tensorflow as tf\n\nfrom log_dataset import call_states\nfrom model import actions, critic\nfrom training import auxiliary, monitor\nfrom training.corrections import collection, matches\n\n\ndef select(rows, indices):\n    return {\n        \"features\": call_states.packed_select(rows[\"features\"], indices),\n        **{\n            name: tf.nest.map_structure(lambda array: array[indices], value)\n            for name, value in rows.items()\n            if name != \"features\"\n        },\n    }\n\n\ndef concatenate(rows):\n    return {\n        \"features\": call_states.packed_concatenate(\n            [row[\"features\"] for row in rows]\n        ),\n        **{\n            name: tf.nest.map_structure(\n                lambda *arrays: numpy.concatenate(arrays),\n                *[row[name] for row in rows],\n            )\n            for name in rows[0]\n            if name != \"features\"\n        },\n    }\n\n\ndef batches(paths, packing, batch_size, seed, localize=None):\n    generator = numpy.random.default_rng(seed)\n    pending = []\n    count = 0\n    for file_index in generator.permutation(len(paths)):\n        with numpy.load(paths[file_index]) as archive:\n            rows = {\n                \"features\": call_states.unflatten(\n                    {\n                        name.removeprefix(\"features/\"): archive[name]\n                        for name in archive.files\n                        if name.startswith(\"features/\")\n                    }\n                ),\n                \"labels\": {\n                    name: archive[\"label/\" + name] for name in auxiliary.LABELS\n                },\n                **{\n                    name: archive[name]\n                    for name in archive.files\n                    if not name.startswith((\"features/\", \"label/\"))\n                },\n            }\n        indices = generator.permutation(len(rows[\"chosen\"]))\n        for begin in range(0, len(indices), batch_size):\n            pending.append(select(rows, indices[begin : begin + batch_size]))\n            count += len(pending[-1][\"chosen\"])\n            if count >= batch_size:\n                combined = concatenate(pending)\n                yield unpack(\n                    select(combined, numpy.arange(batch_size)),\n                    packing,\n                    localize,\n                )\n                pending = [select(combined, numpy.arange(batch_size, count))]\n                count -= batch_size\n    if count:\n        yield unpack(concatenate(pending), packing, localize)\n\n\ndef unpack(rows, packing, localize):\n    with tf.device(\"/CPU:0\"):\n        batch = tf.nest.map_structure(tf.convert_to_tensor, rows)\n        if localize is not None:\n            batch = localize(batch)\n        batch[\"features\"] = call_states.unpack(batch[\"features\"], packing)\n        return batch\n\n\ndef collect(\n    *,\n    root,\n    round_number,\n    match_directory,\n    recorded,\n    order,\n    seed,\n    predict,\n    root_evaluate,\n    packing,\n    report,\n    reference_policy,\n):\n    \"\"\"Mine a round in bounded chunks, retaining completed shards on stop.\"\"\"\n    rollout_files = []\n    counts = {}\n    rollout_positions = {\"targeted\": 0, \"normal\": 0}\n\n    def retain(batch, source):\n        path = root / (\n            f\"round-{round_number}-{source}-\"\n            f\"{len(rollout_files):05d}-rollouts.npz\"\n        )\n        pending = path.with_suffix(\".partial.npz\")\n        numpy.savez_compressed(\n            file=pending,\n            **{\n                \"features/\" + name: value\n                for name, value in call_states.flatten(\n                    call_states.pack_numpy(batch[\"features\"], packing)\n                ).items()\n            },\n            **{\n                \"label/\" + name: value\n                for name, value in batch[\"labels\"].items()\n            },\n            head=batch[\"head\"],\n            legal=batch[\"legal\"],\n            reference_log_probability=batch[\"reference_log_probability\"],\n            chosen=critic.chosen_actions(\n                batch[\"features\"],\n                {\n                    name: numpy.where(\n                        batch[\"head\"] == head, batch[\"chosen\"], -1\n                    )\n                    for head, name in enumerate(actions.TRAIN_POLICY_HEADS)\n                },\n            ).numpy(),\n            payment_points=batch[\"payment_points\"],\n            ending_kind=batch[\"ending_kind\"],\n            ending_source=batch[\"ending_source\"],\n            ending_tenpai=batch[\"ending_tenpai\"],\n            paired_root=batch[\"paired_root\"],\n        )\n        pending.replace(path)\n        rollout_files.append(path)\n        rollout_positions[source] += len(batch[\"head\"])\n\n    for begin in range(0, len(order), 32):\n        selected = order[begin : begin + 32]\n        batch, collected = collection.collect(\n            predict=predict,\n            root_evaluate=root_evaluate,\n            games=len(selected),\n            seed=seed + begin * 4,\n            retain=retain,\n            reference_policy=reference_policy,\n            discover=lambda capture: matches.discover(\n                predict=predict,\n                games=[recorded[index] for index in selected],\n                capture=capture,\n            ),\n        )\n        path = root / f\"round-{round_number}-{begin:05d}-roots.npz\"\n        numpy.savez_compressed(\n            file=path,\n            **{\n                \"features/\" + name: value\n                for name, value in batch[\"features\"].items()\n            },\n            **{\n                name: value\n                for name, value in batch.items()\n                if name != \"features\"\n            },\n            match_index=selected[batch[\"source\"][:, 0]],\n        )\n        for name, value in collected.items():\n            counts[name] = counts.get(name, 0) + value\n        report(\n            \"collecting-roots\",\n            {\n                **counts,\n                **{\n                    \"positions/\" + name: value\n                    for name, value in rollout_positions.items()\n                },\n            },\n        )\n        if (root / \"STOP\").exists():\n            break\n    monitor.write_json(\n        root / f\"round-{round_number}-rollouts.json\",\n        {\n            \"positions\": rollout_positions,\n            \"files\": [path.name for path in rollout_files],\n            \"match_source\": str(match_directory),\n            \"games\": [\n                recorded[index] for index in order[: counts[\"logged_games\"]]\n            ],\n            \"features\": \"sparse-call PackedBatch\",\n            \"auxiliary_labels\": list(auxiliary.LABELS),\n            \"reference_policy\": reference_policy.provenance,\n            \"reference_log_probability\": {\"dtype\": \"float32\", \"shape\": [150]},\n            \"chosen\": \"critic-action-index\",\n        },\n    )\n",
      "sha256": "b7a0bb5d10cc83fe4fc81817bcc44405d5fea759e72f0fe7fbf8c0c1a7235b31"
    },
    {
      "path": "training/corrections/run.py",
      "text": "\"\"\"Mortal matches, match MMD, then MMD on balanced targeted-root reruns.\"\"\"\n\nimport hashlib\nimport json\nimport pathlib\nimport subprocess\nimport sys\nimport time\n\nimport numpy\nimport tensorflow as tf\n\nfrom log_dataset import sakigiri_regret\nfrom model import critic, export\nfrom training import (\n    auxiliary,\n    fixed_reference,\n    match_records,\n    monitor,\n    reporting,\n    self_play,\n)\nfrom training import trainer as base_trainer\nfrom training.corrections import (\n    collection,\n    distributed,\n    matches,\n    rollouts,\n    trainer,\n)\n\n\ndef evaluate(command, weights, output, round_number):\n    command = command.copy()\n    seed_argument = command.index(\"--seed\") + 1\n    games = int(command[command.index(\"--games\") + 1])\n    command[seed_argument] = str(\n        int(command[seed_argument]) + round_number * (games // 4)\n    )\n    subprocess.run(\n        [\n            value.format(weights=str(weights), output=str(output))\n            for value in command\n        ],\n        check=True,\n    )\n\n\ndef validate_launch(args):\n    if (\n        min(\n            args.rounds,\n            args.root_games,\n            args.critic_batch_size,\n            args.actor_batch_size,\n            args.root_batch_size,\n            args.workers,\n        )\n        <= 0\n    ):\n        raise ValueError(\n            \"Round, root-game, batch and worker budgets must be positive\"\n        )\n    if args.root_games > 10000:\n        raise ValueError(\"Root games cannot exceed the 10,000-game match\")\n    command = json.loads(pathlib.Path(args.evaluation_command).read_text())\n    if int(command[command.index(\"--games\") + 1]) != 10000:\n        raise ValueError(\"Each Mortal match must contain 10,000 games\")\n    if \"--mortal-source\" not in command:\n        raise ValueError(\"The match command must select a Mortal source\")\n    int(command[command.index(\"--seed\") + 1])\n    if not all(\n        any(placeholder in value for value in command)\n        for placeholder in (\"{weights}\", \"{output}\")\n    ):\n        raise ValueError(\"Evaluation command needs {weights} and {output}\")\n    if args.sync_command:\n        sync = json.loads(pathlib.Path(args.sync_command).read_text())\n        if not all(\n            any(placeholder in value for value in sync)\n            for placeholder in (\"{root}\", \"{stage}\")\n        ):\n            raise ValueError(\"Sync command needs {root} and {stage}\")\n    devices = tf.config.list_physical_devices(\"GPU\")\n    if len(devices) > 1:\n        raise ValueError(\"Select one learner GPU by UUID\")\n    for device in devices:\n        if args.gpu_memory_mb is None:\n            tf.config.experimental.set_memory_growth(device, True)\n        else:\n            tf.config.set_logical_device_configuration(\n                device,\n                [\n                    tf.config.LogicalDeviceConfiguration(\n                        memory_limit=args.gpu_memory_mb\n                    )\n                ],\n            )\n    tf.keras.utils.set_random_seed(args.seed)\n    return command\n\n\ndef save_checkpoint(network, root, name):\n    weights = root / f\"{name}.weights.h5\"\n    network.save_weights(weights)\n    pending = root / \"latest.weights.h5.pending\"\n    pending.symlink_to(weights.name)\n    pending.replace(root / \"latest.weights.h5\")\n    return weights\n\n\ndef train_phase(\n    *, phase, batches, batch_sizes, learner, root, progress, report, group\n):\n    \"\"\"Fit outcomes, then actor rows, with persistent optimizers.\"\"\"\n    learner.mirror.set_weights(learner.network.actor.get_weights())\n    for update in (\"critic\", \"actor\"):\n        group.set_batch_size(batch_sizes[update])\n        for batch in batches(batch_sizes[update]):\n            metrics = group.update(update, batch, root)\n            if metrics is None:\n                return\n            progress[update + \"_exposures\"] += metrics[\"trained_positions\"]\n            if group.chief:\n                report(\n                    phase + \"-\" + update,\n                    {name: float(value) for name, value in metrics.items()},\n                )\n\n\ndef run(args):\n    command = validate_launch(args)\n    group = distributed.LearnerGroup()\n    root = pathlib.Path(args.output).resolve()\n    if group.chief:\n        root.mkdir(parents=True, exist_ok=False)\n    with group.strategy.scope():\n        features = self_play.initial_features(args.seed)\n        network = export.load_network(args.initial, features)\n        previous = export.load_network(args.initial, features).actor\n        previous.trainable = False\n        learner = trainer.MMDTrainer(\n            network=network,\n            mirror=previous,\n            learning_rate=1e-5,\n        )\n        critic_learner = base_trainer.CriticTrainer(network, features, 1e-5)\n    group.bind(learner, critic_learner, args.critic_batch_size)\n    reference_policy = (\n        fixed_reference.Policy(args.reference) if group.chief else None\n    )\n    if group.chief:\n        weights = save_checkpoint(network, root, \"initial\")\n        monitor.write_json(\n            root / \"plan.json\",\n            {\n                **vars(args),\n                \"method\": \"match-then-root-magnetic-mirror-descent\",\n                \"replicas\": group.replicas,\n                \"evaluation_argv\": command,\n                \"learning_rate\": 1e-5,\n                \"mirror_coefficient\": 0.3,\n                \"magnet_coefficient\": 0.3,\n                \"objective_scale\": 1.0,\n                \"match_training_seats\": [0, 1, 2, 3],\n                \"root_selection_seats\": [0, 1, 2, 3],\n                \"targeted_root_fraction\": 0.5,\n                \"categories\": list(collection.CATEGORIES),\n                \"sakigiri\": sakigiri_regret.DEFINITION,\n                \"continuations_per_root\": 2,\n                \"continuation_policy\": \"sampled-frozen-self-play\",\n                \"continuation_horizon\": \"current-hand\",\n                \"critic_passes_per_phase\": 1,\n                \"critic_loss_coefficients\": {\n                    \"payment_nll\": 0.5,\n                    \"q_mse\": 0.5 * critic.Q_MSE_TO_NLL,\n                    \"nagashi_loss\": 1,\n                    \"critic_constraint_loss\": 1,\n                },\n                \"q_loss_units\": \"J squared; fixed nats/J squared scale\",\n                \"q_mse_to_nll\": critic.Q_MSE_TO_NLL,\n                \"q_targets\": \"known payments with unique continuation J\",\n                \"actor_passes_per_phase\": 1,\n                \"supervised_losses_per_update\": dict.fromkeys(\n                    auxiliary.LABELS, 1.0\n                ),\n                \"initial_sha256\": hashlib.sha256(\n                    pathlib.Path(args.initial).read_bytes()\n                ).hexdigest(),\n                \"reference_files_sha256\": {\n                    str(path.relative_to(args.reference)): hashlib.sha256(\n                        path.read_bytes()\n                    ).hexdigest()\n                    for path in sorted(pathlib.Path(args.reference).rglob(\"*\"))\n                    if path.is_file()\n                },\n                \"reference_policy\": reference_policy.provenance,\n            },\n        )\n    predict = self_play.predictor(network.actor)\n\n    root_evaluate = collection.root_scorer(network)\n    generator = numpy.random.default_rng(args.seed)\n    progress = {\"actor_exposures\": 0, \"critic_exposures\": 0}\n    started = time.monotonic()\n    round_number = 0\n\n    def report(stage, metrics):\n        status = {\n            \"stage\": stage,\n            \"round\": round_number,\n            \"phase_name\": f\"round-{round_number}\",\n            \"rounds\": args.rounds,\n            \"exposures\": progress[\"actor_exposures\"],\n            \"reporting_positions\": (\n                progress[\"actor_exposures\"] + progress[\"critic_exposures\"]\n            ),\n            **progress,\n            \"elapsed_seconds\": time.monotonic() - started,\n            \"updated_at\": time.time(),\n            **metrics,\n        }\n        monitor.write_json(root / \"status.json\", status)\n        with (root / \"progress.jsonl\").open(\"a\") as stream:\n            stream.write(json.dumps(status) + \"\\n\")\n        reporting.write_metrics(\n            root,\n            stage=stage,\n            step=status[\"reporting_positions\"],\n            metrics=metrics,\n            round=round_number,\n        )\n\n    if group.chief:\n        report(\"evaluation\", {})\n        evaluate(command, weights, root / \"initial-evaluation\", 0)\n    match_directory = root / \"initial-evaluation\" / \"matches\"\n    for round_number in range(1, args.rounds + 1):\n        data = root / f\"round-{round_number}-match-data\"\n        if group.chief and not (root / \"STOP\").exists():\n            recorded = matches.sources(match_directory)\n            report(\"match-records\", {})\n            subprocess.run(\n                [\n                    sys.executable,\n                    \"-m\",\n                    \"training.match_records\",\n                    \"--matches\",\n                    str(match_directory),\n                    \"--output\",\n                    str(data),\n                    \"--reference\",\n                    args.reference,\n                    \"--workers\",\n                    str(args.workers),\n                ],\n                check=True,\n            )\n        if distributed.publish_stage(\n            args, group, root, f\"round-{round_number}-match\"\n        ):\n            break\n        train_phase(\n            phase=\"match\",\n            learner=learner,\n            root=root,\n            progress=progress,\n            report=report,\n            group=group,\n            batch_sizes={\n                \"critic\": args.critic_batch_size,\n                \"actor\": args.actor_batch_size,\n            },\n            batches=lambda batch_size: match_records.batches(\n                data,\n                batch_size,\n                args.seed + round_number,\n                decode=group.decode_records,\n            ),\n        )\n        if group.chief:\n            weights = save_checkpoint(\n                network, root, f\"round-{round_number}-match\"\n            )\n        if group.chief and not (root / \"STOP\").exists():\n            rollouts.collect(\n                root=root,\n                round_number=round_number,\n                match_directory=match_directory,\n                recorded=recorded,\n                order=generator.permutation(len(recorded))[: args.root_games],\n                seed=args.seed + round_number * 100000,\n                predict=predict,\n                root_evaluate=root_evaluate,\n                packing=critic_learner.feature_packing,\n                report=report,\n                reference_policy=reference_policy,\n            )\n        if distributed.publish_stage(\n            args, group, root, f\"round-{round_number}-roots\"\n        ):\n            break\n        manifest = json.loads(\n            (root / f\"round-{round_number}-rollouts.json\").read_text()\n        )\n        rollout_files = [root / name for name in manifest[\"files\"]]\n        if not rollout_files:\n            raise ValueError(\"Match pool yielded no eligible targeted roots\")\n        train_phase(\n            phase=\"roots\",\n            learner=learner,\n            root=root,\n            progress=progress,\n            report=report,\n            group=group,\n            batch_sizes={\n                \"critic\": args.root_batch_size,\n                \"actor\": args.root_batch_size,\n            },\n            batches=lambda batch_size: rollouts.batches(\n                paths=rollout_files,\n                packing=critic_learner.feature_packing,\n                batch_size=batch_size,\n                seed=args.seed + round_number,\n                localize=group.localize,\n            ),\n        )\n        if group.chief:\n            weights = save_checkpoint(network, root, f\"round-{round_number}\")\n            if not (root / \"STOP\").exists():\n                report(\"evaluation\", {})\n                evaluate(\n                    command,\n                    weights,\n                    root / f\"round-{round_number}-evaluation\",\n                    round_number,\n                )\n                report(\"round-complete\", {})\n        match_directory = root / f\"round-{round_number}-evaluation\" / \"matches\"\n    if group.chief:\n        report(\"stopped\" if (root / \"STOP\").exists() else \"complete\", {})\n    distributed.publish_stage(args, group, root, \"complete\")\n",
      "sha256": "6176d8b84a8f25425e85a73df11e01633fe186b8c65b1ad006039d0b4930d23d"
    },
    {
      "path": "training/corrections/trainer.py",
      "text": "\"\"\"Magnetic mirror descent at every sampled rollout decision.\"\"\"\n\nimport tensorflow as tf\n\nfrom model import actions\nfrom model import actor as actor_layers\nfrom model import critic, losses\nfrom training import auxiliary, trainer\n\n\ndef mmd_terms(*, features, current, mirror, magnet, values, valid):\n    \"\"\"Expected action value with proximal and fixed-magnet KL penalties.\"\"\"\n    values = tf.stop_gradient(values)\n    mirror = tf.stop_gradient(mirror)\n    magnet = tf.stop_gradient(magnet)\n    probabilities = [\n        critic.candidate_probabilities(\n            features,\n            {\n                name: distribution[:, : actions.ACTOR_OUTPUTS[name][0]]\n                for name in actions.TRAIN_POLICY_HEADS\n            },\n        )\n        for distribution in (current, mirror)\n    ]\n    metrics = {\n        \"policy_gain_objective\": losses.mean_valid(\n            tf.reduce_sum(\n                (probabilities[0] - probabilities[1]) * values, axis=-1\n            ),\n            valid,\n        ),\n        **{\n            name: losses.mean_valid(\n                tf.reduce_sum(tf.exp(current) * (current - reference), axis=-1),\n                valid,\n            )\n            for name, reference in (\n                (\"mirror_kl\", mirror),\n                (\"magnet_kl\", magnet),\n            )\n        },\n    }\n    metrics[\"mmd_loss\"] = (\n        -metrics[\"policy_gain_objective\"]\n        + 0.3 * metrics[\"mirror_kl\"]\n        + 0.3 * metrics[\"magnet_kl\"]\n    )\n    return metrics\n\n\nclass MMDTrainer:\n    \"\"\"One MMD objective for discovery, forced roots and descendants.\"\"\"\n\n    def __init__(self, *, network, mirror, learning_rate):\n        self.network = network\n        self.mirror = mirror\n        self.optimizer = trainer.AdamW(\n            learning_rate=learning_rate, weight_decay=1e-4, clipnorm=1.0\n        )\n        self.optimizer.build(network.actor.trainable_variables)\n\n    @tf.function(reduce_retracing=True)\n    def update(self, batch, valid):\n        mirror = actor_layers.distribution(\n            self.mirror(batch[\"features\"], training=False),\n            batch[\"head\"],\n            batch[\"legal\"],\n        )\n        with tf.GradientTape() as tape:\n            outputs = self.network.actor(batch[\"features\"], training=False)\n            state = self.network.candidate_context(batch[\"features\"], outputs)\n            selected = critic.active_candidates(\n                batch[\"features\"], outputs[\"selected\"]\n            ) & tf.gather(valid, outputs[\"selected\"][:, 0])\n            values = trainer.action_values(\n                network=self.network,\n                features=batch[\"features\"],\n                selected=tf.boolean_mask(outputs[\"selected\"], selected),\n                state=tf.boolean_mask(state, selected),\n            )\n            metrics = mmd_terms(\n                features=batch[\"features\"],\n                current=actor_layers.distribution(\n                    outputs, batch[\"head\"], batch[\"legal\"]\n                ),\n                mirror=mirror,\n                magnet=batch[\"reference_log_probability\"],\n                values=values,\n                valid=valid,\n            )\n            constraints, supervised = auxiliary.reduce_terms(\n                features=batch[\"features\"],\n                labels=batch[\"labels\"],\n                outputs=outputs,\n                valid=valid,\n                terms={\"constraint_loss\": (outputs[\"constraint_loss\"], valid)},\n            )\n            loss = (\n                metrics[\"mmd_loss\"]\n                + 0.01 * constraints[\"constraint_loss\"]\n                + tf.add_n(list(supervised.values()))\n            )\n            scaled = loss / tf.distribute.get_strategy().num_replicas_in_sync\n        return {\n            **metrics,\n            **constraints,\n            **supervised,\n            **trainer.apply_gradients(\n                self.optimizer,\n                tape,\n                scaled,\n                self.network.actor.trainable_variables,\n            ),\n            \"joint_loss\": loss,\n        }\n",
      "sha256": "e4047c46f7cb0cab55b08cb47b60d86f70b15e44b63240dccd06c8ec4b3a0493"
    },
    {
      "path": "training/evaluate.py",
      "text": "\"\"\"Native matches and paired estimates over full seat rotations.\"\"\"\n\nimport argparse\nimport atexit\nimport concurrent.futures\nimport gzip\nimport hashlib\nimport importlib.util\nimport itertools\nimport json\nimport multiprocessing\nimport pathlib\nimport secrets\nimport shutil\nimport time\n\nimport numpy\n\nfrom model import outcomes\nfrom training import reporting\n\nWORKER_POLICIES = {}\nMATCH_FORMATS = (\"riichienv_duplicate_south\", \"riichienv_standard_south\")\n\n\ndef completed_games(root, requested, match_format):\n    root = pathlib.Path(root)\n    path = root / \"games.jsonl\"\n    if not path.exists():\n        return []\n    raw = path.read_bytes()\n    complete = raw[: raw.rfind(b\"\\n\") + 1]\n    if complete != raw:\n        path.write_bytes(complete)\n    results = []\n    for line in complete.splitlines():\n        row = json.loads(line)\n        if row[\"format\"] != match_format:\n            raise ValueError(\"Evaluation format mismatch; use a fresh output\")\n        if (row[\"seed\"], *row[\"new_seats\"]) not in requested:\n            continue\n        with gzip.open(root / row[\"replay\"], \"rt\") as stream:\n            events = [json.loads(line) for line in stream]\n        if events and events[-1][\"type\"] == \"end_game\":\n            results.append(row)\n    return results\n\n\ndef summarize(results, bootstrap_seed=0):\n    rotations = {}\n    for row in results:\n        if (\n            row[\"format\"] not in MATCH_FORMATS\n            or row[\"format\"] != results[0][\"format\"]\n        ):\n            raise ValueError(\"Cannot combine different evaluation formats\")\n        rotation = rotations.setdefault(row[\"seed\"], {})\n        seat = tuple(row[\"new_seats\"])\n        if seat not in ((0,), (1,), (2,), (3,)) or seat in rotation:\n            raise ValueError(\"Expected one distinct candidate seat per game\")\n        rotation[seat] = row\n    complete = [\n        row\n        for _, rotation in sorted(rotations.items())\n        if len(rotation) == 4\n        for _, row in sorted(rotation.items())\n    ]\n    if not complete:\n        return None\n    grouped = {}\n    for row in complete:\n        pair = grouped.setdefault(row[\"seed\"], {\"new\": [], \"old\": []})\n        rank_points = outcomes.saint3_jade_south(row[\"scores\"], row[\"ranks\"])\n        for seat in range(4):\n            pair[\"new\" if seat in row[\"new_seats\"] else \"old\"].append(\n                [\n                    row[\"ranks\"][seat],\n                    row[\"ranks\"][seat] == 1,\n                    row[\"ranks\"][seat] == 4,\n                    rank_points[seat],\n                    row[\"scores\"][seat],\n                    outcomes.SAINT3_JADE_SOUTH_OFFSETS[row[\"ranks\"][seat] - 1],\n                ]\n            )\n    metrics = (\n        \"placement\",\n        \"first\",\n        \"fourth\",\n        \"rank_points\",\n        \"score\",\n        \"placement_points\",\n    )\n    clusters = {\n        model: numpy.array(\n            [numpy.mean(pair[model], 0) for pair in grouped.values()]\n        )\n        for model in (\"new\", \"old\")\n    }\n    difference = clusters[\"new\"] - clusters[\"old\"]\n    generator = numpy.random.default_rng(bootstrap_seed)\n    bootstrap = numpy.concatenate(\n        [\n            difference[\n                generator.integers(\n                    0, len(grouped), (min(64, 2000 - begin), len(grouped))\n                )\n            ].mean(1)\n            for begin in range(0, 2000, 64)\n        ]\n    )\n    return {\n        \"format\": results[0][\"format\"],\n        \"rank_point_formula\": \"ceil((final_score-25000)/1000 + ST3_offset)\",\n        \"rank_point_offsets\": list(outcomes.SAINT3_JADE_SOUTH_OFFSETS),\n        \"observed_games\": len(results),\n        \"compared_games\": len(complete),\n        \"seed_groups\": len(grouped),\n        \"models\": {\n            model: dict(zip(metrics, values.mean(0).tolist()))\n            for model, values in clusters.items()\n        },\n        \"new_minus_old\": dict(zip(metrics, difference.mean(0).tolist())),\n        \"paired_bounds\": dict(\n            zip(\n                metrics,\n                numpy.quantile(bootstrap, [0.025, 0.975], axis=0).T.tolist(),\n            )\n        ),\n    }\n\n\ndef start_worker(root, devices, batch_games):\n    from training import frozen_policy\n\n    device = devices.get()\n    for name in (\"new\", \"old\"):\n        if (root / name / \"checkpoint\").exists():\n            from training import mortal_policy\n\n            WORKER_POLICIES[name] = mortal_policy.MortalPolicy(\n                root / name, device=device, capacity=batch_games * 3\n            )\n        else:\n            WORKER_POLICIES[name] = frozen_policy.FrozenPolicy(\n                model_path=root / name / \"saved_model\",\n                device=device,\n                memory_mb=1536,\n            )\n        atexit.register(WORKER_POLICIES[name].close)\n\n\ndef play_games(tasks):\n    import riichienv\n\n    for policy in WORKER_POLICIES.values():\n        policy.reset([seed for _, seed, _ in tasks])\n    rule = riichienv.GameRule.default_tenhou()\n    match_format = json.loads((tasks[0][0] / \"evaluation.json\").read_text())[\n        \"format\"\n    ]\n    rule.duplicate = match_format == \"riichienv_duplicate_south\"\n    games = [\n        riichienv.RiichiEnv(game_mode=2, seed=seed, rule=rule)\n        for _, seed, _ in tasks\n    ]\n    observations = [env.reset(oya=0) for env in games]\n    while any(not env.done() for env in games):\n        choices = [{} for _ in games]\n        requests = [\n            (game * 4 + actor, env, observation)\n            for game, env in enumerate(games)\n            if not env.done()\n            for actor, observation in observations[game].items()\n        ]\n        pending = []\n        for name, policy in WORKER_POLICIES.items():\n            policy_requests = [\n                request\n                for request in requests\n                if (request[0] % 4 == tasks[request[0] // 4][2])\n                == (name == \"new\")\n            ]\n            if policy_requests:\n                policy.send_requests(policy_requests)\n                pending.append((policy, policy_requests))\n        # Both frozen policies can construct features and infer concurrently.\n        for policy, policy_requests in pending:\n            for request, action in zip(\n                policy_requests,\n                policy.receive_actions(policy_requests),\n                strict=True,\n            ):\n                game, actor = divmod(request[0], 4)\n                choices[game][actor] = action\n        for game, env in enumerate(games):\n            if not env.done():\n                observations[game] = env.step(choices[game])\n    results = []\n    for env, (root, seed, seat) in zip(games, tasks, strict=True):\n        replay_path = f\"replays/{seed}-{seat}.jsonl.gz\"\n        with gzip.open(root / replay_path, \"wt\") as stream:\n            for event in env.mjai_log:\n                stream.write(json.dumps(event) + \"\\n\")\n        ranks = list(env.ranks())\n        results.append(\n            {\n                \"format\": match_format,\n                \"seed\": seed,\n                \"new_seats\": [seat],\n                \"replay\": replay_path,\n                \"ranks\": ranks,\n                \"scores\": list(env.scores()),\n                \"rank_points\": outcomes.saint3_jade_south(\n                    env.scores(), ranks\n                ).tolist(),\n            }\n        )\n    return results\n\n\ndef publish_summary(root, results, bootstrap_seed):\n    comparison = summarize(results, bootstrap_seed)\n    if comparison is not None:\n        summary = root / \"summary.json.partial\"\n        summary.write_text(json.dumps(comparison, indent=2))\n        summary.replace(root / \"summary.json\")\n    values = {\n        \"progress/completed_games\": len(results),\n        \"progress/percent\": 100\n        * len(results)\n        / json.loads((root / \"evaluation.json\").read_text())[\"games\"],\n    }\n    if comparison is not None:\n        for side, metrics in comparison[\"models\"].items():\n            values.update(\n                {f\"{side}/{key}\": value for key, value in metrics.items()}\n            )\n        for key, value in comparison[\"new_minus_old\"].items():\n            values[f\"difference/{key}\"] = value\n            values[f\"difference/{key}_lower\"] = comparison[\"paired_bounds\"][\n                key\n            ][0]\n            values[f\"difference/{key}_upper\"] = comparison[\"paired_bounds\"][\n                key\n            ][1]\n    reporting.write_metrics(\n        root, stage=\"evaluation\", step=len(results), metrics=values\n    )\n\n\ndef merge_parts(parts, output, seed, games, *, complete=False):\n    \"\"\"Publish one match from disjoint host runs with identical policies.\n\n    Live snapshots may contain unfinished JSON lines and missing host\n    manifests. Finalization requires every requested seat and replay.\n    \"\"\"\n    root = pathlib.Path(output)\n    root.mkdir(parents=True, exist_ok=True)\n    requested = {(seed + game // 4, game % 4) for game in range(games)}\n    manifests = []\n    results = {}\n    for part in map(pathlib.Path, parts):\n        if not (part / \"evaluation.json\").exists():\n            if complete:\n                raise ValueError(\"Missing evaluation host manifest\")\n            continue\n        manifest = json.loads((part / \"evaluation.json\").read_text())\n        manifests.append(manifest)\n        if {\n            key: value\n            for key, value in manifest.items()\n            if key not in (\"seed\", \"games\")\n        } != {\n            key: value\n            for key, value in manifests[0].items()\n            if key not in (\"seed\", \"games\")\n        }:\n            raise ValueError(\"Evaluation hosts used different policies\")\n        path = part / \"games.jsonl\"\n        raw = path.read_bytes() if path.exists() else b\"\"\n        for line in raw[: raw.rfind(b\"\\n\") + 1].splitlines():\n            row = json.loads(line)\n            key = (row[\"seed\"], *row[\"new_seats\"])\n            if key not in requested or key in results:\n                raise ValueError(\"Overlapping or unexpected evaluation game\")\n            if row[\"replay\"] != f\"replays/{key[0]}-{key[1]}.jsonl.gz\":\n                raise ValueError(\"Evaluation replay does not match its game\")\n            if (\n                not manifest[\"seed\"]\n                <= row[\"seed\"]\n                < (manifest[\"seed\"] + manifest[\"games\"] // 4)\n            ):\n                raise ValueError(\"Game is outside its host's seed range\")\n            if row[\"format\"] != manifest[\"format\"]:\n                raise ValueError(\"Evaluation game format mismatch\")\n            results[key] = row\n            if complete:\n                with gzip.open(part / row[\"replay\"], \"rt\") as stream:\n                    events = [json.loads(event) for event in stream]\n                if not events or events[-1][\"type\"] != \"end_game\":\n                    raise ValueError(\"Incomplete evaluation replay\")\n                destination = root / row[\"replay\"]\n                destination.parent.mkdir(parents=True, exist_ok=True)\n                shutil.copy2(part / row[\"replay\"], destination)\n    if complete and results.keys() != requested:\n        raise ValueError(\"Evaluation is missing requested games\")\n    if not manifests:\n        return 0\n    (root / \"evaluation.json\").write_text(\n        json.dumps({**manifests[0], \"seed\": seed, \"games\": games}, indent=2)\n        + \"\\n\"\n    )\n    rows = [row for _, row in sorted(results.items())]\n    pending = root / \"games.jsonl.partial\"\n    pending.write_text(\"\".join(json.dumps(row) + \"\\n\" for row in rows))\n    pending.replace(root / \"games.jsonl\")\n    publish_summary(root, rows, seed)\n    return len(rows)\n\n\ndef run(args):\n    from training import frozen_policy\n\n    if args.games <= 0 or args.games % 4:\n        raise ValueError(\"Evaluation requires complete four-game seat groups\")\n    root = pathlib.Path(args.output)\n    root.mkdir(parents=True, exist_ok=True)\n    (root / \"replays\").mkdir(exist_ok=True)\n    requested = {\n        (args.seed + game // 4, game % 4) for game in range(args.games)\n    }\n    manifest = {\n        \"format\": (\n            \"riichienv_standard_south\"\n            if args.mortal_source is not None\n            else \"riichienv_duplicate_south\"\n        ),\n        \"seed\": args.seed,\n        \"games\": args.games,\n        \"frozen_policy_randomness\": \"wall_actor_event_phase\",\n        \"saved_models\": {\n            name: {\n                str(path.relative_to(model_path)): hashlib.sha256(\n                    path.read_bytes()\n                ).hexdigest()\n                for path in sorted(pathlib.Path(model_path).rglob(\"*\"))\n                if path.is_file()\n            }\n            for name, model_path in ((\"new\", args.new), (\"old\", args.old))\n            if name == \"new\" or args.mortal_source is None\n        },\n    }\n    if args.mortal_source is not None:\n        mortal_files = {\n            \"checkpoint\": pathlib.Path(args.old),\n            \"source/libriichi.so\": pathlib.Path(\n                importlib.util.find_spec(\"libriichi\").origin\n            ),\n            **{\n                f\"source/{name}\": pathlib.Path(args.mortal_source)\n                / \"mortal\"\n                / name\n                for name in (\"model.py\", \"engine.py\")\n            },\n            **{\n                f\"adapter/training/{name}\": pathlib.Path(__file__).parent / name\n                for name in (\"mortal_policy.py\", \"frozen_policy.py\")\n            },\n        }\n        manifest[\"mortal\"] = {}\n        for name, path in mortal_files.items():\n            with path.open(\"rb\") as stream:\n                manifest[\"mortal\"][name] = hashlib.file_digest(\n                    stream, \"sha256\"\n                ).hexdigest()\n    manifest_path = root / \"evaluation.json\"\n    if (\n        manifest_path.exists()\n        and json.loads(manifest_path.read_text()) != manifest\n    ):\n        raise ValueError(\"Evaluation settings changed; use a fresh output\")\n    results = completed_games(root, requested, manifest[\"format\"])\n    manifest_path.write_text(json.dumps(manifest, indent=2) + \"\\n\")\n    publish_summary(root, results, args.seed)\n    completed = {(row[\"seed\"], *row[\"new_seats\"]) for row in results}\n    tasks = [(root, seed, seat) for seed, seat in sorted(requested - completed)]\n    if not tasks:\n        return\n    for name, model_path in ((\"new\", args.new), (\"old\", args.old)):\n        path = root / name\n        if not path.exists():\n            if name == \"old\" and args.mortal_source is not None:\n                for filename, source in mortal_files.items():\n                    (path / filename).parent.mkdir(parents=True, exist_ok=True)\n                    shutil.copy2(source, path / filename)\n                continue\n            source = frozen_policy.source_directory(model_path)\n            frozen_policy.freeze_source(source.parent, path / \"source\")\n            # Freeze adjacent packages used by the export's own worker.\n            if (source.parent.parent / \"log_dataset\").is_dir():\n                frozen_policy.freeze_source(\n                    source.parent.parent / \"log_dataset\",\n                    path / \"log_dataset\",\n                )\n            frozen_policy.freeze_source(\n                pathlib.Path(model_path), path / \"saved_model\"\n            )\n    started = time.monotonic()\n    context = multiprocessing.get_context(\"spawn\")\n    devices = context.Queue()\n    for worker in range(args.workers):\n        devices.put(\n            args.devices.split(\",\")[worker % len(args.devices.split(\",\"))]\n        )\n    batches = [\n        tasks[begin : begin + args.batch_games]\n        for begin in range(0, len(tasks), args.batch_games)\n    ]\n    with concurrent.futures.ProcessPoolExecutor(\n        max_workers=args.workers,\n        mp_context=context,\n        initializer=start_worker,\n        initargs=(root, devices, args.batch_games),\n    ) as executor:\n        batches = iter(batches)\n        pending = {\n            executor.submit(play_games, batch)\n            for batch in itertools.islice(batches, 2 * args.workers)\n        }\n        while pending:\n            finished, pending = concurrent.futures.wait(\n                pending, return_when=concurrent.futures.FIRST_COMPLETED\n            )\n            for future in finished:\n                completed = future.result()\n                with (root / \"games.jsonl\").open(\"a\") as stream:\n                    for row in completed:\n                        stream.write(json.dumps(row) + \"\\n\")\n                results.extend(completed)\n                publish_summary(root, results, args.seed)\n                print(\n                    f\"games={len(results)}/{args.games} \"\n                    f\"elapsed_seconds={time.monotonic() - started:.3f}\",\n                    flush=True,\n                )\n            pending.update(\n                executor.submit(play_games, batch)\n                for batch in itertools.islice(batches, len(finished))\n            )\n    devices.close()\n    devices.join_thread()\n\n\ndef main():\n    parser = argparse.ArgumentParser(description=__doc__)\n    parser.add_argument(\"--new\", required=True)\n    parser.add_argument(\"--old\", required=True)\n    parser.add_argument(\n        \"--mortal-source\",\n        help=\"Mortal policy checkout; --old is its .pth or ZIP\",\n    )\n    parser.add_argument(\"--output\", required=True)\n    parser.add_argument(\"--games\", type=int, default=10000)\n    parser.add_argument(\"--seed\", type=int)\n    parser.add_argument(\"--workers\", type=int, default=1)\n    parser.add_argument(\n        \"--devices\", default=\"-1\", help=\"Comma-separated GPU UUIDs; -1 uses CPU\"\n    )\n    parser.add_argument(\"--batch-games\", type=int, default=8)\n    arguments = parser.parse_args()\n    manifest = pathlib.Path(arguments.output) / \"evaluation.json\"\n    if arguments.seed is None:\n        arguments.seed = (\n            json.loads(manifest.read_text())[\"seed\"]\n            if manifest.exists()\n            else secrets.randbits(30)\n        )\n    if arguments.workers < 1 or arguments.batch_games < 1:\n        parser.error(\"workers and batch-games must be positive\")\n    run(arguments)\n\n\nif __name__ == \"__main__\":\n    main()\n",
      "sha256": "1bf1117b711b54a01f4ae1824c8c98672b8f15f1171a6fce4fee7bf26c9bbd79"
    },
    {
      "path": "training/evaluate_imitation.py",
      "text": "\"\"\"Score policy agreement with recorded expert and Mortal validation actions.\"\"\"\n\nimport argparse\nimport hashlib\nimport json\nimport pathlib\nimport shutil\nimport tempfile\nimport time\n\nimport numpy\nimport tensorflow as tf\n\nfrom log_dataset import records, training_data\nfrom model import actions, actor, export\nfrom training import monitor, restoration\n\n\ndef decision_totals(batch, log_policy, target, supported):\n    correct = tf.argmax(log_policy, axis=1, output_type=target.dtype) == target\n    ce = -tf.gather(log_policy, target, batch_dims=1)\n    # The response distribution factors into branch mass and a post-call cut.\n    branch_log = tf.stack(\n        [\n            tf.reduce_logsumexp(group, axis=1)\n            for group in tf.split(log_policy, [1, 37, 37, 37, 37, 1], axis=1)\n        ],\n        axis=1,\n    )\n    branch = tf.where(\n        target == 0, 0, tf.where(target == 149, 5, 1 + (target - 1) // 37)\n    )\n    cut_log = tf.gather(\n        tf.reshape(log_policy[:, 1:149], [-1, 4, 37]),\n        tf.clip_by_value(branch - 1, 0, 3),\n        batch_dims=1,\n    )\n    response = batch[\"head\"] == actions.TRAIN_POLICY_HEADS.index(\n        \"response_policy_logits\"\n    )\n    accepted = response & (branch > 0) & (branch < 5)\n    branch_match = tf.argmax(branch_log, 1, output_type=target.dtype) == branch\n    cut_match = tf.argmax(cut_log, 1, output_type=target.dtype) == (\n        (target - 1) % 37\n    )\n    values = (\n        tf.ones_like(correct),\n        correct,\n        supported,\n        tf.where(supported, ce, 0.0),\n        response,\n        response & branch_match,\n        accepted,\n        accepted & cut_match,\n    )\n    return tf.math.unsorted_segment_sum(\n        tf.stack([tf.cast(value, tf.float64) for value in values], axis=1),\n        batch[\"head\"],\n        len(actions.TRAIN_POLICY_HEADS),\n    )\n\n\ndef rates(row):\n    decisions, correct, supported, nll = row[:4]\n    return {\n        \"decisions\": int(decisions),\n        \"matches\": int(correct),\n        \"errors\": int(decisions - correct),\n        \"top1\": correct / decisions if decisions else None,\n        \"supported_decisions\": int(supported),\n        \"supported_nll\": nll / supported if supported else None,\n    }\n\n\ndef summarize(totals):\n    result = {\n        \"all\": rates(totals.sum(axis=0)),\n        **{\n            name.removesuffix(\"_logits\"): rates(row)\n            for name, row in zip(actions.TRAIN_POLICY_HEADS, totals)\n        },\n    }\n    responses, branch_correct, accepted, cut_correct = totals[:, 4:].sum(axis=0)\n    result[\"response_policy\"].update(\n        branch_top1=branch_correct / responses if responses else None,\n        accepted_chi_pon_decisions=int(accepted),\n        conditional_discard_top1=cut_correct / accepted if accepted else None,\n    )\n    return result\n\n\ndef run(args):\n    if args.batch_size < 1 or (\n        args.max_decisions is not None and args.max_decisions < 1\n    ):\n        raise ValueError(\"Batch size and decision limit must be positive\")\n    records.validate_summary(args.data)\n    manifest = (args.data / \"dataset_summary.json\").read_bytes()\n    summary = json.loads(manifest)\n    assert summary[\"validation_sample\"] == training_data.VALIDATION_SAMPLE\n    paths = []\n    count = 0\n    for row in summary[\"shard_manifest\"]:\n        if row[\"validation_count\"]:\n            path = args.data / row[\"validation_path\"]\n            if \"shard_readiness\" in summary:\n                receipt = args.data / (row[\"path\"] + \".receipt.json\")\n                published = json.loads(receipt.read_text())\n                if (\n                    path.stat().st_size != published[\"validation_bytes\"]\n                    or row[\"validation_count\"] != published[\"validation_count\"]\n                ):\n                    raise ValueError(\n                        f\"Invalid published validation file {path}\"\n                    )\n            paths.append(str(path))\n            count += row[\"validation_count\"]\n            if args.max_decisions is not None and count >= args.max_decisions:\n                break\n    if not count:\n        raise ValueError(\"Empty validation cohort\")\n    decisions = min(count, args.max_decisions or count)\n    batches = (\n        tf.data.TFRecordDataset(paths, compression_type=\"GZIP\")\n        .take(decisions)\n        .batch(args.batch_size)\n    )\n    if args.weights:\n        # The learner atomically replaces latest.weights.h5 as it saves.\n        with tempfile.TemporaryDirectory() as tmp:\n            snapshot = pathlib.Path(tmp) / \"snapshot.weights.h5\"\n            shutil.copyfile(args.weights, snapshot)\n            with snapshot.open(\"rb\") as stream:\n                digest = hashlib.file_digest(stream, \"sha256\").hexdigest()\n            network = export.build_network(\n                training_data.parse_batch(next(iter(batches))[:1])[0]\n            )\n            network.load_weights(snapshot)\n        module = export.ServingModel(network)\n        policy = module.policy\n        checkpoint = args.weights.name\n    else:\n        module = tf.saved_model.load(str(args.model))\n        policy = module.signatures[\"policy\"]\n        checkpoint = args.model.name\n        # A standalone SavedModel need not carry the original H5 hash.\n        digest = None\n\n    @tf.function(input_signature=[tf.TensorSpec([None], tf.string)])\n    def score(raw):\n        parsed = tf.io.parse_example(\n            raw,\n            {\n                name: tf.io.FixedLenFeature([], tf.string)\n                for name in (*records.FIELDS, \"expert/mortal_action\")\n            },\n        )\n        features, labels = records.decode_batch(parsed)\n        head, expert, legal = restoration.policy_choices(features, labels)\n        batch = {\n            \"features\": features,\n            \"head\": head,\n            \"expert\": expert,\n            \"legal\": legal,\n            \"mortal_action\": tf.cast(\n                tf.reshape(\n                    tf.io.decode_raw(parsed[\"expert/mortal_action\"], tf.int16),\n                    [-1],\n                ),\n                tf.int32,\n            ),\n        }\n        log_policy = actor.distribution(\n            policy(**batch[\"features\"]), batch[\"head\"], batch[\"legal\"]\n        )\n        return tf.stack(\n            [\n                decision_totals(\n                    batch,\n                    log_policy,\n                    batch[name],\n                    restoration.policy_target_supported(\n                        batch[\"features\"], batch[\"head\"], batch[name]\n                    ),\n                )\n                for name in (\"expert\", \"mortal_action\")\n            ]\n        )\n\n    totals = numpy.zeros((2, len(actions.TRAIN_POLICY_HEADS), 8), numpy.float64)\n    for raw in batches:\n        totals += score(raw).numpy()\n    if not numpy.isfinite(totals).all():\n        raise ValueError(\"Nonfinite validation measurements\")\n    if not numpy.all(totals[:, :, 0].sum(axis=1) == decisions):\n        raise ValueError(\"Validation record count disagrees with manifest\")\n    return {\n        \"checkpoint\": checkpoint,\n        \"checkpoint_sha256\": digest,\n        \"dataset_sha256\": hashlib.sha256(manifest).hexdigest(),\n        \"partition\": \"validation\",\n        \"max_decisions\": args.max_decisions,\n        \"validation_shards\": len(paths),\n        \"evaluated_at\": time.time(),\n        \"expert\": summarize(totals[0]),\n        \"mortal\": summarize(totals[1]),\n    }\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(description=__doc__)\n    source = parser.add_mutually_exclusive_group(required=True)\n    source.add_argument(\"--model\", type=pathlib.Path)\n    source.add_argument(\"--weights\", type=pathlib.Path)\n    parser.add_argument(\"--data\", type=pathlib.Path, required=True)\n    parser.add_argument(\"--max-decisions\", type=int)\n    parser.add_argument(\"--batch-size\", type=int, default=128)\n    parser.add_argument(\"--output\", type=pathlib.Path)\n    args = parser.parse_args()\n    report = run(args)\n    if args.output:\n        monitor.write_json(args.output, report)\n    else:\n        print(json.dumps(report, indent=2, allow_nan=False))\n",
      "sha256": "91f08c92aaebda64e5f648d8fff5b2ab7dacf614c3dc3e84db6f808efb0afe7c"
    },
    {
      "path": "training/expert.py",
      "text": "\"\"\"Three current-Q expert passes fit policy, critic and beliefs.\"\"\"\n\nimport argparse\nimport concurrent.futures\nimport contextlib\nimport hashlib\nimport json\nimport os\nimport pathlib\nimport sys\nimport time\n\nimport tensorflow as tf\n\nfrom log_dataset import (\n    _native_collection,\n    records,\n    root_states,\n    sakigiri_regret,\n    scoring,\n    training_data,\n)\nfrom model import actions, critic, export\nfrom training import (\n    auxiliary,\n    collection_workers,\n    fixed_reference,\n    imitation,\n    imitation_rollouts,\n    monitor,\n    reporting,\n    restoration,\n    self_play,\n)\nfrom training.corrections import collection, distributed\nfrom training.corrections import trainer as mmd_trainer\n\n\ndef decode_records(raw):\n    parsed = tf.io.parse_example(\n        raw,\n        {\n            name: tf.io.FixedLenFeature([], tf.string)\n            for name in (*records.FIELDS, \"expert/mortal_action\")\n        },\n    )\n    features, labels = records.decode_batch(parsed)\n    head, expert, legal = restoration.policy_choices(features, labels)\n    mortal = tf.cast(\n        tf.reshape(\n            tf.io.decode_raw(parsed[\"expert/mortal_action\"], tf.int16), [-1]\n        ),\n        tf.int32,\n    )\n    return {\n        \"features\": features,\n        \"head\": head,\n        \"expert\": expert,\n        \"legal\": legal,\n        \"chosen\": critic.chosen_actions(features, labels),\n        \"ending_kind\": labels[\"round_end_kind\"],\n        \"ending_source\": labels[\"round_end_source\"],\n        \"ending_tenpai\": labels[\"round_end_tenpai\"],\n        \"payment_points\": tf.gather(\n            tf.reshape(labels[\"terminal_payment\"], [-1, 64]),\n            [\n                kind * 16 + payer * 4 + winner\n                for kind, payer, winner in scoring.CELLS\n            ],\n            axis=1,\n        ),\n        \"reference_action\": critic.chosen_actions(\n            features,\n            {\n                name: tf.where(labels[name] >= 0, mortal, -1)\n                for name in actions.TRAIN_POLICY_HEADS\n            },\n        ),\n        \"labels\": {name: labels[name] for name in auxiliary.LABELS},\n    }\n\n\ndef input_batches(*, data, group, batch_size, seed):\n    \"\"\"Equal natural and focused exposures on disjoint learner shards.\"\"\"\n    if batch_size < group.replicas:\n        raise ValueError(\"Expert batch size must cover every replica\")\n    summary = json.loads(\n        (pathlib.Path(data) / \"dataset_summary.json\").read_text()\n    )\n    assert \"meta/focused_priority\" in summary[\"sampling_fields\"]\n    counts = [\n        sum(\n            sum(row[\"counts\"][:7])\n            for row in summary[\"shard_manifest\"][rank :: group.replicas]\n        )\n        for rank in range(group.replicas)\n    ]\n    if min(counts) == 0:\n        raise ValueError(\"Each replica needs at least one training record\")\n    for rank in range(group.replicas):\n        if not sum(\n            sum(partition[0] for partition in row[\"sampling_counts\"][:7])\n            for row in summary[\"shard_manifest\"][rank :: group.replicas]\n        ):\n            raise ValueError(\"Each replica needs focused records\")\n    sizes = [\n        batch_size // group.replicas + (rank < batch_size % group.replicas)\n        for rank in range(group.replicas)\n    ]\n    steps = max(\n        (count + size - 1) // size for count, size in zip(counts, sizes)\n    )\n    with tf.device(\"/CPU:0\"):\n        streams = []\n        for category in range(2):\n            stream = training_data.dataset(\n                root=data,\n                partition=\"train\",\n                batch_size=1024,\n                rank=group.rank,\n                replicas=group.replicas,\n                seed=seed + category,\n            )\n            if category:\n\n                def emphasize(raw):\n                    metadata = tf.io.parse_example(\n                        raw,\n                        {\n                            \"meta/focused_priority\": tf.io.FixedLenFeature(\n                                [], tf.int64\n                            )\n                        },\n                    )\n                    return tf.repeat(raw, metadata[\"meta/focused_priority\"])\n\n                stream = stream.map(emphasize, num_parallel_calls=2)\n            streams.append(\n                stream.unbatch().shuffle(8192, seed=seed + category).repeat()\n            )\n        stream = tf.data.Dataset.choose_from_datasets(\n            streams,\n            tf.data.Dataset.from_tensor_slices(tf.constant([0, 1], tf.int64))\n            .repeat()\n            .take(counts[group.rank]),\n            stop_on_empty_dataset=True,\n        )\n        stream = stream.apply(\n            tf.data.experimental.assert_cardinality(counts[group.rank])\n        ).batch(sizes[group.rank])\n        # Empty tail replicas repeat a real example with zero valid mass.\n        # Rank-local lengths are known from the verified shard manifest.\n        stream = stream.concatenate(stream.take(1).repeat()).take(steps)\n\n        def decode(step, raw):\n            valid_counts = tf.clip_by_value(\n                tf.constant(counts, tf.int64)\n                - step * tf.constant(sizes, tf.int64),\n                0,\n                tf.constant(sizes, tf.int64),\n            )\n            raw = tf.gather(\n                raw, tf.minimum(tf.range(max(sizes)), tf.size(raw) - 1)\n            )\n            metadata = tf.io.parse_example(\n                raw,\n                {\n                    \"meta/\" + name: tf.io.FixedLenFeature([], dtype)\n                    for name, dtype in (\n                        (\"game_id\", tf.string),\n                        (\"kyoku_id\", tf.string),\n                        (\"decision_index\", tf.int64),\n                        (\"actor\", tf.int64),\n                    )\n                },\n            )\n            return {\n                **decode_records(raw),\n                \"metadata\": {\n                    name.removeprefix(\"meta/\"): value\n                    for name, value in metadata.items()\n                },\n                \"natural\": (\n                    step * tf.cast(sizes[group.rank], tf.int64)\n                    + tf.range(tf.size(raw), dtype=tf.int64)\n                )\n                % 2\n                == 0,\n                \"local_count\": tf.cast(valid_counts[group.rank], tf.int32),\n                \"global_count\": tf.reduce_sum(valid_counts),\n            }\n\n        return stream.enumerate().map(decode, num_parallel_calls=2).prefetch(2)\n\n\ndef save_weights(network, path):\n    pending = path.with_name(\"pending.\" + path.name)\n    network.save_weights(pending)\n    pending.replace(path)\n\n\ndef fit(args, contexts):  # noqa: C901 — executable outline for initialization\n    if (\n        min(args.batch_size, args.rollout_batch_size, args.reference_batch_size)\n        <= 0\n    ):\n        raise ValueError(\"Batch size must be positive\")\n    if args.collection_streams < 4:\n        raise ValueError(\"Collection needs at least four active streams\")\n    if args.collection_interval_batches <= 0:\n        raise ValueError(\"Collection interval must be positive\")\n    command = json.loads(pathlib.Path(args.evaluation_command).read_text())\n    if int(command[command.index(\"--games\") + 1]) != 10000:\n        raise ValueError(\n            \"The initial main-loop match must contain 10,000 games\"\n        )\n    for placeholder in (\"{weights}\", \"{output}\"):\n        if not any(placeholder in value for value in command):\n            raise ValueError(\"Evaluation command needs {weights} and {output}\")\n    devices = tf.config.list_physical_devices(\"GPU\")\n    if len(devices) > 1:\n        raise ValueError(\"Select one learner GPU per worker\")\n    for device in devices:\n        tf.config.experimental.set_memory_growth(device, True)\n    tf.keras.utils.set_random_seed(args.seed)\n    group = distributed.LearnerGroup()\n    root = pathlib.Path(args.output).resolve()\n    if group.chief:\n        root.mkdir(parents=True, exist_ok=False)\n    with group.strategy.scope():\n        features = self_play.initial_features(args.seed)\n        network = export.load_network(args.initial, features)\n        mirror = export.load_network(args.initial, features).actor\n        mirror.trainable = False\n    reference_policy = fixed_reference.Policy(\n        args.reference, batch_size=args.reference_batch_size\n    )\n    workers = contexts.enter_context(\n        collection_workers.CollectionWorkers(\n            reference=(args.reference, tuple(reference_policy.fields)),\n            streams=args.collection_streams,\n        )\n    )\n    collector = contexts.enter_context(\n        concurrent.futures.ThreadPoolExecutor(max_workers=1)\n    )\n    summary_path = pathlib.Path(args.data) / \"dataset_summary.json\"\n    summary = json.loads(summary_path.read_text())\n    expected = sum(summary[\"partition_counts\"][:7])\n    prepared_roots = json.loads(\n        (pathlib.Path(args.data) / \"root-states/complete.json\").read_text()\n    )\n    assert (\n        prepared_roots[\"summary_sha256\"]\n        == hashlib.sha256(summary_path.read_bytes()).hexdigest()\n    )\n    assert prepared_roots[\"input_schema\"] == _native_collection.INPUTS\n    assert prepared_roots[\"limit_games\"] is None\n    assert prepared_roots[\"sakigiri\"] == sakigiri_regret.DEFINITION\n    source = root_states.Store(pathlib.Path(args.data) / \"root-states\")\n    predict = self_play.predictor(network.actor)\n    evaluate_roots = collection.root_scorer(network, with_policy=True)\n    if group.chief:\n        save_weights(network, root / \"initial.weights.h5\")\n        monitor.write_json(\n            root / \"plan.json\",\n            {\n                **vars(args),\n                \"method\": \"q-weighted-expert-imitation\",\n                \"passes\": 3,\n                \"sampling\": {\n                    \"natural\": 0.5,\n                    \"focused\": 0.5,\n                },\n                \"pass_exposures\": expected,\n                \"imitation_rollouts\": {\n                    \"categories\": list(collection.CATEGORIES),\n                    \"positions\": \"focused roots paired with natural-source roots\",\n                    \"targeted_root_fraction\": 0.5,\n                    \"sakigiri\": sakigiri_regret.DEFINITION,\n                    \"advancing_calls\": \"all legal advancing calls plus pass\",\n                    \"continuations_per_action\": 1,\n                    \"position_budget\": (\n                        f\"{args.collection_interval_batches}-batch \"\n                        \"estimated simulated-decision target \"\n                        \"equals human exposures\"\n                    ),\n                    \"budget_unit\": \"all requested decisions in every continuation\",\n                    \"sampling\": (\n                        \"balanced seeds per batch; \"\n                        \"collected together every \"\n                        f\"{args.collection_interval_batches} batches\"\n                    ),\n                    \"overshoot\": \"finish started hands; no debt carryover\",\n                    \"paired_walls\": \"one shared target wall; normal branches independent\",\n                    \"policy\": \"fixed reference after forced root action\",\n                    \"continuation_policy\": reference_policy.provenance,\n                    \"buffered_windows\": 1,\n                    \"collection_interval_batches\": (\n                        args.collection_interval_batches\n                    ),\n                    \"initial_decisions_per_continuation\": 32,\n                    \"length_estimate\": (\n                        \"latest consumed window decisions per continuation\"\n                    ),\n                    \"training\": (\n                        \"critic then MMD actor one window behind; \"\n                        \"drain at pass end\"\n                    ),\n                    \"mmd\": {\n                        \"mirror_kl\": 0.3,\n                        \"magnet_kl\": 0.3,\n                        \"actor_constraints\": 0.01,\n                        \"learning_rate\": 1e-5,\n                        \"magnet\": reference_policy.provenance,\n                        \"mirror\": \"learner immediately before MC critic fit\",\n                    },\n                    \"imitation_labels\": \"unchanged human actions\",\n                },\n                \"replicas\": group.replicas,\n                \"expected_exposures\": expected * 3,\n                \"evaluation_argv\": command,\n                \"initial_sha256\": hashlib.sha256(\n                    pathlib.Path(args.initial).read_bytes()\n                ).hexdigest(),\n                \"dataset_sha256\": hashlib.sha256(\n                    summary_path.read_bytes()\n                ).hexdigest(),\n                \"reference_policy\": summary[\"preparation\"][\"mortal_policy\"],\n                \"weighting_critic\": \"current-network-detached\",\n                \"learning_rates\": {\"imitation\": 1e-5},\n                \"beta_target\": imitation.ESS_TARGET,\n                \"beta_bounds\": [0.0001, 1.28],\n                \"raw_weight_cap\": 20,\n                \"beta_calibration\": \"global-batch-highest-crossing\",\n                \"q_loss_units\": \"J squared; fixed nats/J squared scale\",\n                \"q_mse_to_nll\": critic.Q_MSE_TO_NLL,\n                \"q_targets\": \"known payments with unique continuation J\",\n                \"loss_coefficients\": {\n                    \"imitation\": {\n                        \"expert_ce\": 1,\n                        \"each_auxiliary\": 1,\n                        \"payment_nll\": 0.5,\n                        \"q_mse\": 0.5 * critic.Q_MSE_TO_NLL,\n                        \"nagashi_loss\": 1,\n                        \"critic_constraint_loss\": 1,\n                    },\n                },\n            },\n        )\n    started = time.monotonic()\n    exposures = actor_exposures = critic_exposures = steps = 0\n    reporting_positions = 0\n\n    mc_human_positions = mc_decisions = mc_actor_exposures = 0\n\n    def report(stage, metrics):\n        status = {\n            \"stage\": stage,\n            \"pass\": expert_pass,\n            \"passes\": 3,\n            \"exposures\": exposures,\n            \"reporting_positions\": reporting_positions,\n            \"actor_exposures\": actor_exposures,\n            \"critic_exposures\": critic_exposures,\n            \"steps\": steps,\n            \"mc_human_positions\": mc_human_positions,\n            \"mc_simulated_decisions\": mc_decisions,\n            \"mc_actor_exposures\": mc_actor_exposures,\n            \"elapsed_seconds\": (\n                time.monotonic() - started - group.paused_seconds\n            ),\n            \"updated_at\": time.time(),\n            **metrics,\n        }\n        monitor.write_json(root / \"status.json\", status)\n        with (root / \"progress.jsonl\").open(\"a\") as stream:\n            stream.write(json.dumps(status) + \"\\n\")\n        reporting.write_metrics(\n            root,\n            stage=stage,\n            step=reporting_positions,\n            metrics=metrics,\n            **{\"pass\": expert_pass},\n        )\n        if steps and steps % 256 == 0:\n            save_weights(network, root / \"latest.weights.h5\")\n\n    complete = True\n\n    def fit_pending(batch):\n        nonlocal mc_human_positions, mc_decisions, mc_actor_exposures\n        nonlocal actor_exposures, critic_exposures, steps, complete\n        nonlocal reporting_positions\n        nonlocal decisions_per_continuation\n        wait_started = time.monotonic()\n        rollout_rows, rollout_statistics = pending.result()\n        wait_seconds = time.monotonic() - wait_started\n        credited, spent, continuations = group.sum_counts(\n            tf.constant(\n                [\n                    pending_target,\n                    rollout_statistics[\"simulated_decisions\"],\n                    rollout_statistics[\"continuations\"],\n                ],\n                tf.int32,\n            )\n        ).numpy()\n        mc_human_positions += int(credited)\n        mc_decisions += int(spent)\n        if continuations:\n            decisions_per_continuation = float(spent / continuations)\n        mirror.set_weights(network.actor.get_weights())\n        for update in (\"imitation-rollout\", \"imitation-mmd\"):\n            for rollout_batch in imitation_rollouts.batches(\n                rollout_rows, batch, group, args.rollout_batch_size\n            ):\n                metrics = group.update(update, rollout_batch, root)\n                if metrics is None:\n                    complete = False\n                    break\n                trained = int(metrics[\"trained_positions\"])\n                reporting_positions += trained\n                if update == \"imitation-rollout\":\n                    critic_exposures += trained\n                else:\n                    actor_exposures += trained\n                    mc_actor_exposures += trained\n                steps += bool(trained)\n                if group.chief:\n                    report(\n                        update,\n                        {name: float(value) for name, value in metrics.items()},\n                    )\n            if not complete:\n                break\n        if devices:\n            monitor.write_json(\n                root / f\"memory-rank-{group.rank}.json\",\n                {\n                    **tf.config.experimental.get_memory_info(\"GPU:0\"),\n                    \"human_exposures\": exposures,\n                    \"simulated_decisions\": mc_decisions,\n                    \"updated_at\": time.time(),\n                },\n            )\n        if group.chief:\n            report(\n                \"imitation-collection\",\n                {\n                    \"collection_seconds\": rollout_statistics[\n                        \"collection_seconds\"\n                    ],\n                    \"collection_wait_seconds\": wait_seconds,\n                },\n            )\n\n    for expert_pass in range(1, 4):\n        with group.strategy.scope():\n            learner = imitation.ImitationTrainer(\n                network=network,\n                features=features,\n                learning_rate=1e-5,\n            )\n            rollout_actor = mmd_trainer.MMDTrainer(\n                network=network, mirror=mirror, learning_rate=1e-5\n            )\n        group.bind_expert(\n            learner=learner,\n            rollout_actor=rollout_actor,\n            batch_size=args.batch_size,\n        )\n        if group.chief:\n            report(\"imitation\", {})\n        batches = input_batches(\n            data=args.data,\n            group=group,\n            batch_size=args.batch_size,\n            seed=args.seed + expert_pass - 1,\n        )\n        group.barrier()\n        decisions_per_continuation = 32.0\n        pending = None\n        pending_target = 0\n        seeds = []\n        decision_target = 0\n        for batch_number, batch in enumerate(batches):\n            seeds.extend(\n                imitation_rollouts.select_seeds(\n                    source=source,\n                    batch=batch,\n                    predict=predict,\n                    evaluate=evaluate_roots,\n                    seed=args.seed + exposures + group.rank * group.local_batch,\n                    decisions_per_continuation=decisions_per_continuation,\n                    stop=root / \"STOP\",\n                )\n            )\n            decision_target += int(batch[\"local_count\"])\n            metrics = group.update(\n                \"imitation\",\n                {\n                    name: value\n                    for name, value in batch.items()\n                    if name not in (\"metadata\", \"natural\")\n                },\n                root,\n            )\n            if metrics is None:\n                complete = False\n                break\n            exposures += int(batch[\"global_count\"])\n            reporting_positions += int(batch[\"global_count\"])\n            trained = int(metrics[\"trained_positions\"])\n            actor_exposures += trained\n            critic_exposures += trained\n            steps += bool(trained)\n            if group.chief:\n                report(\n                    \"imitation\",\n                    {name: float(value) for name, value in metrics.items()},\n                )\n            if (\n                (batch_number + 1) % args.collection_interval_batches\n                and exposures < expected * expert_pass\n            ):\n                continue\n            if pending is not None:\n                fit_pending(batch)\n                if not complete:\n                    break\n            pending_target = decision_target\n            pending = collector.submit(\n                imitation_rollouts.collect_window,\n                data=args.data,\n                workers=workers,\n                seeds=seeds,\n                reference_policy=reference_policy,\n                decision_target=decision_target,\n                predict=reference_policy.predict_features,\n                packing=group.packing,\n                directory=root\n                / \"imitation-rollouts\"\n                / f\"pass-{expert_pass}\"\n                / \"window-{:06d}-rank-{}\".format(\n                    batch_number // args.collection_interval_batches, group.rank\n                ),\n                stop=root / \"STOP\",\n            )\n            seeds = []\n            decision_target = 0\n        if pending is not None:\n            if complete:\n                fit_pending(batch)\n            else:\n                pending.result()\n        if not complete:\n            break\n        assert exposures == expected * expert_pass\n        if group.chief:\n            save_weights(network, root / f\"pass-{expert_pass}.weights.h5\")\n            save_weights(network, root / \"latest.weights.h5\")\n    group.barrier()\n    source.close()\n    if group.chief:\n        save_weights(network, root / \"latest.weights.h5\")\n        if complete:\n            save_weights(network, root / \"final.weights.h5\")\n            monitor.write_json(\n                root / \"training-complete.json\",\n                {\n                    \"weights\": str(root / \"final.weights.h5\"),\n                    \"exposures\": exposures,\n                    \"steps\": steps,\n                    \"mc_human_positions\": mc_human_positions,\n                    \"mc_simulated_decisions\": mc_decisions,\n                    \"mc_actor_exposures\": mc_actor_exposures,\n                },\n            )\n        report(\"main-loop-ready\" if complete else \"stopped\", {})\n    group.barrier()\n\n\ndef run(args):\n    with contextlib.ExitStack() as contexts:\n        fit(args, contexts)\n\n\ndef main():\n    parser = argparse.ArgumentParser(description=__doc__)\n    for name in (\n        \"data\",\n        \"initial\",\n        \"reference\",\n        \"output\",\n        \"evaluation-command\",\n    ):\n        parser.add_argument(\"--\" + name, required=True)\n    parser.add_argument(\"--batch-size\", type=int, default=8192)\n    parser.add_argument(\"--rollout-batch-size\", type=int, default=512)\n    parser.add_argument(\"--collection-streams\", type=int, default=512)\n    parser.add_argument(\"--reference-batch-size\", type=int, default=64)\n    parser.add_argument(\"--collection-interval-batches\", type=int, default=16)\n    parser.add_argument(\"--seed\", type=int, required=True)\n    args = parser.parse_args()\n    existing_output = pathlib.Path(args.output).exists()\n    try:\n        run(args)\n    finally:\n        path = pathlib.Path(args.output) / \"status.json\"\n        if (\n            not existing_output\n            and sys.exception() is not None\n            and (\n                \"TF_CONFIG\" not in os.environ\n                or json.loads(os.environ[\"TF_CONFIG\"])[\"task\"][\"index\"] == 0\n            )\n            and path.exists()\n        ):\n            status = json.loads(path.read_text())\n            status.update(\n                stage=\"failed\",\n                error=str(sys.exception()),\n                updated_at=time.time(),\n            )\n            monitor.write_json(path, status)\n\n\nif __name__ == \"__main__\":\n    main()\n",
      "sha256": "e963de6192d4d4b89b434de9dbf0a03e27ef1c10648c087a55f9bded2363b9cb"
    },
    {
      "path": "training/fixed_reference.py",
      "text": "\"\"\"Score immutable policies with their own frozen replay feature producer.\"\"\"\n\nimport hashlib\nimport importlib.util\nimport itertools\nimport json\nimport pathlib\n\nimport numpy\nimport tensorflow as tf\n\nfrom log_dataset import call_states\nfrom model import actor\n\n\ndef native_module(directory):\n    source = (\n        pathlib.Path(directory).resolve(strict=True).parent\n        / \"source/log_dataset/_native_collection.so\"\n    )\n    spec = importlib.util.spec_from_file_location(\n        \"fixed_reference._native_collection\", source\n    )\n    module = importlib.util.module_from_spec(spec)\n    spec.loader.exec_module(module)\n    return module\n\n\nclass FeatureProducer:\n    \"\"\"CPU-only incremental replay using the immutable policy's producer.\"\"\"\n\n    def __init__(self, directory, fields):\n        self.native = native_module(directory)\n        self.fields = {name: self.native.INPUTS[name] for name in fields}\n\n    def stream(self):\n        \"\"\"Create independent replay state for one collector trajectory.\"\"\"\n        replays = {}\n        cursors = {}\n\n        def features(request, collector):\n            phases = numpy.frombuffer(\n                request[\"features\"], call_states.ROW_DTYPE\n            )[\"decision_phase\"]\n            logs = collector.logs()\n            packed = []\n            for game, seat, end, phase in zip(\n                request[\"game\"], request[\"seat\"], request[\"event\"], phases\n            ):\n                if game not in replays:\n                    replays[game] = self.native.FeatureReplay()\n                    cursors[game] = 0\n                if end != cursors[game]:\n                    events = json.loads(logs[game])\n                    replays[game].apply(json.dumps(events[cursors[game] : end]))\n                    cursors[game] = end\n                packed.append(replays[game].pack(int(seat), int(phase)))\n            return {\n                **{\n                    name: numpy.stack(\n                        [\n                            numpy.frombuffer(row[name], spec[\"dtype\"]).reshape(\n                                spec[\"shape\"]\n                            )\n                            for row in packed\n                        ]\n                    )\n                    for name, spec in self.fields.items()\n                },\n                \"decision_phase\": phases.copy(),\n            }\n\n        return features\n\n\nclass Policy:\n    \"\"\"Batch exact frozen features at inclusive MJAI event positions.\"\"\"\n\n    def __init__(self, directory, batch_size=64):\n        directory = pathlib.Path(directory).resolve(strict=True)\n        source = directory.parent / \"source/log_dataset/_native_collection.so\"\n        self.native = native_module(directory)\n        self.module = tf.saved_model.load(str(directory))\n        self.policy = self.module.signatures[\"policy\"]\n        self.batch_size = batch_size\n        self.fields = {\n            name: self.native.INPUTS[name]\n            for name in self.policy.structured_input_signature[1]\n        }\n        self.provenance = {\n            \"files_sha256\": {\n                str(path.relative_to(directory.parent)): hashlib.sha256(\n                    path.read_bytes()\n                ).hexdigest()\n                for path in [\n                    source,\n                    *sorted(\n                        path for path in directory.rglob(\"*\") if path.is_file()\n                    ),\n                ]\n            },\n        }\n\n    def predict_features(self, features):\n        \"\"\"Score frozen-producer arrays, padding only the final GPU batch.\"\"\"\n        count = len(next(iter(features.values())))\n        output = {\n            name: numpy.empty(\n                (count, *spec.shape[1:]), spec.dtype.as_numpy_dtype\n            )\n            for name, spec in self.policy.structured_outputs.items()\n        }\n        for begin in range(0, count, self.batch_size):\n            selected = numpy.minimum(\n                numpy.arange(begin, begin + self.batch_size), count - 1\n            )\n            scores = self.policy(\n                **{\n                    name: tf.convert_to_tensor(features[name][selected])\n                    for name in self.fields\n                }\n            )\n            end = min(begin + self.batch_size, count)\n            for name, values in scores.items():\n                output[name][begin:end] = values.numpy()[: end - begin]\n        return output\n\n    def predict(self, events, requests):\n        \"\"\"Return five policy heads in the original request order.\n\n        Each request is (last applied event index, actor, decision phase).\n        Replay stays inside the selected artifact's native implementation;\n        compact learner features never substitute for frozen model inputs.\n        \"\"\"\n        return self._predict_many([(events, requests)])\n\n    def _predict_many(self, items):\n        items = [\n            (events, numpy.asarray(requests, dtype=numpy.int64).reshape(-1, 3))\n            for events, requests in items\n        ]\n        output = {\n            name: numpy.empty(\n                (sum(len(requests) for _, requests in items), *spec.shape[1:]),\n                spec.dtype.as_numpy_dtype,\n            )\n            for name, spec in self.policy.structured_outputs.items()\n        }\n\n        def rows():\n            offset = 0\n            for events, requests in items:\n                replay = self.native.FeatureReplay()\n                cursor = 0\n                for position in numpy.argsort(requests[:, 0], kind=\"stable\"):\n                    event, seat, phase = requests[position]\n                    replay.apply(json.dumps(events[cursor : event + 1]))\n                    cursor = int(event) + 1\n                    yield offset + position, replay.pack(int(seat), int(phase))\n                offset += len(requests)\n\n        for batch in itertools.batched(rows(), self.batch_size):\n            selected = numpy.asarray([position for position, _ in batch])\n            scores = self.predict_features(\n                {\n                    name: numpy.stack(\n                        [\n                            numpy.frombuffer(buffers[name], spec[\"dtype\"])\n                            .reshape(spec[\"shape\"])\n                            .copy()\n                            for _, buffers in batch\n                        ]\n                    )\n                    for name, spec in self.fields.items()\n                }\n            )\n            for name, values in scores.items():\n                output[name][selected] = values\n        return output\n\n    def distribution(self, events, requests, heads, legal):\n        \"\"\"Return masked, selected-head log probabilities for learner rows.\"\"\"\n        return actor.distribution(\n            self.predict(events, requests), heads, legal\n        ).numpy()\n\n    def distribution_many(self, items):\n        \"\"\"Score (events, requests, heads, legal) items in concatenated order.\"\"\"\n        items = list(items)\n        return actor.distribution(\n            self._predict_many(\n                (events, requests) for events, requests, _, _ in items\n            ),\n            numpy.concatenate([heads for _, _, heads, _ in items]),\n            numpy.concatenate([legal for _, _, _, legal in items]),\n        ).numpy()\n",
      "sha256": "5974f29e93fdd5307ab83121d78ca590835bab5877925301705f298d1e78100b"
    },
    {
      "path": "training/frozen_policy.py",
      "text": "\"\"\"Frozen source snapshots and isolated policy execution.\"\"\"\n\nimport json\nimport os\nimport pathlib\nimport shutil\nimport subprocess\nimport sys\n\nWORKER = r\"\"\"\nimport json\nimport sys\nfrom log_dataset import call_states, features\nfrom model import actions\nfrom log_dataset import replay\nimport numpy\nimport riichienv\nimport tensorflow as tf\n\nfor device in tf.config.list_physical_devices(\"GPU\"):\n    tf.config.set_logical_device_configuration(\n        device,\n        [tf.config.LogicalDeviceConfiguration(memory_limit=int(sys.argv[2]))],\n    )\nsignatures = tf.saved_model.load(sys.argv[1]).signatures\npredict = signatures[\"policy\"]\n\n\ndef infer(values):\n    values = call_states.batch(values)\n    output = predict(\n        **{\n            key: tf.convert_to_tensor(\n                values[key], dtype=spec.dtype\n            )\n            for key, spec in predict.structured_input_signature[1].items()\n        }\n    )\n    return {name: value.numpy() for name, value in output.items()}\n\n\ncontexts = {}\nfor line in sys.stdin:\n    request = json.loads(line)\n    if request[\"reset\"]:\n        contexts.clear()\n    results = [None] * len(request[\"items\"])\n    decisions = []\n    for index, item in enumerate(request[\"items\"]):\n        stream = item[\"stream\"]\n        if stream not in contexts or (\n            item[\"events\"][: contexts[stream][\"cursor\"]]\n            != contexts[stream][\"previous\"]\n        ):\n            contexts[stream] = {\n                \"state\": None,\n                \"cursor\": 0,\n                \"pending\": {},\n                \"previous\": [],\n            }\n        context = contexts[stream]\n        context[\"random_seed\"] = item[\"random_seed\"]\n        numpy.random.seed(\n            numpy.random.SeedSequence(context[\"random_seed\"])\n            .generate_state(4)\n        )\n        for event in item[\"events\"][context[\"cursor\"] :]:\n            if event[\"type\"] == \"start_kyoku\":\n                context[\"state\"] = replay.Replay.from_start(\"frozen\", event)\n                context[\"pending\"].clear()\n            elif context[\"state\"] is not None:\n                if event[\"type\"] in (\"chi\", \"pon\", \"daiminkan\"):\n                    context[\"pending\"] = {\n                        seat: plan\n                        for seat, plan in context[\"pending\"].items()\n                        if seat == event[\"actor\"] and plan[1] == event[\"type\"]\n                    }\n                elif event[\"type\"] in (\"tsumo\", \"dahai\"):\n                    context[\"pending\"].pop(event[\"actor\"], None)\n                elif event[\"type\"] in (\"hora\", \"ryukyoku\", \"end_kyoku\"):\n                    context[\"pending\"].clear()\n                context[\"state\"].apply(event)\n                if event[\"type\"] == \"tsumo\" and \"tiles_left\" in event:\n                    context[\"state\"].live_wall = event[\"tiles_left\"]\n        context[\"cursor\"] = len(item[\"events\"])\n        context[\"previous\"] = item[\"events\"]\n        observation = riichienv.Observation.deserialize_from_base64(\n            item[\"observation\"]\n        )\n        actor = observation.player_id\n        legal = observation.legal_actions()\n        selected = actions.forced_policy_action(context[\"state\"], actor, legal)\n        if actor in context[\"pending\"] and any(\n            action.action_type == riichienv.ActionType.DISCARD\n            for action in legal\n        ):\n            cut, _ = context[\"pending\"].pop(actor)\n            if selected is None:\n                selected = actions.select_discard(\n                    legal, cut, observation.drawn_tile\n                )\n        if selected is not None:\n            results[index] = features.action_event(\n                selected, observation.drawn_tile\n            )\n        else:\n            _, value = actions.policy_request(\n                context[\"state\"], actor, observation\n            )\n            decisions.append((index, context, observation, value))\n    while decisions:\n        output = infer(\n            [value[\"features\"] for _, _, _, value in decisions],\n        )\n        deferred = []\n        for row, (index, context, observation, value) in enumerate(decisions):\n            numpy.random.seed(\n                numpy.random.SeedSequence([\n                    *context[\"random_seed\"],\n                    features.PHASES[value[\"phase\"]] + 1,\n                ]).generate_state(4)\n            )\n            selected, metadata = actions.select_policy_action(\n                value, output, row\n            )\n            if selected is None:\n                value = actions.continue_request(value)\n                if value[\"phase\"] == \"DISCARD\":\n                    selected = actions.forced_policy_action(\n                        context[\"state\"],\n                        observation.player_id,\n                        [\n                            action for action in observation.legal_actions()\n                            if action.action_type\n                            == riichienv.ActionType.DISCARD\n                        ],\n                    )\n                if selected is None:\n                    deferred.append((index, context, observation, value))\n                    continue\n            results[index] = features.action_event(\n                selected, observation.drawn_tile\n            )\n            if \"discard_action\" in metadata and selected.action_type in (\n                riichienv.ActionType.RIICHI,\n                riichienv.ActionType.CHI,\n                riichienv.ActionType.PON,\n            ):\n                context[\"pending\"][observation.player_id] = (\n                    metadata[\"discard_action\"],\n                    results[index][\"type\"],\n                )\n        decisions = deferred\n    print(json.dumps(results), flush=True)\n\"\"\"\n\n\ndef freeze_source(source, target):\n    source, target = pathlib.Path(source), pathlib.Path(target)\n    shutil.copytree(\n        source,\n        target,\n        ignore=shutil.ignore_patterns(\n            \"__pycache__\",\n            \".pytest_cache\",\n            \"*.pyc\",\n            \"target\",\n        ),\n    )\n\n\ndef source_directory(model_path):\n    \"\"\"Find the enclosing release/run snapshot for a SavedModel artifact.\"\"\"\n    for parent in pathlib.Path(model_path).resolve().parents:\n        for worker in parent.glob(\"source/*/frozen_policy.py\"):\n            return worker.parent\n    raise FileNotFoundError(f\"frozen policy source missing for {model_path}\")\n\n\nclass FrozenPolicy:\n    def __init__(self, model_path, device=\"-1\", memory_mb=2048):\n        self.model_path = pathlib.Path(model_path).resolve()\n        self.source = source_directory(self.model_path)\n        self.events = {}\n        self.reset_pending = True\n        self.process = subprocess.Popen(\n            [\n                sys.executable,\n                \"-c\",\n                \"import runpy, sys; sys.path.pop(0);\\n\"\n                \"exec(runpy.run_path('frozen_policy.py')['WORKER'])\",\n                str(self.model_path),\n                str(memory_mb),\n            ],\n            cwd=self.source,\n            stdin=subprocess.PIPE,\n            stdout=subprocess.PIPE,\n            text=True,\n            bufsize=1,\n            env={\n                **os.environ,\n                \"PYTHONPATH\": os.pathsep.join(\n                    (str(self.source.parent), str(self.source.parent.parent))\n                ),\n                \"CUDA_VISIBLE_DEVICES\": device,\n                \"TF_NUM_INTRAOP_THREADS\": \"2\",\n                \"TF_NUM_INTEROP_THREADS\": \"2\",\n                \"TF_CUDNN_USE_AUTOTUNE\": \"0\",\n            },\n        )\n\n    def reset(self, game_seeds):\n        self.game_seeds = game_seeds\n        self.events = {}\n        self.reset_pending = True\n\n    def select_many(self, requests):\n        self.send_requests(requests)\n        return self.receive_actions(requests)\n\n    def send_requests(self, requests):\n        # Decode only new events, retaining the frozen workers' full-history\n        # wire contract. Evaluation resets policies before each new cohort.\n        for env in dict.fromkeys(env for _, env, _ in requests):\n            history = self.events.setdefault(env, [])\n            history.extend(env.mjai_log_since(len(history)))\n        self.process.stdin.write(\n            json.dumps(\n                {\n                    \"reset\": self.reset_pending,\n                    \"items\": [\n                        {\n                            \"stream\": stream,\n                            \"random_seed\": [\n                                self.game_seeds[stream // 4],\n                                stream % 4,\n                                len(self.events[env]),\n                            ],\n                            \"events\": self.events[env],\n                            \"observation\": observation.serialize_to_base64(),\n                        }\n                        for stream, env, observation in requests\n                    ],\n                }\n            )\n            + \"\\n\"\n        )\n        self.process.stdin.flush()\n        self.reset_pending = False\n\n    def receive_actions(self, requests):\n        response = self.process.stdout.readline()\n        if not response:\n            raise RuntimeError(f\"frozen policy exited: {self.process.poll()}\")\n        actions = []\n        for (stream, env, observation), event in zip(\n            requests, json.loads(response), strict=True\n        ):\n            action = observation.select_action_from_mjai(json.dumps(event))\n            if action is None:\n                failure_path = self.model_path.parent / (\n                    f\"illegal-action-{stream}.json\"\n                )\n                failure_path.write_text(\n                    json.dumps(\n                        {\n                            \"stream\": stream,\n                            \"response\": event,\n                            \"observation\": observation.serialize_to_base64(),\n                            \"events\": env.mjai_log,\n                        }\n                    )\n                    + \"\\n\"\n                )\n                raise ValueError(\n                    f\"Opponent returned an illegal action: {event}; \"\n                    f\"legal=\"\n                    f\"{[a.to_mjai() for a in observation.legal_actions()]}; \"\n                    f\"state={failure_path}\"\n                )\n            actions.append(action)\n        return actions\n\n    def close(self):\n        self.process.stdin.close()\n        self.process.wait(timeout=30)\n",
      "sha256": "87e6932c2de5ae024b5e1551788dca9f20254411506da2926ff785cec596a627"
    },
    {
      "path": "training/imitation.py",
      "text": "\"\"\"Q-weighted expert imitation with settlement fitting.\"\"\"\n\nimport tensorflow as tf\n\nfrom model import actor as actor_layers\nfrom model import critic, joint_settlement\nfrom training import auxiliary, restoration, trainer\n\nESS_TARGET = 0.75\n\n\ndef effective_fraction(gaps, beta):\n    log_weights = tf.minimum(gaps / beta, tf.math.log(20.0))\n    weights = tf.exp(log_weights - tf.reduce_max(log_weights, axis=0))\n    return tf.square(tf.reduce_mean(weights, axis=0)) / tf.reduce_mean(\n        tf.square(weights), axis=0\n    )\n\n\ndef calibrate_beta(gaps):\n    \"\"\"Choose the least aggressive crossing of 75% ESS within J bounds.\"\"\"\n    grid = tf.exp(tf.linspace(tf.math.log(0.0001), tf.math.log(1.28), 65))\n    curve = effective_fraction(gaps[:, None], grid)\n    crossings = tf.where(\n        (curve[:-1] - ESS_TARGET) * (curve[1:] - ESS_TARGET) <= 0\n    )[:, 0]\n\n    def crossing():\n        index = crossings[-1]\n        lower, upper = grid[index], grid[index + 1]\n        lower_value = curve[index] - ESS_TARGET\n        for _ in tf.range(20):\n            middle = tf.sqrt(lower * upper)\n            same_side = (\n                effective_fraction(gaps, middle) - ESS_TARGET\n            ) * lower_value > 0\n            lower = tf.where(same_side, middle, lower)\n            upper = tf.where(same_side, upper, middle)\n        return upper\n\n    closest = 64 - tf.argmin(\n        tf.reverse(tf.abs(curve - ESS_TARGET), [0]), output_type=tf.int32\n    )\n    beta = tf.cond(tf.size(crossings) > 0, crossing, lambda: grid[closest])\n    return beta\n\n\ndef imitation_weights(gaps, valid):\n    \"\"\"Global ESS and mean-one weights; padded replicas carry no mass.\"\"\"\n    gaps = tf.debugging.check_numerics(gaps, \"Non-finite Q gap\")\n    gathered = tf.distribute.get_replica_context().all_gather(\n        tf.stack([tf.stop_gradient(gaps), tf.cast(valid, tf.float32)], axis=1),\n        axis=0,\n    )\n    global_gaps = tf.boolean_mask(gathered[:, 0], gathered[:, 1] > 0)\n    beta = calibrate_beta(global_gaps)\n    global_logs = tf.minimum(global_gaps / beta, tf.math.log(20.0))\n    offset = tf.reduce_max(global_logs)\n    weights = tf.exp(\n        tf.where(\n            valid, tf.minimum(gaps / beta, tf.math.log(20.0)) - offset, 0.0\n        )\n    )\n    weights /= tf.reduce_mean(tf.exp(global_logs - offset))\n    return tf.stop_gradient(tf.where(valid, weights, 0.0))\n\n\nclass ImitationTrainer(trainer.CriticTrainer):\n    \"\"\"Fit policy, observed settlements and beliefs with one stage optimizer.\"\"\"\n\n    @tf.function(reduce_retracing=True)\n    def update(self, batch, valid):\n        features = batch[\"features\"]\n        supported = restoration.policy_target_supported(\n            features, batch[\"head\"], batch[\"expert\"]\n        )\n        with tf.GradientTape() as tape:\n            # One live encoding supplies policy, settlement supervision and Q.\n            outputs = self.network.actor(features, training=False)\n            current = actor_layers.distribution(\n                outputs, batch[\"head\"], batch[\"legal\"]\n            )\n            state = self.network.candidate_context(features, outputs)\n            observed = self.network.chosen_inputs(\n                features, outputs, state, batch[\"chosen\"]\n            )\n            statistics = self.network.critic.supervised_statistics(\n                observed,\n                joint_settlement.payment_labels(\n                    points=batch[\"payment_points\"],\n                    public=observed,\n                    ending_kind=batch[\"ending_kind\"],\n                    ending_source=batch[\"ending_source\"],\n                    ending_tenpai=batch[\"ending_tenpai\"],\n                ),\n                valid=valid,\n            )\n            critic_metrics = critic.metrics_from_statistics(statistics)\n            with tape.stop_recording():\n                selected = outputs[\"selected\"]\n                relevant = (\n                    (\n                        selected[:, 1]\n                        == tf.cast(\n                            tf.gather(batch[\"chosen\"], selected[:, 0]),\n                            selected.dtype,\n                        )\n                    )\n                    | (\n                        selected[:, 1]\n                        == tf.cast(\n                            tf.gather(\n                                batch[\"reference_action\"], selected[:, 0]\n                            ),\n                            selected.dtype,\n                        )\n                    )\n                ) & tf.gather(valid, selected[:, 0])\n                # Identical actions have an exactly zero Q gap. Avoid\n                # evaluating their settlement distributions altogether.\n                relevant &= tf.gather(\n                    batch[\"chosen\"] != batch[\"reference_action\"],\n                    selected[:, 0],\n                )\n                values = trainer.action_values(\n                    network=self.network,\n                    features=features,\n                    selected=tf.boolean_mask(selected, relevant),\n                    state=tf.boolean_mask(state, relevant),\n                )\n                gaps = tf.gather(\n                    values, batch[\"chosen\"], batch_dims=1\n                ) - tf.gather(values, batch[\"reference_action\"], batch_dims=1)\n                weights = imitation_weights(gaps, valid)\n                expert_matches = tf.math.top_k(current, k=3).indices == tf.cast(\n                    batch[\"expert\"][:, None], tf.int32\n                )\n            cross_entropy = -tf.gather(current, batch[\"expert\"], batch_dims=1)\n            terms = {\n                \"expert_top1\": (\n                    tf.cast(expert_matches[:, 0], tf.float32),\n                    supported,\n                ),\n                \"expert_top3\": (\n                    tf.cast(tf.reduce_any(expert_matches, -1), tf.float32),\n                    supported,\n                ),\n                \"weighted_ce\": (cross_entropy * weights, supported),\n                \"unweighted_ce\": (cross_entropy, supported),\n                \"policy_target_coverage\": (\n                    tf.cast(supported, tf.float32),\n                    tf.ones_like(valid),\n                ),\n            }\n            metrics, supervised = auxiliary.reduce_terms(\n                features=features,\n                labels=batch[\"labels\"],\n                outputs=outputs,\n                valid=valid,\n                terms=terms,\n            )\n            loss = (\n                metrics[\"weighted_ce\"]\n                + critic.settlement_objective(critic_metrics)\n                + tf.add_n(list(supervised.values()))\n            )\n            scaled = loss / tf.distribute.get_strategy().num_replicas_in_sync\n        return {\n            **metrics,\n            **critic_metrics,\n            **supervised,\n            **trainer.apply_gradients(\n                self.optimizer,\n                tape,\n                scaled,\n                self.network.trainable_variables,\n            ),\n            \"joint_loss\": loss,\n        }\n",
      "sha256": "5df13ace8d27247ecab1c8498c63f703a969fabaaae52a9a266f4f23de715703"
    },
    {
      "path": "training/imitation_rollouts.py",
      "text": "\"\"\"Balanced focused and natural human roots for hand continuations.\"\"\"\n\nimport contextlib\nimport json\nimport pathlib\nimport time\n\nimport numpy\nimport tensorflow as tf\n\nfrom log_dataset import call_states, records, root_states\nfrom model import actions\nfrom model import actor as actor_layers\nfrom model import critic\nfrom training import restoration, self_play\nfrom training.corrections import collection, rollouts\n\n\ndef select_seeds(\n    *, source, batch, predict, evaluate, seed, decisions_per_continuation, stop\n):\n    \"\"\"Select compact balanced starts without simulating any hands.\"\"\"\n    count = int(batch[\"local_count\"])\n    if not count:\n        return []\n    observed = call_states.select(\n        tf.nest.map_structure(lambda value: value.numpy(), batch[\"features\"]),\n        numpy.arange(count),\n    )\n    metadata = {\n        name: value.numpy()[:count] for name, value in batch[\"metadata\"].items()\n    }\n    if any(\n        records.game_partition(game_id.decode()) >= 7\n        for game_id in metadata[\"game_id\"]\n    ):\n        raise ValueError(\"Imitation rollouts cannot use held-out games\")\n    heads = batch[\"head\"].numpy()[:count]\n    legal = batch[\"legal\"].numpy()[:count]\n    eligible = restoration.trainable_decisions(observed, heads, legal).numpy()\n    natural = numpy.flatnonzero(eligible & batch[\"natural\"].numpy()[:count])\n    if not len(natural):\n        return []\n    generator = numpy.random.default_rng(seed)\n    candidates = generator.permutation(numpy.flatnonzero(eligible))\n    selected = []\n    continuations = 0\n    # A random order of all eligible rows induces a uniform random order of\n    # the qualifying subset. Score only enough chunks to fill this budget.\n    for begin in range(0, len(candidates), 32):\n        if continuations * decisions_per_continuation >= count:\n            break\n        rows = candidates[begin : begin + 32]\n        inputs = call_states.select(observed, rows)\n        logits, values = evaluate(inputs)\n        policy = self_play.policy_log_probabilities(\n            logits, heads[rows], legal[rows]\n        )\n        preferred = actor_layers.greedy_choices(policy, heads[rows]).numpy()\n        for local, row in enumerate(rows):\n            if continuations * decisions_per_continuation >= count:\n                break\n            if stop.exists():\n                return []\n            witness = source.witness(\n                game_id=metadata[\"game_id\"][row].decode(),\n                kyoku_id=metadata[\"kyoku_id\"][row].decode(),\n                decision_index=int(metadata[\"decision_index\"][row]),\n                actor=int(metadata[\"actor\"][row]),\n                phase=int(observed[\"decision_phase\"][row]),\n            )\n            choices, categories = collection.targeted_actions(\n                features={\n                    name: value[local]\n                    for name, value in call_states.base(inputs).items()\n                },\n                head=int(heads[row]),\n                legal=legal[row],\n                policy=policy[local],\n                preferred=int(preferred[local]),\n                values=values[local],\n                sakigiri_actions=numpy.asarray(\n                    witness[0] if witness is not None else (), dtype=numpy.int32\n                ),\n            )\n            if not choices:\n                continue\n            selected.extend(\n                [\n                    (\n                        int(row),\n                        {\n                            \"actions\": choices,\n                            \"categories\": categories,\n                            \"kind\": \"targeted\",\n                            \"seed\": seed + int(row),\n                        },\n                    ),\n                    (\n                        int(generator.choice(natural)),\n                        {\n                            \"actions\": [],\n                            \"categories\": [],\n                            \"kind\": \"normal\",\n                            \"seed\": seed + count + len(selected),\n                        },\n                    ),\n                ]\n            )\n            continuations += len(choices) + 2\n    if not selected:\n        return []\n    normal = numpy.array([row for row, _ in selected[1::2]])\n    policy = self_play.policy_log_probabilities(\n        predict(call_states.select(observed, normal)),\n        heads[normal],\n        legal[normal],\n    )\n    for local, (row, selection) in enumerate(selected[1::2]):\n        codes = numpy.flatnonzero(legal[row])\n        probability = numpy.exp(policy[local, codes].astype(numpy.float64))\n        selection[\"actions\"] = generator.choice(\n            codes, size=2, p=probability / probability.sum()\n        ).tolist()\n    return [\n        {\n            \"game_id\": metadata[\"game_id\"][position].decode(),\n            \"kyoku_id\": metadata[\"kyoku_id\"][position].decode(),\n            \"decision_index\": int(metadata[\"decision_index\"][position]),\n            \"actor\": int(metadata[\"actor\"][position]),\n            \"phase\": int(observed[\"decision_phase\"][position]),\n            \"head\": int(heads[position]),\n            **selection,\n            \"affinity\": affinity,\n        }\n        for (position, selection), affinity in zip(\n            selected,\n            tf.gather(\n                batch[\"labels\"][\"candidate_yaku_affinity\"],\n                [position for position, _ in selected],\n            ).numpy(),\n        )\n    ]\n\n\ndef collect_window(*, data, **kwargs):\n    \"\"\"Own SQLite readers in the collection thread, never the learner thread.\"\"\"\n    started = time.monotonic()\n    with contextlib.closing(\n        root_states.Store(pathlib.Path(data) / \"root-states\")\n    ) as source:\n        rows, statistics = collect(source=source, **kwargs)\n    statistics[\"collection_seconds\"] = time.monotonic() - started\n    (kwargs[\"directory\"] / \"statistics.json\").write_text(\n        json.dumps(statistics) + \"\\n\"\n    )\n    return rows, statistics\n\n\ndef collect(\n    *,\n    source,\n    seeds,\n    decision_target,\n    predict,\n    packing,\n    directory,\n    stop,\n    reference_policy,\n    workers,\n):\n    \"\"\"Run the accumulated starts together, with one continuation/action.\"\"\"\n    statistics = {\n        \"roots\": 0,\n        \"continuations\": 0,\n        \"simulated_decisions\": 0,\n        \"decision_target\": decision_target,\n        \"targeted_roots\": 0,\n        \"normal_roots\": 0,\n    }\n    receipt = []\n    reference_logs = []\n    actions_in_order = []\n\n    jobs = []\n    for selection in seeds:\n        if stop.exists():\n            break\n        root = source.root(\n            **{\n                name: selection[name]\n                for name in (\n                    \"game_id\",\n                    \"kyoku_id\",\n                    \"decision_index\",\n                    \"actor\",\n                    \"phase\",\n                )\n            }\n        )\n        payload = root.dumps()\n        reference_logs.append(json.loads(payload)[\"game\"][\"logs\"])\n        wall_seeds = [\n            selection[\"seed\"] + (branch if selection[\"kind\"] == \"normal\" else 0)\n            for branch in range(len(selection[\"actions\"]))\n        ]\n        receipt.append(\n            {\n                name: value\n                for name, value in selection.items()\n                if name not in (\"affinity\", \"seed\")\n            }\n            | {\"wall_seeds\": [[start] for start in wall_seeds]}\n        )\n        statistics[selection[\"kind\"] + \"_roots\"] += 1\n        for category in selection[\"categories\"]:\n            statistics[category] = statistics.get(category, 0) + 1\n        actions_in_order.extend(selection[\"actions\"])\n        jobs.append(\n            {\n                \"root\": payload,\n                \"actions\": selection[\"actions\"],\n                \"wall_seeds\": wall_seeds,\n                \"affinity\": selection[\"affinity\"],\n            }\n        )\n\n    completed = workers.collect(predict, jobs)\n    statistics[\"simulated_decisions\"] = sum(\n        counts[\"simulated_decisions\"] for _, counts in completed\n    )\n    retained = []\n    for action, (rollout, _) in zip(actions_in_order, completed):\n        assert len(rollout[\"chosen\"]) == 1\n        assert (rollout[\"chosen\"] == action).all()\n        retained.append(\n            {\n                \"features\": call_states.pack_numpy(\n                    rollout[\"features\"], packing\n                ),\n                \"labels\": rollout[\"labels\"],\n                \"head\": rollout[\"head\"],\n                \"legal\": rollout[\"legal\"],\n                \"chosen\": critic.chosen_actions(\n                    rollout[\"features\"],\n                    {\n                        name: numpy.where(\n                            rollout[\"head\"] == head, rollout[\"chosen\"], -1\n                        )\n                        for head, name in enumerate(actions.TRAIN_POLICY_HEADS)\n                    },\n                ).numpy(),\n                \"payment_points\": rollout[\"payment_points\"],\n                \"ending_kind\": rollout[\"ending_kind\"],\n                \"ending_source\": rollout[\"ending_source\"],\n                \"ending_tenpai\": rollout[\"ending_tenpai\"],\n            }\n        )\n    statistics[\"roots\"] = len(receipt)\n    statistics[\"continuations\"] = sum(len(row[\"actions\"]) for row in receipt)\n    directory.mkdir(parents=True, exist_ok=False)\n    (directory / \"roots.json\").write_text(json.dumps(receipt) + \"\\n\")\n    (directory / \"statistics.json\").write_text(json.dumps(statistics) + \"\\n\")\n    if not retained:\n        return None, statistics\n    rows = rollouts.concatenate(retained)\n    offsets = numpy.cumsum([0] + [len(row[\"actions\"]) for row in receipt])\n    probabilities = reference_policy.distribution_many(\n        [\n            (\n                events,\n                [(len(events) - 1, selection[\"actor\"], selection[\"phase\"])],\n                rows[\"head\"][offset : offset + 1],\n                rows[\"legal\"][offset : offset + 1],\n            )\n            for events, selection, offset in zip(\n                reference_logs, receipt, offsets[:-1]\n            )\n        ]\n    )\n    rows[\"reference_log_probability\"] = numpy.repeat(\n        probabilities, numpy.diff(offsets), axis=0\n    )\n    numpy.savez_compressed(\n        file=directory / \"outcomes.npz\",\n        **{\n            \"features/\" + name: value\n            for name, value in call_states.flatten(rows[\"features\"]).items()\n        },\n        **{\"label/\" + name: value for name, value in rows[\"labels\"].items()},\n        **{\n            name: value\n            for name, value in rows.items()\n            if name not in (\"features\", \"labels\")\n        },\n    )\n    return rows, statistics\n\n\ndef batches(rows, human, group, batch_size):\n    \"\"\"Equal update counts across ranks, with zero-mass empty-rank padding.\"\"\"\n    count = 0 if rows is None else len(rows[\"chosen\"])\n    local_size = (batch_size + group.replicas - 1) // group.replicas\n    maximum = int(group.maximum(tf.constant(count, tf.int32)))\n    if rows is None:\n        rows = {\n            \"reference_log_probability\": numpy.zeros((1, 150), numpy.float32),\n            \"features\": call_states.pack_numpy(\n                call_states.select(\n                    tf.nest.map_structure(\n                        lambda value: value.numpy(), human[\"features\"]\n                    ),\n                    [0],\n                ),\n                group.packing,\n            ),\n            **{\n                name: tf.nest.map_structure(\n                    lambda value: value.numpy()[:1], human[name]\n                )\n                for name in (\n                    \"head\",\n                    \"legal\",\n                    \"chosen\",\n                    \"payment_points\",\n                    \"ending_kind\",\n                    \"ending_source\",\n                    \"ending_tenpai\",\n                    \"labels\",\n                )\n            },\n        }\n    for begin in range(0, maximum, local_size):\n        selected = rollouts.select(\n            rows,\n            numpy.minimum(\n                numpy.arange(begin, begin + local_size), max(count, 1) - 1\n            ),\n        )\n        yield {\n            **rollouts.unpack(selected, group.packing, None),\n            \"local_count\": tf.constant(max(0, min(local_size, count - begin))),\n            \"global_count\": tf.constant(0),\n        }\n",
      "sha256": "578eb2731021b5f02e195c61f8b6ad5e86d062a69b293c72d7f8629fe5e07eb6"
    },
    {
      "path": "training/match_records.py",
      "text": "\"\"\"Current-hand critic records from completed evaluation match logs.\"\"\"\n\nimport argparse\nimport concurrent.futures\nimport functools\nimport gzip\nimport json\nimport multiprocessing\nimport pathlib\n\nimport numpy\nimport tensorflow as tf\n\nfrom log_dataset import (\n    call_states,\n    features,\n    records,\n    replay,\n    scoring,\n    training_data,\n    training_targets,\n)\nfrom model import critic, outcomes\nfrom training import auxiliary, fixed_reference, restoration\n\n\ndef game_records(path, reference_policy):\n    \"\"\"Label all recoverable choices in a completed four-seat match.\"\"\"\n    path = pathlib.Path(path)\n    with gzip.open(path, \"rt\") as stream:\n        events = [json.loads(line) for line in stream]\n    outcomes.normalize_draw_payments(events)\n    outcomes.normalize_recorded_endings(events)\n    starts = [\n        index\n        for index, event in enumerate(events)\n        if event[\"type\"] == \"start_kyoku\"\n    ]\n    raw = []\n    requests = []\n    for start, end in zip(starts, starts[1:] + [len(events)]):\n        state = replay.Replay(path.stem, events[start:end])\n        target = {\n            \"payment\": outcomes.terminal_payments(state.events),\n            \"bonus\": numpy.full((4, 4, 4), -1, numpy.int16),\n            \"score\": numpy.full(\n                (4, 4, 4, len(scoring.BONUS_HAN)), -1, numpy.int16\n            ),\n        }\n        for observation in state.observations():\n            raw.append(training_data.serialize(observation, target))\n            requests.append(\n                (\n                    start + state.event_index,\n                    observation.actor,\n                    observation.features[\"decision_phase\"],\n                )\n            )\n    packed, labels = records.parse_batch(raw)\n    heads, _, legal = restoration.policy_choices(packed, labels)\n    probabilities = reference_policy.distribution(\n        events, requests, heads.numpy(), legal.numpy()\n    )\n    for value, probability in zip(raw, probabilities, strict=True):\n        example = tf.train.Example.FromString(value)\n        example.features.feature[\n            \"reference_log_probability\"\n        ].bytes_list.value.append(probability.astype(numpy.float32).tobytes())\n        yield example.SerializeToString()\n\n\ndef label_rollouts(logs, indices, packed, *, root_affinity=None):\n    \"\"\"Join native decisions to their branch's hidden hands and future tenpai.\n\n    root_affinity may be supplied when all rows retain the same root features.\n    \"\"\"\n    labels = {\n        name: numpy.empty(\n            (len(indices), *records.LABELS[name][\"shape\"]),\n            records.LABELS[name][\"dtype\"],\n        )\n        for name in auxiliary.LABELS\n    }\n    base = call_states.base(packed)\n    phases = {code: phase for phase, code in features.PHASES.items()}\n    for game, events in enumerate(logs):\n        starts = [\n            index\n            for index, event in enumerate(events)\n            if event[\"type\"] == \"start_kyoku\"\n        ] + [len(events)]\n        game_rows = numpy.flatnonzero(indices[:, 0] == game)\n        for hand in numpy.unique(indices[game_rows, 1]):\n            hand_events = events[starts[hand] : starts[hand + 1]]\n            state = replay.Replay(str(game), hand_events)\n            hand_rows = game_rows[indices[game_rows, 1] == hand]\n            state.targets = training_targets.round_targets(\n                replay.Replay.from_start(str(game), hand_events[0]),\n                hand_events,\n                indices=indices[hand_rows, 3] - starts[hand] - 1,\n            )\n            for row in hand_rows:\n                # Native event is the number of events consumed before next().\n                # A declined win or kan may yield a new phase at the same event.\n                index = indices[row, 3] - starts[hand] - 1\n                while state.event_index < index:\n                    state.apply(hand_events[state.event_index + 1])\n                assert state.event_index == index\n                observation = replay.Observation(\n                    actor=int(indices[row, 2]),\n                    features={\n                        name: values[row] for name, values in base.items()\n                    },\n                )\n                training_targets.attach(\n                    observation, state, index, affinity=root_affinity\n                )\n                observation.ron_legal = training_targets.ron_labels(\n                    state,\n                    observation.actor,\n                    phases[base[\"decision_phase\"][row]],\n                )[\"ron_legal\"]\n                for name in labels:\n                    labels[name][row] = getattr(observation, name)\n    return labels\n\n\n@functools.cache\ndef load_reference(directory):\n    tf.config.set_visible_devices([], \"GPU\")\n    return fixed_reference.Policy(directory)\n\n\ndef write_shard(task):\n    path, games, reference = task\n    reference_policy = load_reference(reference)\n    positions = 0\n    with tf.io.TFRecordWriter(str(path) + \".partial\", options=\"GZIP\") as writer:\n        for game in games:\n            for raw in game_records(game, reference_policy):\n                writer.write(raw)\n                positions += 1\n    pathlib.Path(str(path) + \".partial\").replace(path)\n    return {\n        \"path\": path.name,\n        \"games\": len(games),\n        \"positions\": positions,\n        \"reference_policy\": reference_policy.provenance,\n    }\n\n\ndef decode_records(raw):\n    \"\"\"Chosen critic action, observed payments and supervised belief labels.\"\"\"\n    parsed = tf.io.parse_example(\n        raw,\n        {\n            name: tf.io.FixedLenFeature([], tf.string)\n            for name in (*records.FIELDS, \"reference_log_probability\")\n        },\n    )\n    features, labels = records.decode_batch(parsed)\n    head, _, legal = restoration.policy_choices(features, labels)\n    return {\n        \"head\": head,\n        \"legal\": legal,\n        \"features\": features,\n        \"labels\": {name: labels[name] for name in auxiliary.LABELS},\n        \"reference_log_probability\": tf.reshape(\n            tf.io.decode_raw(\n                parsed[\"reference_log_probability\"],\n                tf.float32,\n            ),\n            [-1, 150],\n        ),\n        \"chosen\": critic.chosen_actions(features, labels),\n        \"ending_kind\": labels[\"round_end_kind\"],\n        \"ending_source\": labels[\"round_end_source\"],\n        \"ending_tenpai\": labels[\"round_end_tenpai\"],\n        \"payment_points\": tf.gather(\n            tf.reshape(labels[\"terminal_payment\"], [-1, 64]),\n            numpy.ravel_multi_index(numpy.asarray(scoring.CELLS).T, (4, 4, 4)),\n            axis=1,\n        ),\n    }\n\n\ndef batches(output, batch_size, seed, decode=decode_records):\n    \"\"\"One finite shuffled pass, including every row in the final batch.\"\"\"\n    output = pathlib.Path(output)\n    manifest = json.loads((output / \"dataset.json\").read_text())\n    if manifest[\"auxiliary_labels\"] != list(auxiliary.LABELS):\n        raise ValueError(\"Rebuild match records with supervised belief labels\")\n    return (\n        tf.data.Dataset.from_tensor_slices(\n            [str(output / row[\"path\"]) for row in manifest[\"shards\"]]\n        )\n        .shuffle(len(manifest[\"shards\"]), seed=seed)\n        .interleave(\n            lambda path: tf.data.TFRecordDataset(path, compression_type=\"GZIP\"),\n            cycle_length=8,\n            block_length=64,\n            num_parallel_calls=4,\n            deterministic=True,\n        )\n        .shuffle(8192, seed=seed)\n        .batch(batch_size)\n        .map(decode, num_parallel_calls=2)\n        .prefetch(2)\n    )\n\n\ndef build(matches, output, workers, reference):\n    \"\"\"Convert the completed evaluator manifest in isolated CPU workers.\"\"\"\n    matches = pathlib.Path(matches)\n    output = pathlib.Path(output)\n    manifest = json.loads((matches / \"evaluation.json\").read_text())\n    games = [\n        json.loads(line)\n        for line in (matches / \"games.jsonl\").read_text().splitlines()\n    ]\n    assert len(games) == manifest[\"games\"]\n    paths = sorted(matches / game[\"replay\"] for game in games)\n    assert len(set(paths)) == len(paths)\n    output.mkdir(parents=True)\n    with concurrent.futures.ProcessPoolExecutor(\n        max_workers=workers,\n        mp_context=multiprocessing.get_context(\"spawn\"),\n    ) as pool:\n        shards = list(\n            pool.map(\n                write_shard,\n                [\n                    (\n                        output / f\"train-{start // 100:04d}.tfrecord.gz\",\n                        paths[start : start + 100],\n                        reference,\n                    )\n                    for start in range(0, len(paths), 100)\n                ],\n            )\n        )\n    reference_policy = shards[0].pop(\"reference_policy\")\n    assert all(\n        row.pop(\"reference_policy\") == reference_policy for row in shards[1:]\n    )\n    result = {\n        \"games\": len(games),\n        \"positions\": sum(row[\"positions\"] for row in shards),\n        \"auxiliary_labels\": list(auxiliary.LABELS),\n        \"reference_policy\": reference_policy,\n        \"reference_log_probability\": {\"dtype\": \"float32\", \"shape\": [150]},\n        \"shards\": shards,\n    }\n    (output / \"dataset.json\").write_text(json.dumps(result, indent=2))\n    return result\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(description=__doc__)\n    parser.add_argument(\"--matches\", required=True)\n    parser.add_argument(\"--output\", required=True)\n    parser.add_argument(\"--workers\", type=int, default=16)\n    parser.add_argument(\"--reference\", required=True)\n    arguments = parser.parse_args()\n    print(\n        json.dumps(\n            build(\n                arguments.matches,\n                arguments.output,\n                arguments.workers,\n                arguments.reference,\n            )\n        )\n    )\n",
      "sha256": "b960fb22d518a0265ef9518e4bb9241f7b0c6058dc4e43f4692e49099f944d99"
    },
    {
      "path": "training/monitor.py",
      "text": "\"\"\"Atomic progress metadata for training and monitoring.\"\"\"\n\nimport json\n\n\ndef write_json(path, value):\n    \"\"\"Replace run metadata atomically so readers never see partial JSON.\"\"\"\n    temporary = path.with_suffix(\".partial\")\n    temporary.write_text(json.dumps(value, indent=2) + \"\\n\")\n    temporary.replace(path)\n",
      "sha256": "526abb09dc489e0cab08fc9348cb5fed125eb99ee837f76a868b87e0dafd6880"
    },
    {
      "path": "training/mortal_policy.py",
      "text": "\"\"\"Frozen Mortal opponent using RiichiEnv's private-seat MJAI stream.\"\"\"\n\nimport concurrent.futures\nimport importlib.util\nimport io\nimport json\nimport os\nimport pathlib\nimport queue\nimport subprocess\nimport sys\nimport zipfile\n\nfrom training import frozen_policy\n\n\nclass MortalPolicy(frozen_policy.FrozenPolicy):\n    def __init__(self, root, capacity, device=\"-1\"):\n        root = pathlib.Path(root).resolve()\n        self.model_path = root / \"checkpoint\"\n        self.reset_pending = True\n        self.process = subprocess.Popen(\n            args=[\n                sys.executable,\n                \"-m\",\n                \"training.mortal_policy\",\n                str(root),\n                str(capacity),\n            ],\n            stdin=subprocess.PIPE,\n            stdout=subprocess.PIPE,\n            text=True,\n            bufsize=1,\n            cwd=root,\n            env={\n                **os.environ,\n                \"CUDA_VISIBLE_DEVICES\": device,\n                \"PYTHONPATH\": str(pathlib.Path(root) / \"adapter\"),\n            },\n        )\n\n    def send_requests(self, requests):\n        self.process.stdin.write(\n            json.dumps(\n                {\n                    \"reset\": self.reset_pending,\n                    \"items\": [\n                        {\n                            \"stream\": stream,\n                            \"seat\": observation.player_id,\n                            \"events\": observation.new_events(),\n                        }\n                        for stream, _, observation in requests\n                    ],\n                }\n            )\n            + \"\\n\"\n        )\n        self.process.stdin.flush()\n        self.reset_pending = False\n\n\nclass BatchedReactions:\n    \"\"\"Batch neural requests while each upstream Bot keeps its event loop.\"\"\"\n\n    def __init__(self, opponent, capacity):\n        self.infer = opponent.react_batch\n        opponent.react_batch = self.inference_request\n        self.queue = queue.SimpleQueue()\n        self.pool = concurrent.futures.ThreadPoolExecutor(max_workers=capacity)\n\n    def inference_request(self, obs, masks, invisible):\n        future = concurrent.futures.Future()\n        self.queue.put((obs, masks, future))\n        return future.result()\n\n    def react(self, bot, events):\n        try:\n            reaction = None\n            # https://riichi.dev/docs/mortal: every new event, final response.\n            for event in events:\n                response = bot.react(event)\n                # A delayed dora announcement can follow a kakan in the\n                # same observation. It updates state, not the response.\n                if json.loads(event)[\"type\"] != \"dora\":\n                    reaction = response\n            return None if reaction is None else json.loads(reaction)\n        finally:\n            self.queue.put(None)\n\n    def select_many(self, bots, items):\n        futures = [\n            self.pool.submit(self.react, bots[item[\"stream\"]], item[\"events\"])\n            for item in items\n        ]\n        return self.collect(futures)\n\n    def collect(self, futures):\n        \"\"\"Resolve inference from tasks that signal completion on the queue.\"\"\"\n        active = len(futures)\n        while active:\n            pending = []\n            # Each active Bot either needs inference or has finished.\n            while len(pending) < active:\n                request = self.queue.get()\n                if request is None:\n                    active -= 1\n                else:\n                    pending.append(request)\n            if pending:\n                try:\n                    output = self.infer(\n                        [obs for request in pending for obs in request[0]],\n                        [mask for request in pending for mask in request[1]],\n                        None,\n                    )\n                    offset = 0\n                    for obs, _, future in pending:\n                        future.set_result(\n                            tuple(\n                                values[offset : offset + len(obs)]\n                                for values in output\n                            )\n                        )\n                        offset += len(obs)\n                finally:\n                    # Release waiting callers if inference fails.\n                    for _, _, future in pending:\n                        future.cancel()\n        return [future.result() for future in futures]\n\n\ndef load_engine(root, device):\n    import torch\n\n    sys.path.insert(0, str(root / \"source\"))\n    modules = {}\n    for name in (\"engine\", \"model\"):\n        spec = importlib.util.spec_from_file_location(\n            \"mortal_\" + name, root / \"source\" / (name + \".py\")\n        )\n        modules[name] = importlib.util.module_from_spec(spec)\n        spec.loader.exec_module(modules[name])\n\n    torch.set_num_threads(2)\n    checkpoint = root / \"checkpoint\"\n    if zipfile.is_zipfile(checkpoint):\n        with zipfile.ZipFile(checkpoint) as archive:\n            # A torch checkpoint is itself a ZIP; only unwrap the model bundle.\n            if len(archive.namelist()) == 1:\n                checkpoint = io.BytesIO(archive.read(archive.namelist()[0]))\n    state = torch.load(checkpoint, map_location=\"cpu\", weights_only=True)\n    brain = modules[\"model\"].Brain(\n        version=state[\"config\"][\"control\"][\"version\"],\n        **state[\"config\"][\"resnet\"],\n    )\n    dqn = modules[\"model\"].DQN(version=state[\"config\"][\"control\"][\"version\"])\n    # Preserve the upstream checkpoint key and engine API.\n    brain.load_state_dict(state[\"mortal\"], strict=True)\n    dqn.load_state_dict(state[\"current_dqn\"], strict=True)\n    return modules[\"engine\"].MortalEngine(\n        brain=brain,\n        dqn=dqn,\n        is_oracle=False,\n        version=state[\"config\"][\"control\"][\"version\"],\n        device=torch.device(device),\n        enable_amp=False,\n        enable_rule_based_agari_guard=True,\n        name=\"mortal\",\n    )\n\n\ndef run(root, capacity):\n    device = \"cpu\" if os.environ[\"CUDA_VISIBLE_DEVICES\"] == \"-1\" else \"cuda:0\"\n    opponent = load_engine(root, device)\n    import libriichi.mjai\n\n    bots = {}\n    batcher = BatchedReactions(opponent, capacity)\n    for line in sys.stdin:\n        request = json.loads(line)\n        if request[\"reset\"]:\n            bots.clear()\n        for item in request[\"items\"]:\n            if item[\"stream\"] not in bots:\n                bots[item[\"stream\"]] = libriichi.mjai.Bot(\n                    opponent, item[\"seat\"]\n                )\n        print(\n            json.dumps(batcher.select_many(bots, request[\"items\"])), flush=True\n        )\n    batcher.pool.shutdown()\n\n\nif __name__ == \"__main__\":\n    run(pathlib.Path(sys.argv[1]), int(sys.argv[2]))\n",
      "sha256": "01f28abee066f4463e3a4b9ed546f1724968eb0fbe89e26eb76158d3b5898878"
    },
    {
      "path": "training/reporting.py",
      "text": "\"\"\"Append framework-independent metric observations for run reporting.\"\"\"\n\nimport json\nimport pathlib\nimport time\n\n\ndef write_metrics(root, *, stage, step, metrics, **context):\n    \"\"\"Write a report on the loop's shared cumulative position clock.\n\n    Stage changes do not reset step. Run constants belong in plan.json.\n    \"\"\"\n    row = {\n        \"time\": time.time(),\n        \"step\": int(step),\n        \"stage\": stage,\n        **context,\n        \"metrics\": {name: float(value) for name, value in metrics.items()},\n    }\n    with (pathlib.Path(root) / \"metrics.jsonl\").open(\"a+b\") as stream:\n        if stream.tell():\n            stream.seek(-1, 2)\n            if stream.read(1) != b\"\\n\":\n                # An interrupted evaluator can resume the same output. Remove\n                # only its incomplete trailing record before appending again.\n                end = stream.tell()\n                while end:\n                    start = max(0, end - 65536)\n                    stream.seek(start)\n                    newline_ix = stream.read(end - start).rfind(b\"\\n\")\n                    if newline_ix >= 0:\n                        stream.truncate(start + newline_ix + 1)\n                        break\n                    end = start\n                else:\n                    stream.truncate(0)\n        stream.write(json.dumps(row, allow_nan=False).encode() + b\"\\n\")\n",
      "sha256": "708f547a856bdc63a56f89f113e92f834e5cfd0cb0d494a85a14dde292b36901"
    },
    {
      "path": "training/restoration.py",
      "text": "\"\"\"Expert records and policy labels for structural restoration.\"\"\"\n\nimport tensorflow as tf\n\nfrom log_dataset import call_states\nfrom model import actions, actor\n\n\ndef policy_choices(features, labels):\n    \"\"\"Recover the active policy head, observed choice and legal mask.\"\"\"\n    choices = tf.stack(\n        [\n            tf.cast(labels[name], tf.int32)\n            for name in actions.TRAIN_POLICY_HEADS\n        ],\n        axis=1,\n    )\n    tf.debugging.assert_equal(\n        tf.reduce_sum(tf.cast(choices >= 0, tf.int32), axis=1), 1\n    )\n    head = tf.argmax(choices >= 0, axis=1, output_type=tf.int32)\n    expert = tf.gather(choices, head, batch_dims=1)\n    masks = actions.legal_choices(features)\n    legal = tf.gather(\n        tf.stack(\n            [\n                tf.pad(masks[name], [[0, 0], [0, 150 - masks[name].shape[-1]]])\n                for name in actions.TRAIN_POLICY_HEADS\n            ],\n            axis=1,\n        ),\n        head,\n        batch_dims=1,\n    )\n    tf.debugging.assert_equal(tf.gather(legal, expert, batch_dims=1), True)\n    return head, expert, legal\n\n\ndef trainable_decisions(features, head, legal):\n    \"\"\"Identify choices still open to the actor at this decision.\"\"\"\n    # Declaring commits the cut. Staying dama leaves the ordinary discard\n    # eligible even when the player could have declared instead.\n    riichi_cut = (\n        head == actions.TRAIN_POLICY_HEADS.index(\"discard_policy_logits\")\n    ) & (features[\"riichi_state\"][:, 0] > 0)\n    return (tf.math.count_nonzero(legal, axis=1) > 1) & ~riichi_cut\n\n\ndef policy_target_supported(features, head, target):\n    \"\"\"Whether the exact teacher action survives the actor's forced cut rule.\"\"\"\n\n    def rejected_cut(inputs, tile):\n        safe = actor.final_wall_safe_cuts(\n            inputs, tf.cast(inputs[\"discard_action_legal\"], tf.bool)\n        )\n        return tf.reduce_any(safe, axis=1) & ~tf.gather(\n            safe, tile, batch_dims=1\n        )\n\n    # Only ordinary and dama branches consume the current board's cut.\n    discard = (head == 0) | ((head == 1) & (target < 37))\n    rejected = discard & rejected_cut(features, target % 37)\n    # The joint chi/pon label uses the chosen child's ordinary discard.\n    owner = features[\"post_call_owner\"]\n    child_target = tf.gather(target, owner)\n    chosen_child = (\n        (tf.gather(head, owner) == 2)\n        & (child_target > 0)\n        & (child_target < 149)\n        & (features[\"post_call_option\"] == (child_target - 1) // 37)\n    )\n    child_rejected = chosen_child & rejected_cut(\n        call_states.post(features), (child_target - 1) % 37\n    )\n    return ~(\n        rejected\n        | (\n            tf.math.unsorted_segment_sum(\n                tf.cast(child_rejected, tf.int32), owner, tf.size(head)\n            )\n            > 0\n        )\n    )\n",
      "sha256": "da813bce62fa735fec40f58bd7cd9631e38380c94cbf131c671047d308a0b433"
    },
    {
      "path": "training/self_play.py",
      "text": "\"\"\"Fixed-policy south-game collection for on-policy training.\"\"\"\n\nimport itertools\nimport json\n\nimport numpy\n\nfrom log_dataset import _native_collection, call_states\nfrom model import actions, outcomes\n\n\ndef initial_features(seed):\n    \"\"\"Valid model-build inputs from fresh simulator states, without records.\"\"\"\n    collector = _native_collection.NativeCollector(8, seed)\n    request = collector.next()\n    return call_states.from_request(request)\n\n\ndef predictor(actor):\n    \"\"\"Pack on the CPU and transfer a few lossless buffers per inference.\"\"\"\n    import tensorflow as tf\n\n    from log_dataset import training_data\n\n    strategy = tf.distribute.get_strategy()\n    packing = training_data.PackedBatch(\n        {\n            name: tf.TensorSpec([None, *spec[\"shape\"]], spec[\"dtype\"])\n            for name, spec in _native_collection.INPUTS.items()\n        }\n    )\n\n    def infer(inputs):\n        outputs = actor(call_states.unpack(inputs, packing), training=False)\n        return tf.concat(\n            [outputs[name] for name in actions.TRAIN_POLICY_HEADS],\n            axis=1,\n        )\n\n    @tf.function(\n        input_signature=[\n            {\n                \"base\": {\n                    dtype: tf.TensorSpec(\n                        [None, None],\n                        (\n                            \"float32\"\n                            if dtype in (\"bool\", \"int8\", \"int16\", \"int32\")\n                            else dtype\n                        ),\n                    )\n                    for dtype in packing.groups\n                },\n                \"post\": {\n                    dtype: tf.TensorSpec(\n                        [None, None],\n                        (\n                            \"float32\"\n                            if dtype in (\"bool\", \"int8\", \"int16\", \"int32\")\n                            else dtype\n                        ),\n                    )\n                    for dtype in packing.groups\n                },\n                \"owner\": tf.TensorSpec([None], \"int32\"),\n                \"option\": tf.TensorSpec([None], \"int32\"),\n            },\n            tf.TensorSpec([], tf.int32),\n        ]\n    )\n    def predict(inputs, count):\n        if strategy.num_replicas_in_sync == 1:\n            outputs = strategy.run(infer, args=(inputs,))\n        else:\n            size = tf.shape(next(iter(inputs[\"base\"].values())))[0] // (\n                strategy.num_replicas_in_sync\n            )\n            with tf.device(\"/CPU:0\"):\n                distributed = (\n                    strategy.experimental_distribute_values_from_function(\n                        lambda ctx: call_states.tensor_packed_select(\n                            inputs,\n                            tf.range(\n                                ctx.replica_id_in_sync_group * size,\n                                (ctx.replica_id_in_sync_group + 1) * size,\n                            ),\n                        )\n                    )\n                )\n            outputs = strategy.gather(\n                strategy.run(infer, args=(distributed,)), axis=0\n            )\n        return outputs[:count]\n\n    boundaries = numpy.cumsum(\n        [actions.ACTOR_OUTPUTS[name][0] for name in actions.TRAIN_POLICY_HEADS]\n    )[:-1]\n\n    def packed_predict(inputs):\n        count = len(inputs[\"decision_phase\"])\n        size = (count + strategy.num_replicas_in_sync - 1) // (\n            strategy.num_replicas_in_sync\n        )\n        size = (1 << (size - 1).bit_length()) * strategy.num_replicas_in_sync\n        indices = numpy.minimum(numpy.arange(size), count - 1)\n        with tf.device(\"/CPU:0\"):\n            packed = tf.nest.map_structure(\n                tf.convert_to_tensor,\n                call_states.pack_numpy(\n                    call_states.select(inputs, indices), packing\n                ),\n            )\n            count = tf.constant(count, tf.int32)\n        # Transfer one contiguous buffer; simulation consumes NumPy logits.\n        return dict(\n            zip(\n                actions.TRAIN_POLICY_HEADS,\n                numpy.split(predict(packed, count).numpy(), boundaries, axis=1),\n            )\n        )\n\n    return packed_predict\n\n\ndef collection_counts():\n    return dict.fromkeys(\n        (\n            \"games\",\n            \"hands\",\n            \"wins\",\n            \"tsumo_wins\",\n            \"win_points\",\n            \"dealin_hands\",\n            \"dealin_points\",\n            \"riichi_hands\",\n            \"riichi_wins\",\n            \"riichi_dealins\",\n            \"riichi_turn_sum\",\n            \"open_hands\",\n            \"draws\",\n            \"exhaustive_draws\",\n            \"exhaustive_tenpai_seats\",\n            \"simulated_decisions\",\n        ),\n        0,\n    )\n\n\ndef improving_call_choices(features):\n    \"\"\"Legal call/discard choices that strictly reduce actual shanten.\"\"\"\n    # Family-category inputs clip high shanten; efficiency retains its value.\n    distance = features[\"self_efficiency\"][..., 0] * 8\n    calls = features[\"call_discard_legal\"].astype(bool) & (\n        features[\"call_discard_shanten\"] < distance[..., None, None] + 1\n    )\n    # Kan efficiency stores actual shanten / 8, before the replacement draw.\n    kan = features[\"kan_legal_mask\"][..., 1:].astype(bool) & (\n        features[\"kan_efficiency\"][..., 0] * 8 < distance[..., None]\n    )\n    decline = numpy.zeros((*distance.shape, 1), bool)\n    response = numpy.concatenate(\n        (\n            decline,\n            calls.reshape(*distance.shape, 148),\n            (kan.any(axis=-1) & (features[\"response_legal_mask\"][..., 3] > 0))[\n                ..., None\n            ],\n        ),\n        axis=-1,\n    )\n    return response, numpy.concatenate((decline, kan), axis=-1)\n\n\ndef policy_log_probabilities(outputs, heads, legal):\n    \"\"\"Normalize active policy heads over their exact legal action masks.\"\"\"\n    scores = numpy.full((len(heads), 150), -1e9, numpy.float32)\n    for head, name in enumerate(actions.TRAIN_POLICY_HEADS):\n        rows = heads == head\n        scores[rows, : actions.ACTOR_OUTPUTS[name][0]] = numpy.asarray(\n            outputs[name]\n        )[rows]\n    scores[~legal] = -1e9\n    scores -= scores.max(axis=1, keepdims=True)\n    log_probability = scores - numpy.log(\n        numpy.exp(scores).sum(axis=1, keepdims=True)\n    )\n    log_probability[~legal] = -1e9\n    return log_probability\n\n\ndef request_batch(request):\n    \"\"\"Decode one native request for simulation or recorded-match discovery.\"\"\"\n    return {\n        \"features\": call_states.from_request(request),\n        \"head\": numpy.asarray(request[\"head\"]),\n        \"legal\": numpy.frombuffer(request[\"legal\"], numpy.bool_).reshape(\n            len(request[\"head\"]), 150\n        ),\n        \"indices\": numpy.asarray(\n            [request[name] for name in (\"game\", \"hand\", \"seat\", \"event\")]\n        ).T,\n    }\n\n\ndef collect(\n    predict,\n    games,\n    seed,\n    *,\n    collector=None,\n    with_labels=False,\n    reference_policy=None,\n):\n    return collect_streams(\n        predict,\n        [\n            collection_steps(\n                games,\n                seed,\n                collector=collector,\n                with_labels=with_labels,\n                reference_policy=reference_policy,\n            )\n        ],\n    )[0]\n\n\ndef collect_streams(\n    predict, streams, max_active=None, *, concatenate=call_states.concatenate\n):\n    \"\"\"Batch independent trajectories without merging their RNGs or targets.\"\"\"\n    if max_active is None:\n        streams = list(streams)\n        max_active = len(streams)\n    streams = iter(streams)\n    results = []\n    active = {}\n    while True:\n        for stream in itertools.islice(streams, max_active - len(active)):\n            active[len(results)] = (stream, next(stream))\n            results.append(None)\n        if not active:\n            break\n        outputs = predict(\n            next(iter(active.values()))[1]\n            if len(active) == 1\n            else concatenate([item[1] for item in active.values()])\n        )\n        offset = 0\n        for index, (stream, features) in list(active.items()):\n            count = len(features[\"decision_phase\"])\n            try:\n                active[index] = (\n                    stream,\n                    stream.send(\n                        {\n                            name: value[offset : offset + count]\n                            for name, value in outputs.items()\n                        }\n                    ),\n                )\n            except StopIteration as finished:\n                results[index] = finished.value\n                del active[index]\n            offset += count\n    return results\n\n\ndef collection_steps(\n    games,\n    seed,\n    *,\n    collector=None,\n    forced_root=None,\n    with_labels=False,\n    reference_policy=None,\n    root_only=False,\n    root_affinity=None,\n    policy_features=None,\n):\n    \"\"\"Collect fresh games or supplied native continuations, without records.\n\n    root_affinity supplies visible route labels shared by root-only rows.\n    \"\"\"\n    first = True\n    if collector is None:\n        collector = _native_collection.NativeCollector(games, seed)\n    generator = numpy.random.default_rng(seed)\n    batches = []\n    simulated_decisions = 0\n    while (request := collector.next()) is not None:\n        count = len(request[\"head\"])\n        simulated_decisions += count\n        batch = request_batch(request)\n        outputs = yield (\n            batch[\"features\"]\n            if policy_features is None\n            else policy_features(request, collector)\n        )\n        batch[\"behavior\"] = policy_log_probabilities(\n            outputs, batch[\"head\"], batch[\"legal\"]\n        )\n        cumulative = numpy.exp(batch[\"behavior\"]).cumsum(\n            axis=1, dtype=numpy.float64\n        )\n        cumulative /= cumulative[:, -1:]\n        batch[\"chosen\"] = (\n            generator.random((len(cumulative), 1)) >= cumulative\n        ).sum(axis=1)\n        batch[\"paired_root\"] = numpy.zeros(count, numpy.bool_)\n        if first and forced_root is not None:\n            decision, action = forced_root\n            rows = numpy.arange(games) * (count // games) + decision\n            assert batch[\"legal\"][rows, action].all()\n            batch[\"chosen\"][rows] = action\n            batch[\"behavior\"][rows] = -1e9\n            batch[\"behavior\"][rows, action] = 0\n            batch[\"paired_root\"][rows] = True\n        first = False\n        collector.submit(batch[\"chosen\"].tolist())\n        if root_only:\n            if batch[\"paired_root\"].any():\n                selected = numpy.flatnonzero(batch[\"paired_root\"])\n                batches.append(\n                    {\n                        \"features\": call_states.select(\n                            batch[\"features\"], selected\n                        ),\n                        **{\n                            name: value[selected]\n                            for name, value in batch.items()\n                            if name != \"features\"\n                        },\n                    }\n                )\n        else:\n            batches.append(batch)\n    logs, statistics = collector.finish()\n    statistics[\"simulated_decisions\"] = simulated_decisions\n    logs = [json.loads(events) for events in logs]\n    for events in logs:\n        outcomes.normalize_draw_payments(events)\n    payments = []\n    endings = []\n    for events in logs:\n        assert events[-1][\"type\"] in (\"end_game\", \"start_kyoku\")\n        starts = [\n            i\n            for i, event in enumerate(events)\n            if event[\"type\"] == \"start_kyoku\"\n        ]\n        completed = len(starts) - (events[-1][\"type\"] != \"end_game\")\n        hands = [\n            events[start:end]\n            for start, end in zip(\n                starts[:completed], starts[1:] + [len(events)]\n            )\n        ]\n        payments.append([outcomes.terminal_payments(hand) for hand in hands])\n        endings.extend(outcomes.terminal_ending(hand) for hand in hands)\n    indices = numpy.concatenate([batch.pop(\"indices\") for batch in batches])\n    hand_indices = (\n        numpy.concatenate(\n            ([0], numpy.cumsum([len(game) for game in payments]))\n        )[indices[:, 0]]\n        + indices[:, 1]\n    )\n    batch = {\n        name: numpy.concatenate([batch[name] for batch in batches])\n        for name in (\"head\", \"legal\", \"chosen\", \"behavior\", \"paired_root\")\n    }\n    features = call_states.concatenate([part[\"features\"] for part in batches])\n    if with_labels:\n        from training import match_records\n\n        batch[\"labels\"] = match_records.label_rollouts(\n            logs, indices, features, root_affinity=root_affinity\n        )\n    if reference_policy is not None:\n        batch[\"reference_log_probability\"] = numpy.empty(\n            (len(indices), 150), numpy.float32\n        )\n        for game, events in enumerate(logs):\n            selected = numpy.flatnonzero(indices[:, 0] == game)\n            batch[\"reference_log_probability\"][selected] = (\n                reference_policy.distribution(\n                    events,\n                    numpy.column_stack(\n                        (\n                            indices[selected, 3] - 1,\n                            indices[selected, 2],\n                            features[\"decision_phase\"][selected],\n                        )\n                    ),\n                    batch[\"head\"][selected],\n                    batch[\"legal\"][selected],\n                )\n            )\n    payment_kind, payer, recipient = numpy.nonzero(outcomes.PAYMENT_CELLS)\n    batch[\"payment_points\"] = numpy.concatenate(payments)[\n        hand_indices[:, None],\n        payment_kind,\n        (indices[:, 2, None] + payer) % 4,\n        (indices[:, 2, None] + recipient) % 4,\n    ] + numpy.int32(1000) * (\n        (payment_kind == 3) & (features[\"riichi_state\"][:, recipient] == 2)\n    )\n    batch[\"ending_kind\"] = numpy.asarray(\n        [ending[\"round_end_kind\"] for ending in endings], dtype=numpy.int8\n    )[hand_indices]\n    source = numpy.asarray(\n        [ending[\"round_end_source\"] for ending in endings], dtype=numpy.int8\n    )[hand_indices]\n    batch[\"ending_source\"] = numpy.where(\n        source >= 0, (source - indices[:, 2]) % 4, -1\n    ).astype(numpy.int8)\n    batch[\"ending_tenpai\"] = numpy.stack(\n        [ending[\"round_end_tenpai\"] for ending in endings]\n    )[\n        hand_indices[:, None],\n        (indices[:, 2, None] + numpy.arange(4)) % 4,\n    ]\n    batch[\"features\"] = features\n    return batch, statistics\n",
      "sha256": "aafdc3b626737d18fb537540f777a7ac6cef0552e5f3605e35116370b1b54732"
    },
    {
      "path": "training/trainer.py",
      "text": "\"\"\"Shared optimizer, detached action values and observed-payment fitting.\"\"\"\n\nimport tensorflow as tf\n\nfrom log_dataset import call_states, training_data\nfrom model import critic, joint_settlement\nfrom training import auxiliary\n\n\nclass AdamW(tf.keras.optimizers.AdamW):\n    \"\"\"Clip already-reduced gradients; do not sum them a second time.\"\"\"\n\n    def _all_reduce_sum_gradients(self, grads_and_vars):\n        return grads_and_vars\n\n\ndef apply_gradients(optimizer, tape, loss, variables):\n    # Sum repeated tile entries locally: each embedding has only 34 rows.\n    # Clip and synchronize the actual table gradient, not every occurrence.\n    pairs = [\n        (tf.convert_to_tensor(gradient), variable)\n        for gradient, variable in zip(tape.gradient(loss, variables), variables)\n        if gradient is not None\n    ]\n    gradients = tf.distribute.get_replica_context().all_reduce(\n        tf.distribute.ReduceOp.SUM, [gradient for gradient, _ in pairs]\n    )\n    norm = tf.debugging.check_numerics(\n        tf.linalg.global_norm(gradients), \"Non-finite global gradient norm\"\n    )\n    with tf.control_dependencies([norm]):\n        optimizer.apply_gradients(\n            zip(gradients, [variable for _, variable in pairs])\n        )\n    return {\"gradient/global_norm\": norm}\n\n\ndef action_values(*, network, features, selected, state, chunk_size=256):\n    \"\"\"Detached settlement forecasts for the MMD actor's legal actions.\"\"\"\n    public = joint_settlement.public_inputs(features)\n    inputs = {\n        **{\n            name: tf.gather(value, selected[:, 0])\n            for name, value in public.items()\n        },\n        **critic.public_inputs(features, selected),\n        \"state\": tf.stop_gradient(state),\n    }\n    positions, position_indices = tf.unique(selected[:, 0])\n    payoffs = joint_settlement.gather_position_payoffs(\n        {**public, \"dealer\": features[\"dealer_relative_seat\"]},\n        positions,\n    )\n    integer_fields = tuple(\n        name for name, value in inputs.items() if value.dtype == tf.int32\n    )\n    inputs = {\n        name: (\n            tf.bitcast(value, tf.float32) if name in integer_fields else value\n        )\n        for name, value in inputs.items()\n    }\n    weights = [\n        tf.stop_gradient(value.value.read_value())\n        for value in network.critic.trainable_variables\n    ]\n    chunk_count = (tf.shape(selected)[0] + chunk_size - 1) // chunk_size\n    values = tf.TensorArray(\n        tf.float32, size=chunk_count, element_shape=[chunk_size]\n    )\n    for chunk in tf.range(chunk_count):\n        indices = tf.minimum(\n            chunk * chunk_size + tf.range(chunk_size),\n            tf.shape(selected)[0] - 1,\n        )\n        values = values.write(\n            chunk,\n            network.critic.candidate_chunk(\n                inputs={\n                    name: tf.gather(value, indices)\n                    for name, value in inputs.items()\n                },\n                payoff=tf.gather(payoffs, tf.gather(position_indices, indices)),\n                weights=weights,\n                integer_fields=integer_fields,\n            ),\n        )\n    return tf.stop_gradient(\n        tf.scatter_nd(\n            selected,\n            tf.reshape(values.stack(), [-1])[: tf.shape(selected)[0]],\n            [tf.shape(features[\"decision_phase\"])[0], 295],\n        )\n    )\n\n\nclass CriticTrainer:\n    \"\"\"Observed payment likelihood, critic constraints and supervised beliefs.\"\"\"\n\n    def __init__(self, network, features, learning_rate):\n        self.network = network\n        self.feature_packing = training_data.PackedBatch(\n            call_states.base(features)\n        )\n        self.optimizer = AdamW(\n            learning_rate=learning_rate, weight_decay=1e-4, clipnorm=1.0\n        )\n        self.optimizer.build(network.trainable_variables)\n\n    @tf.function(reduce_retracing=True)\n    def critic_update(self, batch, valid):\n        features = call_states.unpack(batch[\"features\"], self.feature_packing)\n        with tf.GradientTape() as tape:\n            encoded = self.network.encoder(features, training=False)\n            state = self.network.candidate_context(features, encoded)\n            observed = self.network.chosen_inputs(\n                features, encoded, state, batch[\"chosen\"]\n            )\n            statistics = self.network.critic.supervised_statistics(\n                observed,\n                joint_settlement.payment_labels(\n                    points=batch[\"payment_points\"],\n                    public=observed,\n                    ending_kind=batch[\"ending_kind\"],\n                    ending_source=batch[\"ending_source\"],\n                    ending_tenpai=batch[\"ending_tenpai\"],\n                ),\n                valid=valid,\n            )\n            metrics = critic.metrics_from_statistics(statistics)\n            _, supervised = auxiliary.reduce_terms(\n                features=features,\n                labels=batch[\"labels\"],\n                outputs=encoded,\n                valid=valid,\n                terms={},\n            )\n            loss = critic.settlement_objective(metrics) + tf.add_n(\n                list(supervised.values())\n            )\n            scaled = loss / tf.distribute.get_strategy().num_replicas_in_sync\n        return {\n            **metrics,\n            **supervised,\n            **apply_gradients(\n                self.optimizer, tape, scaled, self.network.trainable_variables\n            ),\n            \"loss\": loss,\n        }\n",
      "sha256": "7a88d795957e4ce7d4476c98167e1183175a229b14cd795f9e4df84184203454"
    }
  ],
  "output_routes": [
    {
      "id": "opponent_shanten_logits",
      "dtype": "float32",
      "signatures": [
        "serving_default"
      ],
      "title": "Opponent shanten",
      "producer": "head-shanten",
      "inputs": [
        {
          "nodes": [
            "belief-refinement"
          ],
          "title": "Refined board state",
          "detail": "A 512-channel board vector supplies a shared 48-channel prior for all three opponents.",
          "source": {
            "path": "model/beliefs.py",
            "line": 332
          }
        },
        {
          "nodes": [
            "river-summaries"
          ],
          "title": "Opponent river summary",
          "detail": "Each opponent contributes their own 256-channel river vector to the observation projection.",
          "source": {
            "path": "model/beliefs.py",
            "line": 291
          }
        },
        {
          "fields": [
            "meld_tiles",
            "dealer_relative_seat",
            "riichi_state",
            "opponent_discard_count",
            "live_wall_count",
            "last_tedashi_tile_id"
          ],
          "title": "Public shanten evidence",
          "detail": "The readout uses meld count, dealer flag, riichi, discard count, live wall and last tedashi. Declared riichi or four melds also forces tenpai.",
          "source": {
            "path": "model/beliefs.py",
            "line": 289
          },
          "decision_only": true,
          "nodes": [
            "inputs-parent-table",
            "inputs-parent-opponents"
          ]
        }
      ],
      "kind": "learned head",
      "sharing": "Same board/observation/readout weights across all three opponents; local inputs differ.",
      "description": "Categorical logits over four clipped shanten classes per opponent; class 0 denotes tenpai. Public constraints mask non-tenpai support where required. HTTP softmax probabilities feed reviewer readiness/difficulty; also an internally supervised prediction.",
      "source": {
        "path": "model/beliefs.py",
        "line": 276
      },
      "shape": [
        3,
        4
      ],
      "row_axis": "decision",
      "ownership": "Observed decision; shared with call alternatives",
      "execution": "Infer once from the original observed board. Hypothetical chi/pon branches gather the same parent posterior by owner.",
      "row_source": {
        "path": "model/actor.py",
        "line": 479
      },
      "group": "Beliefs",
      "multiplicity": "3 opponents × 4 shanten classes",
      "consumers": [
        {
          "title": "Direct supervised loss",
          "source": {
            "path": "training/auxiliary.py",
            "line": 41
          },
          "link": "#training/expert-joint"
        },
        {
          "title": "Prediction inspection",
          "source": {
            "path": "model/inference.py",
            "line": 118
          }
        },
        {
          "title": "Structural wait",
          "link": "#architecture/head-structural-wait",
          "source": {
            "path": "model/beliefs.py",
            "line": 47
          }
        },
        {
          "title": "Shanten-weighted ukeire",
          "link": "#architecture/actor-policy-context",
          "source": {
            "path": "model/network.py",
            "line": 75
          }
        },
        {
          "title": "Policy context",
          "link": "#architecture/actor-policy-context",
          "source": {
            "path": "model/network.py",
            "line": 75
          }
        },
        {
          "title": "Settlement state",
          "link": "#architecture/critic-state-assembly",
          "source": {
            "path": "model/network.py",
            "line": 201
          }
        }
      ]
    },
    {
      "id": "opponent_ukeire_by_shanten_logits",
      "dtype": "float32",
      "signatures": [],
      "title": "Conditional ukeire",
      "producer": "head-ukeire",
      "inputs": [
        {
          "nodes": [
            "belief-readouts"
          ],
          "title": "Initial improving-tile logits",
          "detail": "A Dense readout of the refined board supplies a trainable base for each opponent, shanten class and tile.",
          "source": {
            "path": "model/beliefs.py",
            "line": 272
          }
        },
        {
          "nodes": [
            "tile-attention-1"
          ],
          "title": "Tile-attention correction",
          "detail": "The final tile tokens combine board context, tile identity and public copy bounds with detached initial shanten, improving-tile and count estimates. A learned residual corrects each base logit.",
          "source": {
            "path": "model/beliefs.py",
            "line": 262
          }
        }
      ],
      "kind": "learned head",
      "sharing": "Independent opponent/class/tile coefficients; actor/critic share predictions.",
      "description": "Internal network output; not exported for serving. Independent Bernoulli logits over 34 structural improving-tile indicators, conditional on each opponent’s shanten class; apply sigmoid.",
      "source": {
        "path": "model/beliefs.py",
        "line": 424
      },
      "shape": [
        3,
        4,
        34
      ],
      "row_axis": "decision",
      "ownership": "Observed decision; shared with call alternatives",
      "execution": "Infer once from the original observed board. Hypothetical chi/pon branches gather the same parent posterior by owner.",
      "row_source": {
        "path": "model/actor.py",
        "line": 479
      },
      "group": "Beliefs",
      "multiplicity": "3 opponents × 4 shanten classes × 34 base tiles",
      "consumers": [
        {
          "title": "Direct supervised loss",
          "source": {
            "path": "training/auxiliary.py",
            "line": 41
          },
          "link": "#training/expert-joint"
        },
        {
          "title": "Structural wait",
          "link": "#architecture/head-structural-wait",
          "source": {
            "path": "model/beliefs.py",
            "line": 47
          }
        },
        {
          "title": "Shanten-weighted ukeire",
          "link": "#architecture/actor-policy-context",
          "source": {
            "path": "model/network.py",
            "line": 75
          }
        },
        {
          "title": "Settlement state",
          "link": "#architecture/critic-state-assembly",
          "source": {
            "path": "model/network.py",
            "line": 201
          }
        }
      ]
    },
    {
      "id": "opponent_hand_count_logits",
      "dtype": "float32",
      "signatures": [],
      "title": "Opponent tile counts",
      "producer": "head-counts",
      "inputs": [
        {
          "nodes": [
            "belief-readouts"
          ],
          "title": "Initial tile-count logits",
          "detail": "A Dense readout of the refined board supplies trainable count logits for ordinary and red tiles.",
          "source": {
            "path": "model/beliefs.py",
            "line": 468
          }
        },
        {
          "nodes": [
            "tile-attention-1"
          ],
          "title": "Tile-attention correction",
          "detail": "The final tile tokens combine board context, tile identity and public copy bounds with detached initial shanten, improving-tile and count estimates. A learned residual corrects each base logit.",
          "source": {
            "path": "model/beliefs.py",
            "line": 262
          }
        },
        {
          "fields": [
            "meld_tiles",
            "known_unavailable_counts",
            "candidate_hand_red",
            "public_visible_red_counts"
          ],
          "title": "Public tile supply and hand sizes",
          "detail": "Exposed melds bound each count. Remaining ordinary and red copies and concealed hand sizes constrain the joint projection across opponents.",
          "source": {
            "path": "model/beliefs.py",
            "line": 595
          },
          "decision_only": true,
          "nodes": [
            "inputs-parent-hand",
            "inputs-parent-table"
          ]
        },
        {
          "fields": [
            "dora_multiplicity",
            "seat_wind",
            "prevailing_wind"
          ],
          "title": "Projection weights",
          "detail": "Dora, red fives and value honors determine the relative cost of moving each count marginal.",
          "source": {
            "path": "model/beliefs.py",
            "line": 597
          },
          "decision_only": true,
          "nodes": [
            "inputs-parent-table"
          ]
        }
      ],
      "kind": "learned head",
      "sharing": "Independent opponent/tile/count coefficients; actor/critic share predictions.",
      "description": "Internal network output; not exported for serving. Categorical logits over counts 0–4 for each ordinary/red tile class and opponent, after support masking and count projection. Counts include observed meld occupancy.",
      "source": {
        "path": "model/beliefs.py",
        "line": 424
      },
      "shape": [
        3,
        37,
        5
      ],
      "row_axis": "decision",
      "ownership": "Observed decision; shared with call alternatives",
      "execution": "Infer once from the original observed board. Hypothetical chi/pon branches gather the same parent posterior by owner.",
      "row_source": {
        "path": "model/actor.py",
        "line": 479
      },
      "group": "Beliefs",
      "multiplicity": "3 opponents × 37 tile/red channels × 5 count classes",
      "consumers": [
        {
          "title": "Direct supervised loss",
          "source": {
            "path": "training/auxiliary.py",
            "line": 41
          },
          "link": "#training/expert-joint"
        },
        {
          "title": "Completion yaku",
          "link": "#architecture/head-completion-yaku",
          "source": {
            "path": "model/beliefs.py",
            "line": 458
          }
        },
        {
          "title": "Ron eligibility",
          "link": "#architecture/head-ron-eligibility",
          "source": {
            "path": "model/network.py",
            "line": 44
          }
        },
        {
          "title": "Policy context",
          "link": "#architecture/actor-policy-context",
          "source": {
            "path": "model/network.py",
            "line": 75
          }
        },
        {
          "title": "Settlement state",
          "link": "#architecture/critic-state-assembly",
          "source": {
            "path": "model/network.py",
            "line": 201
          }
        }
      ]
    },
    {
      "id": "round_completion_yaku_logits",
      "dtype": "float32",
      "signatures": [],
      "title": "Completion yaku",
      "producer": "head-completion-yaku",
      "inputs": [
        {
          "nodes": [
            "belief-refinement"
          ],
          "title": "Refined board state",
          "detail": "The 512-channel board vector supplies the base logits for self and all three opponents, for ron and tsumo.",
          "source": {
            "path": "model/beliefs.py",
            "line": 518
          }
        },
        {
          "nodes": [
            "head-counts"
          ],
          "via": [
            "completion-evidence"
          ],
          "title": "Opponent tile counts",
          "detail": "Expected physical tile counts supply suit, dora and red-five summaries to the opponent-only residual.",
          "detached": true,
          "source": {
            "path": "model/beliefs.py",
            "line": 529
          }
        },
        {
          "nodes": [
            "river-summaries"
          ],
          "via": [
            "completion-evidence"
          ],
          "title": "Opponent river summary",
          "detail": "Each 256-channel river vector joins the 33 tile-summary channels for that opponent.",
          "source": {
            "path": "model/beliefs.py",
            "line": 401
          }
        },
        {
          "fields": [
            "candidate_hand_counts",
            "candidate_hand_red",
            "known_unavailable_counts",
            "public_visible_red_counts",
            "dora_multiplicity"
          ],
          "via": [
            "completion-evidence"
          ],
          "title": "Own hand and unseen tiles",
          "detail": "The current hand in slot 0, remaining tile supply and dora multiplicities contribute to the opponent-only residual.",
          "source": {
            "path": "model/beliefs.py",
            "line": 367
          },
          "nodes": [
            "inputs-parent-hand",
            "inputs-parent-table",
            "inputs-child-hand",
            "inputs-child-table"
          ]
        },
        {
          "fields": [
            "meld_tiles",
            "meld_type",
            "known_unavailable_counts",
            "candidate_hand_counts",
            "trigger_tile_id",
            "trigger_valid",
            "trigger_source",
            "seat_wind",
            "prevailing_wind"
          ],
          "title": "Public yaku support",
          "detail": "Fixed melds restrict compatible yaku. Claimable copies, the offered discard and player and round winds determine which value-honor triplets are possible.",
          "source": {
            "path": "model/payment_scoring.py",
            "line": 245
          },
          "nodes": [
            "inputs-parent-hand",
            "inputs-parent-table",
            "inputs-parent-actions",
            "inputs-child-hand",
            "inputs-child-table",
            "inputs-child-actions"
          ]
        }
      ],
      "kind": "learned head",
      "sharing": "Same prediction used by actor and critic; independent output coefficients per player and win kind. One additional residual map is shared across opponents.",
      "description": "Internal network output; not exported for serving. Constrained Bernoulli logits for 23 yaku labels on the highest-scoring completion of the next observed tenpai shape, indexed by player and ron/tsumo. This conditional completion target is not a win-probability target.",
      "source": {
        "path": "model/beliefs.py",
        "line": 458
      },
      "shape": [
        4,
        2,
        23
      ],
      "row_axis": "board",
      "ownership": "Decision and after-call positions",
      "execution": "The same readout runs at the decision and again after each possible chi or pon. The actor returns the decision prediction and uses the after-call predictions to score follow-up discards.",
      "row_source": {
        "path": "model/actor.py",
        "line": 465
      },
      "group": "Beliefs",
      "multiplicity": "4 players × 2 win modes × 23 yaku",
      "consumers": [
        {
          "title": "Direct supervised loss",
          "source": {
            "path": "training/auxiliary.py",
            "line": 41
          },
          "link": "#training/expert-joint"
        },
        {
          "title": "Completion potential (han/fu)",
          "link": "#architecture/head-completion-score",
          "source": {
            "path": "model/beliefs.py",
            "line": 458
          }
        },
        {
          "title": "Ron eligibility",
          "link": "#architecture/head-ron-eligibility",
          "source": {
            "path": "model/network.py",
            "line": 44
          }
        },
        {
          "title": "Policy context",
          "link": "#architecture/actor-policy-context",
          "source": {
            "path": "model/network.py",
            "line": 75
          }
        },
        {
          "title": "Settlement state",
          "link": "#architecture/critic-state-assembly",
          "source": {
            "path": "model/network.py",
            "line": 201
          }
        }
      ]
    },
    {
      "id": "round_completion_score_logits",
      "dtype": "float32",
      "signatures": [],
      "title": "Completion potential (han/fu)",
      "producer": "head-completion-score",
      "inputs": [
        {
          "nodes": [
            "belief-refinement"
          ],
          "title": "Refined board state",
          "detail": "The 512-channel board vector supplies the base logits for self and all three opponents, for ron and tsumo.",
          "source": {
            "path": "model/beliefs.py",
            "line": 518
          }
        },
        {
          "nodes": [
            "head-completion-yaku"
          ],
          "title": "Completion yaku probabilities",
          "detail": "Own-seat ron and tsumo yaku probabilities constrain the score distribution through minimum han.",
          "detached": true,
          "source": {
            "path": "model/beliefs.py",
            "line": 549
          }
        },
        {
          "fields": [
            "candidate_fu",
            "meld_tiles",
            "meld_type",
            "riichi_state",
            "public_bonus"
          ],
          "title": "Public score support",
          "detail": "Own candidate-zero fu, public melds, riichi and visible bonus han restrict the own-hand score support.",
          "source": {
            "path": "model/payment_scoring.py",
            "line": 454
          },
          "nodes": [
            "inputs-parent-table",
            "inputs-parent-hand",
            "inputs-child-table",
            "inputs-child-hand"
          ]
        }
      ],
      "kind": "learned head",
      "sharing": "Own-seat readout, independent output coefficients per win kind.",
      "description": "Best ordinary finish of the next observed tenpai shape, for our own hand, separately for ron/tsumo. Includes actual riichi, visible dora/red and applicable menzen tsumo; excludes hypothetical ura, ippatsu and special-event bonuses. Predicts completion potential, not win probability or the eventual winning score. Actor and critic consume these detached probabilities. Softmax over 38 scoring classes, shared with settlement; internal output.",
      "source": {
        "path": "model/beliefs.py",
        "line": 458
      },
      "shape": [
        1,
        2,
        38
      ],
      "row_axis": "board",
      "ownership": "Decision and after-call positions",
      "execution": "The same readout runs at the decision and again after each possible chi or pon. The actor returns the decision prediction and uses the after-call predictions to score follow-up discards.",
      "row_source": {
        "path": "model/actor.py",
        "line": 465
      },
      "group": "Beliefs",
      "multiplicity": "Own hand × 2 win modes × 38 score states",
      "consumers": [
        {
          "title": "Direct supervised loss",
          "source": {
            "path": "training/auxiliary.py",
            "line": 41
          },
          "link": "#training/expert-joint"
        },
        {
          "title": "Policy context",
          "link": "#architecture/actor-policy-context",
          "source": {
            "path": "model/network.py",
            "line": 75
          }
        },
        {
          "title": "Settlement state",
          "link": "#architecture/critic-state-assembly",
          "source": {
            "path": "model/network.py",
            "line": 201
          }
        }
      ]
    },
    {
      "id": "opponent_wait_logits",
      "dtype": "float32",
      "signatures": [],
      "title": "Structural wait",
      "producer": "head-structural-wait",
      "inputs": [
        {
          "nodes": [
            "head-shanten"
          ],
          "title": "Tenpai probability",
          "detail": "The constrained shanten distribution supplies the probability of class 0 for each opponent.",
          "source": {
            "path": "model/beliefs.py",
            "line": 51
          }
        },
        {
          "nodes": [
            "head-ukeire"
          ],
          "title": "Improving tiles at tenpai",
          "detail": "The shanten-zero slice supplies the conditional probability for each of 34 tile types. Multiplying by tenpai probability gives the joint wait.",
          "source": {
            "path": "model/beliefs.py",
            "line": 52
          }
        }
      ],
      "kind": "derived prediction",
      "sharing": "No independent weights; inherits shanten/improving heads",
      "description": "Internal network output; not exported for serving. Bernoulli log-odds for joint tenpai-and-structural-wait events. The probability is P(shanten=0)·P(tile improves | shanten=0); furiten and yaku legality are not equivalent to this event.",
      "source": {
        "path": "model/beliefs.py",
        "line": 47
      },
      "shape": [
        3,
        34
      ],
      "row_axis": "decision",
      "ownership": "Observed decision; shared with call alternatives",
      "execution": "Infer once from the original observed board. Hypothetical chi/pon branches gather the same parent posterior by owner.",
      "row_source": {
        "path": "model/actor.py",
        "line": 479
      },
      "group": "Beliefs",
      "multiplicity": "3 opponents × 34 base tiles",
      "consumers": [
        {
          "title": "Candidate ron risk",
          "link": "#architecture/head-ron",
          "source": {
            "path": "model/candidate_predictions.py",
            "line": 25
          }
        }
      ]
    },
    {
      "id": "route_affinity_logits",
      "dtype": "float32",
      "signatures": [],
      "title": "Candidate route affinity",
      "producer": "head-route",
      "inputs": [
        {
          "nodes": [
            "candidate-projection"
          ],
          "title": "Raw candidate state",
          "detail": "The 384-channel candidate vector before actor-only attention supplies three learned logits. Its board and action indices select the hand for the route mask.",
          "source": {
            "path": "model/candidate_predictions.py",
            "line": 10
          }
        },
        {
          "fields": [
            "candidate_meld_tiles",
            "candidate_meld_types",
            "discard_candidate_hand",
            "kan_candidate_hand"
          ],
          "title": "Candidate melds and hand indices",
          "detail": "The discard or kan hand index selects the meld tiles and types that permit tanyao, flush and outside-hand routes.",
          "source": {
            "path": "model/candidate_predictions.py",
            "line": 69
          },
          "nodes": [
            "inputs-parent-hand",
            "inputs-parent-actions",
            "inputs-child-hand",
            "inputs-child-actions"
          ]
        }
      ],
      "kind": "learned head",
      "sharing": "Dense 384→3 shared across candidate rows; actor/critic consume predictions.",
      "description": "Three candidate-conditioned Bernoulli logits for tanyao, flush and outside-hand affinity. Observed route targets supervise the readout. Actor and critic read detached probabilities.",
      "source": {
        "path": "model/candidate_predictions.py",
        "line": 10
      },
      "shape": [
        3
      ],
      "row_axis": "selected candidate",
      "ownership": "Decision actions and follow-up discards",
      "execution": "One row per legal action after complete-set attention. Call-plus-discard candidates share their original decision owner and retain canonical action IDs.",
      "row_source": {
        "path": "model/actor.py",
        "line": 522
      },
      "group": "Beliefs",
      "multiplicity": "3 routes per selected candidate",
      "consumers": [
        {
          "title": "Direct supervised loss",
          "source": {
            "path": "training/auxiliary.py",
            "line": 41
          },
          "link": "#training/expert-joint"
        },
        {
          "title": "Discard",
          "link": "#architecture/head-discard",
          "source": {
            "path": "model/actor.py",
            "line": 192
          }
        },
        {
          "title": "Riichi",
          "link": "#architecture/head-riichi",
          "source": {
            "path": "model/actor.py",
            "line": 192
          }
        },
        {
          "title": "Kan",
          "link": "#architecture/head-kan",
          "source": {
            "path": "model/actor.py",
            "line": 192
          }
        },
        {
          "title": "Settlement state",
          "link": "#architecture/critic-state-assembly",
          "source": {
            "path": "model/network.py",
            "line": 201
          }
        }
      ]
    },
    {
      "id": "candidate_ron_logits",
      "dtype": "float32",
      "signatures": [],
      "title": "Candidate ron risk",
      "producer": "head-ron",
      "inputs": [
        {
          "nodes": [
            "head-structural-wait"
          ],
          "title": "Structural wait on the offered tile",
          "detail": "The base-tile wait probability multiplies each opponent’s learned eligibility. Red and ordinary fives use the same wait.",
          "detached": true,
          "source": {
            "path": "model/candidate_predictions.py",
            "line": 36
          }
        },
        {
          "nodes": [
            "head-ron-eligibility"
          ],
          "title": "Shared tile eligibility",
          "detail": "Gather the observed-board eligibility at the discarded base tile, including across call alternatives.",
          "source": {
            "path": "model/candidate_predictions.py",
            "line": 34
          }
        },
        {
          "fields": [
            "decision_phase",
            "genbutsu_to_seat",
            "known_unavailable_counts",
            "meld_tiles"
          ],
          "title": "Discard and safe-tile masks",
          "detail": "The decision phase gates discard, dama and riichi candidates, including local post-call discards. Genbutsu and provably safe exhausted honors suppress ron.",
          "source": {
            "path": "model/candidate_predictions.py",
            "line": 47
          },
          "nodes": [
            "inputs-parent-table",
            "inputs-parent-opponents",
            "inputs-parent-actions",
            "inputs-child-table",
            "inputs-child-opponents",
            "inputs-child-actions"
          ]
        }
      ],
      "kind": "derived prediction",
      "sharing": "No independent weights; candidates offering the same base tile share immediate risk.",
      "description": "Three opponent ron probabilities per supported candidate, trained on observed ron legality. The final actor scorer reads detached probabilities.",
      "source": {
        "path": "model/candidate_predictions.py",
        "line": 25
      },
      "shape": [
        3
      ],
      "row_axis": "selected candidate",
      "ownership": "Decision actions and follow-up discards",
      "execution": "One row per legal action after complete-set attention. Call-plus-discard candidates share their original decision owner and retain canonical action IDs.",
      "row_source": {
        "path": "model/actor.py",
        "line": 522
      },
      "group": "Beliefs",
      "multiplicity": "3 opponents per selected candidate",
      "consumers": [
        {
          "title": "Direct supervised loss",
          "source": {
            "path": "training/auxiliary.py",
            "line": 41
          },
          "link": "#training/expert-joint"
        },
        {
          "title": "Discard",
          "link": "#architecture/head-discard",
          "source": {
            "path": "model/actor.py",
            "line": 192
          }
        },
        {
          "title": "Riichi",
          "link": "#architecture/head-riichi",
          "source": {
            "path": "model/actor.py",
            "line": 192
          }
        },
        {
          "title": "Kan (fixed at zero)",
          "link": "#architecture/head-kan",
          "source": {
            "path": "model/actor.py",
            "line": 192
          }
        }
      ]
    },
    {
      "id": "discard_policy_logits",
      "dtype": "float32",
      "signatures": [
        "serving_default",
        "policy"
      ],
      "title": "Discard policy",
      "producer": "head-discard",
      "inputs": [
        {
          "title": "Raw candidate state",
          "detail": "The scorer reads detached 384-channel local candidate states. Legal-set pooling separately conditions actor context.",
          "nodes": [
            "candidate-projection"
          ],
          "source": {
            "path": "model/network.py",
            "line": 156
          }
        },
        {
          "title": "Policy context",
          "detail": "The 768-channel actor context queries detached legal candidates through 128-channel attention and receives the projected weighted-value residual.",
          "nodes": [
            "actor-policy-context",
            "actor-candidate-pool"
          ],
          "source": {
            "path": "model/actor.py",
            "line": 320
          }
        },
        {
          "title": "Route affinity",
          "detail": "Three detached route probabilities attach to the local candidate.",
          "nodes": [
            "head-route"
          ],
          "source": {
            "path": "model/actor.py",
            "line": 160
          },
          "detached": true
        },
        {
          "title": "Ron risk",
          "detail": "Three detached probabilities describe ron liability for the cut.",
          "nodes": [
            "head-ron"
          ],
          "source": {
            "path": "model/actor.py",
            "line": 160
          },
          "detached": true
        },
        {
          "title": "Discard support and tile evidence",
          "detail": "The local board supplies legal cuts, opening-discard symmetry and final-wall safe-cut support.",
          "nodes": [
            "inputs-parent-actions",
            "inputs-parent-hand",
            "inputs-parent-table",
            "inputs-parent-opponents",
            "inputs-child-actions",
            "inputs-child-hand",
            "inputs-child-table",
            "inputs-child-opponents"
          ],
          "source": {
            "path": "model/actor.py",
            "line": 33
          }
        }
      ],
      "kind": "shared policy branch",
      "sharing": "Discard, riichi and kan branches share the 1158→512→1 candidate scorer, also reused for follow-up discards.",
      "description": "Legality-constrained categorical action logits over 34 ordinary tile classes plus three red-five classes. Consumed by live action selection, self-play, policy training and reviewer grading.",
      "source": {
        "path": "model/actor.py",
        "line": 192
      },
      "shape": [
        37
      ],
      "row_axis": "decision",
      "ownership": "Decision discard and after-call scorer",
      "execution": "One 37-way output per decision. Each possible chi or pon also runs the same scorer to supply the follow-up discard distribution.",
      "row_source": {
        "path": "model/actor.py",
        "line": 444
      },
      "group": "Actor",
      "multiplicity": "37 physical discard classes",
      "consumers": [
        {
          "title": "Legal action selection",
          "source": {
            "path": "model/actions.py",
            "line": 252
          }
        },
        {
          "title": "Policy and serving signatures",
          "source": {
            "path": "model/export.py",
            "line": 28
          }
        },
        {
          "title": "Post-call discard distribution",
          "link": "#architecture/head-response",
          "source": {
            "path": "model/actor.py",
            "line": 559
          }
        },
        {
          "title": "Active policy weights on critic candidates",
          "link": "#math/candidate-mass",
          "source": {
            "path": "model/critic.py",
            "line": 1408
          }
        },
        {
          "title": "Terminal payment probabilities",
          "link": "#outputs/terminal_payment_probabilities",
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        },
        {
          "title": "Final placement probabilities",
          "link": "#outputs/final_placement_probabilities",
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        },
        {
          "title": "Review outcome probabilities",
          "link": "#outputs/review_outcome_probabilities",
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        },
        {
          "title": "Settlement mean",
          "link": "#outputs/settlement_mean",
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        },
        {
          "title": "Settlement variance",
          "link": "#outputs/settlement_variance",
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        }
      ]
    },
    {
      "id": "riichi_policy_logits",
      "dtype": "float32",
      "signatures": [
        "serving_default",
        "policy"
      ],
      "title": "Riichi policy",
      "producer": "head-riichi",
      "inputs": [
        {
          "title": "Raw candidate state",
          "detail": "The scorer reads detached 384-channel local candidate states. Legal-set pooling separately conditions actor context.",
          "nodes": [
            "candidate-projection"
          ],
          "source": {
            "path": "model/network.py",
            "line": 156
          }
        },
        {
          "title": "Policy context",
          "detail": "The 768-channel actor context queries detached legal candidates through 128-channel attention and receives the projected weighted-value residual.",
          "nodes": [
            "actor-policy-context",
            "actor-candidate-pool"
          ],
          "source": {
            "path": "model/actor.py",
            "line": 320
          }
        },
        {
          "title": "Route affinity",
          "detail": "Three detached route probabilities attach to the local candidate.",
          "nodes": [
            "head-route"
          ],
          "source": {
            "path": "model/actor.py",
            "line": 160
          },
          "detached": true
        },
        {
          "title": "Ron risk",
          "detail": "Three detached probabilities describe ron liability for the cut.",
          "nodes": [
            "head-ron"
          ],
          "source": {
            "path": "model/actor.py",
            "line": 160
          },
          "detached": true
        },
        {
          "title": "Riichi and discard support",
          "detail": "The decision position’s legal discards and declaration mask select the two 37-tile branches. The discard scorer also applies opening symmetry and the dama branch’s final-wall support.",
          "nodes": [
            "inputs-parent-actions",
            "inputs-parent-table",
            "inputs-parent-hand",
            "inputs-parent-opponents"
          ],
          "source": {
            "path": "model/actor.py",
            "line": 27
          }
        }
      ],
      "kind": "shared policy branch",
      "sharing": "Discard, riichi and kan branches share the 1158→512→1 candidate scorer, also reused for follow-up discards.",
      "description": "Joint categorical action logits over declaration status × discard class: 37 dama choices followed by 37 riichi choices. Consumed by live selection and reviewer branch-conditional discard grading.",
      "source": {
        "path": "model/actor.py",
        "line": 192
      },
      "shape": [
        74
      ],
      "row_axis": "decision",
      "ownership": "Decision position",
      "execution": "The actor returns one row per decision. It reuses the same policy weights after a possible call to score the follow-up discard.",
      "row_source": {
        "path": "model/actor.py",
        "line": 444
      },
      "group": "Actor",
      "multiplicity": "2 choices (dama / riichi) × 37 discard classes",
      "consumers": [
        {
          "title": "Legal action selection",
          "source": {
            "path": "model/actions.py",
            "line": 252
          }
        },
        {
          "title": "Policy and serving signatures",
          "source": {
            "path": "model/export.py",
            "line": 28
          }
        },
        {
          "title": "Riichi decision marginal",
          "link": "#architecture/head-riichi_action",
          "source": {
            "path": "model/actor.py",
            "line": 71
          }
        },
        {
          "title": "Active policy weights on critic candidates",
          "link": "#math/candidate-mass",
          "source": {
            "path": "model/critic.py",
            "line": 1408
          }
        },
        {
          "title": "Terminal payment probabilities",
          "link": "#outputs/terminal_payment_probabilities",
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        },
        {
          "title": "Final placement probabilities",
          "link": "#outputs/final_placement_probabilities",
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        },
        {
          "title": "Review outcome probabilities",
          "link": "#outputs/review_outcome_probabilities",
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        },
        {
          "title": "Settlement mean",
          "link": "#outputs/settlement_mean",
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        },
        {
          "title": "Settlement variance",
          "link": "#outputs/settlement_variance",
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        }
      ]
    },
    {
      "id": "kan_action_logits",
      "dtype": "float32",
      "signatures": [
        "serving_default",
        "policy"
      ],
      "title": "Kan policy",
      "producer": "head-kan",
      "inputs": [
        {
          "title": "Raw candidate state",
          "detail": "The scorer reads detached 384-channel local candidate states. Legal-set pooling separately conditions actor context.",
          "nodes": [
            "candidate-projection"
          ],
          "source": {
            "path": "model/network.py",
            "line": 156
          }
        },
        {
          "title": "Policy context",
          "detail": "The 768-channel actor context queries detached legal candidates through 128-channel attention and receives the projected weighted-value residual.",
          "nodes": [
            "actor-policy-context",
            "actor-candidate-pool"
          ],
          "source": {
            "path": "model/actor.py",
            "line": 320
          }
        },
        {
          "title": "Route affinity",
          "detail": "Three detached route probabilities attach to the local candidate.",
          "nodes": [
            "head-route"
          ],
          "source": {
            "path": "model/actor.py",
            "line": 160
          },
          "detached": true
        },
        {
          "title": "Ron risk (fixed at zero)",
          "detail": "The shared scorer receives this input on kan candidates. The discard eligibility mask fixes its probability at zero.",
          "nodes": [
            "head-ron"
          ],
          "source": {
            "path": "model/candidate_predictions.py",
            "line": 47
          },
          "detached": true
        },
        {
          "title": "Legal kan options",
          "detail": "One pass slot and 34 tile types are masked by the decision position’s kan legality vector.",
          "nodes": [
            "inputs-parent-actions"
          ],
          "source": {
            "path": "model/actions.py",
            "line": 330
          }
        }
      ],
      "kind": "shared policy branch",
      "sharing": "Discard, riichi and kan branches share the 1158→512→1 candidate scorer, also reused for follow-up discards.",
      "description": "Categorical logits over decline followed by 34 tile-indexed kan candidates; total width 35. Consumed by live kan selection, reviewer grading and legal-action presentation.",
      "source": {
        "path": "model/actor.py",
        "line": 192
      },
      "shape": [
        35
      ],
      "row_axis": "decision",
      "ownership": "Decision position",
      "execution": "The actor returns one row per decision. It reuses the same policy weights after a possible call to score the follow-up discard.",
      "row_source": {
        "path": "model/actor.py",
        "line": 444
      },
      "group": "Actor",
      "multiplicity": "1 pass + 34 kan tile types",
      "consumers": [
        {
          "title": "Legal action selection",
          "source": {
            "path": "model/actions.py",
            "line": 252
          }
        },
        {
          "title": "Policy and serving signatures",
          "source": {
            "path": "model/export.py",
            "line": 28
          }
        },
        {
          "title": "Active policy weights on critic candidates",
          "link": "#math/candidate-mass",
          "source": {
            "path": "model/critic.py",
            "line": 1408
          }
        },
        {
          "title": "Terminal payment probabilities",
          "link": "#outputs/terminal_payment_probabilities",
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        },
        {
          "title": "Final placement probabilities",
          "link": "#outputs/final_placement_probabilities",
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        },
        {
          "title": "Review outcome probabilities",
          "link": "#outputs/review_outcome_probabilities",
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        },
        {
          "title": "Settlement mean",
          "link": "#outputs/settlement_mean",
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        },
        {
          "title": "Settlement variance",
          "link": "#outputs/settlement_variance",
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        }
      ]
    },
    {
      "id": "win_decision_logits",
      "dtype": "float32",
      "signatures": [
        "serving_default",
        "policy"
      ],
      "title": "Win / pass",
      "producer": "head-win",
      "inputs": [
        {
          "title": "Board and belief context",
          "detail": "The 768-channel policy context enters the two-logit win/pass readout.",
          "nodes": [
            "actor-policy-context"
          ],
          "source": {
            "path": "model/actor.py",
            "line": 204
          }
        },
        {
          "title": "Win eligibility",
          "detail": "The public win kind determines whether the win slot is legal.",
          "nodes": [
            "inputs-parent-actions"
          ],
          "source": {
            "path": "model/actions.py",
            "line": 314
          },
          "fields": [
            "win_kind"
          ]
        }
      ],
      "kind": "learned head",
      "sharing": "One actor-only Dense 2 readout.",
      "description": "Two categorical logits: decline (0), accept the currently legal ron/tsumo opportunity (1). Apply softmax on the last axis. Consumed by live WIN accept/decline selection and the five-head policy signature.",
      "source": {
        "path": "model/actor.py",
        "line": 204
      },
      "shape": [
        2
      ],
      "row_axis": "decision",
      "ownership": "Decision position",
      "execution": "The actor returns one row per decision. It reuses the same policy weights after a possible call to score the follow-up discard.",
      "row_source": {
        "path": "model/actor.py",
        "line": 444
      },
      "group": "Actor",
      "multiplicity": "2 choices (pass / win)",
      "consumers": [
        {
          "title": "Legal action selection",
          "source": {
            "path": "model/actions.py",
            "line": 252
          }
        },
        {
          "title": "Policy and serving signatures",
          "source": {
            "path": "model/export.py",
            "line": 28
          }
        }
      ]
    },
    {
      "id": "call_choice",
      "dtype": "float32",
      "signatures": [],
      "title": "Call choice",
      "producer": "head-call-choice",
      "inputs": [
        {
          "title": "Policy context at the decision",
          "detail": "One Dense layer on the decision position’s 768-channel policy context produces six raw branch logits. The decision phase mask is applied when building the response policy.",
          "nodes": [
            "actor-policy-context"
          ],
          "source": {
            "path": "model/actor.py",
            "line": 555
          }
        }
      ],
      "kind": "learned head",
      "sharing": "One six-way readout shared across original call windows; distinct from the shared follow-up discard scorer.",
      "description": "Independent learned readout for pass, three chi patterns, pon and daiminkan. Zero-initialized kernel and bias precede legal branch normalization.",
      "source": {
        "path": "model/actor.py",
        "line": 423
      },
      "shape": [
        6
      ],
      "row_axis": "decision",
      "ownership": "Decision position",
      "execution": "One row per original decision.",
      "row_source": {
        "path": "model/actor.py",
        "line": 444
      },
      "group": "Actor",
      "multiplicity": "1 pass + 3 chi patterns + 1 pon + 1 daiminkan",
      "consumers": [
        {
          "title": "Six-way call normalization and response composition",
          "link": "#architecture/head-response",
          "source": {
            "path": "model/actor.py",
            "line": 559
          }
        }
      ]
    },
    {
      "id": "response_policy_logits",
      "dtype": "float32",
      "signatures": [
        "serving_default",
        "policy"
      ],
      "title": "Response policy",
      "producer": "head-response",
      "inputs": [
        {
          "title": "Call choice at the decision",
          "detail": "The original decision supplies the six branch logits, normalized over legal choices.",
          "nodes": [
            "head-call-choice"
          ],
          "source": {
            "path": "model/actor.py",
            "line": 553
          }
        },
        {
          "title": "After-call discard distribution",
          "detail": "The same discard scorer runs in each after-call position. Its 37 log probabilities describe the follow-up discard.",
          "nodes": [
            "head-discard"
          ],
          "source": {
            "path": "model/actor.py",
            "line": 535
          }
        },
        {
          "title": "Decision and call indices",
          "detail": "Owner and option scatter each follow-up discard distribution into the matching chi or pon slot for its decision.",
          "nodes": [
            "inputs-call-routing"
          ],
          "source": {
            "path": "model/actor.py",
            "line": 540
          }
        },
        {
          "title": "Response legality",
          "detail": "Pass and daiminkan support plus one 4 × 37 call-discard mask define admissible response slots. Kuikae exclusions remain specific to each call option.",
          "nodes": [
            "inputs-parent-actions"
          ],
          "source": {
            "path": "model/actor.py",
            "line": 545
          },
          "fields": [
            "response_legal_mask",
            "call_discard_legal"
          ]
        }
      ],
      "kind": "factorized policy branch",
      "sharing": "Independent call-choice Dense 6; follow-up discard parameters shared with the ordinary policy.",
      "description": "Categorical action logits with support [pass, 3×37 chi/discard, 1×37 pon/discard, open kan]; total width 150. Consumed by live selection and joint response/follow-up discard presentation.",
      "source": {
        "path": "model/actor.py",
        "line": 559
      },
      "shape": [
        150
      ],
      "row_axis": "decision",
      "ownership": "Call choice and follow-up discard",
      "execution": "One response distribution per decision combines the call choice with zero to four follow-up discard distributions, one for each legal chi or pon.",
      "row_source": {
        "path": "model/actor.py",
        "line": 562
      },
      "group": "Actor",
      "multiplicity": "1 pass + (3 chi + 1 pon) × 37 cuts + 1 daiminkan = 150",
      "consumers": [
        {
          "title": "Legal action selection",
          "source": {
            "path": "model/actions.py",
            "line": 252
          }
        },
        {
          "title": "Policy and serving signatures",
          "source": {
            "path": "model/export.py",
            "line": 28
          }
        },
        {
          "title": "Call-kind marginal",
          "link": "#architecture/head-response_action",
          "source": {
            "path": "model/actor.py",
            "line": 72
          }
        },
        {
          "title": "Chi-pattern marginal",
          "link": "#architecture/head-chi_pattern",
          "source": {
            "path": "model/actor.py",
            "line": 81
          }
        },
        {
          "title": "Active policy weights on critic candidates",
          "link": "#math/candidate-mass",
          "source": {
            "path": "model/critic.py",
            "line": 1408
          }
        },
        {
          "title": "Terminal payment probabilities",
          "link": "#outputs/terminal_payment_probabilities",
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        },
        {
          "title": "Final placement probabilities",
          "link": "#outputs/final_placement_probabilities",
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        },
        {
          "title": "Review outcome probabilities",
          "link": "#outputs/review_outcome_probabilities",
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        },
        {
          "title": "Settlement mean",
          "link": "#outputs/settlement_mean",
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        },
        {
          "title": "Settlement variance",
          "link": "#outputs/settlement_variance",
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        }
      ]
    },
    {
      "id": "riichi_action_logits",
      "dtype": "float32",
      "signatures": [
        "serving_default"
      ],
      "title": "Riichi decision marginal",
      "producer": "head-riichi_action",
      "inputs": [
        {
          "title": "Joint riichi policy",
          "detail": "Log-sum-exp across 37 cuts gives each of the two declaration choices.",
          "nodes": [
            "head-riichi"
          ],
          "source": {
            "path": "model/actor.py",
            "line": 66
          }
        }
      ],
      "kind": "derived marginal",
      "sharing": "No parameters; uses the shared policy scorer through its source branch.",
      "description": "Branch log-masses obtained by logsumexp over discard classes for dama and riichi; softmax yields the declaration marginal. Derived serving summary used by reviewer declaration grading and live action presentation; no separate learned parameters.",
      "source": {
        "path": "model/actor.py",
        "line": 71
      },
      "shape": [
        2
      ],
      "row_axis": "decision",
      "ownership": "Decision position",
      "execution": "One row per original decision.",
      "row_source": {
        "path": "model/actor.py",
        "line": 444
      },
      "group": "Actor",
      "multiplicity": "2 choices (dama / riichi)",
      "consumers": [
        {
          "title": "Prediction inspection",
          "source": {
            "path": "model/inference.py",
            "line": 118
          }
        }
      ]
    },
    {
      "id": "response_action_logits",
      "dtype": "float32",
      "signatures": [
        "serving_default"
      ],
      "title": "Call-kind marginal",
      "producer": "head-response_action",
      "inputs": [
        {
          "title": "Joint response policy",
          "detail": "The pass slot, all chi cuts, all pon cuts and daiminkan slot yield four action-type logits.",
          "nodes": [
            "head-response"
          ],
          "source": {
            "path": "model/actor.py",
            "line": 72
          }
        }
      ],
      "kind": "derived marginal",
      "sharing": "No parameters; uses the shared policy scorer through its source branch.",
      "description": "Branch log-masses for pass, chi, pon and open kan, computed by logsumexp over compatible joint response actions. Derived serving summary used by reviewer call grading and live action presentation; no separate learned parameters.",
      "source": {
        "path": "model/actor.py",
        "line": 72
      },
      "shape": [
        4
      ],
      "row_axis": "decision",
      "ownership": "Call choice and follow-up discard",
      "execution": "One response distribution per decision combines the call choice with zero to four follow-up discard distributions, one for each legal chi or pon.",
      "row_source": {
        "path": "model/actor.py",
        "line": 562
      },
      "group": "Actor",
      "multiplicity": "4 choices (pass / chi / pon / daiminkan)",
      "consumers": [
        {
          "title": "Prediction inspection",
          "source": {
            "path": "model/inference.py",
            "line": 118
          }
        }
      ]
    },
    {
      "id": "chi_pattern_logits",
      "dtype": "float32",
      "signatures": [
        "serving_default"
      ],
      "title": "Chi-pattern marginal",
      "producer": "head-chi_pattern",
      "inputs": [
        {
          "title": "Chi branches of the response policy",
          "detail": "Each of three chi-pattern logits sums over the 37 following discard choices.",
          "nodes": [
            "head-response"
          ],
          "source": {
            "path": "model/actor.py",
            "line": 81
          }
        }
      ],
      "kind": "derived marginal",
      "sharing": "No parameters; uses the shared policy scorer through its source branch.",
      "description": "Logsumexp aggregates over follow-up discards for each of the three chi patterns; softmax gives the pattern distribution conditional on the chi branch. Derived serving summary consumed by dynamic reviewer grading of the recorded chi pattern; no separate learned parameters.",
      "source": {
        "path": "model/actor.py",
        "line": 81
      },
      "shape": [
        3
      ],
      "row_axis": "decision",
      "ownership": "Call choice and follow-up discard",
      "execution": "One response distribution per decision combines the call choice with zero to four follow-up discard distributions, one for each legal chi or pon.",
      "row_source": {
        "path": "model/actor.py",
        "line": 562
      },
      "group": "Actor",
      "multiplicity": "3 chi patterns, each summing over 37 cuts",
      "consumers": [
        {
          "title": "Prediction inspection",
          "source": {
            "path": "model/inference.py",
            "line": 118
          }
        }
      ]
    },
    {
      "id": "event_logits",
      "dtype": "float32",
      "signatures": [],
      "title": "Events + 4 nagashi",
      "producer": "head-event",
      "inputs": [
        {
          "title": "49 attended readout vectors",
          "detail": "The shared readout produces 45 ordinary logits and four constrained nagashi signals. Qualifier masks derive 15 nagashi event logits.",
          "nodes": [
            "critic-result-attention"
          ],
          "source": {
            "path": "model/critic.py",
            "line": 895
          }
        }
      ],
      "kind": "learned readout with fixed subset expansion",
      "sharing": "Dense 32→1 shared across events after result attention.",
      "description": "The shared scalar readout produces 45 ordinary event logits and four nagashi logits. Their qualifier masks derive 15 additional combinations, giving 60 event probabilities.",
      "source": {
        "path": "model/critic.py",
        "line": 815
      },
      "shape": [
        60
      ],
      "row_axis": "evaluated candidate",
      "ownership": "Candidate at the decision",
      "execution": "One row per critic candidate. It reads the raw action state; call candidates retain their after-call hand/board evidence and original-window settlement legality. Supervised fitting selects the recorded action.",
      "row_source": {
        "path": "model/network.py",
        "line": 227
      },
      "group": "Critic",
      "multiplicity": "45 ordinary events + 15 derived nagashi qualifier sets",
      "consumers": [
        {
          "title": "Joint event probability",
          "link": "#architecture/settlement-decoder",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 523
          }
        },
        {
          "title": "Joint settlement law",
          "link": "#outputs/joint_probability",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 468
          }
        },
        {
          "title": "Critic support constraint loss",
          "link": "#outputs/critic_constraint_loss",
          "source": {
            "path": "model/critic.py",
            "line": 1097
          }
        }
      ]
    },
    {
      "id": "deposit_logits",
      "dtype": "float32",
      "signatures": [],
      "title": "Deposit mask",
      "producer": "head-deposit",
      "inputs": [
        {
          "title": "Event-conditioned deposit vectors",
          "detail": "One shared linear readout takes eight features for each of the 60 events and 16 deposit masks. These features combine the event vector, pooled player states and fixed role counts.",
          "nodes": [
            "critic-deposits"
          ],
          "source": {
            "path": "model/critic.py",
            "line": 1092
          }
        }
      ],
      "kind": "learned head",
      "sharing": "Dense 8→1 shared across event/mask pairs.",
      "description": "The same 8 → 1 affine readout scores each of the 16 depositor subsets for each terminal event.",
      "source": {
        "path": "model/critic.py",
        "line": 819
      },
      "shape": [
        60,
        16
      ],
      "row_axis": "evaluated candidate",
      "ownership": "Candidate at the decision",
      "execution": "One row per critic candidate. It reads the raw action state; call candidates retain their after-call hand/board evidence and original-window settlement legality. Supervised fitting selects the recorded action.",
      "row_source": {
        "path": "model/network.py",
        "line": 227
      },
      "group": "Critic",
      "multiplicity": "60 events × 16 depositor subsets",
      "consumers": [
        {
          "title": "Event-conditioned deposit probability",
          "link": "#architecture/settlement-decoder",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 523
          }
        },
        {
          "title": "Joint settlement law",
          "link": "#outputs/joint_probability",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 465
          }
        },
        {
          "title": "Critic support constraint loss",
          "link": "#outputs/critic_constraint_loss",
          "source": {
            "path": "model/critic.py",
            "line": 1097
          }
        }
      ]
    },
    {
      "id": "score_logits",
      "dtype": "float32",
      "signatures": [],
      "title": "Settlement value (han/fu)",
      "producer": "head-score",
      "inputs": [
        {
          "title": "Claim state with public scoring evidence",
          "detail": "Sixteen 96-channel claim states include public fu, bonus han, open-hand and riichi evidence.",
          "nodes": [
            "critic-claim-state"
          ],
          "source": {
            "path": "model/critic.py",
            "line": 971
          }
        },
        {
          "title": "Public fu, bonus and score support",
          "detail": "The readout also gets known meld fu. Dealer, open hand, riichi, bonus and yakuman feasibility constrain its 38 total-han/fu outcomes.",
          "nodes": [
            "inputs-parent-table",
            "inputs-parent-hand",
            "inputs-parent-actions"
          ],
          "source": {
            "path": "model/critic.py",
            "line": 972
          }
        }
      ],
      "kind": "learned head",
      "sharing": "Dense 96→38 shared across claims.",
      "description": "Single total han/fu distribution for each winning claim, conditioned on action, claimant, win method and public scoring evidence. Trained through observed settlement likelihood.",
      "source": {
        "path": "model/critic.py",
        "line": 972
      },
      "shape": [
        24,
        38
      ],
      "row_axis": "evaluated candidate",
      "ownership": "Candidate at the decision",
      "execution": "One row per critic candidate. It reads the raw action state; call candidates retain their after-call hand/board evidence and original-window settlement legality. Supervised fitting selects the recorded action.",
      "row_source": {
        "path": "model/network.py",
        "line": 227
      },
      "group": "Critic",
      "multiplicity": "24 payment cells × 38 total scoring classes",
      "consumers": [
        {
          "title": "Total-score probabilities",
          "link": "#architecture/settlement-decoder",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 523
          }
        },
        {
          "title": "Total settlement score probabilities",
          "link": "#outputs/score_probability",
          "source": {
            "path": "model/critic.py",
            "line": 1090
          }
        },
        {
          "title": "Critic support constraint loss",
          "link": "#outputs/critic_constraint_loss",
          "source": {
            "path": "model/critic.py",
            "line": 1097
          }
        }
      ]
    },
    {
      "id": "terminal_payment_probabilities",
      "dtype": "float32",
      "signatures": [
        "serving_default"
      ],
      "producer": "settlement-decoder",
      "inputs": [
        {
          "title": "Candidate payment marginals",
          "detail": "Each action has a 40-cell probability table indexed by amount. Serving embeds it in the full 4 × 4 × 4 grid.",
          "nodes": [
            "settlement-decoder"
          ],
          "source": {
            "path": "model/export.py",
            "line": 127
          },
          "outputs": [
            "payment_probability"
          ]
        },
        {
          "title": "Active policy weights",
          "detail": "The phase policy weights active candidates. The win phase gives its sole forecast unit mass.",
          "nodes": [
            "head-discard",
            "head-riichi",
            "head-response",
            "head-kan"
          ],
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        },
        {
          "title": "Decision phase and action IDs",
          "detail": "Filter the candidate IDs from the decision and possible calls to the decision phase.",
          "nodes": [
            "call-candidate-merge",
            "inputs-parent-actions"
          ],
          "source": {
            "path": "model/export.py",
            "line": 35
          }
        }
      ],
      "kind": "Derived output",
      "sharing": "Fixed computation across rows.",
      "description": "Policy-mixture categorical transfer marginals indexed by payment kind, payer, recipient and amount-support class. Consumed by reviewer/live typed-payment outcome estimates.",
      "shape": [
        4,
        4,
        4,
        60
      ],
      "title": "Terminal payment probabilities",
      "source": {
        "path": "model/export.py",
        "line": 178
      },
      "row_axis": "decision",
      "ownership": "Action mixture at the decision",
      "execution": "One row per decision after weighting active candidates by the phase policy. Each chi or pon candidate includes its follow-up discard.",
      "row_source": {
        "path": "model/export.py",
        "line": 147
      },
      "group": "Critic",
      "multiplicity": "4 payment kinds × 4 payers × 4 recipients × 60 amount classes",
      "consumers": [
        {
          "title": "Typed payment forecast",
          "source": {
            "path": "model/inference.py",
            "line": 193
          }
        }
      ]
    },
    {
      "id": "payment_values",
      "dtype": "float32",
      "signatures": [
        "serving_default"
      ],
      "producer": "settlement-decoder",
      "inputs": [
        {
          "title": "Public riichi pot",
          "detail": "The 56 fixed payment values are followed by four bank amounts derived from the decision position’s riichi pot.",
          "nodes": [
            "inputs-parent-table"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 1027
          },
          "fields": [
            "riichi_sticks"
          ]
        }
      ],
      "kind": "Derived output",
      "sharing": "Fixed computation across rows.",
      "description": "Per-position monetary support vector: fixed PAYMENT_VALUES followed by four public-state-dependent bank atoms. HTTP exposes these as structured_outcome.values; live UI aliases them as terminal_payment_values.",
      "shape": [
        60
      ],
      "title": "Payment values",
      "source": {
        "path": "model/export.py",
        "line": 164
      },
      "row_axis": "decision",
      "ownership": "Decision position",
      "execution": "One public support vector per original decision.",
      "row_source": {
        "path": "model/export.py",
        "line": 164
      },
      "group": "Critic",
      "multiplicity": "56 fixed point values + 4 pot-dependent bank amounts",
      "consumers": [
        {
          "title": "Typed payment amount support",
          "source": {
            "path": "model/inference.py",
            "line": 194
          }
        }
      ]
    },
    {
      "id": "final_placement_probabilities",
      "dtype": "float32",
      "signatures": [
        "serving_default"
      ],
      "producer": "continuation-payoffs",
      "inputs": [
        {
          "title": "Joint settlement probability",
          "detail": "The critic supplies the exact distribution over rule-enumerated settlements and deposit masks for each evaluated action.",
          "nodes": [
            "settlement-decoder"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 527
          },
          "outputs": [
            "joint_probability"
          ]
        },
        {
          "title": "Post-hand placements",
          "detail": "The fixed continuation mapping reads post-hand scores, ranks, support, dealer, hand number and pot.",
          "nodes": [
            "continuation-payoffs"
          ],
          "source": {
            "path": "model/export.py",
            "line": 78
          },
          "outputs": [
            "joint_scores",
            "joint_ranks",
            "joint_support"
          ]
        },
        {
          "title": "Active policy weights",
          "detail": "The phase policy weights active candidates. The win phase gives its sole forecast unit mass.",
          "nodes": [
            "head-discard",
            "head-riichi",
            "head-response",
            "head-kan"
          ],
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        },
        {
          "title": "Decision phase and action IDs",
          "detail": "Filter the candidate IDs from the decision and possible calls to the decision phase.",
          "nodes": [
            "call-candidate-merge",
            "inputs-parent-actions"
          ],
          "source": {
            "path": "model/export.py",
            "line": 35
          }
        }
      ],
      "kind": "Derived output",
      "sharing": "Fixed computation across rows.",
      "description": "Policy-mixture actor final-rank marginal obtained by integrating current-hand outcomes through the fixed continuation distribution. Consumed by the reviewer/live placement display; not an independent learned head.",
      "shape": [
        4
      ],
      "title": "Final placement probabilities",
      "source": {
        "path": "model/export.py",
        "line": 165
      },
      "row_axis": "decision",
      "ownership": "Action mixture at the decision",
      "execution": "One row per decision after weighting active candidates by the phase policy. Each chi or pon candidate includes its follow-up discard.",
      "row_source": {
        "path": "model/export.py",
        "line": 147
      },
      "group": "Critic",
      "multiplicity": "4 final placements for the acting player",
      "consumers": [
        {
          "title": "Prediction inspection",
          "source": {
            "path": "model/inference.py",
            "line": 118
          }
        }
      ]
    },
    {
      "id": "review_outcome_probabilities",
      "dtype": "float32",
      "signatures": [
        "serving_default"
      ],
      "producer": "settlement-decoder",
      "inputs": [
        {
          "title": "Joint settlement probability",
          "detail": "The critic supplies the exact distribution over rule-enumerated settlements and deposit masks for each evaluated action.",
          "nodes": [
            "settlement-decoder"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 527
          },
          "outputs": [
            "joint_probability"
          ]
        },
        {
          "title": "Settlement event categories",
          "detail": "The event ID in the rule support selects one of seven disjoint outcomes from the acting player’s perspective.",
          "nodes": [
            "settlement-decoder"
          ],
          "source": {
            "path": "model/export.py",
            "line": 120
          },
          "outputs": [
            "joint_support"
          ]
        },
        {
          "title": "Active policy weights",
          "detail": "The phase policy weights active candidates. The win phase gives its sole forecast unit mass.",
          "nodes": [
            "head-discard",
            "head-riichi",
            "head-response",
            "head-kan"
          ],
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        },
        {
          "title": "Decision phase and action IDs",
          "detail": "Filter the candidate IDs from the decision and possible calls to the decision phase.",
          "nodes": [
            "call-candidate-merge",
            "inputs-parent-actions"
          ],
          "source": {
            "path": "model/export.py",
            "line": 35
          }
        }
      ],
      "kind": "Derived output",
      "sharing": "Fixed computation across rows.",
      "description": "Policy-mixture marginal over seven disjoint event categories: deal-in, actor win, tenpai draw, noten draw, opponent tsumo, other ron and abort. Consumed by reviewer event summaries.",
      "shape": [
        7
      ],
      "title": "Review outcome probabilities",
      "source": {
        "path": "model/export.py",
        "line": 168
      },
      "row_axis": "decision",
      "ownership": "Action mixture at the decision",
      "execution": "One row per decision after weighting active candidates by the phase policy. Each chi or pon candidate includes its follow-up discard.",
      "row_source": {
        "path": "model/export.py",
        "line": 147
      },
      "group": "Critic",
      "multiplicity": "7 mutually exclusive hand-ending categories",
      "consumers": [
        {
          "title": "Prediction inspection",
          "source": {
            "path": "model/inference.py",
            "line": 118
          }
        }
      ]
    },
    {
      "id": "settlement_mean",
      "dtype": "float32",
      "signatures": [
        "serving_default"
      ],
      "producer": "settlement-decoder",
      "inputs": [
        {
          "title": "Joint settlement probability",
          "detail": "The critic supplies the exact distribution over rule-enumerated settlements and deposit masks for each evaluated action.",
          "nodes": [
            "settlement-decoder"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 527
          },
          "outputs": [
            "joint_probability"
          ]
        },
        {
          "title": "Joint transfer amounts",
          "detail": "The fixed payment classes and bank transfers reconstruct four player deltas and a balancing bank delta for every outcome.",
          "nodes": [
            "settlement-decoder"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 1078
          },
          "outputs": [
            "joint_classes",
            "joint_bank"
          ]
        },
        {
          "title": "Active policy weights",
          "detail": "The phase policy weights active candidates. The win phase gives its sole forecast unit mass.",
          "nodes": [
            "head-discard",
            "head-riichi",
            "head-response",
            "head-kan"
          ],
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        },
        {
          "title": "Decision phase and action IDs",
          "detail": "Filter the candidate IDs from the decision and possible calls to the decision phase.",
          "nodes": [
            "call-candidate-merge",
            "inputs-parent-actions"
          ],
          "source": {
            "path": "model/export.py",
            "line": 35
          }
        }
      ],
      "kind": "Derived output",
      "sharing": "Fixed computation across rows.",
      "description": "First moment of policy-mixture honba-free net transfers for actor-relative players 0–3 and bank. The underlying joint support retains inter-transfer covariance. HTTP structured_outcome.settlement_mean feeds reviewer actor-relative EV display.",
      "shape": [
        5
      ],
      "title": "Settlement mean",
      "source": {
        "path": "model/export.py",
        "line": 173
      },
      "row_axis": "decision",
      "ownership": "Action mixture at the decision",
      "execution": "One row per decision after weighting active candidates by the phase policy. Each chi or pon candidate includes its follow-up discard.",
      "row_source": {
        "path": "model/export.py",
        "line": 147
      },
      "group": "Critic",
      "multiplicity": "4 players + 1 riichi bank",
      "consumers": [
        {
          "title": "Settlement mean in the review",
          "source": {
            "path": "model/inference.py",
            "line": 195
          }
        }
      ]
    },
    {
      "id": "settlement_variance",
      "dtype": "float32",
      "signatures": [
        "serving_default"
      ],
      "producer": "settlement-decoder",
      "inputs": [
        {
          "title": "Joint settlement probability",
          "detail": "The critic supplies the exact distribution over rule-enumerated settlements and deposit masks for each evaluated action.",
          "nodes": [
            "settlement-decoder"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 527
          },
          "outputs": [
            "joint_probability"
          ]
        },
        {
          "title": "Joint transfer amounts",
          "detail": "The fixed payment classes and bank transfers reconstruct four player deltas and a balancing bank delta for every outcome.",
          "nodes": [
            "settlement-decoder"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 1078
          },
          "outputs": [
            "joint_classes",
            "joint_bank"
          ]
        },
        {
          "title": "Active policy weights",
          "detail": "The phase policy weights active candidates. The win phase gives its sole forecast unit mass.",
          "nodes": [
            "head-discard",
            "head-riichi",
            "head-response",
            "head-kan"
          ],
          "source": {
            "path": "model/export.py",
            "line": 148
          }
        },
        {
          "title": "Decision phase and action IDs",
          "detail": "Filter the candidate IDs from the decision and possible calls to the decision phase.",
          "nodes": [
            "call-candidate-merge",
            "inputs-parent-actions"
          ],
          "source": {
            "path": "model/export.py",
            "line": 35
          }
        }
      ],
      "kind": "Derived output",
      "sharing": "Fixed computation across rows.",
      "description": "Elementwise second central moment of policy-mixture honba-free player/bank net transfers: max(E[X²] − E[X]², 0). HTTP takes its square root into structured_outcome.settlement_stddev for uncertainty displays.",
      "shape": [
        5
      ],
      "title": "Settlement variance",
      "source": {
        "path": "model/export.py",
        "line": 174
      },
      "row_axis": "decision",
      "ownership": "Action mixture at the decision",
      "execution": "One row per decision after weighting active candidates by the phase policy. Each chi or pon candidate includes its follow-up discard.",
      "row_source": {
        "path": "model/export.py",
        "line": 147
      },
      "group": "Critic",
      "multiplicity": "4 players + 1 riichi bank",
      "consumers": [
        {
          "title": "Settlement standard deviation",
          "source": {
            "path": "model/inference.py",
            "line": 196
          }
        }
      ]
    },
    {
      "id": "critic_action_indices",
      "dtype": "int32",
      "signatures": [
        "serving_default"
      ],
      "producer": "call-candidate-merge",
      "inputs": [
        {
          "title": "Decision phase and action IDs",
          "detail": "Filter the candidate IDs from the decision and possible calls to the decision phase.",
          "nodes": [
            "call-candidate-merge",
            "inputs-parent-actions"
          ],
          "source": {
            "path": "model/export.py",
            "line": 35
          }
        }
      ],
      "kind": "Derived output",
      "sharing": "Fixed computation across rows.",
      "description": "Sparse row index pairs [input-position index, canonical critic-action index]. All other critic_* outputs share this row ordering. HTTP joins candidate point predictions to original actions; reviewer/live code uses the resulting action_values IDs.",
      "shape": [
        2
      ],
      "title": "Critic action indices",
      "source": {
        "path": "model/export.py",
        "line": 193
      },
      "row_axis": "active candidate",
      "ownership": "Legal action at the decision",
      "execution": "One row per candidate legal at the decision, including call-and-discard choices. The win/pass phase uses one current-hand forecast.",
      "row_source": {
        "path": "model/export.py",
        "line": 36
      },
      "group": "Critic",
      "multiplicity": "2 integers (decision row, canonical action ID 0–294)",
      "consumers": [
        {
          "title": "Join action values to decisions",
          "source": {
            "path": "model/inference.py",
            "line": 186
          }
        }
      ]
    },
    {
      "id": "critic_expected_points",
      "dtype": "float32",
      "signatures": [
        "serving_default"
      ],
      "producer": "settlement-decoder",
      "inputs": [
        {
          "title": "Joint settlement probability",
          "detail": "The critic supplies the exact distribution over rule-enumerated settlements and deposit masks for each evaluated action.",
          "nodes": [
            "settlement-decoder"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 527
          },
          "outputs": [
            "joint_probability"
          ]
        },
        {
          "title": "Post-settlement scores",
          "detail": "The score deltas retain the player and riichi-bank transfers and honba for each settlement.",
          "nodes": [
            "settlement-decoder"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 343
          },
          "outputs": [
            "joint_scores"
          ]
        },
        {
          "title": "Current scores",
          "detail": "Gather raw East/South/West/North point totals by seat_wind into actor-relative order for settlement.",
          "nodes": [
            "inputs-parent-table"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 316
          },
          "fields": [
            "scores",
            "seat_wind"
          ]
        },
        {
          "title": "Decision phase and action IDs",
          "detail": "Filter the candidate IDs from the decision and possible calls to the decision phase.",
          "nodes": [
            "call-candidate-merge",
            "inputs-parent-actions"
          ],
          "source": {
            "path": "model/export.py",
            "line": 35
          }
        }
      ],
      "kind": "Derived output",
      "sharing": "Fixed computation across rows.",
      "description": "Per-active-candidate expected post-hand score minus current score for four actor-relative players, in points. HTTP action_values.expected_points feeds reviewer action deltas and live decision timing.",
      "shape": [
        4
      ],
      "title": "Critic expected points",
      "source": {
        "path": "model/export.py",
        "line": 139
      },
      "row_axis": "active candidate",
      "ownership": "Legal action at the decision",
      "execution": "One row per candidate legal at the decision, including call-and-discard choices. The win/pass phase uses one current-hand forecast.",
      "row_source": {
        "path": "model/export.py",
        "line": 36
      },
      "group": "Critic",
      "multiplicity": "4 actor-relative player point deltas per active action",
      "consumers": [
        {
          "title": "Expected points by action",
          "source": {
            "path": "model/inference.py",
            "line": 184
          }
        }
      ]
    },
    {
      "id": "score_probability",
      "dtype": "float32",
      "signatures": [],
      "producer": "settlement-decoder",
      "inputs": [
        {
          "title": "Total settlement score",
          "detail": "Softmax over 38 total han/fu classes for each winning claim.",
          "nodes": [
            "head-score"
          ],
          "source": {
            "path": "model/critic.py",
            "line": 1090
          },
          "outputs": [
            "score_logits"
          ]
        }
      ],
      "kind": "Derived output",
      "sharing": "Fixed computation across rows.",
      "description": "One row per critic candidate. It reads the raw action state; call candidates retain their after-call hand/board evidence and original-window settlement legality. Supervised fitting selects the recorded action.",
      "source": {
        "path": "model/critic.py",
        "line": 1090
      },
      "shape": [
        24,
        38
      ],
      "title": "Total settlement score probabilities",
      "row_axis": "evaluated candidate",
      "ownership": "Candidate at the decision",
      "execution": "One row per critic candidate. It reads the raw action state; call candidates retain their after-call hand/board evidence and original-window settlement legality. Supervised fitting selects the recorded action.",
      "row_source": {
        "path": "model/network.py",
        "line": 227
      },
      "group": "Critic",
      "multiplicity": "24 winning payment cells × 38 final scoring classes",
      "consumers": [
        {
          "title": "Observed settlement likelihood",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 624
          },
          "link": "#math/payment-likelihood"
        },
        {
          "title": "Joint settlement law",
          "link": "#outputs/joint_probability",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 276
          }
        }
      ]
    },
    {
      "id": "joint_probability",
      "dtype": "float32",
      "signatures": [],
      "producer": "settlement-decoder",
      "inputs": [
        {
          "title": "Settlement event logits",
          "detail": "Apply event legality and normalize over 60 mutually exclusive joint endings.",
          "nodes": [
            "head-event"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 468
          }
        },
        {
          "title": "Event-conditioned deposit logits",
          "detail": "Normalize the 16 deposit patterns separately for each legal event.",
          "nodes": [
            "head-deposit"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 465
          }
        },
        {
          "title": "Claim score probabilities",
          "detail": "Gather the required one or two claimant likelihoods for each enumerated settlement.",
          "nodes": [
            "settlement-decoder"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 276
          },
          "outputs": [
            "score_probability",
            "pao_logits"
          ]
        },
        {
          "title": "Public event support at the decision",
          "detail": "Public board and action facts at the decision constrain the combinations of winners, ready seats and paid deposits.",
          "nodes": [
            "inputs-parent-table",
            "inputs-parent-actions",
            "inputs-parent-hand",
            "inputs-parent-opponents"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 463
          }
        },
        {
          "title": "Constrained responsibility allocation",
          "detail": "Only true-yakuman score mass can redirect through a responsible payer.",
          "nodes": [
            "head-pao"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 276
          },
          "outputs": [
            "pao_logits"
          ]
        }
      ],
      "kind": "Derived output",
      "sharing": "Fixed computation across rows.",
      "description": "One row per critic candidate. It reads the raw action state; call candidates retain their after-call hand/board evidence and original-window settlement legality. Supervised fitting selects the recorded action.",
      "source": {
        "path": "model/joint_settlement.py",
        "line": 527
      },
      "shape": [
        12863,
        16
      ],
      "title": "Joint settlement law",
      "row_axis": "evaluated candidate",
      "ownership": "Candidate at the decision",
      "execution": "One row per critic candidate. It reads the raw action state; call candidates retain their after-call hand/board evidence and original-window settlement legality. Supervised fitting selects the recorded action.",
      "row_source": {
        "path": "model/network.py",
        "line": 227
      },
      "group": "Critic",
      "multiplicity": "12,863 settlements per dealer × 16 deposit masks",
      "consumers": [
        {
          "title": "Observed settlement likelihood",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 624
          },
          "link": "#math/payment-likelihood"
        },
        {
          "title": "Final placement probabilities",
          "link": "#outputs/final_placement_probabilities",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 527
          }
        },
        {
          "title": "Review outcome probabilities",
          "link": "#outputs/review_outcome_probabilities",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 527
          }
        },
        {
          "title": "Settlement mean",
          "link": "#outputs/settlement_mean",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 527
          }
        },
        {
          "title": "Settlement variance",
          "link": "#outputs/settlement_variance",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 527
          }
        },
        {
          "title": "Critic expected points",
          "link": "#outputs/critic_expected_points",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 527
          }
        },
        {
          "title": "Candidate payment marginals",
          "link": "#outputs/payment_probability",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 527
          }
        },
        {
          "title": "Expected action utility (Q)",
          "link": "#outputs/action_values",
          "source": {
            "path": "model/critic.py",
            "line": 1141
          }
        }
      ]
    },
    {
      "id": "joint_classes",
      "dtype": "int64",
      "signatures": [],
      "producer": "settlement-decoder",
      "inputs": [
        {
          "title": "Dealer at the decision",
          "detail": "Dealer-relative seat indexes the precomputed per-dealer block of settlement support.",
          "nodes": [
            "inputs-parent-table"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 333
          },
          "fields": [
            "dealer_relative_seat"
          ]
        }
      ],
      "kind": "Derived output",
      "sharing": "Fixed computation across rows.",
      "description": "One row per critic candidate. It reads the raw action state; call candidates retain their after-call hand/board evidence and original-window settlement legality. Supervised fitting selects the recorded action.",
      "source": {
        "path": "model/joint_settlement.py",
        "line": 360
      },
      "shape": [
        12863,
        36
      ],
      "title": "Settlement payment classes",
      "row_axis": "evaluated candidate",
      "ownership": "Candidate at the decision",
      "execution": "One row per critic candidate. It reads the raw action state; call candidates retain their after-call hand/board evidence and original-window settlement legality. Supervised fitting selects the recorded action.",
      "row_source": {
        "path": "model/network.py",
        "line": 227
      },
      "group": "Critic",
      "multiplicity": "12,863 settlements per dealer × 36 directed payment cells",
      "consumers": [
        {
          "title": "Settlement mean",
          "link": "#outputs/settlement_mean",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 1078
          }
        },
        {
          "title": "Settlement variance",
          "link": "#outputs/settlement_variance",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 1078
          }
        },
        {
          "title": "Candidate payment marginals",
          "link": "#outputs/payment_probability",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 334
          }
        }
      ]
    },
    {
      "id": "joint_support",
      "dtype": "int64",
      "signatures": [],
      "producer": "settlement-decoder",
      "inputs": [
        {
          "title": "Dealer at the decision",
          "detail": "Dealer-relative seat indexes the precomputed per-dealer block of settlement support.",
          "nodes": [
            "inputs-parent-table"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 333
          },
          "fields": [
            "dealer_relative_seat"
          ]
        }
      ],
      "kind": "Derived output",
      "sharing": "Fixed computation across rows.",
      "description": "One row per critic candidate. It reads the raw action state; call candidates retain their after-call hand/board evidence and original-window settlement legality. Supervised fitting selects the recorded action.",
      "source": {
        "path": "model/joint_settlement.py",
        "line": 364
      },
      "shape": [
        12863,
        6
      ],
      "title": "Settlement support",
      "row_axis": "evaluated candidate",
      "ownership": "Candidate at the decision",
      "execution": "One row per critic candidate. It reads the raw action state; call candidates retain their after-call hand/board evidence and original-window settlement legality. Supervised fitting selects the recorded action.",
      "row_source": {
        "path": "model/network.py",
        "line": 227
      },
      "group": "Critic",
      "multiplicity": "12,863 settlements per dealer × 6 descriptors",
      "consumers": [
        {
          "title": "Final placement probabilities",
          "link": "#outputs/final_placement_probabilities",
          "source": {
            "path": "model/export.py",
            "line": 78
          }
        },
        {
          "title": "Review outcome probabilities",
          "link": "#outputs/review_outcome_probabilities",
          "source": {
            "path": "model/export.py",
            "line": 120
          }
        },
        {
          "title": "Riichi-bank movements",
          "link": "#outputs/joint_bank",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 335
          }
        },
        {
          "title": "Candidate payment marginals",
          "link": "#outputs/payment_probability",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 335
          }
        }
      ]
    },
    {
      "id": "joint_bank",
      "dtype": "float32",
      "signatures": [],
      "producer": "settlement-decoder",
      "inputs": [
        {
          "title": "Rule-enumerated settlements",
          "detail": "The support records each ending, winner bits, draw mask, pot collector, dealer and event index.",
          "nodes": [
            "settlement-decoder"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 335
          },
          "outputs": [
            "joint_support"
          ]
        },
        {
          "title": "Public riichi pot",
          "detail": "The 56 fixed payment values are followed by four bank amounts derived from the decision position’s riichi pot.",
          "nodes": [
            "inputs-parent-table"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 1027
          },
          "fields": [
            "riichi_sticks"
          ]
        }
      ],
      "kind": "Derived output",
      "sharing": "Fixed computation across rows.",
      "description": "One row per critic candidate. It reads the raw action state; call candidates retain their after-call hand/board evidence and original-window settlement legality. Supervised fitting selects the recorded action.",
      "source": {
        "path": "model/joint_settlement.py",
        "line": 361
      },
      "shape": [
        12863,
        16,
        4
      ],
      "title": "Riichi-bank movements",
      "row_axis": "evaluated candidate",
      "ownership": "Candidate at the decision",
      "execution": "One row per critic candidate. It reads the raw action state; call candidates retain their after-call hand/board evidence and original-window settlement legality. Supervised fitting selects the recorded action.",
      "row_source": {
        "path": "model/network.py",
        "line": 227
      },
      "group": "Critic",
      "multiplicity": "12,863 settlements per dealer × 16 deposit masks × 4 players",
      "consumers": [
        {
          "title": "Settlement mean",
          "link": "#outputs/settlement_mean",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 1078
          }
        },
        {
          "title": "Settlement variance",
          "link": "#outputs/settlement_variance",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 1078
          }
        },
        {
          "title": "Post-hand scores",
          "link": "#outputs/joint_scores",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 336
          }
        }
      ]
    },
    {
      "id": "joint_scores",
      "dtype": "float32",
      "signatures": [],
      "producer": "settlement-decoder",
      "inputs": [
        {
          "title": "Current scores",
          "detail": "Gather raw East/South/West/North point totals by seat_wind into actor-relative order for settlement.",
          "nodes": [
            "inputs-parent-table"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 316
          },
          "fields": [
            "scores",
            "seat_wind"
          ]
        },
        {
          "title": "Dealer at the decision",
          "detail": "Dealer-relative seat indexes the precomputed per-dealer block of settlement support.",
          "nodes": [
            "inputs-parent-table"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 333
          },
          "fields": [
            "dealer_relative_seat"
          ]
        },
        {
          "title": "Bank movements",
          "detail": "Public pot and the depositor mask determine each player’s payment into or claim on the bank.",
          "nodes": [
            "settlement-decoder"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 336
          },
          "outputs": [
            "joint_bank"
          ]
        },
        {
          "title": "Honba at the decision",
          "detail": "The repeat counter scales the per-cell honba transfers before scoring each outcome.",
          "nodes": [
            "inputs-parent-table"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 340
          },
          "fields": [
            "honba"
          ]
        }
      ],
      "kind": "Derived output",
      "sharing": "Fixed computation across rows.",
      "description": "One row per critic candidate. It reads the raw action state; call candidates retain their after-call hand/board evidence and original-window settlement legality. Supervised fitting selects the recorded action.",
      "source": {
        "path": "model/joint_settlement.py",
        "line": 362
      },
      "shape": [
        12863,
        16,
        4
      ],
      "title": "Post-hand scores",
      "row_axis": "evaluated candidate",
      "ownership": "Candidate at the decision",
      "execution": "One row per critic candidate. It reads the raw action state; call candidates retain their after-call hand/board evidence and original-window settlement legality. Supervised fitting selects the recorded action.",
      "row_source": {
        "path": "model/network.py",
        "line": 227
      },
      "group": "Critic",
      "multiplicity": "12,863 settlements per dealer × 16 deposit masks × 4 players",
      "consumers": [
        {
          "title": "Final placement probabilities",
          "link": "#outputs/final_placement_probabilities",
          "source": {
            "path": "model/export.py",
            "line": 78
          }
        },
        {
          "title": "Critic expected points",
          "link": "#outputs/critic_expected_points",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 343
          }
        },
        {
          "title": "Post-hand placements",
          "link": "#outputs/joint_ranks",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 343
          }
        }
      ]
    },
    {
      "id": "joint_ranks",
      "dtype": "int64",
      "signatures": [],
      "producer": "settlement-decoder",
      "inputs": [
        {
          "title": "Post-settlement scores",
          "detail": "The score deltas retain the player and riichi-bank transfers and honba for each settlement.",
          "nodes": [
            "settlement-decoder"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 343
          },
          "outputs": [
            "joint_scores"
          ]
        },
        {
          "title": "Seat priority",
          "detail": "Original dealer priority breaks ties between equal post-settlement scores.",
          "nodes": [
            "inputs-parent-table"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 344
          },
          "fields": [
            "dealer_relative_seat",
            "hands_remaining"
          ]
        }
      ],
      "kind": "Derived output",
      "sharing": "Fixed computation across rows.",
      "description": "One row per critic candidate. It reads the raw action state; call candidates retain their after-call hand/board evidence and original-window settlement legality. Supervised fitting selects the recorded action.",
      "source": {
        "path": "model/joint_settlement.py",
        "line": 363
      },
      "shape": [
        12863,
        16,
        4
      ],
      "title": "Post-hand placements",
      "row_axis": "evaluated candidate",
      "ownership": "Candidate at the decision",
      "execution": "One row per critic candidate. It reads the raw action state; call candidates retain their after-call hand/board evidence and original-window settlement legality. Supervised fitting selects the recorded action.",
      "row_source": {
        "path": "model/network.py",
        "line": 227
      },
      "group": "Critic",
      "multiplicity": "12,863 settlements per dealer × 16 deposit masks × 4 players",
      "consumers": [
        {
          "title": "Final placement probabilities",
          "link": "#outputs/final_placement_probabilities",
          "source": {
            "path": "model/export.py",
            "line": 78
          }
        }
      ]
    },
    {
      "id": "payment_probability",
      "dtype": "float32",
      "signatures": [],
      "producer": "settlement-decoder",
      "inputs": [
        {
          "title": "Joint settlement probability",
          "detail": "The critic supplies the exact distribution over rule-enumerated settlements and deposit masks for each evaluated action.",
          "nodes": [
            "settlement-decoder"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 527
          },
          "outputs": [
            "joint_probability"
          ]
        },
        {
          "title": "Directed transfer classes",
          "detail": "A rule table gives one base payment amount class per directed transfer cell for each supported settlement.",
          "nodes": [
            "settlement-decoder"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 334
          },
          "outputs": [
            "joint_classes"
          ]
        },
        {
          "title": "Rule-enumerated settlements",
          "detail": "The support records each ending, winner bits, draw mask, pot collector, dealer and event index.",
          "nodes": [
            "settlement-decoder"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 335
          },
          "outputs": [
            "joint_support"
          ]
        }
      ],
      "kind": "Derived output",
      "sharing": "Fixed computation across rows.",
      "description": "One row per critic candidate. It reads the raw action state; call candidates retain their after-call hand/board evidence and original-window settlement legality. Supervised fitting selects the recorded action.",
      "source": {
        "path": "model/critic.py",
        "line": 1122
      },
      "shape": [
        40,
        60
      ],
      "title": "Candidate payment marginals",
      "row_axis": "evaluated candidate",
      "ownership": "Candidate at the decision",
      "execution": "One row per critic candidate. It reads the raw action state; call candidates retain their after-call hand/board evidence and original-window settlement legality. Supervised fitting selects the recorded action.",
      "row_source": {
        "path": "model/network.py",
        "line": 227
      },
      "group": "Critic",
      "multiplicity": "40 active payment cells × 60 amount classes",
      "consumers": [
        {
          "title": "Terminal payment probabilities",
          "link": "#outputs/terminal_payment_probabilities",
          "source": {
            "path": "model/export.py",
            "line": 127
          }
        }
      ]
    },
    {
      "id": "belief_constraint_loss",
      "dtype": "float32",
      "signatures": [],
      "producer": "belief-constraints",
      "inputs": [
        {
          "title": "Raw and constrained shanten/count logits",
          "detail": "KL to the stopped, constrained distributions is averaged across opponents and tile-count channels.",
          "nodes": [
            "belief-constraints"
          ],
          "source": {
            "path": "model/beliefs.py",
            "line": 502
          }
        }
      ],
      "kind": "Training term",
      "sharing": "Fixed computation across rows.",
      "description": "One aggregate constraint value per original decision. The policy also computes penalties on hypothetical after-call positions.",
      "source": {
        "path": "model/beliefs.py",
        "line": 502
      },
      "shape": [],
      "title": "Shanten and count constraint loss",
      "row_axis": "decision",
      "ownership": "Decision position",
      "execution": "One aggregate constraint value per original decision. The policy also computes penalties on hypothetical after-call positions.",
      "row_source": {
        "path": "model/network.py",
        "line": 161
      },
      "group": "Training",
      "multiplicity": "1 scalar per decision",
      "consumers": [
        {
          "title": "Actor structural constraints",
          "link": "#outputs/constraint_loss",
          "source": {
            "path": "model/network.py",
            "line": 161
          }
        }
      ]
    },
    {
      "id": "route_constraint_loss",
      "dtype": "float32",
      "signatures": [],
      "producer": "actor-candidate-aux",
      "inputs": [
        {
          "title": "Raw and supported route logits",
          "detail": "A stopped constrained target supervises the three raw route logits. Candidate penalties are averaged per decision.",
          "nodes": [
            "actor-candidate-aux"
          ],
          "source": {
            "path": "model/candidate_predictions.py",
            "line": 18
          }
        }
      ],
      "kind": "Training term",
      "sharing": "Fixed computation across rows.",
      "description": "One aggregate constraint value per original decision. The policy also computes penalties on hypothetical after-call positions.",
      "source": {
        "path": "model/candidate_predictions.py",
        "line": 16
      },
      "shape": [],
      "title": "Route-support constraint loss",
      "row_axis": "decision",
      "ownership": "Decision position",
      "execution": "One aggregate constraint value per original decision. The policy also computes penalties on hypothetical after-call positions.",
      "row_source": {
        "path": "model/network.py",
        "line": 161
      },
      "group": "Training",
      "multiplicity": "1 scalar per decision",
      "consumers": [
        {
          "title": "Actor structural constraints",
          "link": "#outputs/constraint_loss",
          "source": {
            "path": "model/network.py",
            "line": 161
          }
        }
      ]
    },
    {
      "id": "round_completion_yaku_logits_constraint_loss",
      "dtype": "float32",
      "signatures": [],
      "producer": "actor-completion",
      "inputs": [
        {
          "title": "Raw and supported completion yaku",
          "detail": "Binary divergence to the stopped constrained yaku target is averaged across players and win kinds.",
          "nodes": [
            "actor-completion"
          ],
          "source": {
            "path": "model/beliefs.py",
            "line": 556
          }
        }
      ],
      "kind": "Training term",
      "sharing": "Fixed computation across rows.",
      "description": "One aggregate constraint value per original decision. The policy also computes penalties on hypothetical after-call positions.",
      "source": {
        "path": "model/beliefs.py",
        "line": 554
      },
      "shape": [],
      "title": "Completion yaku constraint loss",
      "row_axis": "decision",
      "ownership": "Decision position",
      "execution": "One aggregate constraint value per original decision. The policy also computes penalties on hypothetical after-call positions.",
      "row_source": {
        "path": "model/network.py",
        "line": 161
      },
      "group": "Training",
      "multiplicity": "1 scalar per decision",
      "consumers": [
        {
          "title": "Actor structural constraints",
          "link": "#outputs/constraint_loss",
          "source": {
            "path": "model/network.py",
            "line": 161
          }
        }
      ]
    },
    {
      "id": "round_completion_score_logits_constraint_loss",
      "dtype": "float32",
      "signatures": [],
      "producer": "actor-completion",
      "inputs": [
        {
          "title": "Raw and supported completion han/fu",
          "detail": "Categorical divergence to the constrained score target is averaged across players and win kinds.",
          "nodes": [
            "actor-completion"
          ],
          "source": {
            "path": "model/beliefs.py",
            "line": 554
          }
        }
      ],
      "kind": "Training term",
      "sharing": "Fixed computation across rows.",
      "description": "One aggregate constraint value per original decision. The policy also computes penalties on hypothetical after-call positions.",
      "source": {
        "path": "model/beliefs.py",
        "line": 554
      },
      "shape": [],
      "title": "Completion score constraint loss",
      "row_axis": "decision",
      "ownership": "Decision position",
      "execution": "One aggregate constraint value per original decision. The policy also computes penalties on hypothetical after-call positions.",
      "row_source": {
        "path": "model/network.py",
        "line": 161
      },
      "group": "Training",
      "multiplicity": "1 scalar per decision",
      "consumers": [
        {
          "title": "Actor structural constraints",
          "link": "#outputs/constraint_loss",
          "source": {
            "path": "model/network.py",
            "line": 161
          }
        }
      ]
    },
    {
      "id": "constraint_loss",
      "dtype": "float32",
      "signatures": [],
      "producer": "actor",
      "inputs": [
        {
          "title": "Four per-board constraint terms",
          "detail": "Sum the belief, route, completion-yaku and completion-score divergences.",
          "nodes": [
            "belief-constraints",
            "actor-candidate-aux",
            "actor-completion"
          ],
          "source": {
            "path": "model/network.py",
            "line": 161
          },
          "outputs": [
            "belief_constraint_loss",
            "route_constraint_loss",
            "round_completion_yaku_logits_constraint_loss",
            "round_completion_score_logits_constraint_loss"
          ]
        }
      ],
      "kind": "Training term",
      "sharing": "Fixed computation across rows.",
      "description": "Per-position sum of belief, route and completion-yaku/score projection divergences. The MMD actor objective applies coefficient 0.01.",
      "shape": [],
      "title": "Actor structural constraints",
      "source": {
        "path": "model/network.py",
        "line": 161
      },
      "row_axis": "decision",
      "ownership": "Decision position",
      "execution": "One aggregate constraint value per original decision. The policy also computes penalties on hypothetical after-call positions.",
      "row_source": {
        "path": "model/network.py",
        "line": 161
      },
      "group": "Training",
      "multiplicity": "1 scalar per decision",
      "consumers": [
        {
          "title": "Actor structural loss",
          "source": {
            "path": "training/corrections/trainer.py",
            "line": 101
          },
          "link": "#training/actor"
        }
      ]
    },
    {
      "id": "critic_constraint_loss",
      "dtype": "float32",
      "signatures": [],
      "producer": "critic",
      "inputs": [
        {
          "title": "Raw and constrained critic factors",
          "detail": "Compare raw versus constrained score, event and event-conditioned deposit distributions. Public legality fixes the targets.",
          "nodes": [
            "head-score",
            "head-event",
            "head-deposit"
          ],
          "source": {
            "path": "model/critic.py",
            "line": 1097
          }
        },
        {
          "title": "Public event support at the decision",
          "detail": "Public board and action facts at the decision constrain the combinations of winners, ready seats and paid deposits.",
          "nodes": [
            "inputs-parent-table",
            "inputs-parent-actions",
            "inputs-parent-hand",
            "inputs-parent-opponents"
          ],
          "source": {
            "path": "model/joint_settlement.py",
            "line": 463
          }
        }
      ],
      "kind": "Training term",
      "sharing": "Fixed computation across rows.",
      "description": "One row per critic candidate. It reads the raw action state; call candidates retain their after-call hand/board evidence and original-window settlement legality. Supervised fitting selects the recorded action.",
      "source": {
        "path": "model/critic.py",
        "line": 1097
      },
      "shape": [],
      "title": "Critic support constraint loss",
      "row_axis": "evaluated candidate",
      "ownership": "Candidate at the decision",
      "execution": "One row per critic candidate. It reads the raw action state; call candidates retain their after-call hand/board evidence and original-window settlement legality. Supervised fitting selects the recorded action.",
      "row_source": {
        "path": "model/network.py",
        "line": 227
      },
      "group": "Training",
      "multiplicity": "1 scalar per evaluated action",
      "consumers": [
        {
          "title": "Critic training statistics",
          "link": "#outputs/critic_statistics",
          "source": {
            "path": "model/critic.py",
            "line": 1185
          }
        }
      ]
    },
    {
      "id": "critic_statistics",
      "dtype": "float32",
      "signatures": [],
      "producer": "critic",
      "inputs": [
        {
          "title": "Recorded-action settlement distribution",
          "detail": "Recorded-action targets supply settlement NLL and directly supervised nagashi marginals.",
          "nodes": [
            "settlement-decoder",
            "call-candidate-merge"
          ],
          "source": {
            "path": "model/critic.py",
            "line": 1170
          }
        },
        {
          "title": "Structural constraints",
          "detail": "The batch aggregates score, event and deposit constraint penalties on valid rows.",
          "nodes": [
            "settlement-decoder",
            "head-event"
          ],
          "source": {
            "path": "model/critic.py",
            "line": 1185
          },
          "outputs": [
            "critic_constraint_loss"
          ]
        }
      ],
      "kind": "Training statistic",
      "sharing": "Fixed computation across rows.",
      "description": "One 9 × 2 matrix per batch sums each metric’s numerator and denominator over eligible recorded actions.",
      "source": {
        "path": "model/network.py",
        "line": 256
      },
      "shape": [
        5,
        2
      ],
      "title": "Critic training statistics",
      "row_axis": "batch",
      "ownership": "Recorded actions across the batch",
      "execution": "One 9 × 2 matrix per batch sums each metric’s numerator and denominator over eligible recorded actions.",
      "row_source": {
        "path": "model/critic.py",
        "line": 1189
      },
      "group": "Training",
      "multiplicity": "5 statistics × 2 values (weighted numerator, denominator) per batch",
      "consumers": [
        {
          "title": "Observed settlement fit",
          "source": {
            "path": "training/trainer.py",
            "line": 130
          },
          "link": "#training/critic"
        }
      ]
    },
    {
      "id": "action_values",
      "dtype": "float32",
      "signatures": [],
      "producer": "continuation-payoffs",
      "inputs": [
        {
          "title": "Action-conditioned settlement mass",
          "detail": "The candidate critic supplies the probability of each outcome. Its expectation against the payoff table is stopped before learner use.",
          "nodes": [
            "settlement-decoder"
          ],
          "source": {
            "path": "model/critic.py",
            "line": 1141
          },
          "outputs": [
            "joint_probability"
          ]
        },
        {
          "title": "Fixed continuation payoffs",
          "detail": "Settlement scores and placements give the fixed J for each outcome. The same public payoff table is reused for candidate actions at the same decision.",
          "nodes": [
            "continuation-payoffs"
          ],
          "source": {
            "path": "training/trainer.py",
            "line": 50
          }
        },
        {
          "title": "Decision and action indices",
          "detail": "Each evaluated action supplies a (decision row, action ID) pair for the dense Q grid.",
          "nodes": [
            "call-candidate-merge"
          ],
          "source": {
            "path": "training/trainer.py",
            "line": 91
          }
        }
      ],
      "kind": "Detached learner output",
      "sharing": "Fixed computation across rows.",
      "description": "One 295-slot action grid per decision. Each evaluated candidate value fills the matching decision and action slot. Unused slots hold zero.",
      "source": {
        "path": "training/trainer.py",
        "line": 38
      },
      "shape": [
        295
      ],
      "title": "Expected action utility (Q)",
      "row_axis": "decision",
      "ownership": "Action grid at the decision",
      "execution": "One 295-slot action grid per decision. Each evaluated candidate value fills the matching decision and action slot. Unused slots hold zero.",
      "row_source": {
        "path": "training/trainer.py",
        "line": 88
      },
      "group": "Training",
      "multiplicity": "295 action slots per decision, 1 detached Q per evaluated action",
      "consumers": [
        {
          "title": "Q-weighted expert update",
          "source": {
            "path": "training/imitation.py",
            "line": 125
          },
          "link": "#training/expert-joint"
        },
        {
          "title": "MMD actor update",
          "source": {
            "path": "training/corrections/trainer.py",
            "line": 76
          },
          "link": "#training/actor"
        }
      ]
    },
    {
      "id": "ron_eligibility_logits",
      "dtype": "float32",
      "signatures": [],
      "title": "Ron eligibility",
      "producer": "head-ron-eligibility",
      "inputs": [
        {
          "nodes": [
            "board-output"
          ],
          "title": "Observed board",
          "detail": "Current hand and observed table produce one shared opponent/tile eligibility table.",
          "source": {
            "path": "model/network.py",
            "line": 44
          }
        },
        {
          "nodes": [
            "completion-evidence"
          ],
          "title": "Opponent yaku hidden state",
          "detail": "Attached 64-channel evidence state per opponent. Ron supervision trains the hidden projection and river features directly.",
          "source": {
            "path": "model/network.py",
            "line": 50
          }
        },
        {
          "nodes": [
            "head-completion-yaku"
          ],
          "title": "Opponent ron-yaku probabilities",
          "detail": "Detached 23-category ron probabilities per opponent from the supported completion-yaku head.",
          "source": {
            "path": "model/network.py",
            "line": 50
          },
          "detached": true
        },
        {
          "nodes": [
            "head-counts"
          ],
          "via": [
            "completion-evidence"
          ],
          "title": "Detached opponent counts",
          "detail": "Count probabilities supply suit/dora/red evidence for the attached yaku hidden state; ron gradients stop at the count predictions.",
          "detached": true,
          "source": {
            "path": "model/beliefs.py",
            "line": 529
          }
        }
      ],
      "kind": "learned head",
      "sharing": "Shared Dense599→128 + GELU → Dense34 across the three opponents.",
      "description": "Eligibility table inferred once from the observed board and reused across ordinary, riichi and call-discard alternatives.",
      "source": {
        "path": "model/network.py",
        "line": 44
      },
      "shape": [
        3,
        34
      ],
      "row_axis": "decision",
      "ownership": "Observed decision; shared with call alternatives",
      "execution": "Infer once from the original observed board. Hypothetical chi/pon branches gather the same parent posterior by owner.",
      "row_source": {
        "path": "model/actor.py",
        "line": 479
      },
      "group": "Beliefs",
      "multiplicity": "3 opponents × 34 base tiles",
      "consumers": [
        {
          "title": "Candidate ron risk",
          "link": "#architecture/head-ron",
          "source": {
            "path": "model/candidate_predictions.py",
            "line": 25
          }
        }
      ]
    },
    {
      "id": "pao_logits",
      "dtype": "float32",
      "signatures": [],
      "title": "Pao allocation",
      "producer": "head-pao",
      "inputs": [
        {
          "title": "Claim and responsible-player evidence",
          "detail": "Sixteen claim vectors combine with four player vectors and role flags for shared responsibility allocation.",
          "nodes": [
            "critic-claim-state",
            "critic-player-projection"
          ],
          "source": {
            "path": "model/critic.py",
            "line": 1034
          }
        },
        {
          "title": "Known responsibility and true-yakuman support",
          "detail": "Public payer, riichi and score support mask invalid responsibility allocations.",
          "nodes": [
            "inputs-parent-table",
            "inputs-parent-actions"
          ],
          "source": {
            "path": "model/critic.py",
            "line": 1070
          }
        }
      ],
      "kind": "learned head",
      "sharing": "Shared claimant, player and role projections; scalar readout tied across claims and seats.",
      "description": "Predict four payer allocations per claim, constrained by known responsibility and true-yakuman support.",
      "source": {
        "path": "model/critic.py",
        "line": 1034
      },
      "shape": [
        16,
        4
      ],
      "row_axis": "evaluated candidate",
      "ownership": "Candidate at the decision",
      "execution": "One row per critic candidate. It reads the raw action state; call candidates retain their after-call hand/board evidence and original-window settlement legality. Supervised fitting selects the recorded action.",
      "row_source": {
        "path": "model/network.py",
        "line": 227
      },
      "group": "Critic",
      "multiplicity": "16 claims × 4 payer allocations",
      "consumers": [
        {
          "title": "Observed settlement likelihood",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 624
          },
          "link": "#math/payment-likelihood"
        },
        {
          "title": "Exact responsibility payments",
          "link": "#architecture/settlement-decoder",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 523
          }
        },
        {
          "title": "Joint settlement law",
          "link": "#outputs/joint_probability",
          "source": {
            "path": "model/joint_settlement.py",
            "line": 276
          }
        }
      ]
    }
  ]
}
