tinycodinglm / chess /chess-0096.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
3.45 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 a high-performance transposition table with aging and replacement schemes for chess engines

Assistant

#include <cstdint>
#include <cstring>
#include <algorithm>

struct TTEntry {
uint64_t key16; // 16-bit key for verification
uint16_t move; // best move encoded
int16_t score; // evaluation score
uint8_t depth; // search depth
uint8_t flag; // 0=lower, 1=upper, 2=exact
uint8_t generation; // aging counter
};

class TranspositionTable {
TTEntry* table;
size_t numEntries;
uint8_t currentGeneration;
size_t usedEntries;

markdown
struct IterEntry {
    TTEntry* entry;
    size_t index;
};

public:
TranspositionTable(size_t mbSize) {
numEntries = (mbSize * 1024 * 1024) / sizeof(TTEntry);
table = new TTEntry[numEntries];
clear();
}

markdown
~TranspositionTable() { delete[] table; }

void clear() {
    memset(table, 0, numEntries * sizeof(TTEntry));
    currentGeneration = 0;
    usedEntries = 0;
}

void newSearch() { currentGeneration++; }

TTEntry* probe(uint64_t hash) const {
    size_t idx = hash % numEntries;
    TTEntry* entry = &table[idx];
    if (entry->key16 == (hash >> 48)) return entry;
    // Check adjacent entries (cluster of 4)
    for (int i = 1; i < 4; i++) {
        entry = &table[(idx + i) % numEntries];
        if (entry->key16 == (hash >> 48)) return entry;
    }
    return nullptr;
}

void store(uint64_t hash, int depth, int score, int flag, uint16_t move) {
    size_t idx = hash % numEntries;
    TTEntry* entry = &table[idx];
    TTEntry* replace = entry;

    // Find best slot to replace
    for (int i = 0; i < 4; i++) {
        TTEntry* e = &table[(idx + i) % numEntries];
        if (e->key16 == 0) {
            replace = e;
            break;
        }
        // Prefer: deeper search, same generation, older entry
        if (e->generation != currentGeneration) {
            replace = e;
            break;
        }
        if (e->depth < depth) {
            replace = e;
        }
    }

    replace->key16 = hash >> 48;
    replace->move = move;
    replace->score = score;
    replace->depth = depth;
    replace->flag = flag;
    replace->generation = currentGeneration;
}

void ageEntries() {
    for (size_t i = 0; i < numEntries; i++) {
        if (table[i].generation < currentGeneration - 1) {
            memset(&table[i], 0, sizeof(TTEntry));
        }
    }
}

double occupancy() const {
    size_t used = 0;
    for (size_t i = 0; i < numEntries; i++) {
        if (table[i].key16 != 0) used++;
    }
    return (double)used / numEntries;
}

};