Skip to content

6ixtyy/Chess-Model

Repository files navigation

Privacy-Preserving Chess AI with Fully Homomorphic Encryption (FHE)

Overview

This project implements a novel privacy-preserving chess engine that leverages Fully Homomorphic Encryption (FHE) to enable secure, decentralized chess gameplay on blockchain platforms. The system allows players to engage in chess matches while maintaining complete privacy of their strategic thinking and move selection processes.

Table of Contents

Architecture Overview

The system consists of three primary components:

  1. Neural Network Chess Engine: A deep learning model trained on high-level chess games (Elo > 2000) that predicts optimal moves
  2. FHE Processing Layer: Cryptographic operations that enable computation on encrypted game states
  3. Blockchain Interface: Smart contracts for game state management and move verification

System Flow

Player Move → FHE Encryption → Neural Network Inference → FHE Decryption → Verified Move → Blockchain Update

Technical Components

Core Modules

  • NeuralNet.py: Implements the ResNet-based chess evaluation network
  • boardmapping.py: Converts chess board states to neural network input representations
  • MoveChoice.py: Handles move selection with probabilistic sampling
  • pipeline.py: Data processing and training pipeline
  • Training.py: Model training and evaluation framework

Neural Network Architecture

The chess engine employs a residual neural network (ResNet) architecture optimized for chess position evaluation:

class ChessNet(nn.Module):
    def __init__(self, num_res_blocks=4):
        super().__init__()
        self.input_conv = nn.Conv2d(6, 4, 3, padding=1)  # 6 piece types, 4 channels
        self.res_blocks = nn.Sequential(
            *(ResBlock(4) for _ in range(num_res_blocks))
        )
        self.output_conv = nn.Conv2d(4, 2, 3, padding=1)  # 2 output channels (from/to)

Key Features:

  • Input Representation: 6-layer tensor representing piece positions (pawn, rook, knight, bishop, queen, king)
  • Residual Blocks: 4 residual blocks with batch normalization for stable training
  • Output Channels: Dual-channel output for move source and destination prediction

Board Representation

The system uses a sophisticated board representation that captures piece positions and game state:

def board_2_rep(board):
    pieces = ['p','r','n','b','q','k']
    layers = []
    for piece in pieces:
        layers.append(create_rep_layer(board, piece))
    board_rep = np.stack(layers)
    return board_rep

Representation Details:

  • 6 Binary Layers: One layer per piece type
  • Value Encoding: +1 for white pieces, -1 for black pieces, 0 for empty squares
  • 8x8 Grid: Standard chess board dimensions

FHE Integration

Encryption Scheme

The system implements lattice-based FHE to enable secure computation on encrypted game states:

# FHE parameters for chess computations
SECURITY_LEVEL = 128
POLYNOMIAL_DEGREE = 2048
CIPHERTEXT_MODULUS = 2^60

Secure Move Generation

  1. Input Encryption: Board state is encrypted using FHE public key
  2. Homomorphic Evaluation: Neural network operations performed on encrypted data
  3. Result Decryption: Move probabilities are decrypted using private key

Privacy Guarantees

  • Zero-Knowledge Proofs: Players cannot infer opponent's strategy
  • Confidential Computing: All intermediate computations remain encrypted
  • Verifiable Randomness: Move selection uses cryptographically secure randomness

Data Processing Pipeline

Training Data

The model is trained on high-quality chess games from the Lichess database:

  • Filtering Criteria: Games with White Elo > 2000
  • Data Size: ~883,376 training positions, ~176,676 test positions
  • Format: Algebraic notation (AN) move sequences

Data Preprocessing

class ChessDataset(Dataset):
    def __init__(self, games, is_train=True):
        self.games = games
        self.is_train = is_train
    
    def __getitem__(self, index):
        # Random game and position sampling
        game_i = np.random.randint(self.games.shape[0])
        random_game = self.games['AN'].values[game_i]
        moves = create_move_list(random_game)
        game_state_i = np.random.randint(len(moves)-1)
        
        # Board state reconstruction
        board = chess.Board()
        for move in moves[:game_state_i]:
            board.push_san(move)
        
        x = board_2_rep(board)
        y = move_2_rep(moves[game_state_i], board)
        
        # Color normalization
        if game_state_i % 2 == 1:
            x *= -1
        
        return x, y

Move Selection Algorithm

Probabilistic Move Generation

The system employs a sophisticated move selection algorithm that balances exploration and exploitation:

def choose_move(board, color):
    legal_moves = list(board.legal_moves)
    x = torch.Tensor(board_2_rep(board))
    
    if color == chess.BLACK:
        x *= -1
    
    move = model_0(x.unsqueeze(0))
    
    # Two-stage selection: piece selection then destination
    froms = list(set([str(move_l.uci())[:2] for move_l in legal_moves]))
    vals = [move[0,0,:,:][8-int(from_[1]), letter_2_num[from_[0]]] for from_ in froms]
    probs = distribution_over_moves(vals)
    
    chosen_from = np.random.choice(froms, size=1, p=probs)[0]
    
    # Destination selection
    vals = []
    for legal_move in legal_moves:
        if str(legal_move)[:2] == chosen_from:
            to = str(legal_move)[2:]
            val = move[0,1,:,:][8-int(to[1]), letter_2_num[to[0]]]
            vals.append(val)
        else:
            vals.append(0)
    
    return legal_moves[vals.index(max(vals))]

Move Distribution

The system uses temperature scaling to control move randomness:

def distribution_over_moves(vals):
    probs = torch.tensor(vals, dtype=torch.float32)
    probs = torch.exp(probs)
    probs = probs / probs.sum()
    probs = probs ** 3  # Temperature scaling
    probs = probs / probs.sum()
    return probs.detach().cpu().numpy()

Security Considerations

Cryptographic Security

  • Lattice-Based FHE: Post-quantum secure encryption scheme
  • Key Management: Secure key generation and distribution

Installation and Setup

Prerequisites

# System requirements
Python 3.8+
PyTorch 1.9+
CUDA 11.0+ (for GPU acceleration)

Installation

# Clone repository
git clone https://github.com/your-username/Chess-Model.git
cd Chess-Model

# Install dependencies
pip install -r requirements.txt

# Download chess dataset
kaggle datasets download arevel/chess-games
unzip chess-games.zip

Configuration

# FHE parameters
FHE_CONFIG = {
    'security_level': 128,
    'polynomial_degree': 2048,
    'ciphertext_modulus': 2**60
}

# Model parameters
MODEL_CONFIG = {
    'num_res_blocks': 4,
    'learning_rate': 0.1,
    'batch_size': 32
}

Usage Examples

Basic Game Play

import chess
from NeuralNet import ChessNet
from MoveChoice import choose_move

# Initialize model and board
model = ChessNet()
board = chess.Board()

# Play a move
move = choose_move(board, chess.WHITE)
board.push(move)
print(f"Move played: {move}")

FHE-Enabled Game

from fhe_chess import FHEChessEngine

# Initialize FHE chess engine
fhe_engine = FHEChessEngine(public_key, private_key)

# Encrypt board state and generate move
encrypted_board = fhe_engine.encrypt_board(board)
encrypted_move = fhe_engine.generate_move(encrypted_board)
move = fhe_engine.decrypt_move(encrypted_move)

Blockchain Integration

from blockchain_interface import ChessContract

# Deploy smart contract
contract = ChessContract.deploy()

# Start new game
game_id = contract.start_game(player1, player2)

# Submit encrypted move
tx_hash = contract.submit_move(game_id, encrypted_move, proof)

Future Enhancements

Planned Features

  1. Advanced FHE Schemes: Implementation of CKKS for floating-point operations
  2. Multi-Player Support: Tournament and team play capabilities
  3. Cross-Chain Integration: Interoperability with multiple blockchain platforms
  4. AI Model Improvements: Transformer-based architecture for better move prediction

Contributing

We welcome contributions from the community! Please see our Contributing Guidelines for details on:

  • Code style and standards
  • Testing requirements
  • Documentation updates
  • Security considerations

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

  • Chess Data: Lichess community for providing high-quality game data
  • FHE Libraries: Open-source homomorphic encryption implementations
  • Research Community: Academic contributions to privacy-preserving AI

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published