|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
print("Initializing... Loading libraries.")
|
|
import torch
|
|
import torch.nn as nn
|
|
import numpy as np
|
|
import matplotlib.pyplot as plt
|
|
import seaborn as sns
|
|
from sklearn.metrics import confusion_matrix, classification_report
|
|
import random
|
|
import os
|
|
import argparse
|
|
import datetime
|
|
import json
|
|
|
|
print("Libraries loaded successfully.\n")
|
|
|
|
|
|
|
|
|
|
|
|
def setup_directories(args):
|
|
"""Creates a unique, timestamped directory for the current run to store all outputs."""
|
|
timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
|
|
run_name = f"run_{timestamp}_N{args.n_bits}_L{args.l_layers}_H{args.hidden_size}_{args.parity_type}"
|
|
base_dir = "parity_nn_results"
|
|
run_dir = os.path.join(base_dir, run_name)
|
|
plots_dir = os.path.join(run_dir, "plots")
|
|
os.makedirs(plots_dir, exist_ok=True)
|
|
print(f"Created output directory: {run_dir}")
|
|
return run_dir, plots_dir
|
|
|
|
def generate_data(num_samples, num_bits, parity_type='even'):
|
|
"""
|
|
Generates input data and corresponding labels based on the specified parity rule.
|
|
|
|
Args:
|
|
num_samples (int): The number of data samples to generate.
|
|
num_bits (int): The bit-width of each data sample.
|
|
parity_type (str): The rule for calculating the label.
|
|
'even': Standard even parity bit (1 if odd number of 1s, 0 if even).
|
|
'odd': Standard odd parity bit (1 if even number of 1s, 0 if odd).
|
|
'majority': Label is 1 if the count of 1s > N/2, else 0.
|
|
|
|
Returns:
|
|
tuple: A tuple containing torch tensors for data and labels.
|
|
"""
|
|
data = []
|
|
labels = []
|
|
for _ in range(num_samples):
|
|
bits = [random.randint(0, 1) for _ in range(num_bits)]
|
|
sum_of_bits = sum(bits)
|
|
|
|
if parity_type == 'even':
|
|
label = sum_of_bits % 2
|
|
elif parity_type == 'odd':
|
|
label = (sum_of_bits + 1) % 2
|
|
elif parity_type == 'majority':
|
|
label = 1 if sum_of_bits > num_bits / 2 else 0
|
|
else:
|
|
raise ValueError(f"Unknown parity_type: {parity_type}")
|
|
|
|
data.append(bits)
|
|
labels.append(label)
|
|
|
|
return torch.tensor(data, dtype=torch.float32), torch.tensor(labels, dtype=torch.float32).reshape(-1, 1)
|
|
|
|
class ParityNet(nn.Module):
|
|
"""A flexible feed-forward neural network model."""
|
|
def __init__(self, input_size, hidden_size, num_hidden_layers, output_size, activation_func='relu'):
|
|
super(ParityNet, self).__init__()
|
|
|
|
if activation_func.lower() == 'relu':
|
|
activation = nn.ReLU()
|
|
elif activation_func.lower() == 'tanh':
|
|
activation = nn.Tanh()
|
|
elif activation_func.lower() == 'leakyrelu':
|
|
activation = nn.LeakyReLU()
|
|
else:
|
|
raise ValueError("Unsupported activation function. Choose 'relu', 'tanh', or 'leakyrelu'.")
|
|
|
|
layers = []
|
|
|
|
layers.append(nn.Linear(input_size, hidden_size))
|
|
layers.append(activation)
|
|
|
|
for _ in range(num_hidden_layers - 1):
|
|
layers.append(nn.Linear(hidden_size, hidden_size))
|
|
layers.append(activation)
|
|
|
|
layers.append(nn.Linear(hidden_size, output_size))
|
|
layers.append(nn.Sigmoid())
|
|
|
|
self.layers = nn.Sequential(*layers)
|
|
|
|
def forward(self, x):
|
|
return self.layers(x)
|
|
|
|
def train_model(model, train_data, train_labels, test_data, test_labels, args, run_dir):
|
|
"""Trains the model and logs performance and difficult samples."""
|
|
criterion = nn.BCELoss()
|
|
optimizer = torch.optim.Adam(model.parameters(), lr=args.learning_rate)
|
|
|
|
history = {'epoch': [], 'train_loss': [], 'val_acc': []}
|
|
hard_samples = {}
|
|
|
|
print("\n" + "="*50)
|
|
print("=== STARTING TRAINING ===")
|
|
print(f"Epochs: {args.epochs}, LR: {args.learning_rate}, Stop Threshold: {args.min_loss_threshold}")
|
|
print("="*50)
|
|
|
|
|
|
plt.ion()
|
|
fig, ax = plt.subplots(figsize=(10, 6))
|
|
|
|
for epoch in range(args.epochs):
|
|
model.train()
|
|
outputs = model(train_data)
|
|
loss = criterion(outputs, train_labels)
|
|
|
|
optimizer.zero_grad()
|
|
loss.backward()
|
|
optimizer.step()
|
|
|
|
if (epoch + 1) % args.plot_update_freq == 0:
|
|
model.eval()
|
|
with torch.no_grad():
|
|
val_outputs = model(test_data)
|
|
predicted = (val_outputs > 0.5).float()
|
|
accuracy = (predicted == test_labels).sum().float() / len(test_labels)
|
|
|
|
|
|
misclassified_mask = (predicted != test_labels).flatten()
|
|
for i, is_misclassified in enumerate(misclassified_mask):
|
|
if is_misclassified:
|
|
sample_str = ''.join(map(str, test_data[i].int().tolist()))
|
|
hard_samples[sample_str] = hard_samples.get(sample_str, 0) + 1
|
|
|
|
history['epoch'].append(epoch + 1)
|
|
history['train_loss'].append(loss.item())
|
|
history['val_acc'].append(accuracy.item())
|
|
|
|
print(f'Epoch [{epoch+1}/{args.epochs}], Loss: {loss.item():.5f}, Validation Accuracy: {accuracy.item():.4f}')
|
|
|
|
|
|
ax.clear()
|
|
ax.plot(history['epoch'], history['train_loss'], 'r-', label='Training Loss')
|
|
ax.set_xlabel(f"Epoch (x{args.plot_update_freq})")
|
|
ax.set_ylabel("Loss", color='r')
|
|
ax.tick_params(axis='y', labelcolor='r')
|
|
|
|
ax2 = ax.twinx()
|
|
ax2.plot(history['epoch'], history['val_acc'], 'b-', label='Validation Accuracy')
|
|
ax2.set_ylabel("Accuracy", color='b')
|
|
ax2.tick_params(axis='y', labelcolor='b')
|
|
ax2.set_ylim(0, 1.05)
|
|
|
|
fig.suptitle("Live Training Progress")
|
|
fig.legend(loc="upper center", bbox_to_anchor=(0.5, 0.95), ncol=2)
|
|
plt.grid(True)
|
|
plt.draw()
|
|
plt.pause(0.01)
|
|
|
|
if loss.item() < args.min_loss_threshold:
|
|
print(f"\nReached minimum loss threshold of {args.min_loss_threshold} at epoch {epoch+1}. Stopping training.")
|
|
break
|
|
|
|
plt.ioff()
|
|
print("\n" + "="*50)
|
|
print("=== TRAINING COMPLETE ===")
|
|
print("="*50 + "\n")
|
|
|
|
|
|
if hard_samples:
|
|
hard_samples_path = os.path.join(run_dir, "hard_samples.json")
|
|
sorted_hard_samples = sorted(hard_samples.items(), key=lambda item: item[1], reverse=True)
|
|
with open(hard_samples_path, 'w') as f:
|
|
json.dump(dict(sorted_hard_samples), f, indent=4)
|
|
print(f"Logged {len(hard_samples)} unique hard-to-learn samples to {hard_samples_path}")
|
|
|
|
return model, history
|
|
|
|
|
|
def evaluate_model(model, test_data, test_labels):
|
|
"""Evaluates the final model and returns a dictionary of metrics."""
|
|
model.eval()
|
|
with torch.no_grad():
|
|
outputs = model(test_data)
|
|
predicted = (outputs > 0.5).float()
|
|
accuracy = (predicted == test_labels).sum().float() / len(test_labels)
|
|
|
|
|
|
margins_ones = outputs[predicted == 1] - 0.5
|
|
margins_zeros = 0.5 - outputs[predicted == 0]
|
|
|
|
results = {
|
|
"accuracy": accuracy.item(),
|
|
"raw_outputs": outputs.flatten().numpy(),
|
|
"predictions": predicted.flatten().numpy(),
|
|
"labels": test_labels.flatten().numpy(),
|
|
"margins_ones": margins_ones.numpy(),
|
|
"margins_zeros": margins_zeros.numpy(),
|
|
"conf_matrix": confusion_matrix(test_labels.numpy(), predicted.numpy()),
|
|
"class_report": classification_report(test_labels.numpy(), predicted.numpy(), output_dict=True, zero_division=0)
|
|
}
|
|
return results
|
|
|
|
def generate_plots(history, results, args, plots_dir):
|
|
"""Generates and saves a suite of analytical plots."""
|
|
print("Generating and saving analysis plots...")
|
|
plt.style.use('seaborn-v0_8-whitegrid')
|
|
|
|
|
|
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 6))
|
|
fig.suptitle(f'Training History for N={args.n_bits} {args.parity_type.title()} Parity', fontsize=16)
|
|
|
|
ax1.plot(history['epoch'], history['train_loss'], label='Training Loss', color='crimson')
|
|
ax1.set_title('Training Loss over Epochs')
|
|
ax1.set_xlabel('Epoch')
|
|
ax1.set_ylabel('Binary Cross-Entropy Loss')
|
|
ax1.legend()
|
|
|
|
ax2.plot(history['epoch'], history['val_acc'], label='Validation Accuracy', color='royalblue')
|
|
ax2.set_title('Validation Accuracy over Epochs')
|
|
ax2.set_xlabel('Epoch')
|
|
ax2.set_ylabel('Accuracy')
|
|
ax2.set_ylim(0, 1.05)
|
|
ax2.legend()
|
|
|
|
plt.tight_layout(rect=[0, 0.03, 1, 0.95])
|
|
plt.savefig(os.path.join(plots_dir, "01_training_history.png"))
|
|
plt.show()
|
|
|
|
|
|
plt.figure(figsize=(8, 6))
|
|
sns.heatmap(results['conf_matrix'], annot=True, fmt='d', cmap='Blues',
|
|
xticklabels=['Predicted 0', 'Predicted 1'],
|
|
yticklabels=['Actual 0', 'Actual 1'])
|
|
plt.title('Confusion Matrix on Test Set', fontsize=14)
|
|
plt.ylabel('True Label')
|
|
plt.xlabel('Predicted Label')
|
|
plt.savefig(os.path.join(plots_dir, "02_confusion_matrix.png"))
|
|
plt.show()
|
|
|
|
|
|
plt.figure(figsize=(12, 6))
|
|
plt.hist(results['margins_zeros'], bins=20, alpha=0.7, color='coral', label='Margins for "0" Predictions')
|
|
plt.hist(results['margins_ones'], bins=20, alpha=0.7, color='teal', label='Margins for "1" Predictions')
|
|
plt.title('Distribution of Prediction Margins (Confidence)', fontsize=14)
|
|
plt.xlabel('Margin (Distance from 0.5 threshold)')
|
|
plt.ylabel('Frequency')
|
|
plt.legend()
|
|
plt.savefig(os.path.join(plots_dir, "03_prediction_margins.png"))
|
|
plt.show()
|
|
|
|
|
|
plt.figure(figsize=(10, 7))
|
|
jitter = np.random.normal(0, 0.015, size=len(results['labels']))
|
|
colors = ['coral' if l == 0 else 'teal' for l in results['labels']]
|
|
plt.scatter(results['labels'] + jitter, results['raw_outputs'], c=colors, alpha=0.6)
|
|
plt.axhline(y=0.5, color='r', linestyle='--', label='Decision Boundary (0.5)')
|
|
plt.title('Model Raw Output vs. True Labels', fontsize=14)
|
|
plt.xlabel('True Label (with jitter)')
|
|
plt.ylabel('Sigmoid Output (Probability)')
|
|
plt.xticks([0, 1], ['Class 0', 'Class 1'])
|
|
plt.legend()
|
|
plt.savefig(os.path.join(plots_dir, "04_outputs_vs_labels.png"))
|
|
plt.show()
|
|
print("All plots saved.")
|
|
|
|
|
|
def generate_report(args, results, run_dir):
|
|
"""Generates and saves a comprehensive text report of the run."""
|
|
report_path = os.path.join(run_dir, "report.txt")
|
|
|
|
|
|
def get_margin_stats(margins):
|
|
if len(margins) == 0: return "N/A", "N/A", "N/A"
|
|
return f"{np.min(margins):.4f}", f"{np.max(margins):.4f}", f"{np.mean(margins):.4f}"
|
|
|
|
min_m0, max_m0, avg_m0 = get_margin_stats(results['margins_zeros'])
|
|
min_m1, max_m1, avg_m1 = get_margin_stats(results['margins_ones'])
|
|
|
|
tn, fp, fn, tp = results['conf_matrix'].ravel() if results['conf_matrix'].size == 4 else (0,0,0,0)
|
|
|
|
report_content = f"""
|
|
# ==========================================================
|
|
# == PARITY NEURAL NETWORK EXPERIMENT REPORT
|
|
# ==========================================================
|
|
# Run Directory: {run_dir}
|
|
# Report Time: {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
|
|
#
|
|
# ==========================================================
|
|
# == HYPERPARAMETERS
|
|
# ==========================================================
|
|
# Problem Type: {args.parity_type.title()}
|
|
# Input Bits (N): {args.n_bits}
|
|
# Hidden Layers (L): {args.l_layers}
|
|
# Neurons per Hidden Layer: {args.hidden_size}
|
|
# Activation Function: {args.activation.upper()}
|
|
#
|
|
# --- Training Configuration ---
|
|
# Epochs: {args.epochs}
|
|
# Learning Rate: {args.learning_rate}
|
|
# Train Samples: {args.num_train_samples}
|
|
# Test Samples: {args.num_test_samples}
|
|
# Loss Stop Threshold: {args.min_loss_threshold}
|
|
#
|
|
# ==========================================================
|
|
# == EVALUATION RESULTS
|
|
# ==========================================================
|
|
# Final Test Accuracy: {results['accuracy']:.4f}
|
|
#
|
|
# --- Confusion Matrix ---
|
|
# True Positives (1->1): {tp}
|
|
# True Negatives (0->0): {tn}
|
|
# False Positives (0->1): {fp}
|
|
# False Negatives (1->0): {fn}
|
|
#
|
|
# --- Prediction Margin Analysis (Confidence) ---
|
|
# | Min | Max | Average
|
|
# ----------------------------------------------------------
|
|
# Margin (Zeros): | {min_m0:<7} | {max_m0:<7} | {avg_m0:<7}
|
|
# Margin (Ones): | {min_m1:<7} | {max_m1:<7} | {avg_m1:<7}
|
|
#
|
|
# ==========================================================
|
|
# == CONCLUSION
|
|
# ==========================================================
|
|
# The model was trained to solve the {args.n_bits}-bit '{args.parity_type}' problem.
|
|
# With a final test accuracy of {results['accuracy']:.2%}, the network has demonstrated
|
|
# {'a high degree of success' if results['accuracy'] > 0.95 else 'a moderate level of success' if results['accuracy'] > 0.7 else 'difficulty'}
|
|
# in learning the underlying logical rule.
|
|
#
|
|
# The margin analysis indicates the model's confidence. Larger average margins
|
|
# suggest a more robust and decisive model. The generated plots provide
|
|
# further visual insight into the training process and final performance.
|
|
#
|
|
# This experiment explores the capability of a simple Feed-Forward Network
|
|
# to learn complex, non-linear functions like parity, a task often cited
|
|
# as a challenge for non-recurrent architectures but clearly achievable
|
|
# with sufficient network capacity and training.
|
|
#
|
|
"""
|
|
print("\n" + report_content)
|
|
with open(report_path, "w") as f:
|
|
f.write(report_content)
|
|
print(f"Report saved to {report_path}")
|
|
|
|
def user_inference_loop(model, args):
|
|
"""An interactive loop for the user to test the model. replicate the label-calculation logic directly within the user_inference_loop. This isolates the calculation and uses the user's provided bit string, fixing the crash and ensuring the "True Label" is accurate for the given input. With this correction, the interactive mode will now function as intended, correctly comparing the model's prediction against the true calculated label for your input. System integrity restored."""
|
|
print("\n" + "="*50)
|
|
print("=== INTERACTIVE INFERENCE MODE ===")
|
|
print(f"Enter a {args.n_bits}-bit binary string (e.g., {'10101'[:args.n_bits]}) or 'q' to quit.")
|
|
print("="*50)
|
|
|
|
model.eval()
|
|
while True:
|
|
user_input = input(f"Input ({args.n_bits} bits) > ")
|
|
if user_input.lower() == 'q':
|
|
break
|
|
|
|
if len(user_input) != args.n_bits or not all(c in '01' for c in user_input):
|
|
print(f"Error: Please enter exactly {args.n_bits} bits (0s and 1s).")
|
|
continue
|
|
|
|
bits = [int(c) for c in user_input]
|
|
data_tensor = torch.tensor(bits, dtype=torch.float32).reshape(1, -1)
|
|
|
|
with torch.no_grad():
|
|
output = model(data_tensor)
|
|
prediction = (output > 0.5).int().item()
|
|
confidence = output.item()
|
|
|
|
print(f" Model Output: {confidence:.4f}")
|
|
print(f" -> Predicted Label: {prediction}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
sum_of_bits = sum(bits)
|
|
true_label = -1
|
|
|
|
if args.parity_type == 'even':
|
|
true_label = sum_of_bits % 2
|
|
elif args.parity_type == 'odd':
|
|
true_label = (sum_of_bits + 1) % 2
|
|
elif args.parity_type == 'majority':
|
|
true_label = 1 if sum_of_bits > args.n_bits / 2 else 0
|
|
|
|
|
|
|
|
print(f" -> True Label ({args.parity_type}): {true_label} {'(Correct)' if prediction == true_label else '(Incorrect)'}\n")
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser(description="Train a Neural Network for the N-Bit Parity Problem.")
|
|
|
|
|
|
parser.add_argument('-n', '--n_bits', type=int, default=5, help="Number of input bits (N).")
|
|
parser.add_argument('-l', '--l_layers', type=int, default=2, help="Number of hidden layers (L).")
|
|
parser.add_argument('-hs', '--hidden_size', type=int, default=10, help="Number of neurons per hidden layer.")
|
|
parser.add_argument('-a', '--activation', type=str, default='relu', choices=['relu', 'tanh', 'leakyrelu'], help="Activation function for hidden layers.")
|
|
|
|
|
|
parser.add_argument('-e', '--epochs', type=int, default=10000, help="Maximum number of training epochs.")
|
|
parser.add_argument('-lr', '--learning_rate', type=float, default=0.003, help="Optimizer learning rate.")
|
|
parser.add_argument('-loss', '--min_loss_threshold', type=float, default=0.01, help="Loss threshold to stop training early.")
|
|
parser.add_argument('-puf', '--plot_update_freq', type=int, default=100, help="Frequency (in epochs) to update the live plot.")
|
|
|
|
|
|
parser.add_argument('-pt', '--parity_type', type=str, default='even', choices=['even', 'odd', 'majority'], help="The logical rule to learn.")
|
|
parser.add_argument('-nts', '--num_train_samples', type=int, default=2000, help="Number of samples for the training dataset.")
|
|
parser.add_argument('-ntests', '--num_test_samples', type=int, default=500, help="Number of samples for the test dataset.")
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
run_dir, plots_dir = setup_directories(args)
|
|
|
|
with open(os.path.join(run_dir, 'hyperparameters.json'), 'w') as f:
|
|
json.dump(vars(args), f, indent=4)
|
|
|
|
|
|
print(f"\nGenerating {args.num_train_samples} training and {args.num_test_samples} test samples for {args.n_bits}-bit '{args.parity_type}' parity...")
|
|
train_data, train_labels = generate_data(args.num_train_samples, args.n_bits, args.parity_type)
|
|
test_data, test_labels = generate_data(args.num_test_samples, args.n_bits, args.parity_type)
|
|
print("Data generation complete.")
|
|
|
|
|
|
model = ParityNet(args.n_bits, args.hidden_size, args.l_layers, 1, args.activation)
|
|
print("\nModel Architecture:")
|
|
print(model)
|
|
|
|
|
|
trained_model, history = train_model(model, train_data, train_labels, test_data, test_labels, args, run_dir)
|
|
|
|
|
|
model_path = os.path.join(run_dir, f"parity_nn_N{args.n_bits}_{args.parity_type}.pth")
|
|
torch.save(trained_model.state_dict(), model_path)
|
|
print(f"Trained model weights saved to: {model_path}")
|
|
|
|
|
|
if len(history['epoch']) > 0:
|
|
final_results = evaluate_model(trained_model, test_data, test_labels)
|
|
generate_report(args, final_results, run_dir)
|
|
generate_plots(history, final_results, args, plots_dir)
|
|
else:
|
|
print("\nTraining was too short to generate a full report and plots.")
|
|
|
|
|
|
user_inference_loop(trained_model, args)
|
|
|
|
print("\nSupercoding LLM task complete. System returning to normal operation.") |