Module contents
Stage 5 of 9Advanced 120 min

The self-play system

Build the systems side: CPU-core search workers, a GPU inference server batching their requests, a game buffer with policy and value targets, a trainer consuming data and publishing network versions, and orchestration to keep the system working overnight without intervention.

After this lesson you can

  • Implement self-play workers and an inference server with inter-process queues.
  • Store games with visit distribution and outcome and sample training batches.
  • Coordinate network publication and server reload without stopping the system.
  • Measure games per hour, GPU utilization, and the relationship between generated and consumed data.

Before you start

From tree to a game factory

PUCT search chooses a move from a network and simulations. Improving the network through self-play requires much more: generate games, turn them into examples, store a data window, train, and make new weights available to searches. Every component can work separately while the complete system stalls, mixes versions, or learns labels from the wrong perspective.

The self-play pipeline we build has four responsibilities: search workers produce trajectories; a server batches requests and runs the network; a buffer retains positions and targets; a trainer consumes samples and publishes versions. Bounded queues and supervision are part of correctness: if a consumer falls behind, producers must wait or apply an explicit policy rather than fill memory indefinitely.

InteractiveThe running system
Discrete-event model: it does not run Connect 4 or measure the GPU. The initial view accumulates 1200 steps to show flow; “From zero” shows startup.
Workers → queue → inference → worker response. Episodes → replay → trainer → new version for future episodes.
1 · Workers
12345678

4 computing · 0 waiting · 4 in service

Each episode retains one version until completion.

2 · FIFO request queue

0 of 8 workers are queued.

When the server is free, a batch dispatches at the maximum or when the oldest request waits 3 steps.

3 · Inference server

Active batch: 4 requests

Service for a batch of size b: 2+b steps. The response immediately returns to the worker.

4 · Games and replay

8 completed episodes · 32 positions stored in total.

FIFO buffer: 32 / 128 positions.

Oldest version present: 0.

5 · Trainer and publication

Updates: 109 · reads: 218.

Published version: 13. Each worker adopts it at the start of another episode.

Sampling with replacement does not remove positions from the buffer.

  • Worker computation
  • Queued request
  • Batch in service

Model rules: each worker computes 6 steps and holds at most one pending request; each position needs 16 responses and each episode contains 4 positions. If the buffer is nonempty, the trainer performs two reads with replacement every 4 steps and publishes a version every 8 updates. Positions, evaluations, and versions are teaching counters, not real games or parameters. Rates and utilization accumulate from model start; an idle server may be awaiting requests or batch formation. The model does not separate batches by version or represent failures, transfers, CPU contention, or timing variability.

8
Maximum batch
Model time1200 steps
Completed inferences / 100 steps66.33
Server busy99.6 %
Mean queue wait0.03 steps
Reads / generated positions6.81
The figure simulates a queueing system with explicit parameters and virtual steps. Change worker count and maximum batch, advance the clock, and observe requests, buffer, and trainer. Rates belong to that model, not GPU measurements.

A growing queue shows a rate imbalance but does not by itself identify its cause. Inference capacity may be insufficient, the server may wait to fill batches, or the trainer may consume faster than positions arrive. In the figure, capacity and times are defined by a reproducible model; the lab must measure them. Device utilization is not playing strength: producing many games with a defective network accelerates production of defective data.

The figure’s model uses virtual steps. Each worker computes for 6 steps and holds at most one pending request. When the server is free it dispatches on reaching maximum batch or when the oldest request has waited at least 3 steps; a batch of size bb takes 2+b2+b steps. One position requires 16 responses and an episode contains 4 positions; replay stores up to 128 positions and the trainer makes two reads with replacement every 4 steps when data exist. These rules explore a producer-consumer system; they are not measurements or a quantitative description of Connect 4. The model does not separate batches by network version. Changing worker count or maximum batch restarts that simulation with the same rules.

What travels through the system

A game is a sequence of nonterminal states, actions, and finally an outcome. At each position sts_t, search produces visits N(st,a)N(s_t,a) for legal actions. In this lab the policy target πt\pi_t normalizes visits; choosing the action uses a temperature that can produce another distribution. Value target ztz_t is the final result from the player who moved in that position. If the winner is the player to move, zt=+1z_t=+1; if the opponent won, −1-1; a draw is 00. Sign changes between turns in an alternating game, but the result must not be inferred before the game ends.

Replay-buffer targets are tuples of state, legal actions, visit distribution, result, and metadata. Network version, seed or generator state, opening, game identifier, and temperature and noise conventions are useful. Raw visits allow reconstruction of how the distribution was obtained; saving only the chosen move discards information about explored alternatives. The lab saves version, worker, actions, and normalized distribution; legal actions derive from the occupancy mask. It does not save raw visits or generator state per game: that limitation prevents reproducing each trajectory from its isolated record. An interrupted game has no valid final outcome and must not silently become a draw.

Processes, queues, and one CUDA owner

The batched inference server receives requests from multiple workers, gathers a batch up to a maximum or deadline, and returns each response to its requester. A request needs a unique identifier and associated response path; distributing outputs by arrival order without correlation can deliver a policy for another board. On a shared GPU, keeping one process as model and CUDA owner while game workers run on CPU avoids creating an independent CUDA context per worker.

On Windows, spawn starts new interpreters. Target functions must be importable and launching protected by if __name__ == '__main__', as the PyTorch Windows documentation explains. A function defined only in an interactive cell may not be importable by the child. multiprocessing queues serialize objects; an implementation must close producers, drain or signal completion, wait for children, and handle errors. Python documentation warns that abruptly terminating a process using a queue can corrupt it. empty() is not used as a reliable test of concurrent completion.

A queue copies and reconstructs carried objects; for large arrays, consider shared memory and pass only block name, dimensions, and type through the queue. This changes the lifetime contract: the producer cannot reuse the block while the server reads it, and processes need a signal to agree when reading is complete. Each process closes its own reference and on Windows the block is freed when all close. Sharing CPU memory does not itself create a shared CUDA model or avoid device transfer. The lab uses serialized queues to keep that contract simple; shared memory is an alternative to measure and test separately.

Batching does not mean waiting indefinitely for a full batch. The first item sets a deadline and, if the server is free, a partial batch is processed at expiry. This is not a hard response deadline: if the server remains busy with another batch, a request may wait longer and dispatch when it becomes available. A small maximum reduces formation delay but may waste capacity; a large one can increase latency or deliver stale information to searches. The relationship depends on request arrival, inference duration, and CPU work. Measure wait time, effective batch sizes, and completed throughput, not only configured maximum size.

Buffer, reuse, and age

A bounded FIFO buffer retains the newest examples and discards the oldest when full. The trainer samples with replacement: drawing an example does not remove it. If a window generates GG new positions and consumes CC samples, C/GC/G measures aggregate reuse in that window, provided G>0G>0. It approximates uses per position only under conditions such as stable rate and buffer size. Alone it reveals neither age distribution nor how often each example was used.

A buffer that is too large can retain games from old networks and shift the training distribution; one too small can yield high correlation among recent samples. If the trainer consumes much faster than data arrive, reuse rises and it can overfit a narrow set. If it consumes too slowly, positions accumulate or are discarded before use. Recording generation and consumption by version diagnoses both without assuming the aggregate rate tells the whole story.

The lab’s credit mechanism makes the relationship concrete. Each 16 new positions accumulate credit for one 64-sample update. Starting from an empty buffer and zero credit, once the buffer holds at least 64 positions, and assuming every game is processed without error, the GG positions generated since the start permit U=⌊G/16⌋U=\lfloor G/16\rfloor updates and C=64UC=64U reads. For example, with G=100G=100 there are 6 updates and 384 reads, so C/G=3.84C/G=3.84. This is total consumption divided by total generation, not the number of times each position was read: sampling is with replacement and some positions may have been discarded or never chosen.

Publish weights without mixing versions

The trainer writes weights to a checkpoint with a versioned name and computes its hash; only after writing and verifying does it announce the version with path and hash. The server loads the candidate network separately and swaps its reference at a batch boundary, so each response can be associated with a specific version. If loading fails, it retains the previous version and records failure. For a game fixing a version at the start, the server must keep it available until that game’s requests finish, or explicitly reject work if it can no longer do so. The hash is checked during publication, but this lab does not retain it in a per-version log for later audit.

On Windows, check open and replacement errors on the actual system. Writing a temporary file in the same directory and publishing an immutable version name only after closing and verification avoids announcing an incomplete file; it does not automatically guarantee durability across power loss. The os.replace documentation states atomicity as a POSIX requirement, so we will not extend it without tests to every Windows filesystem.

Publishing the latest version reduces delay but does not guarantee monotonic improvement. Evaluating a candidate against a previous version adds cost and statistical noise and can slow updates. AlphaGo Zero describes evaluation over 400 games and a threshold above 55% to accept a network; AlphaZero describes continuous updating of the latest network. These are different systems and evaluation decisions, not proof that either guarantees improvement at every publication.

Measure without confusing capacity and outcome

Games per hour are 36003600 times completed games divided by observed seconds. Generated positions and consumed samples are counted in the same window and explicit units; a position sampled multiple times counts multiple times in consumption. Inference throughput alone does not determine games per hour: queries per move depend on terminals, cache, tree size, and initial evaluation.

Utilization reported by nvidia-smi is, according to NVIDIA, the fraction of the sampling window during which at least one kernel ran. It is neither the percentage of compute units occupied nor a memory measure. On a shared GPU it is a device-wide signal and cannot all be attributed to this lesson’s pipeline. Also record queue latency, batch sizes, versions, memory, and samples per second, and distinguish a live process from one actually producing games.

A continuous-operation test needs timestamps, progress throughout the interval, detection of failed processes, and clean shutdown. A short run multiplied by a factor does not demonstrate long-duration stability. If interrupted, record the test as incomplete; only an actual run of more than eight hours without intervention supports claiming that specific goal was met.

Lab

First reproduce the previous lesson’s engine and supervised training using its current cells. The initial checkpoint is stored as CPU tensors; subsequent runs create their own directory and do not mix data or overwrite versions. CUDA is required for the test server. The experiment-leading process renews the heartbeat file, and the Windows Job Object terminates descendants if the supervisor disappears.

[ ]Reproduced engine and solverLocal GPU
W, H, S = 7, 6, 7
ORDER = (3, 2, 4, 1, 5, 0, 6)
BOTTOM = sum(1 << (c * S) for c in range(W))
BOARD = BOTTOM * ((1 << H) - 1)

def win(p):
    for d in (1, 6, 7, 8):
        pairs = p & (p >> d)
        if pairs & (pairs >> (2 * d)):
            return True
    return False

def move_bit(mask, c):
    legal = (mask + BOTTOM) & BOARD
    return legal & (((1 << H) - 1) << (c * S))

def position(sequence):
    # sequence contiene columnas desde cero y termina antes de ganar.
    current = mask = 0
    for c in sequence:
        if not 0 <= c < W:
            raise ValueError('Columna fuera del tablero')
        b = move_bit(mask, c)
        if not b or win(current | b):
            raise ValueError('Columna llena o partida ya terminada')
        current, mask = current ^ mask, mask | b
    return current, mask

class Solver:
    def __init__(self):
        self.table = {}
        self.nodes = 0

    def search(self, current, mask, alpha, beta):
        self.nodes += 1
        if mask == BOARD:
            return 0
        key = current + mask
        entry = self.table.get(key)
        if entry is not None:
            lower, upper = entry
            if lower == upper:
                return lower
            alpha, beta = max(alpha, lower), min(beta, upper)
            if alpha >= beta:
                return lower if lower >= beta else upper
        a0, b0 = alpha, beta
        best = -2
        for c in ORDER:
            b = move_bit(mask, c)
            if not b:
                continue
            if win(current | b):
                value = 1
            else:
                value = -self.search(current ^ mask, mask | b, -beta, -alpha)
            best = max(best, value)
            alpha = max(alpha, best)
            if alpha >= beta:
                break
        lower, upper = self.table.get(key, (-1, 1))
        if best <= a0:
            upper = min(upper, best)
        elif best >= b0:
            lower = max(lower, best)
        else:
            lower = upper = best
        self.table[key] = (lower, upper)
        return best

    def value(self, current, mask):
        return self.search(current, mask, -2, 2)

    def analyze(self, current, mask):
        values = []
        for c in range(W):
            b = move_bit(mask, c)
            if not b:
                values.append(None)
            elif win(current | b):
                values.append(1)
            else:
                values.append(-self.value(current ^ mask, mask | b))
        return values


import numpy as np
from numba import njit, types
from numba.typed import Dict

@njit
def n_win(p):
    for d in (1, 6, 7, 8):
        pairs = p & (p >> d)
        if pairs & (pairs >> (2*d)):
            return True
    return False

@njit
def n_bit(mask, c):
    return ((mask + BOTTOM) & BOARD) & (63 << (c*7))

@njit
def n_search(p, mask, alpha, beta, table, counter):
    counter[0] += 1
    if mask == BOARD:
        return 0
    key = p + mask
    if key in table:
        entry = table[key]
        lower, upper = entry // 3 - 1, entry % 3 - 1
        if lower == upper:
            return lower
        alpha, beta = max(alpha, lower), min(beta, upper)
        if alpha >= beta:
            return lower if lower >= beta else upper
    a0, b0 = alpha, beta
    best = -2
    for c in (3, 2, 4, 1, 5, 0, 6):
        b = n_bit(mask, c)
        if not b:
            continue
        if n_win(p | b):
            table[key] = 8
            return 1
        value = -n_search(p ^ mask, mask | b, -beta, -alpha, table, counter)
        best = max(best, value)
        alpha = max(alpha, best)
        if alpha >= beta:
            break
    lower, upper = -1, 1
    if key in table:
        entry = table[key]
        lower, upper = entry // 3 - 1, entry % 3 - 1
    if best <= a0:
        upper = min(upper, best)
    elif best >= b0:
        lower = max(lower, best)
    else:
        lower = upper = best
    table[key] = (lower + 1)*3 + upper + 1
    return best

@njit
def n_analyze(p, mask, table, counter):
    result = np.full(7, -2, dtype=np.int64)
    for c in range(7):
        b = n_bit(mask, c)
        if b:
            if n_win(p | b):
                result[c] = 1
            else:
                result[c] = -n_search(p ^ mask, mask | b, -2, 2, table, counter)
    return result

@njit
def n_value(p, mask, table, counter):
    if n_search(p, mask, -1, 0, table, counter) < 0:
        return -1
    if n_search(p, mask, 0, 1, table, counter) >= 1:
        return 1
    return 0
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Rebuild the network and save initial weightsLocal GPU
"""Experimento de política y valor con el oráculo de la lección actual p12-l01."""
import json
import gc
import math
import os
import random
import re
import time
from pathlib import Path
import numpy as np
os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG', ':4096:8')
import torch
from torch import nn
import torch.nn.functional as F

torch.set_num_threads(1)
random.seed(1203)
np.random.seed(1203)
torch.manual_seed(1203)
torch.use_deterministic_algorithms(True)

def reflect(x):
    out = 0
    for c in range(7):
        out |= ((x >> (7*c)) & 127) << (7*(6-c))
    return out

def generate(engine, n=20000):
    from numba import types
    from numba.typed import Dict
    win, bit, analyze = engine['win'], engine['move_bit'], engine['n_analyze']
    table = Dict.empty(key_type=types.int64, value_type=types.int64)
    counter = np.zeros(1, np.int64)
    rng = random.Random(1201)
    records, seen = [], set()
    attempts = 0
    while len(records) < n:
        p = mask = 0
        seq = []
        for _ in range(36):
            legal = [(c, bit(mask, c)) for c in range(7)]
            legal = [(c,b) for c,b in legal if b and not win(p | b)]
            if not legal:
                break
            c, b = rng.choice(legal)
            seq.append(c)
            p, mask = p ^ mask, mask | b
        attempts += 1
        if len(seq) != 36 or p + mask in seen:
            continue
        seen.add(p + mask)
        values = [int(v) for v in analyze(p, mask, table, counter)]
        records.append({'sequence': seq, 'p': p, 'mask': mask, 'values': values})
        if len(records) % 1000 == 0:
            table.clear()
    print('Posiciones etiquetadas:', len(records), 'intentos:', attempts, flush=True)
    return records

def key(record):
    p, mask = record['p'], record['mask']
    return min((p,mask), (reflect(p), reflect(mask)))

def split(records):
    groups = {}
    for row in records:
        groups.setdefault(key(row), []).append(row)
    keys = list(groups)
    random.Random(1203).shuffle(keys)
    cutoff = int(.8 * len(keys))
    train = [row for k in keys[:cutoff] for row in groups[k]]
    test = [row for k in keys[cutoff:] for row in groups[k]]
    assert set(map(key,train)).isdisjoint(set(map(key,test)))
    print('Grupos de posición y reflejo:', len(groups), '; entrenamiento:', len(train), '; prueba:', len(test), flush=True)
    return train,test

def encode(row):
    p, mask = row['p'], row['mask']
    x = np.zeros((2,6,7), dtype=np.float32)
    for c in range(7):
        for r in range(6):
            bit = 1 << (7*c+r)
            x[0,r,c] = bool(p & bit)
            x[1,r,c] = bool((p ^ mask) & bit)
    legal = np.array([v != -2 for v in row['values']])
    if not legal.any():
        raise ValueError('No se puede evaluar un estado terminal sin jugadas legales')
    best = max(v for v in row['values'] if v != -2)
    optimal = np.array([v == best for v in row['values']], dtype=np.float32)
    policy = optimal / optimal.sum()
    return x, legal, policy, np.float32(best)

def tensors(rows):
    z = [encode(row) for row in rows]
    return [torch.tensor(np.stack([x[i] for x in z])) for i in range(4)]

class Block(nn.Module):
    def __init__(self, channels):
        super().__init__()
        self.conv1 = nn.Conv2d(channels, channels, 3, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(channels)
        self.conv2 = nn.Conv2d(channels, channels, 3, padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(channels)
    def forward(self, x):
        y = F.relu(self.bn1(self.conv1(x)))
        return F.relu(x + self.bn2(self.conv2(y)))

class PolicyValue(nn.Module):
    def __init__(self, channels=32, blocks=3):
        super().__init__()
        self.stem = nn.Sequential(nn.Conv2d(2,channels,3,padding=1,bias=False), nn.BatchNorm2d(channels), nn.ReLU())
        self.tower = nn.Sequential(*(Block(channels) for _ in range(blocks)))
        self.policy = nn.Sequential(nn.Conv2d(channels,2,1), nn.ReLU(), nn.Flatten(), nn.Linear(84,7))
        self.value = nn.Sequential(nn.Conv2d(channels,1,1), nn.ReLU(), nn.Flatten(), nn.Linear(42,32), nn.ReLU(), nn.Linear(32,1), nn.Tanh())
    def forward(self,x,legal):
        y = self.tower(self.stem(x))
        logits = self.policy(y).masked_fill(~legal, -1e9)
        return logits, self.value(y).squeeze(-1)


def train_run():
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    print('Dispositivo:', device, flush=True)
    eng = {'win': win, 'move_bit': move_bit, 'n_analyze': n_analyze}
    records = generate(eng)
    training, testing = split(records)
    X,L,P,V = tensors(training)
    Xt,Lt,Pt,Vt = tensors(testing)
    model = PolicyValue().to(device)
    print('Parámetros:', sum(p.numel() for p in model.parameters()), flush=True)
    optimizer = torch.optim.AdamW(model.parameters(), lr=0.001, weight_decay=1e-4)
    order_rng = torch.Generator().manual_seed(1203)
    losses = []
    for epoch in range(12):
        model.train()
        order = torch.randperm(len(X), generator=order_rng)
        total = 0
        for ix in order.split(256):
            x,l,p,v = X[ix].to(device), L[ix].to(device), P[ix].to(device), V[ix].to(device)
            # La misma reflexión transforma tablero, legales y objetivo de política.
            flip = (torch.rand(len(ix), generator=order_rng) < .5).to(device)
            x[flip] = x[flip].flip(-1)
            l[flip] = l[flip].flip(-1)
            p[flip] = p[flip].flip(-1)
            logits, value = model(x,l)
            loss = -(p*F.log_softmax(logits,dim=1)).sum(dim=1).mean() + F.mse_loss(value,v)
            optimizer.zero_grad(set_to_none=True)
            loss.backward()
            optimizer.step()
            total += loss.item()*len(ix)
        losses.append(total / len(X))
        print('Época:', epoch+1, 'pérdida:', round(losses[-1],4), flush=True)
    model.eval()
    print('Red supervisada reconstruida con la partición de p12-l03')
    return model, testing

model, heldout = train_run()

from pathlib import Path
import gc
repo = next(p for p in (Path.cwd(), *Path.cwd().parents) if (p / 'package.json').is_file())
lab = repo / 'labs/runs/p12-l05/lesson-lab'
lab.mkdir(parents=True, exist_ok=True)
state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
torch.save(state, lab / 'initial.pt')
del state, model
gc.collect()
if torch.cuda.is_available():
    torch.cuda.synchronize()
    clear = getattr(torch._C, '_cuda_clearCublasWorkspaces', None)
    if clear:
        clear()
    torch.cuda.empty_cache()
    print('CUDA activa tras liberar la red inicial:', torch.cuda.memory_allocated())
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The following code creates importable modules from the preceding engine and architecture. The local PUCT adaptation removes each reservation before backing up its leaf: if a backup fails, cleanup reverts only reservations that remain. The server batches at most 64 states and the 5 ms deadline begins when the oldest request is enqueued. Each game pins a version; the server retains it while in use. The trainer samples with replacement. Targets are normalized visits, while actions use temperature 1 for the first eight moves and then temperature 0, with Dirichlet noise at the root.

Checkpoints have immutable names, are closed and verified before announcement. If loading fails, the server retains the previous network and the coordinator stops the experiment with error. Disk replay rotates: the audit checks all retained files, which may represent only part of a long run. Rates are cumulative; nvidia-smi utilization and memory are global to the shared GPU.

Follow a game to check the contract. First the worker requests acquire: the server reserves the active version and returns its identifier. Throughout that game, each eval request carries that identifier, even if the trainer announces another network meanwhile. For example, if requests of 8 and 4 states from two workers with the same version arrive before the deadline, the server can evaluate them together as a batch of 12 and distribute the first 8 and next 4 outputs by request identifier. A different-version request is not mixed into that batch. When the game ends, its version is saved and release sent; the server discards an old network only once no games reserve it. This sequence explains the protocol, not a batch-size measurement.

[ ]Create modules for Windows processesLocal GPU
# En Windows spawn necesita funciones importables; se escriben módulos completos.
puct_source = r'''"""PUCT para el motor y la red de p12-l01 y p12-l03.

El evaluador recibe [(current, mask), ...] y devuelve logits (B, 7) y valores
(B,), siempre desde la perspectiva del jugador que mueve en cada estado.
"""
from dataclasses import dataclass, field
import math
import numpy as np

W, H, S = 7, 6, 7
BOTTOM = sum(1 << (c * S) for c in range(W))
BOARD = BOTTOM * ((1 << H) - 1)


def win(p):
    for d in (1, 6, 7, 8):
        pairs = p & (p >> d)
        if pairs & (pairs >> (2 * d)):
            return True
    return False


def move_bit(mask, c):
    return ((mask + BOTTOM) & BOARD) & (63 << (c * S))


def encode(states):
    x = np.zeros((len(states), 2, H, W), dtype=np.float32)
    legal = np.zeros((len(states), W), dtype=bool)
    for i, (p, mask) in enumerate(states):
        for c in range(W):
            legal[i, c] = bool(move_bit(mask, c))
            for r in range(H):
                bit = 1 << (S*c + r)
                x[i, 0, r, c] = bool(p & bit)
                x[i, 1, r, c] = bool((p ^ mask) & bit)
    return x, legal


class TorchEvaluator:
    """Adaptador de la clase PolicyValue de p12-l03, con inferencia agrupada."""
    def __init__(self, model, device):
        self.model, self.device = model, device
        self.model.eval()

    def __call__(self, states):
        import torch
        x, legal = encode(states)
        if not legal.any(axis=1).all():
            raise ValueError('La red no evalúa posiciones sin acciones legales')
        with torch.inference_mode():
            logits, values = self.model(torch.from_numpy(x).to(self.device),
                                        torch.from_numpy(legal).to(self.device))
        return logits.cpu().numpy(), values.cpu().numpy()


@dataclass
class Edge:
    prior: float
    visits: int = 0
    total: float = 0.0  # Valor desde el jugador del padre.
    virtual: int = 0
    child: object = None


@dataclass
class Node:
    p: int
    mask: int
    terminal: object = None  # None no terminal, -1 derrota, 0 empate.
    edges: dict = field(default_factory=dict)
    expanded: bool = False
    pending: bool = False


def expand(node, logits):
    """Softmax exclusivamente sobre legales; rechaza salidas no finitas."""
    actions = [c for c in range(W) if move_bit(node.mask, c)]
    if node.terminal is not None or not actions:
        raise ValueError('No se expande un estado terminal')
    logits = np.asarray(logits, dtype=float)
    if logits.shape != (W,) or not np.isfinite(logits[actions]).all():
        raise ValueError('Logits legales inválidos')
    weights = np.exp(logits[actions] - np.max(logits[actions]))
    weights /= weights.sum()
    node.edges = {c: Edge(float(prior)) for c, prior in zip(actions, weights)}
    node.expanded = True


def child_of(node, action):
    edge = node.edges[action]
    if edge.child is None:
        bit = move_bit(node.mask, action)
        mask = node.mask | bit
        terminal = -1 if win(node.p | bit) else (0 if mask == BOARD else None)
        edge.child = Node(node.p ^ node.mask, mask, terminal)
    return edge.child


def select(node, c_puct, virtual_loss):
    # Con cero visitas se usa sqrt(1) para que el prior decida la primera rama.
    parent_visits = sum(e.visits + e.virtual for e in node.edges.values())
    root = math.sqrt(max(1, parent_visits))
    def score(edge):
        n = edge.visits + edge.virtual
        q = (edge.total - virtual_loss * edge.virtual) / n if n else 0.0
        return q + c_puct * edge.prior * root / (1 + n)
    return max(node.edges, key=lambda c: score(node.edges[c]))


def apply_virtual(path):
    for edge in path:
        edge.virtual += 1


def revert_virtual(path):
    for edge in path:
        if edge.virtual <= 0:
            raise AssertionError('Pérdida virtual sin reserva')
        edge.virtual -= 1


def backup(path, leaf_value):
    """Cada arista guarda el valor desde el jugador que la eligió."""
    value = float(leaf_value)
    for edge in reversed(path):
        value = -value
        edge.visits += 1
        edge.total += value


def policy_from_visits(counts, temperature):
    counts = np.asarray(counts, dtype=np.int64)
    if counts.shape != (W,) or np.any(counts < 0) or counts.sum() == 0:
        raise ValueError('Se necesitan visitas no negativas y alguna positiva')
    if not np.isfinite(temperature) or temperature < 0:
        raise ValueError('Temperatura inválida')
    out = np.zeros(W, dtype=float)
    if temperature == 0:
        out[np.argmax(counts)] = 1.0
    else:
        active = counts > 0
        log_weights = np.log(counts[active])
        # Restar antes de dividir evita inf - inf con temperatura muy pequeña.
        with np.errstate(over='ignore'):
            log_weights = (log_weights - log_weights.max()) / temperature
        weights = np.exp(log_weights)
        out[active] = weights / weights.sum()
    return out


def search(p, mask, evaluator, simulations=200, batch_size=16, c_puct=1.5,
           virtual_loss=1.0, noise_fraction=0.0, alpha=0.3, rng=None):
    """Raíz evaluada aparte; cada simulación aumenta una visita de raíz.

    La recolección termina antes de llenar el lote si alcanza una hoja ya
    reservada; así no se cuenta una misma evaluación como varias simulaciones.
    Los terminales se resuelven sin red. No se comparten árboles ni hilos.
    """
    if simulations < 1 or batch_size < 1:
        raise ValueError('Presupuesto y lote deben ser positivos')
    if not all(np.isfinite(x) for x in (c_puct, virtual_loss, noise_fraction)):
        raise ValueError('Parámetros de búsqueda no finitos')
    if c_puct < 0 or virtual_loss < 0 or not 0 <= noise_fraction <= 1:
        raise ValueError('Parámetros de búsqueda inválidos')
    if noise_fraction and (not np.isfinite(alpha) or alpha <= 0):
        raise ValueError('Alpha debe ser positivo')
    if (p & ~mask) or (mask & ~BOARD) or mask == BOARD or win(p) or win(p ^ mask):
        raise ValueError('La raíz debe ser una posición no terminal')
    rng = np.random.default_rng() if rng is None else rng
    root = Node(p, mask)

    def evaluate(nodes):
        logits, values = evaluator([(n.p, n.mask) for n in nodes])
        logits, values = np.asarray(logits), np.asarray(values)
        if logits.shape != (len(nodes), W) or values.shape != (len(nodes),):
            raise ValueError('Dimensiones del evaluador inválidas')
        if not np.isfinite(values).all() or np.any(np.abs(values) > 1):
            raise ValueError('Valores fuera de [-1, 1]')
        for node, row in zip(nodes, logits):
            expand(node, row)
        return values

    evaluate([root])
    if noise_fraction:
        noise = rng.dirichlet(np.full(len(root.edges), alpha))
        for edge, sample in zip(root.edges.values(), noise):
            edge.prior = (1-noise_fraction)*edge.prior + noise_fraction*sample

    done = 0
    while done < simulations:
        queued = []
        try:
            while len(queued) < batch_size and done + len(queued) < simulations:
                node, path = root, []
                while node.expanded:
                    action = select(node, c_puct, virtual_loss)
                    edge = node.edges[action]
                    path.append(edge)
                    node = child_of(node, action)
                if node.terminal is not None:
                    backup(path, node.terminal)
                    done += 1
                elif node.pending:
                    # Liberar las reservas previas antes de volver a seleccionar.
                    break
                else:
                    node.pending = True
                    apply_virtual(path)
                    queued.append((node, path))
            if queued:
                values = evaluate([node for node, _ in queued])
                for (node, path), value in zip(queued, values):
                    revert_virtual(path)
                    node.pending = False
                    backup(path, value)
                    done += 1
                queued.clear()
        finally:
            for node, path in queued:
                revert_virtual(path)
                node.pending = False
    counts = np.zeros(W, dtype=np.int64)
    for action, edge in root.edges.items():
        counts[action] = edge.visits
    return root, counts
'''
before = r'''                for (node, path), value in zip(queued, values):
                    revert_virtual(path)
                    node.pending = False
                    backup(path, value)
                    done += 1
                queued.clear()'''
after = r'''                for value in values:
                    node, path = queued.pop(0)
                    revert_virtual(path)
                    node.pending = False
                    backup(path, value)
                    done += 1'''
assert puct_source.count(before) == 1
(lab / 'puct_game.py').write_text(puct_source.replace(before, after) + '\n', encoding='utf-8')
(lab / 'net.py').write_text(r'''import torch
from torch import nn
import torch.nn.functional as F

class Block(nn.Module):
    def __init__(self, channels):
        super().__init__()
        self.conv1 = nn.Conv2d(channels, channels, 3, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(channels)
        self.conv2 = nn.Conv2d(channels, channels, 3, padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(channels)
    def forward(self, x):
        y = F.relu(self.bn1(self.conv1(x)))
        return F.relu(x + self.bn2(self.conv2(y)))

class PolicyValue(nn.Module):
    def __init__(self, channels=32, blocks=3):
        super().__init__()
        self.stem = nn.Sequential(nn.Conv2d(2,channels,3,padding=1,bias=False), nn.BatchNorm2d(channels), nn.ReLU())
        self.tower = nn.Sequential(*(Block(channels) for _ in range(blocks)))
        self.policy = nn.Sequential(nn.Conv2d(channels,2,1), nn.ReLU(), nn.Flatten(), nn.Linear(84,7))
        self.value = nn.Sequential(nn.Conv2d(channels,1,1), nn.ReLU(), nn.Flatten(), nn.Linear(42,32), nn.ReLU(), nn.Linear(32,1), nn.Tanh())
    def forward(self,x,legal):
        y = self.tower(self.stem(x))
        logits = self.policy(y).masked_fill(~legal, -1e9)
        return logits, self.value(y).squeeze(-1)
''', encoding='utf-8')
(lab / 'pipeline.py').write_text(r'''"""Autojuego en procesos, servidor CUDA, replay acotado y entrenador CPU."""
import argparse
import collections
import datetime
import hashlib
import json
import logging
import logging.handlers
import multiprocessing as mp
import os
import queue
import random
import subprocess
import time
import traceback
from pathlib import Path


def checksum(path):
    h = hashlib.sha256()
    with open(path,'rb') as f:
        for block in iter(lambda: f.read(1024*1024),b''):
            h.update(block)
    return h.hexdigest()


def publish_file(state, version, folder):
    import torch
    folder = Path(folder)
    folder.mkdir(parents=True,exist_ok=True)
    target = folder / f'version-{version:08d}.pt'
    tmp = folder / f'version-{version:08d}.tmp'
    if target.exists() or tmp.exists():
        raise FileExistsError('Una versión nunca se sobrescribe')
    with tmp.open('xb') as f:
        torch.save(state,f)
        f.flush()
        os.fsync(f.fileno())
    digest = checksum(tmp)
    os.replace(tmp,target)
    if checksum(target) != digest:
        raise IOError('Hash del checkpoint no coincide')
    return str(target.resolve()),digest


def inference_server(requests, replies, updates, events, initial_path, gpu_required):
    import numpy as np
    import torch
    from net import PolicyValue
    from puct_game import encode
    torch.set_num_threads(1)
    if gpu_required and not torch.cuda.is_available():
        raise RuntimeError('La prueba requiere CUDA')
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    models, leases = {}, {}
    current = 0
    pending_version = None
    def load(version,path,digest=None):
        if digest is not None and checksum(path) != digest:
            raise IOError('El hash no coincide; se conserva la versión anterior')
        state = torch.load(path,map_location='cpu',weights_only=True)
        model = PolicyValue().to(device)
        model.load_state_dict(state)
        model.eval()
        models[version] = model
        leases[version] = 0
        del state
    load(0,initial_path)
    events.put(('server_ready',str(device),os.getpid()))
    deferred = collections.deque()
    stopping = False
    n_calls = n_states = n_requests = 0
    total_wait = max_wait = 0.0
    batch_sizes, inference_versions = collections.Counter(), collections.Counter()
    last_stats = time.monotonic()
    try:
        while not stopping:
            try:
                while True:
                    proposal = updates.get_nowait()
                    if pending_version is None or proposal[0] > pending_version[0]:
                        pending_version = proposal
            except queue.Empty:
                pass
            for version in list(models):
                if version != current and leases[version] == 0:
                    del models[version], leases[version]
            if pending_version is not None and len(models) < 2:
                version,path,digest = pending_version
                pending_version = None
                if version > current:
                    try:
                        load(version,path,digest)
                        current = version
                        events.put(('published',version))
                    except Exception as error:
                        events.put(('publication_error',version,str(error)))
            try:
                item = deferred.popleft() if deferred else requests.get(timeout=.1)
            except queue.Empty:
                continue
            kind,wid,rid,payload,enqueued = item
            if kind == 'stop':
                stopping = True
                continue
            if kind == 'acquire':
                leases[current] += 1
                replies[wid].put((rid,True,current))
                continue
            if kind == 'release':
                if payload not in leases or leases[payload] <= 0:
                    raise RuntimeError('Liberación de versión sin reserva')
                leases[payload] -= 1
                continue
            if kind != 'eval':
                raise ValueError('Petición desconocida')
            version,states = payload
            batch = [(wid,rid,states,enqueued)]
            nstates = len(states)
            deadline = enqueued+.005
            while nstates < 64 and time.monotonic() < deadline:
                try:
                    nxt = requests.get(timeout=max(0,deadline-time.monotonic()))
                except queue.Empty:
                    break
                nk,nw,nr,npayload,nqueued = nxt
                if nk == 'eval' and npayload[0] == version and nstates+len(npayload[1]) <= 64:
                    batch.append((nw,nr,npayload[1],nqueued)); nstates += len(npayload[1])
                else:
                    deferred.append(nxt)
                if time.monotonic() >= deadline:
                    break
            try:
                if version not in models:
                    raise RuntimeError('Versión solicitada no disponible')
                now = time.monotonic()
                waits = [max(0.,now-arrival) for _,_,_,arrival in batch]
                states = [s for _,_,part,_ in batch for s in part]
                x,legal = encode(states)
                if not legal.any(axis=1).all():
                    raise ValueError('Estado sin acción legal')
                with torch.inference_mode():
                    logits,values = models[version](torch.from_numpy(x).to(device),
                                                    torch.from_numpy(legal).to(device))
                logits,values = logits.cpu().numpy(),values.cpu().numpy()
                offset = 0
                for worker,request,part,_ in batch:
                    size = len(part)
                    replies[worker].put((request,True,(logits[offset:offset+size].tolist(),
                                                       values[offset:offset+size].tolist())))
                    offset += size
                n_calls += 1
                n_states += nstates
                n_requests += len(batch)
                total_wait += sum(waits)
                max_wait = max(max_wait,max(waits))
                batch_sizes[nstates] += 1
                inference_versions[version] += nstates
                if time.monotonic()-last_stats >= 1:
                    events.put(('inference',n_calls,n_states,n_requests,total_wait,max_wait,dict(batch_sizes),dict(inference_versions)))
                    n_calls = n_states = n_requests = 0
                    total_wait = max_wait = 0.0
                    batch_sizes.clear(); inference_versions.clear()
                    last_stats = time.monotonic()
            except Exception as error:
                for worker,request,_,_ in batch:
                    replies[worker].put((request,False,str(error)))
    finally:
        if n_calls:
            events.put(('inference',n_calls,n_states,n_requests,total_wait,max_wait,dict(batch_sizes),dict(inference_versions)))
        models.clear()
        if device.type == 'cuda':
            torch.cuda.synchronize()
            clear = getattr(torch._C,'_cuda_clearCublasWorkspaces',None)
            if clear: clear()
            torch.cuda.empty_cache()
            events.put(('cuda_after_cleanup',torch.cuda.memory_allocated()))


def play_worker(wid,requests,replies,games,events,stop,simulations):
    import numpy as np
    from puct_game import BOARD, move_bit, win, search, policy_from_visits
    rng = np.random.default_rng(120500+wid)
    next_id = 0
    def request(kind,payload=None):
        nonlocal next_id
        next_id += 1
        requests.put((kind,wid,next_id,payload,time.monotonic()),timeout=30)
        rid,ok,value = replies.get(timeout=60)
        if rid != next_id or not ok:
            raise RuntimeError(f'Respuesta inválida o error: {value}')
        return value
    while not stop.is_set():
        version = request('acquire')
        samples = []
        try:
            def evaluator(states):
                logits,values = request('eval',(version,states))
                return np.asarray(logits),np.asarray(values)
            p = mask = 0
            winner = None
            for ply in range(42):
                _,counts = search(p,mask,evaluator,simulations=simulations,batch_size=8,
                                  c_puct=1.5,noise_fraction=.25,alpha=.3,rng=rng)
                pi = (counts/counts.sum()).tolist()
                action = int(rng.choice(7,p=policy_from_visits(counts,1. if ply < 8 else 0.)))
                samples.append((p,mask,pi,ply%2,action))
                bit = move_bit(mask,action)
                if win(p | bit):
                    winner = ply%2
                    break
                if mask | bit == BOARD:
                    break
                p,mask = p ^ mask,mask | bit
            trajectory = [{'p':int(p),'mask':int(mask),'pi':pi,'action':action,
                           'z':0 if winner is None else (1 if actor == winner else -1)}
                          for p,mask,pi,actor,action in samples]
            games.put({'worker':wid,'version':version,'samples':trajectory},timeout=60)
        finally:
            requests.put(('release',wid,0,version,time.monotonic()),timeout=30)
    events.put(('worker_stopped',wid))


def train_replay(games,updates,events,initial_path,folder,publish_seconds):
    import numpy as np
    import torch
    import torch.nn.functional as F
    from net import PolicyValue
    from puct_game import encode
    torch.set_num_threads(1)
    torch.manual_seed(1205)
    model = PolicyValue().cpu()
    model.load_state_dict(torch.load(initial_path,map_location='cpu',weights_only=True))
    optim = torch.optim.AdamW(model.parameters(),lr=0.001,weight_decay=1e-4)
    rng = random.Random(1205)
    replay = collections.deque(maxlen=10000)
    credit = 0.0
    updates_done = 0
    version = 0
    last_publish = time.monotonic()
    root = Path(folder)
    root.mkdir(parents=True,exist_ok=True)
    logger = logging.getLogger('replay')
    logger.setLevel(logging.INFO)
    handler = logging.handlers.RotatingFileHandler(root/'replay.jsonl',maxBytes=4*1024*1024,
                                                     backupCount=8,encoding='utf-8')
    logger.addHandler(handler)
    try:
        while True:
            try:
                game = games.get(timeout=.5)
            except queue.Empty:
                continue
            if game is None:
                break
            samples = game['samples']
            if not samples or any(len(row['pi'])!=7 or abs(sum(row['pi'])-1)>1e-6 or row['z'] not in (-1,0,1) for row in samples):
                raise ValueError('Trayectoria inválida')
            logger.info(json.dumps(game,separators=(',',':')))
            handler.flush()
            events.put(('game',game['worker'],game['version'],len(samples),time.monotonic()))
            replay.extend({**row,'version':game['version']} for row in samples)
            credit += len(samples)/16
            while credit >= 1 and len(replay) >= 64:
                batch = rng.choices(list(replay),k=64)
                x,legal = encode([(r['p'],r['mask']) for r in batch])
                target = torch.tensor(np.asarray([r['pi'] for r in batch]),dtype=torch.float32)
                z = torch.tensor([r['z'] for r in batch],dtype=torch.float32)
                logits,value = model(torch.from_numpy(x),torch.from_numpy(legal))
                loss = -(target*F.log_softmax(logits,dim=1)).sum(1).mean()+F.mse_loss(value,z)
                optim.zero_grad(set_to_none=True)
                loss.backward()
                optim.step()
                credit -= 1
                updates_done += 1
                used = dict(collections.Counter(r['version'] for r in batch))
                events.put(('train',64,len(replay),updates_done,used))
            if updates_done and time.monotonic()-last_publish >= publish_seconds:
                version += 1
                path,digest = publish_file(model.state_dict(),version,root/'versions')
                updates.put((version,path,digest),timeout=30)
                events.put(('offered',version))
                last_publish = time.monotonic()
    finally:
        handler.close()
        logger.removeHandler(handler)
    events.put(('trainer_stopped',updates_done,len(replay)))


def guarded(name,target,events,*args):
    try:
        target(*args)
    except BaseException:
        events.put(('error',name,traceback.format_exc()))
        raise


def gpu_sample():
    try:
        result = subprocess.run(['nvidia-smi','--query-gpu=utilization.gpu,memory.used',
                                 '--format=csv,noheader,nounits'],capture_output=True,text=True,timeout=5,check=True)
        first = result.stdout.strip().splitlines()[0].split(',')
        return {'gpu_utilization_percent_global':int(first[0]),'gpu_memory_mib_global':int(first[1])}
    except (OSError,ValueError,IndexError,subprocess.SubprocessError):
        return None


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--stop-file',required=True)
    parser.add_argument('--log',required=True)
    parser.add_argument('--initial',default='labs/runs/p12-l05/initial.pt')
    parser.add_argument('--folder',default='labs/runs/p12-l05/run')
    parser.add_argument('--workers',type=int,default=4)
    parser.add_argument('--simulations',type=int,default=200)
    parser.add_argument('--max-seconds',type=float,default=0)
    parser.add_argument('--publish-seconds',type=float,default=120)
    parser.add_argument('--event-capacity',type=int,default=2048)
    parser.add_argument('--allow-cpu',action='store_true')
    args = parser.parse_args()
    ctx = mp.get_context('spawn')
    requests = ctx.Queue(maxsize=128)
    replies = [ctx.Queue(maxsize=8) for _ in range(args.workers)]
    games = ctx.Queue(maxsize=32)
    updates = ctx.Queue(maxsize=32)
    events = ctx.Queue(maxsize=args.event_capacity)
    stop_workers = ctx.Event()
    initial = str(Path(args.initial).resolve())
    folder_path = Path(args.folder).resolve()
    folder_path.mkdir(parents=True,exist_ok=True)
    if any(folder_path.iterdir()):
        raise FileExistsError('El directorio de datos debe estar vacío y ser exclusivo de esta ejecución')
    with (folder_path/'run.lock').open('x',encoding='utf-8') as f:
        f.write(f'pid={os.getpid()}\n')
    folder = str(folder_path)
    eventargs = lambda name, fn, *a: (name,fn,events,*a)
    server = ctx.Process(name='inference',target=guarded,args=eventargs('inference',inference_server,requests,replies,updates,events,initial,not args.allow_cpu))
    trainer = ctx.Process(name='trainer',target=guarded,args=eventargs('trainer',train_replay,games,updates,events,initial,folder,args.publish_seconds))
    workers = [ctx.Process(name=f'worker-{i}',target=guarded,args=eventargs(f'worker-{i}',play_worker,i,requests,replies[i],games,events,stop_workers,args.simulations)) for i in range(args.workers)]
    children = [server,trainer,*workers]
    counters = {'games':0,'generated':0,'consumed':0,'updates':0,'published':0,
                'inference_calls':0,'evaluated_states':0,'errors':[],
                'first_game_s':None,'last_game_s':None,'max_game_gap_s':0.0,
                'inference_requests':0,'queue_wait_sum_s':0.,'queue_wait_max_s':0.,
                'batch_sizes':{},'generated_by_version':{},'consumed_by_version':{},'inference_by_version':{}}
    started = time.monotonic()
    last_log = 0.
    last_gpu = 0.
    sample = None
    log = Path(args.log)
    log.parent.mkdir(parents=True,exist_ok=True)
    stopfile = Path(args.stop_file)
    def record(kind):
        elapsed = time.monotonic()-started
        payload = {'kind':kind,'utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),
                   'elapsed_s':elapsed,'counters':counters.copy(),
                   'games_per_hour_cumulative':counters['games']*3600/elapsed if elapsed else None,
                   'replay_reuse_cumulative':counters['consumed']/counters['generated'] if counters['generated'] else None,
                   'workers_alive':sum(p.is_alive() for p in workers),'gpu':sample}
        if kind == 'start':
            payload['settings'] = {'workers':args.workers,'simulations':args.simulations,
                                   'publish_seconds':args.publish_seconds,
                                   'target':'visits normalized', 'temperature':'1 for ply<8, then 0',
                                   'root_noise_fraction':.25,'root_dirichlet_alpha':.3,
                                   'tree_batch':8,'inference_batch_max':64,'wait_from_enqueue_s':.005}
            payload['sha256'] = {str(p.name):checksum(p) for p in
                                 (Path(__file__),Path(__file__).with_name('puct_game.py'),
                                  Path(__file__).with_name('net.py'),Path(initial))}
        with log.open('a',encoding='utf-8') as f:
            f.write(json.dumps(payload,separators=(',',':'))+'\n'); f.flush()
        print(json.dumps(payload,separators=(',',':')),flush=True)
    def add_game(msg):
        moment = msg[4]-started
        if counters['first_game_s'] is None:
            counters['first_game_s'] = moment
        if counters['last_game_s'] is not None:
            counters['max_game_gap_s'] = max(counters['max_game_gap_s'],moment-counters['last_game_s'])
        counters['last_game_s'] = moment
        counters['games'] += 1
        counters['generated'] += msg[3]
        key = str(msg[2])
        counters['generated_by_version'][key] = counters['generated_by_version'].get(key,0)+msg[3]
    def add_train(msg):
        counters['consumed'] += msg[1]; counters['updates'] = msg[3]
        for version,n in msg[4].items():
            key = str(version)
            counters['consumed_by_version'][key] = counters['consumed_by_version'].get(key,0)+n
    def add_inference(msg):
        counters['inference_calls'] += msg[1]; counters['evaluated_states'] += msg[2]
        counters['inference_requests'] += msg[3]; counters['queue_wait_sum_s'] += msg[4]
        counters['queue_wait_max_s'] = max(counters['queue_wait_max_s'],msg[5])
        for size,n in msg[6].items():
            key = str(size)
            counters['batch_sizes'][key] = counters['batch_sizes'].get(key,0)+n
        for version,n in msg[7].items():
            key = str(version)
            counters['inference_by_version'][key] = counters['inference_by_version'].get(key,0)+n
    def process_event(msg):
        kind = msg[0]
        if kind == 'game': add_game(msg)
        elif kind == 'train': add_train(msg)
        elif kind == 'published': counters['published'] = msg[1]
        elif kind == 'inference': add_inference(msg)
        elif kind in ('error','publication_error'): counters['errors'].append(msg[1:])
        elif kind == 'cuda_after_cleanup': counters['cuda_active_after_cleanup'] = msg[1]
    def join_draining(processes, timeout):
        deadline = time.monotonic()+timeout
        while any(p.is_alive() for p in processes) and time.monotonic() < deadline:
            try:
                process_event(events.get(timeout=.1))
            except queue.Empty:
                pass
        for p in processes:
            p.join(timeout=0)
    def put_draining(q,item,timeout,label):
        deadline = time.monotonic()+timeout
        while time.monotonic() < deadline:
            try:
                q.put(item,timeout=.1)
                return
            except queue.Full:
                try:
                    process_event(events.get_nowait())
                except queue.Empty:
                    pass
        counters['errors'].append([label])
    try:
        server.start(); trainer.start()
        for p in workers: p.start()
        record('start')
        while not stopfile.exists() and not (args.max_seconds and time.monotonic()-started >= args.max_seconds):
            try:
                msg = events.get(timeout=.5)
                process_event(msg)
                if msg[0] in ('error','publication_error'): break
            except queue.Empty:
                pass
            if any(p.exitcode is not None for p in children):
                counters['errors'].append(['child_exit',[(p.name,p.exitcode) for p in children]]); break
            now = time.monotonic()
            if now-last_gpu >= 30: sample = gpu_sample(); last_gpu = now
            if now-last_log >= 15: record('heartbeat'); last_log = now
    except KeyboardInterrupt:
        counters['errors'].append(['interrupt'])
    finally:
        stop_workers.set()
        join_draining(workers,90)
        for p in workers:
            if p.is_alive():
                counters['errors'].append(['forced_termination',p.name]); p.terminate(); p.join(timeout=10)
        put_draining(games,None,10,'trainer_stop_queue_full')
        join_draining([trainer],90)
        put_draining(requests,('stop',0,0,None,time.monotonic()),10,'server_stop_queue_full')
        join_draining([server],90)
        for p in children:
            if p.is_alive():
                counters['errors'].append(['forced_termination',p.name]); p.terminate(); p.join(timeout=10)
        while True:
            try:
                process_event(events.get_nowait())
            except queue.Empty:
                break
        counters['exitcodes'] = {p.name:p.exitcode for p in children}
        record('end')
    if counters['errors'] or any(p.exitcode != 0 for p in children):
        raise SystemExit(1)


if __name__ == '__main__':
    mp.freeze_support()
    main()
''', encoding='utf-8')
(lab / 'guardian.py').write_text(r'''"""Supervisor Windows para un proceso cooperativo y todos sus descendientes.

Ejemplo: python guardian.py --output-dir run -- python pipeline.py
Se añaden al comando --stop-file y --log con rutas propias de cada ejecución.
Los datos de progreso se añaden a guardian.jsonl; stdout y stderr a pipeline-stdout.log.
La duración por defecto supera ocho horas. Las opciones de duración y período
permiten también pruebas cortas; no convierten una prueba corta en una larga.
"""

from __future__ import annotations

import argparse
import ctypes
from ctypes import wintypes
import datetime as dt
import json
import msvcrt
import os
from pathlib import Path
import signal
import subprocess
import sys
import time
import uuid


kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
HANDLE = wintypes.HANDLE
DWORD = wintypes.DWORD
BOOL = wintypes.BOOL
ULONG_PTR = ctypes.c_size_t


class IO_COUNTERS(ctypes.Structure):
    _fields_ = [(n, ctypes.c_ulonglong) for n in (
        "ReadOperationCount", "WriteOperationCount", "OtherOperationCount",
        "ReadTransferCount", "WriteTransferCount", "OtherTransferCount")]


class BASIC_LIMIT_INFORMATION(ctypes.Structure):
    _fields_ = [("PerProcessUserTimeLimit", ctypes.c_longlong),
                ("PerJobUserTimeLimit", ctypes.c_longlong),
                ("LimitFlags", DWORD), ("MinimumWorkingSetSize", ctypes.c_size_t),
                ("MaximumWorkingSetSize", ctypes.c_size_t),
                ("ActiveProcessLimit", DWORD), ("Affinity", ULONG_PTR),
                ("PriorityClass", DWORD), ("SchedulingClass", DWORD)]


class EXTENDED_LIMIT_INFORMATION(ctypes.Structure):
    _fields_ = [("BasicLimitInformation", BASIC_LIMIT_INFORMATION),
                ("IoInfo", IO_COUNTERS), ("ProcessMemoryLimit", ctypes.c_size_t),
                ("JobMemoryLimit", ctypes.c_size_t),
                ("PeakProcessMemoryUsed", ctypes.c_size_t),
                ("PeakJobMemoryUsed", ctypes.c_size_t)]


class BASIC_ACCOUNTING_INFORMATION(ctypes.Structure):
    _fields_ = [("TotalUserTime", ctypes.c_longlong),
                ("TotalKernelTime", ctypes.c_longlong),
                ("ThisPeriodTotalUserTime", ctypes.c_longlong),
                ("ThisPeriodTotalKernelTime", ctypes.c_longlong),
                ("TotalPageFaultCount", DWORD), ("TotalProcesses", DWORD),
                ("ActiveProcesses", DWORD), ("TotalTerminatedProcesses", DWORD)]


class STARTUPINFO(ctypes.Structure):
    _fields_ = [("cb", DWORD), ("lpReserved", wintypes.LPWSTR),
                ("lpDesktop", wintypes.LPWSTR), ("lpTitle", wintypes.LPWSTR),
                ("dwX", DWORD), ("dwY", DWORD), ("dwXSize", DWORD),
                ("dwYSize", DWORD), ("dwXCountChars", DWORD),
                ("dwYCountChars", DWORD), ("dwFillAttribute", DWORD),
                ("dwFlags", DWORD), ("wShowWindow", wintypes.WORD),
                ("cbReserved2", wintypes.WORD),
                ("lpReserved2", ctypes.POINTER(ctypes.c_byte)),
                ("hStdInput", HANDLE), ("hStdOutput", HANDLE),
                ("hStdError", HANDLE)]


class PROCESS_INFORMATION(ctypes.Structure):
    _fields_ = [("hProcess", HANDLE), ("hThread", HANDLE),
                ("dwProcessId", DWORD), ("dwThreadId", DWORD)]


def bind(name, argtypes, restype):
    fn = getattr(kernel32, name)
    fn.argtypes, fn.restype = argtypes, restype
    return fn


CreateJobObject = bind("CreateJobObjectW", [ctypes.c_void_p, wintypes.LPCWSTR], HANDLE)
SetInformationJobObject = bind("SetInformationJobObject", [HANDLE, ctypes.c_int, ctypes.c_void_p, DWORD], BOOL)
QueryInformationJobObject = bind("QueryInformationJobObject", [HANDLE, ctypes.c_int, ctypes.c_void_p, DWORD, ctypes.c_void_p], BOOL)
AssignProcessToJobObject = bind("AssignProcessToJobObject", [HANDLE, HANDLE], BOOL)
TerminateJobObject = bind("TerminateJobObject", [HANDLE, wintypes.UINT], BOOL)
CreateProcess = bind("CreateProcessW", [wintypes.LPCWSTR, wintypes.LPWSTR, ctypes.c_void_p, ctypes.c_void_p,
                     BOOL, DWORD, ctypes.c_void_p, wintypes.LPCWSTR,
                     ctypes.POINTER(STARTUPINFO), ctypes.POINTER(PROCESS_INFORMATION)], BOOL)
ResumeThread = bind("ResumeThread", [HANDLE], DWORD)
TerminateProcess = bind("TerminateProcess", [HANDLE, wintypes.UINT], BOOL)
WaitForSingleObject = bind("WaitForSingleObject", [HANDLE, DWORD], DWORD)
GetExitCodeProcess = bind("GetExitCodeProcess", [HANDLE, ctypes.POINTER(DWORD)], BOOL)
CloseHandle = bind("CloseHandle", [HANDLE], BOOL)
OpenProcess = bind("OpenProcess", [DWORD, BOOL, DWORD], HANDLE)


def check(value):
    if not value:
        raise ctypes.WinError(ctypes.get_last_error())
    return value


def active_processes(job):
    info = BASIC_ACCOUNTING_INFORMATION()
    check(QueryInformationJobObject(job, 1, ctypes.byref(info), ctypes.sizeof(info), None))
    return info.ActiveProcesses


def run(args):
    out = Path(args.output_dir).resolve()
    out.mkdir(parents=True, exist_ok=True)
    run_id = uuid.uuid4().hex
    stop_file = out / ("stop-" + run_id)
    started = time.monotonic()
    job = process = thread = owner = None
    requested = False
    forced = False
    signal_received = None

    def on_signal(signum, _frame):
        nonlocal signal_received
        signal_received = signum

    for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGBREAK):
        signal.signal(sig, on_signal)

    with (out / "guardian.jsonl").open("a", encoding="utf-8", buffering=1) as records:
        def record(event, **fields):
            entry = {"run_id": run_id, "event": event,
                     "utc": dt.datetime.now(dt.timezone.utc).isoformat(),
                     "elapsed_seconds": round(time.monotonic() - started, 6), **fields}
            records.write(json.dumps(entry, ensure_ascii=False) + "\n")
            records.flush()
            os.fsync(records.fileno())

        try:
            if args.owner_pid is not None:
                owner = check(OpenProcess(0x00100000, False, args.owner_pid))  # SYNCHRONIZE
                if WaitForSingleObject(owner, 0) != 0x102:  # WAIT_TIMEOUT: aún vivo
                    raise RuntimeError("El propietario ya no está vivo")
            lease_path = Path(args.lease_file).resolve() if args.lease_file else None
            lease_mtime = lease_deadline = None
            if lease_path:
                stat = lease_path.stat()
                age = time.time() - stat.st_mtime
                if age < -1 or age >= args.lease_timeout_seconds:
                    raise RuntimeError("El archivo de latido no está fresco")
                lease_mtime = stat.st_mtime_ns
                lease_deadline = time.monotonic() + args.lease_timeout_seconds - max(age, 0)
            job = check(CreateJobObject(None, None))
            limits = EXTENDED_LIMIT_INFORMATION()
            limits.BasicLimitInformation.LimitFlags = 0x00002000  # KILL_ON_JOB_CLOSE
            check(SetInformationJobObject(job, 9, ctypes.byref(limits), ctypes.sizeof(limits)))
            env = dict(os.environ)
            env["GUARDIAN_STOP_FILE"] = str(stop_file)
            env["GUARDIAN_RUN_ID"] = run_id
            env_block = ctypes.create_unicode_buffer("\0".join(f"{k}={v}" for k, v in sorted(env.items(), key=lambda item: item[0].upper())) + "\0\0")
            command_args = args.command + ["--stop-file", str(stop_file), "--log", str(out / ("pipeline-" + run_id + ".jsonl"))]
            command = ctypes.create_unicode_buffer(subprocess.list2cmdline(command_args))
            with (out / "pipeline-stdout.log").open("ab", buffering=0) as output, open(os.devnull, "rb") as null:
                output_handle = msvcrt.get_osfhandle(output.fileno())
                null_handle = msvcrt.get_osfhandle(null.fileno())
                os.set_handle_inheritable(output_handle, True)
                os.set_handle_inheritable(null_handle, True)
                si = STARTUPINFO()
                si.cb = ctypes.sizeof(si)
                si.dwFlags = 0x100  # STARTF_USESTDHANDLES
                si.hStdInput, si.hStdOutput, si.hStdError = null_handle, output_handle, output_handle
                pi = PROCESS_INFORMATION()
                check(CreateProcess(None, command, None, None, True,
                                    0x00000004 | 0x00000200 | 0x00000400,
                                    env_block, None, ctypes.byref(si), ctypes.byref(pi)))
                process, thread = pi.hProcess, pi.hThread
                # El proceso aún está suspendido: no puede crear hijos antes de entrar en el Job.
                check(AssignProcessToJobObject(job, process))
                record("started", pid=pi.dwProcessId, command=command_args,
                       stop_file=str(stop_file), target_seconds=args.duration_seconds,
                       heartbeat_seconds=args.heartbeat_seconds, grace_seconds=args.grace_seconds,
                       owner_pid=args.owner_pid, lease_file=str(lease_path) if lease_path else None,
                       lease_timeout_seconds=args.lease_timeout_seconds if lease_path else None)
                if ResumeThread(thread) == 0xFFFFFFFF:
                    raise ctypes.WinError(ctypes.get_last_error())
                pipeline_started = time.monotonic()
                CloseHandle(thread)
                thread = None

            next_heartbeat = started
            stop_at = None
            stop_reason = None
            root_exit = None
            while True:
                now = time.monotonic()
                owner_dead = False
                if owner:
                    owner_status = WaitForSingleObject(owner, 0)
                    if owner_status not in (0, 0x102):
                        raise ctypes.WinError(ctypes.get_last_error())
                    owner_dead = owner_status == 0
                lease_expired = False
                if lease_path:
                    try:
                        stat = lease_path.stat()
                        if stat.st_mtime_ns != lease_mtime:
                            age = time.time() - stat.st_mtime
                            if -1 <= age < args.lease_timeout_seconds:
                                lease_mtime = stat.st_mtime_ns
                                lease_deadline = now + args.lease_timeout_seconds - max(age, 0)
                    except OSError:
                        lease_expired = True
                    lease_expired = lease_expired or now >= lease_deadline
                if root_exit is None and WaitForSingleObject(process, 0) == 0:
                    code = DWORD()
                    check(GetExitCodeProcess(process, ctypes.byref(code)))
                    root_exit = code.value
                    record("root_exit", exit_code=root_exit, active_processes=active_processes(job))
                count = active_processes(job)
                if count == 0:
                    break
                if not requested and (now - pipeline_started >= args.duration_seconds or signal_received is not None or root_exit is not None or owner_dead or lease_expired):
                    requested = True
                    stop_at = now
                    reason = ("owner_exit" if owner_dead else "lease_expired" if lease_expired
                              else "signal" if signal_received is not None
                              else "root_exit" if root_exit is not None else "duration")
                    stop_reason = reason
                    with stop_file.open("x", encoding="utf-8") as f:
                        f.write(json.dumps({"run_id": run_id, "reason": reason}) + "\n")
                        f.flush()
                        os.fsync(f.fileno())
                    record("stop_requested", reason=reason, signal=signal_received, active_processes=count)
                if requested and not forced and now - stop_at >= args.grace_seconds:
                    check(TerminateJobObject(job, 1))
                    forced = True
                    record("forced_termination", active_processes=count)
                if now >= next_heartbeat:
                    record("heartbeat", active_processes=count, stop_requested=requested)
                    next_heartbeat = now + args.heartbeat_seconds
                time.sleep(min(0.2, args.heartbeat_seconds))

            if root_exit is None:
                check(WaitForSingleObject(process, 5000) == 0)
                code = DWORD()
                check(GetExitCodeProcess(process, ctypes.byref(code)))
                root_exit = code.value
                record("root_exit", exit_code=root_exit, active_processes=0)
            elapsed = time.monotonic() - pipeline_started
            work_elapsed = stop_at - pipeline_started if stop_at is not None else None
            complete = (stop_reason == "duration" and not forced and signal_received is None
                        and root_exit == 0 and work_elapsed >= args.duration_seconds)
            record("finished", exit_code=root_exit, active_processes=active_processes(job),
                   forced=forced, stop_reason=stop_reason,
                   duration_reached=bool(work_elapsed is not None and work_elapsed >= args.duration_seconds),
                   pipeline_elapsed_seconds=round(elapsed, 6),
                   work_elapsed_seconds=round(work_elapsed, 6) if work_elapsed is not None else None,
                   long_run=bool(complete and work_elapsed > 8 * 3600), complete=complete)
            return 0 if complete else 1
        except BaseException as exc:
            # Cerrar el último handle del Job mata a los procesos asignados.
            if process and not job:
                TerminateProcess(process, 1)
            elif process and thread:
                TerminateProcess(process, 1)  # también cubre fallo al asignar el Job
            try:
                record("error", error_type=type(exc).__name__, message=str(exc))
            finally:
                raise
        finally:
            if thread:
                CloseHandle(thread)
            if process:
                CloseHandle(process)
            if job:
                CloseHandle(job)
            if owner:
                CloseHandle(owner)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output-dir", required=True)
    parser.add_argument("--duration-seconds", type=float, default=8 * 3600 + 1)
    parser.add_argument("--heartbeat-seconds", type=float, default=30)
    parser.add_argument("--grace-seconds", type=float, default=120)
    parser.add_argument("--owner-pid", type=int, help="PID del proceso propietario que debe permanecer vivo")
    parser.add_argument("--lease-file", help="Archivo cuyo latido debe renovar el propietario")
    parser.add_argument("--lease-timeout-seconds", type=float, default=120)
    parser.add_argument("command", nargs=argparse.REMAINDER)
    args = parser.parse_args()
    if args.command and args.command[0] == "--":
        args.command = args.command[1:]
    if (not args.command or (args.owner_pid is not None and args.owner_pid <= 0)
            or any(not 0 < x < float("inf") for x in (args.duration_seconds, args.heartbeat_seconds, args.grace_seconds, args.lease_timeout_seconds))):
        parser.error("Indica un comando y tiempos positivos y finitos")
    return run(args)


if __name__ == "__main__":
    sys.exit(main())
''', encoding='utf-8')
(lab / 'audit_replay.py').write_text(r'''import json
import sys
from pathlib import Path
from puct_game import BOARD, move_bit, win

folder = Path(sys.argv[1])
logs = sorted(folder.glob('replay.jsonl*'))
assert logs, 'No hay archivos de replay retenidos'
games = [json.loads(line) for log in logs for line in log.read_text(encoding='utf-8').splitlines()]
print('Archivos retenidos auditados:', [p.name for p in logs])
print('La cobertura se limita a los archivos retenidos; la rotaci\u00f3n puede haber descartado partidas anteriores.')
positions = 0
versions = set()
for game in games:
    versions.add(game['version'])
    if game['version']:
        assert (folder/'versions'/f"version-{game['version']:08d}.pt").exists()
    p = mask = 0
    samples = game['samples']
    winner = None
    for ply,row in enumerate(samples):
        assert (row['p'],row['mask']) == (p,mask)
        assert len(row['pi']) == 7 and abs(sum(row['pi'])-1) < 1e-6
        assert all(prob >= 0 and (move_bit(mask,c) or prob == 0) for c,prob in enumerate(row['pi']))
        c = row['action']
        stone = move_bit(mask,c)
        assert stone and row['pi'][c] > 0
        terminal = win(p|stone) or (mask|stone)==BOARD
        if terminal:
            assert ply == len(samples)-1
            winner = ply%2 if win(p|stone) else None
        else:
            assert ply < len(samples)-1
            p,mask = p^mask,mask|stone
        positions += 1
    assert all(row['z'] == (0 if winner is None else (1 if i%2==winner else -1)) for i,row in enumerate(samples))
print('Partidas auditadas:',len(games),'posiciones:',positions,'versiones:',sorted(versions))
''', encoding='utf-8')
print('Módulos escritos en', lab)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Supervision, audit, and shutdownLocal GPU
import json
import os
import subprocess
import sys
import threading
import time
import uuid

def run_guarded(seconds, workers, simulations, publish_seconds, event_capacity=2048):
    folder = lab / ('run-' + uuid.uuid4().hex)
    folder.mkdir()
    lease = folder / 'lease'
    lease.write_text('vivo', encoding='utf-8')
    halted = threading.Event()
    def renew():
        while not halted.wait(30):
            os.utime(lease, None)
    thread = threading.Thread(target=renew, daemon=True)
    thread.start()
    process = None
    try:
        command = [sys.executable, str(lab/'guardian.py'), '--output-dir', str(folder),
                   '--duration-seconds', str(seconds), '--heartbeat-seconds', '30',
                   '--grace-seconds', '120', '--owner-pid', str(os.getpid()),
                   '--lease-file', str(lease), '--lease-timeout-seconds', '120', '--',
                   sys.executable, str(lab/'pipeline.py'), '--folder', str(folder/'data'),
                   '--initial', str(lab/'initial.pt'), '--workers', str(workers),
                   '--simulations', str(simulations), '--publish-seconds', str(publish_seconds),
                   '--event-capacity', str(event_capacity)]
        process = subprocess.Popen(command, cwd=repo, creationflags=subprocess.CREATE_NO_WINDOW)
        code = process.wait()
        if code:
            raise RuntimeError(f'Supervisor terminó con código {code}; registros: {folder}')
        guardians = [json.loads(line) for line in (folder/'guardian.jsonl').read_text(encoding='utf-8').splitlines()]
        finish = guardians[-1]
        assert finish['event'] == 'finished' and finish['complete'] and not finish['forced']
        assert finish['active_processes'] == 0
        log = folder / ('pipeline-' + finish['run_id'] + '.jsonl')
        rows = [json.loads(line) for line in log.read_text(encoding='utf-8').splitlines()]
        end = rows[-1]
        assert end['kind'] == 'end'
        counters = end['counters']
        assert not counters['errors'] and all(v == 0 for v in counters['exitcodes'].values())
        assert counters['cuda_active_after_cleanup'] == 0 and counters['games'] > 0
        assert sum(counters['generated_by_version'].values()) == counters['generated']
        assert sum(counters['consumed_by_version'].values()) == counters['consumed']
        assert sum(counters['inference_by_version'].values()) == counters['evaluated_states']
        assert sum(counters['batch_sizes'].values()) == counters['inference_calls']
        assert sum(int(k)*v for k,v in counters['batch_sizes'].items()) == counters['evaluated_states']
        subprocess.run([sys.executable, str(lab/'audit_replay.py'), str(folder/'data')],
                       cwd=repo, check=True)
        print('Directorio:', folder)
        print('Supervisor:', json.dumps({k: finish[k] for k in
              ('complete', 'long_run', 'stop_reason', 'forced', 'active_processes')}, ensure_ascii=False))
        summary = {k: counters[k] for k in
                   ('games', 'generated', 'consumed', 'updates',
                    'inference_calls', 'evaluated_states', 'cuda_active_after_cleanup', 'exitcodes')}
        summary['last_accepted_version'] = counters['published']
        summary['games_per_hour_cumulative'] = end['games_per_hour_cumulative']
        summary['replay_reuse_cumulative'] = end['replay_reuse_cumulative']
        print('Contadores tras el drenaje:', json.dumps(summary, ensure_ascii=False))
        gpu = [r['gpu'] for r in rows if r['kind'] == 'heartbeat' and r['gpu']]
        if gpu:
            print('GPU global compartida; registros con lectura:', len(gpu),
                  '; sin lectura:', sum(r['kind'] == 'heartbeat' and not r['gpu'] for r in rows),
                  '; rango de utilización (%):',
                  min(x['gpu_utilization_percent_global'] for x in gpu),
                  max(x['gpu_utilization_percent_global'] for x in gpu),
                  '; rango de memoria (MiB):', min(x['gpu_memory_mib_global'] for x in gpu),
                  max(x['gpu_memory_mib_global'] for x in gpu))
        else:
            print('GPU global compartida: sin lecturas disponibles')
        print('Contadores completos por versión y lote: archivo', log)
        return finish, end, rows, guardians
    finally:
        halted.set()
        thread.join()
        if process is not None and process.poll() is None:
            # Al morir guardian se cierra el Job y Windows termina sus descendientes.
            process.terminate()
            process.wait(timeout=30)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Short system checkLocal GPU
# Prueba breve real; no demuestra continuidad durante ocho horas.
finish, end, rows, guardians = run_guarded(35, workers=2, simulations=16, publish_seconds=3, event_capacity=1)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The next cell executes the real prolonged test, so launch it manually in the local environment. The 29400 seconds include startup margin; they do not replace checking more than eight hours between the first and last recorded games. To avoid counting games processed during draining, use counters from the last heartbeat before the stop request. Require every heartbeat interval and the final interval to stop to be at most 120 seconds; the maximum gap between games and from the last game to stop must not exceed 300 seconds. Also check that all workers appear alive in every pre-stop heartbeat. These observations sample progress; they do not prove every worker was active at every instant. At the end, shutdown, versions, and counters are checked; interruption or error invalidates the test. Supervisor and pipeline output remain in the run’s unique directory.

[ ]Supervised continuous testLocal GPU
from datetime import datetime
finish, end, rows, guardians = run_guarded(29400, workers=4, simulations=200, publish_seconds=120)
stop = next(row for row in guardians if row['event'] == 'stop_requested')
stop_time = datetime.fromisoformat(stop['utc'])
heartbeats = [row for row in rows if row['kind'] == 'heartbeat'
              and datetime.fromisoformat(row['utc']) < stop_time]
assert heartbeats and all(row['workers_alive'] == 4 for row in heartbeats)
c = heartbeats[-1]['counters']
assert c['first_game_s'] is not None and c['last_game_s'] is not None
times = [datetime.fromisoformat(row['utc']) for row in heartbeats]
assert all(0 <= (b-a).total_seconds() <= 120 for a,b in zip(times, times[1:]))
since_heartbeat = (stop_time - times[-1]).total_seconds()
assert 0 <= since_heartbeat <= 120
assert since_heartbeat + heartbeats[-1]['elapsed_s'] - c['last_game_s'] <= 300
active = c['last_game_s'] - c['first_game_s']
print('Segundos entre partidas registradas antes de la parada:', active)
print('Mayor intervalo entre registros antes de la parada:', c['max_game_gap_s'])
print('Antes de la parada: partidas:', c['games'], 'posiciones:', c['generated'],
      'muestras consumidas:', c['consumed'], 'reutilización:', c['consumed']/c['generated'])
print('Partidas por hora acumuladas antes de la parada:', heartbeats[-1]['games_per_hour_cumulative'])
assert finish['long_run'] and active > 8*3600 and c['max_game_gap_s'] <= 300
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In a real run on 28 October 2026, with four workers and 200 simulations per move, more than eight hours elapsed between games recorded before stopping. The 1948 preceding heartbeats showed all four workers alive. The final pre-stop heartbeat recorded 10 513 games, 336 653 positions, and 1 346 560 consumed samples. After queues drained, totals were 10 522, 337 003, and 1 347 968, respectively. The last version accepted by the server had identifier 240; that identifier is not a count of versions or proof that the network improved.

The 1948 heartbeat readings showed global shared-GPU utilization from 1% to 100% and global memory from 686 to 7724 MiB. These are whole-device observations, not per-process attribution or general performance limits; heartbeats may repeat the same sample. In this run all 10 522 games were retained and audited in eight files. Rotation limits retention, so another run may retain only part. Shutdown recorded zero processes in the Job, all children without error, and zero active CUDA memory on the server after cleanup. This establishes observed operation, not that the system improves playing strength or behaves identically on another machine.

The next cell summarizes captured data and recomputes reuse; it does not rerun the test. SHA-256 identifiers allow checking original records when available in the repository. To produce a new measurement, execute the preceding prolonged cell.

[ ]Summary of a measured runLocal GPU
import hashlib
from pathlib import Path

repo = next(p for p in (Path.cwd(), *Path.cwd().parents) if (p / 'package.json').is_file())

medido = {
    'trabajadores': 4,
    'simulaciones_por_jugada': 200,
    'primera_partida_s': 7.299736900022253,
    'ultima_partida_antes_s': 29382.90255910001,
    'antes': {'partidas': 10513, 'posiciones': 336653, 'muestras': 1346560},
    'tras_drenaje': {'partidas': 10522, 'posiciones': 337003, 'muestras': 1347968},
    'ultima_version_aceptada': 240,
    'heartbeats_con_gpu_global': 1948,
    'heartbeats_sin_gpu_global': 0,
    'utilizacion_global_min_max_pct': (1, 100),
    'memoria_global_min_max_mib': (686, 7724),
    'partidas_retenidas_y_auditadas': 10522,
    'posiciones_retenidas_y_auditadas': 337003,
    'archivos_replay_retenidos': 8,
    'procesos_en_job_al_cierre': 0,
    'codigos_salida_hijos': (0, 0, 0, 0, 0, 0),
    'cuda_activa_tras_limpieza': 0,
}
assert medido['partidas_retenidas_y_auditadas'] == medido['tras_drenaje']['partidas']
assert medido['posiciones_retenidas_y_auditadas'] == medido['tras_drenaje']['posiciones']
intervalo = medido['ultima_partida_antes_s'] - medido['primera_partida_s']
assert intervalo > 8 * 3600
print('Configuración:', medido['trabajadores'], 'trabajadores,',
      medido['simulaciones_por_jugada'], 'simulaciones por jugada; intervalo observado:',
      round(intervalo / 3600, 4), 'horas')
for etapa in ('antes', 'tras_drenaje'):
    datos = medido[etapa]
    print(etapa, datos, 'reutilización:', round(datos['muestras'] / datos['posiciones'], 4))
print('Última versión aceptada:', medido['ultima_version_aceptada'])
print('GPU global compartida (%):', medido['utilizacion_global_min_max_pct'],
      'memoria global (MiB):', medido['memoria_global_min_max_mib'],
      'lecturas presentes/ausentes:', medido['heartbeats_con_gpu_global'],
      medido['heartbeats_sin_gpu_global'])
print('Replay auditado:', medido['partidas_retenidas_y_auditadas'], 'partidas en',
      medido['archivos_replay_retenidos'], 'archivos')
print('Cierre: procesos en Job:', medido['procesos_en_job_al_cierre'],
      '; códigos de salida de los hijos:', medido['codigos_salida_hijos'],
      '; CUDA activa tras limpieza:', medido['cuda_activa_tras_limpieza'])

logs = repo / 'labs/runs/p12-l05/run-long'
hashes = {
    'guardian.jsonl': '0dd72203fed5c5b267e8acc032b8becffcd439b50000ae181be9ea47e746e29d',
    'pipeline-1dff6b2a42d2480d8694524377fa5aa3.jsonl': '7d067ef5f6ea66c99d974da3100d317e83dff08884835804cdb8719998af590f',
}
for nombre, esperado in hashes.items():
    archivo = logs / nombre
    if archivo.exists():
        digest = hashlib.sha256()
        with archivo.open('rb') as f:
            for bloque in iter(lambda: f.read(1024 * 1024), b''):
                digest.update(bloque)
        assert digest.hexdigest() == esperado, f'El registro {nombre} no coincide con el capturado'
        print('Registro comprobado:', nombre, digest.hexdigest())
    else:
        print('Registro original no disponible:', nombre, '; SHA-256:', esperado)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

NumericAn inference ceiling
Twenty workers share a server capable of completing 25 000 evaluations per second. Assume exactly one evaluation for each of 400 simulations per move, 36 moves per game, continuous saturation, and no other cost. What is the ceiling in games per hour?
QuizThe trainer runs ahead
The trainer consumes samples at a much higher rate than new positions are generated. What conclusion is valid?
QuizPublish or filter
What distinguishes publishing every new network from requiring a candidate to win an evaluation against its predecessor?
QuizWho owns the GPU?
On Windows several CPU workers need to evaluate positions with the same network on a shared GPU. Which design avoids creating one CUDA context per worker?
QuizA game crossing a publication
A game reserved version 4. While it waits for an evaluation, the trainer announces version 5. Which behavior preserves one version per game?
CodeDispatch by size or deadline
Implement InferenceServer(evaluate, max_batch, max_wait) as a deterministic request aggregator. push(key, value, now) adds a request and returns a list of (key, result) pairs if max_batch is reached, or [] otherwise. flush_due(now) processes the batch if max_wait has elapsed since its first request; otherwise return []. evaluate receives values in order and returns results in the same order. Each dispatched batch is emptied and its deadline begins with the next first request. Times are monotonic, keys are unique, and max_batch is positive.
class InferenceServer:
  def __init__(self, evaluate, max_batch, max_wait):
      pass

  def push(self, key, value, now):
      pass

  def flush_due(self, now):
      pass
Shift+Enter to run
[ ]Ideal game ceilingBrowser
print('Evaluaciones por partida:', 400 * 36)
print('Partidas por hora:', 25000 * 3600 / (400 * 36))
print('Estados agrupados en el ejemplo:', 8 + 4)
generadas = 100
actualizaciones = generadas // 16
lecturas = 64 * actualizaciones
print('Actualizaciones, lecturas y cociente:', actualizaciones, lecturas, lecturas / generadas)

Summary

Key idea
Self-play is a concurrent system with perspective, version, and provenance contracts. Bounded queues, one CUDA owner, and supervised shutdown help preserve those contracts; rates and stability are established with real records, not extrapolation.