Skip to main content

Interpretability for LeelaChessZero networks.

Project description

logo

lczerolens :mag:

ci publish docs

Leela Chess Zero (lc0) Lens: a set of utilities to make the analysis of Leela Chess Zero networks easy.

Getting Started

Installs

pip install lczerolens

Load a Model

Build a model from leela file (convert then load):

from lczerolens import AutoBuilder

model = AutoBuilder.from_path(
    "leela-network.onnx"
)

Predict a Move

Use a wrapper and the utils to predict a policy vector and obtain an UCI move:

import chess
import torch

from lczerolens import move_utils, ModelWrapper

# Wrap the model
wrapper = ModelWrapper(model)
board = chess.Board()

# Get the model predictions
out = wrapper.predict(board)
policy = out["policy"]

# Use the prediction
best_move_index = policy.argmax()
move = move_utils.decode_move(best_move_index)
board.push(move)

print(uci_move, board)

Compute a Heatmap

Use a lens to compute a heatmap

from lczerolens import visualisation_utils, LrpLens

# Get the lens
lens = LrpLens()

# Compute the relevance
assert lens.is_compatible(wrapper)
relevance = lens.compute_heatmap(board, wrapper)

# Choose a plane index and render the heatmap on the board
plane_index = 0
heatmap = relevance_tensor[plane_index].view(64)
if board.turn == chess.BLACK:
    heatmap = heatmap.view(8, 8).flip(0).view(64)
svg_board, fig = visualisation_utils.render_heatmap(
    board, heatmap, normalise="abs"
)

Convert a Network

To convert a network you'll need to have installed the lc0 extra:

pip install lczerolens[lc0]
from lczerolens import lczero as lczero_utils

lczero_utils.convert_to_onnx(
    "leela-network.pb.gz",
    "leela-network.onnx"
)

Demo

Additionally, you can run the gradio demo locally (also deployed on HF). First you'll need gradio, which is packaged in the demo extra:

pip install lczerolens[demo]

And then launch the demo (running on port 8000):

make demo

Full Documentation

:red_circle: Documentation coming soon.

Contribute

See the guidelines in CONTRIBUTING.md.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

lczerolens-0.2.0.tar.gz (38.5 kB view hashes)

Uploaded Source

Built Distribution

lczerolens-0.2.0-py3-none-any.whl (47.9 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page