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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import chess
|
| 2 |
+
import chess.engine
|
| 3 |
+
import numpy as np
|
| 4 |
+
import tensorflow as tf
|
| 5 |
+
import time
|
| 6 |
+
import os
|
| 7 |
+
import datetime
|
| 8 |
+
import shutil # For zip creation
|
| 9 |
+
from google.colab import files # For download trigger
|
| 10 |
+
|
| 11 |
+
# --- 1. Neural Network (Policy and Value Network) ---
|
| 12 |
+
class PolicyValueNetwork(tf.keras.Model):
|
| 13 |
+
def __init__(self, num_moves):
|
| 14 |
+
super(PolicyValueNetwork, self).__init__()
|
| 15 |
+
self.conv1 = tf.keras.layers.Conv2D(32, 3, activation='relu', padding='same')
|
| 16 |
+
self.flatten = tf.keras.layers.Flatten()
|
| 17 |
+
self.dense_policy = tf.keras.layers.Dense(num_moves, activation='softmax', name='policy_head')
|
| 18 |
+
self.dense_value = tf.keras.layers.Dense(1, activation='tanh', name='value_head')
|
| 19 |
+
|
| 20 |
+
def call(self, inputs):
|
| 21 |
+
x = self.conv1(inputs)
|
| 22 |
+
x = self.flatten(x)
|
| 23 |
+
policy = self.dense_policy(x)
|
| 24 |
+
value = self.dense_value(x)
|
| 25 |
+
return policy, value
|
| 26 |
+
|
| 27 |
+
# --- 2. Move Encoding/Decoding (Correct and Deterministic Implementation) ---
|
| 28 |
+
NUM_POSSIBLE_MOVES = 4672 # Correct value based on deterministic encoding
|
| 29 |
+
NUM_INPUT_PLANES = 12
|
| 30 |
+
|
| 31 |
+
# Load model weights
|
| 32 |
+
policy_value_net = PolicyValueNetwork(NUM_POSSIBLE_MOVES)
|
| 33 |
+
|
| 34 |
+
# dummy input for building network
|
| 35 |
+
dummy_input = tf.random.normal((1, 8, 8, NUM_INPUT_PLANES))
|
| 36 |
+
policy, value = policy_value_net(dummy_input)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# Load the weights (replace 'your_model.weights.h5' with your actual file)
|
| 40 |
+
try:
|
| 41 |
+
model_path = "/stockzero/models_weights/StockZero-2025-03-24-1727.weights.h5"
|
| 42 |
+
policy_value_net.load_weights(model_path)
|
| 43 |
+
print(f"Model weights loaded successfully from '{model_path}'")
|
| 44 |
+
except Exception as e:
|
| 45 |
+
print(f"Error loading weights: {e}")
|
| 46 |
+
|
| 47 |
+
# --- Create output directory and set output paths ---
|
| 48 |
+
OUTPUT_DIR = "/content/converted_models"
|
| 49 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True) # Create the folder if it does not exist
|
| 50 |
+
|
| 51 |
+
SAVED_MODEL_DIR = os.path.join(OUTPUT_DIR, "saved_model")
|
| 52 |
+
KERAS_MODEL_PATH = os.path.join(OUTPUT_DIR, "model.keras")
|
| 53 |
+
H5_MODEL_PATH = os.path.join(OUTPUT_DIR, "model_weights.h5")
|
| 54 |
+
PYTORCH_MODEL_PATH = os.path.join(OUTPUT_DIR, "pytorch_model.pth")
|
| 55 |
+
PYTORCH_FULL_MODEL_PATH = os.path.join(OUTPUT_DIR, "pytorch_full_model.pth")
|
| 56 |
+
ONNX_MODEL_PATH = os.path.join(OUTPUT_DIR, "model.onnx")
|
| 57 |
+
TFLITE_MODEL_PATH = os.path.join(OUTPUT_DIR, "model.tflite")
|
| 58 |
+
BIN_FILE_PATH = os.path.join(OUTPUT_DIR, "model_weights.bin")
|
| 59 |
+
NUMPY_FILE_PATH = os.path.join(OUTPUT_DIR, "model_weights.npz")
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# --- 1. Keras/TensorFlow (SavedModel format) ---
|
| 63 |
+
try:
|
| 64 |
+
tf.saved_model.save(policy_value_net, SAVED_MODEL_DIR)
|
| 65 |
+
print(f"Model saved as SavedModel to '{SAVED_MODEL_DIR}'")
|
| 66 |
+
except Exception as e:
|
| 67 |
+
print(f"Error saving model as SavedModel: {e}")
|
| 68 |
+
|
| 69 |
+
# --- 2. Keras .keras Format (Weights + Architecture) ---
|
| 70 |
+
try:
|
| 71 |
+
policy_value_net.save(KERAS_MODEL_PATH)
|
| 72 |
+
print(f"Model saved as Keras .keras format to '{KERAS_MODEL_PATH}'")
|
| 73 |
+
except Exception as e:
|
| 74 |
+
print(f"Error saving as .keras format: {e}")
|
| 75 |
+
# --- 3. Keras/TensorFlow (.h5 - Weights) ---
|
| 76 |
+
try:
|
| 77 |
+
policy_value_net.save_weights(H5_MODEL_PATH)
|
| 78 |
+
print(f"Model weights saved as .h5 to '{H5_MODEL_PATH}'")
|
| 79 |
+
except Exception as e:
|
| 80 |
+
print(f"Error saving model weights as .h5: {e}")
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
# --- 4. PyTorch ---
|
| 84 |
+
import torch
|
| 85 |
+
import torch.nn as nn
|
| 86 |
+
|
| 87 |
+
class PyTorchPolicyValueNetwork(nn.Module):
|
| 88 |
+
def __init__(self, num_moves):
|
| 89 |
+
super(PyTorchPolicyValueNetwork, self).__init__()
|
| 90 |
+
self.conv1 = nn.Conv2d(12, 32, kernel_size=3, padding=1) # Input 12 channels for chess
|
| 91 |
+
self.relu = nn.ReLU()
|
| 92 |
+
self.flatten = nn.Flatten()
|
| 93 |
+
self.dense_policy = nn.Linear(8*8*32, num_moves) # Calculate size using the parameters from keras layer, after flatten output is 8*8*32
|
| 94 |
+
self.softmax = nn.Softmax(dim=1)
|
| 95 |
+
self.dense_value = nn.Linear(8*8*32, 1)
|
| 96 |
+
self.tanh = nn.Tanh()
|
| 97 |
+
|
| 98 |
+
def forward(self, x):
|
| 99 |
+
x = self.relu(self.conv1(x))
|
| 100 |
+
x = self.flatten(x)
|
| 101 |
+
policy = self.softmax(self.dense_policy(x))
|
| 102 |
+
value = self.tanh(self.dense_value(x))
|
| 103 |
+
return policy, value
|
| 104 |
+
|
| 105 |
+
try:
|
| 106 |
+
pytorch_model = PyTorchPolicyValueNetwork(NUM_POSSIBLE_MOVES)
|
| 107 |
+
|
| 108 |
+
# Get Keras layers
|
| 109 |
+
keras_conv1 = policy_value_net.conv1
|
| 110 |
+
keras_dense_policy = policy_value_net.dense_policy
|
| 111 |
+
keras_dense_value = policy_value_net.dense_value
|
| 112 |
+
|
| 113 |
+
# Transfer weights from Keras to PyTorch
|
| 114 |
+
pytorch_model.conv1.weight = torch.nn.Parameter(torch.tensor(keras_conv1.kernel.numpy().transpose(3,2,0,1), dtype=torch.float32))
|
| 115 |
+
pytorch_model.conv1.bias = torch.nn.Parameter(torch.tensor(keras_conv1.bias.numpy(), dtype=torch.float32))
|
| 116 |
+
|
| 117 |
+
pytorch_model.dense_policy.weight = torch.nn.Parameter(torch.tensor(keras_dense_policy.kernel.numpy().transpose(), dtype=torch.float32))
|
| 118 |
+
pytorch_model.dense_policy.bias = torch.nn.Parameter(torch.tensor(keras_dense_policy.bias.numpy(), dtype=torch.float32))
|
| 119 |
+
|
| 120 |
+
pytorch_model.dense_value.weight = torch.nn.Parameter(torch.tensor(keras_dense_value.kernel.numpy().transpose(), dtype=torch.float32))
|
| 121 |
+
pytorch_model.dense_value.bias = torch.nn.Parameter(torch.tensor(keras_dense_value.bias.numpy(), dtype=torch.float32))
|
| 122 |
+
|
| 123 |
+
torch.save(pytorch_model.state_dict(), PYTORCH_MODEL_PATH)
|
| 124 |
+
print(f"PyTorch model weights saved to '{PYTORCH_MODEL_PATH}'")
|
| 125 |
+
|
| 126 |
+
torch.save(pytorch_model, PYTORCH_FULL_MODEL_PATH) # Save full model
|
| 127 |
+
print(f"PyTorch model saved as '{PYTORCH_FULL_MODEL_PATH}'")
|
| 128 |
+
except Exception as e:
|
| 129 |
+
print(f"Error during PyTorch conversion: {e}")
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
# --- 5. ONNX ---
|
| 133 |
+
import tf2onnx
|
| 134 |
+
try:
|
| 135 |
+
spec = (tf.TensorSpec((None, 8, 8, 12), tf.float32, name="input"),)
|
| 136 |
+
onnx_model, _ = tf2onnx.convert.from_keras(policy_value_net, input_signature=spec)
|
| 137 |
+
|
| 138 |
+
with open(ONNX_MODEL_PATH, "wb") as f:
|
| 139 |
+
f.write(onnx_model.SerializeToString())
|
| 140 |
+
print(f"Model saved as ONNX to '{ONNX_MODEL_PATH}'")
|
| 141 |
+
except Exception as e:
|
| 142 |
+
print(f"Error saving model as ONNX: {e}")
|
| 143 |
+
|
| 144 |
+
# --- 6. TensorFlow Lite ---
|
| 145 |
+
try:
|
| 146 |
+
converter = tf.lite.TFLiteConverter.from_keras_model(policy_value_net)
|
| 147 |
+
tflite_model = converter.convert()
|
| 148 |
+
|
| 149 |
+
with open(TFLITE_MODEL_PATH, 'wb') as f:
|
| 150 |
+
f.write(tflite_model)
|
| 151 |
+
print(f"Model saved as TFLite to '{TFLITE_MODEL_PATH}'")
|
| 152 |
+
except Exception as e:
|
| 153 |
+
print(f"Error converting to TFLite: {e}")
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
# --- 7. Binary (.bin) format (Custom Implementation) ---
|
| 157 |
+
try:
|
| 158 |
+
with open(BIN_FILE_PATH, 'wb') as f:
|
| 159 |
+
for layer in policy_value_net.layers:
|
| 160 |
+
for weight in layer.weights:
|
| 161 |
+
weight_arr = weight.numpy()
|
| 162 |
+
f.write(weight_arr.tobytes())
|
| 163 |
+
print(f"Model weights saved as .bin to '{BIN_FILE_PATH}'")
|
| 164 |
+
except Exception as e:
|
| 165 |
+
print(f"Error saving model weights as .bin: {e}")
|
| 166 |
+
|
| 167 |
+
# --- 8. NumPy arrays (.npz) format ---
|
| 168 |
+
try:
|
| 169 |
+
all_weights = {}
|
| 170 |
+
for layer in policy_value_net.layers:
|
| 171 |
+
for i, weight in enumerate(layer.weights):
|
| 172 |
+
all_weights[f"{layer.name}_weight_{i}"] = weight.numpy()
|
| 173 |
+
np.savez(NUMPY_FILE_PATH, **all_weights)
|
| 174 |
+
print(f"Model weights saved as NumPy arrays to '{NUMPY_FILE_PATH}'")
|
| 175 |
+
except Exception as e:
|
| 176 |
+
print(f"Error saving model weights as NumPy: {e}")
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
# --- 9. TensorFlow.js (requires command line tool)---
|
| 180 |
+
# --- This would require the TensorFlow.js converter tool ---
|
| 181 |
+
# --- Command-Line example shown below (run in shell, not in the script) ---
|
| 182 |
+
# --- tensorflowjs_converter --input_format=tf_saved_model ./saved_model ./tfjs_model ---
|
| 183 |
+
print("To convert to TensorFlow.js format, run the 'tensorflowjs_converter' command-line tool (see comments in script).")
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
# --- Zip all files and create download ---
|
| 187 |
+
try:
|
| 188 |
+
current_datetime = datetime.datetime.now()
|
| 189 |
+
zip_file_name = f"converted_models-{current_datetime.strftime('%Y%m%d%H%M')}"
|
| 190 |
+
zip_file_path = f"/directory/{zip_file_name}"
|
| 191 |
+
shutil.make_archive(zip_file_path, 'zip', OUTPUT_DIR) # Create zip archive
|
| 192 |
+
print(f"All converted model files zipped to '{zip_file_path}.zip'")
|
| 193 |
+
files.download(f"{zip_file_path}.zip") # Trigger download in Colab
|
| 194 |
+
print("Download should start in a moment.")
|
| 195 |
+
except Exception as e:
|
| 196 |
+
print(f"Error zipping and creating download: {e}")
|