Skip to content

[AnimalShogi] precompute the CAN_MOVE table once instead of per _can_move call#1324

Open
gweber wants to merge 1 commit into
sotetsuk:mainfrom
gweber:animalshogi-precompute-canmove
Open

[AnimalShogi] precompute the CAN_MOVE table once instead of per _can_move call#1324
gweber wants to merge 1 commit into
sotetsuk:mainfrom
gweber:animalshogi-precompute-canmove

Conversation

@gweber

@gweber gweber commented Jun 10, 2026

Copy link
Copy Markdown

What

_can_move rebuilt the full (5, 12, 12) CAN_MOVE table — via a triple-nested vmap — on every call, only to index a single entry:

def _can_move(piece, from_, to):
    def can_move(piece, from_, to): ...        # pure movement geometry
    CAN_MOVE = jax.vmap(jax.vmap(jax.vmap(can_move, ...)))(jnp.arange(5), jnp.arange(12), jnp.arange(12))
    return CAN_MOVE[piece, from_, to]

The table depends only on movement geometry, so this lifts it to a module-level constant (as the Zobrist tables already are). _can_move runs ~1700× per _legal_action_mask (132 move checks + 132×12 in _is_checked), so the rebuild dominated.

Behaviour & perf

Pure refactor, no behavioural change — legal_action_mask matches the previous implementation across 250 states, and tests/test_animal_shogi.py passes (5/5). Measured ~1.57× faster _legal_action_mask (1.42 → 0.91 ms, B=200, CPU) and ~1.2× faster compile. (XLA does not fully constant-fold the per-call rebuild, so this is a real runtime win, not only a tracing/clarity one.)

…move call

_can_move rebuilt the full (5, 12, 12) CAN_MOVE table via a triple-nested vmap
on every call, only to index a single entry. The table depends solely on
movement geometry, so lift it to a module-level constant (as the Zobrist tables
already are). _can_move runs ~1700x per _legal_action_mask (132 move checks +
132x12 in _is_checked), so the rebuild dominated.

~1.57x faster _legal_action_mask, ~1.2x faster compile. Output identical:
legal_action_mask matches the previous implementation across 250 states;
tests/test_animal_shogi.py passes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant