# zainkhatri/chess_cnn_analysis architecture

> Architecture diagram of the GitHub repository zainkhatri/chess_cnn_analysis, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-03-28). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/zainkhatri/chess_cnn_analysis
- Repository: https://github.com/zainkhatri/chess_cnn_analysis

## Overview

##### Project Type and Purpose
- Type: This is a deep learning research project focused on chess position evaluation and move prediction.
- Purpose: It implements advanced convolutional neural networks (CNNs) – incorporating residual connections, attention mechanisms, and a dual-head design – to evaluate chess positions and recommend moves based on a processed dataset.

##### File Structure
- The top-level files (README.md, RUNS.md, INITIAL.md) provide general project documentation.
- The nn directory contains the core Python scripts:
- Data processing (data_processing.py) for converting chess FENs into 12-channel tensors.
- Model definition (model.py) where the ChessCNN (and the enhanced version) are implemented along with supporting modules (ResidualBlock and AttentionModule).
- Game analysis (analyze_game.py and game_advisor.py) which employ the trained model to evaluate games and provide move suggestions.
- The models folder under nn hosts trained model checkpoints and training history files indicating iterative runs.
- Additional files (package.json, package-lock.json) suggest dependency management and may be used for project setup rather than directly impacting the core architecture.

##### README for Architectural Insights
- The README clearly outlines:
- The dual-head architecture: one head for move prediction (policy head) and one for position evaluation (value head).
- Specific components like the Residual Blocks and Attention Module.
- The data processing pipeline, which extracts positions from PGN files, encodes them, and uses Stockfish for ground truth generation.
- Integration points: use of Stockfish in the game advisor and visual tools (e.g., attention maps and evaluation charts).
- Training configuration, including focal loss for handling class imbalance and a custom learning rate scheduler.

##### Key Components
a. Data Input and Preprocessing
- PGN Files and Stockfish engine (external service) are used to generate annotated chess positions.
- Data Processing Pipeline: converts FEN strings into 12-channel 8×8 tensors and maps moves to indices.
- Processed Data Files (e.g., processed_data.pt) are stored for training.

b. Neural Network Model (ChessCNN / EnhancedChessCNN)
- Initial convolution layer with batch normalization and ReLU.
- Multiple Residual Blocks for deeper representation.
- Attention Module that highlights important board regions.
- Dual-head output:
- Policy Head (for move prediction) using a final linear layer to predict one among 1968 moves.
- Value Head (for position evaluation) producing a value between -1 and 1.

c. Training Engine and Infrastructure
- Training Script (train_model.py) that ties together optimizer (AdamW), focal loss for class imbalance, and a custom learning rate scheduler.
- Model checkpoints and training histories are saved in a designated models folder.

d. Inference and Analysis
- Game Advisor Module (game_advisor.py) responsible for running the analysis on chess games, generating evaluation charts, and identifying mistakes.
- Integration with Stockfish serves as an external evidential source for comparing predictions.

##### Relationships & Interactions
- Start from raw chess data (PGN) ➜ use Data Processing Pipeline ➜ generate tensors.
- Tensors feed into the ChessCNN model during training, where forward passes calculate both policy and value outputs.
- Loss functions (including focal loss) and custom schedulers help update the model during training.
- Post-training, the ChessAdvisor uses the trained model to analyze games. Outputs (evaluations, heatmaps, summaries) flow back to the user.

##### Architectural Patterns & Design Principles
- Modular Design: Each component (data processing, model training, game analysis) is in its own script/module.
- Dual-Head Architecture: Simultaneous predictions for move suggestion and board evaluation.
- Use of Residual Connections and Attention: Helps with deep network training and focusing on critical board areas.
- External Integration: Stockfish for label generation and comparison, enabling a “hybrid” approach combining traditional chess evaluation with deep learning.

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% Data Ingestion & Preprocessing
    subgraph "Data Ingestion & Preprocessing"
        A["PGN Files"]:::external
        B["Data Processing (FEN->12-channel tensor)"]:::data
        C["Processed Data Storage"]:::data
    end

    %% Neural Network Architecture
    subgraph "Neural Network Architecture"
        D["Initial Convolution + BatchNorm + ReLU"]:::model
        E["Residual Blocks"]:::model
        F["Attention Module"]:::model
        G["Dual-head Output: Policy & Value"]:::model
    end

    %% Training Engine & Infrastructure
    subgraph "Training Engine & Infrastructure"
        H["Training Script (train_model.py, AdamW, Focal Loss, Scheduler)"]:::training
        I["Model Checkpoints & Histories"]:::training
    end

    %% Inference & Game Analysis
    subgraph "Inference & Game Analysis"
        J["Game Analysis (analyze_game.py)"]:::inference
        K["Game Advisor (game_advisor.py)"]:::inference
        L["Stockfish Engine"]:::external
    end

    %% Data Flow Connections
    A -->|"feeds"| B
    B -->|"processes"| C
    C -->|"input to"| D
    D -->|"passes feature maps to"| E
    E -->|"flows into"| F
    F -->|"culminates in"| G
    G -->|"triggers"| H
    H -->|"saves model to"| I
    I -->|"provides trained_model"| K
    G -->|"outputs predictions to"| J
    J -->|"analyzes using"| K
    K -->|"integrates_with"| L

    %% Click Events for Component Mapping
    click B "https://github.com/zainkhatri/chess_cnn_analysis/blob/main/nn/data_processing.py"
    click C "https://github.com/zainkhatri/chess_cnn_analysis/tree/main/nn/processed_data"
    click D "https://github.com/zainkhatri/chess_cnn_analysis/blob/main/nn/model.py"
    click E "https://github.com/zainkhatri/chess_cnn_analysis/blob/main/nn/model.py"
    click F "https://github.com/zainkhatri/chess_cnn_analysis/blob/main/nn/model.py"
    click G "https://github.com/zainkhatri/chess_cnn_analysis/blob/main/nn/model.py"
    click H "https://github.com/zainkhatri/chess_cnn_analysis/blob/main/nn/train_model.py"
    click I "https://github.com/zainkhatri/chess_cnn_analysis/tree/main/nn/models"
    click J "https://github.com/zainkhatri/chess_cnn_analysis/blob/main/nn/analyze_game.py"
    click K "https://github.com/zainkhatri/chess_cnn_analysis/blob/main/nn/game_advisor.py"

    %% Styles
    classDef external fill:#f9d9ff,stroke:#333,stroke-width:2px;
    classDef data fill:#cce5ff,stroke:#333,stroke-width:2px;
    classDef model fill:#ffcccc,stroke:#333,stroke-width:2px;
    classDef training fill:#ccffcc,stroke:#333,stroke-width:2px;
    classDef inference fill:#fff2cc,stroke:#333,stroke-width:2px;
```
