inference.py
python · 35 lines · Exact bytes
Version & provenance · state-v2-cm7
Recorded SHA-256 e6579de1cfbc4c0b054ebddf232e5cac91244bb2db68c7fe17802da3aa640d5dRendered SHA-256 e6579de1cfbc4c0b054ebddf232e5cac91244bb2db68c7fe17802da3aa640d5d
Apache-2.0 original project code; dependencies retain their own licenses. License notes. Line links are stable within this snapshot. CM-7 completed implementation source; original and public rendered hashes recorded. Host-specific paths use /work placeholders; inspect reproduction instructions before running. Separate Rust helper retains its GPL license.
1"""Authoritative board/phase wrapper around the same preparation codec."""
2import codec as c
3
4class State:
5 def __init__(self,board=None,history_plies=16,repetition_history_complete=True):
6 self.board=(c.chess.Board() if board is None else board.copy(stack=True));c.check_board(self.board)
7 if type(self.board.halfmove_clock) is not int or self.board.halfmove_clock<0 or type(self.board.fullmove_number) is not int or self.board.fullmove_number<1:raise ValueError('invalid clock metadata')
8 if type(history_plies) is not int or not 0<=history_plies<=16:raise ValueError('history bound')
9 self.history_plies=history_plies;self.prefix=[];self.repetition_history_complete=repetition_history_complete
10 @classmethod
11 def from_fen(cls,fen):
12 # FEN does not contain repetition history; callers must retain adjudication
13 # state separately. No invented prior plies or guessed repetition counts.
14 return cls(c.chess.Board(fen),0,False)
15 def inputs(self):
16 if self.board.is_game_over(claim_draw=False):raise ValueError('automatic terminal position')
17 value=c.prompt(self.board,self.history_plies)
18 value['input_ids']+=self.prefix;value['attention_mask'] += [1]*len(self.prefix)
19 value['position_ids']=list(range(len(value['input_ids'])))
20 value['metadata']['repetition_history_complete']=self.repetition_history_complete
21 return value
22 def mask(self,legal=False):
23 if self.board.is_game_over(claim_draw=False):return [False]*c.VOCAB
24 return c.masks(self.board,self.prefix,legal)
25 def feed(self,token):
26 if type(token) is not int or not 0<=token<c.VOCAB or not self.mask(True)[token]:raise ValueError('invalid/illegal token for phase')
27 proposed=self.prefix+[token]
28 if len(proposed)<3:self.prefix=proposed;return None
29 move=c.decode(proposed)
30 if move not in self.board.legal_moves:raise ValueError('illegal complete move')
31 self.board.push(move);self.prefix=[];return move
32 def finish(self):
33 if self.prefix:raise ValueError('incomplete move')
34 return self.board.copy(stack=True)
35