tinycodinglm / chess /chess-0079.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
3.26 kB
opencode trace
System You are an expert programmer specializing in chess programming and game AI. You implement efficient algorithms with optimal performance.

You are an expert programmer specializing in chess programming and game AI. You implement efficient algorithms with optimal performance.

User

Implement SPSA (Simultaneous Perturbation Stochastic Approximation) tuning for chess evaluation parameters

Assistant

#include <cstdint>
#include <random>
#include <vector>
#include <cmath>
#include <algorithm>

struct SPSATuner {
struct Parameter {
double value;
double minVal, maxVal;
std::string name;
};

markdown
std::vector<Parameter> params;
double a, c, A, alpha, gamma;
int iterations;
std::mt19937 rng;

SPSATuner(double a_init, double c_init, int maxIter)
    : a(a_init), c(c_init), A(maxIter / 10), alpha(0.602), gamma(0.101),
      iterations(maxIter), rng(std::random_device{}()) {}

void addParameter(double initial, double minV, double maxV, const std::string& name) {
    params.push_back({initial, minV, maxV, name});
}

void tune(std::function<double(const std::vector<double>&)> evaluate) {
    for (int k = 0; k < iterations; k++) {
        // Generate perturbation vector
        std::vector<double> delta(params.size());
        std::bernoulli_distribution bernoulli(0.5);
        for (size_t i = 0; i < params.size(); i++) {
            delta[i] = bernoulli(rng) ? 1.0 : -1.0;
        }

        // Evaluate at theta + c*delta and theta - c*delta
        std::vector<double> thetaPlus(params.size()), thetaMinus(params.size());
        for (size_t i = 0; i < params.size(); i++) {
            thetaPlus[i] = params[i].value + c * delta[i];
            thetaMinus[i] = params[i].value - c * delta[i];
            // Clamp
            thetaPlus[i] = std::clamp(thetaPlus[i], params[i].minVal, params[i].maxVal);
            thetaMinus[i] = std::clamp(thetaMinus[i], params[i].minVal, params[i].maxVal);
        }

        double yPlus = evaluate(thetaPlus);
        double yMinus = evaluate(thetaMinus);

        // Compute gain sequence
        double ak = a / std::pow(A + k + 1, alpha);
        double ck_tilde = c / std::pow(k + 1, gamma);

        // Update parameters
        for (size_t i = 0; i < params.size(); i++) {
            double gradient = (yPlus - yMinus) / (2.0 * ck_tilde * delta[i]);
            params[i].value += ak * gradient;
            params[i].value = std::clamp(params[i].value, params[i].minVal, params[i].maxVal);
        }

        if (k % 100 == 0) {
            printf("Iteration %d: y+=%.4f y-=%.4f\n", k, yPlus, yMinus);
        }
    }
}

void printResults() {
    printf("Tuning results:\n");
    for (auto& p : params) {
        printf("  %s: %.4f\n", p.name.c_str(), p.value);
    }
}

};