File size: 7,044 Bytes
d3a24e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
"""Offline + online training loop for the world model.

This script can run in two modes:
1. Offline: Train on pre-collected transitions from a replay buffer file.
2. Online: Play games and train the world model incrementally.

Usage:
    uv run python training/train_world_model.py --mode offline --buffer data/buffer.pkl
    uv run python training/train_world_model.py --mode online --games ls20,ls21
"""

from __future__ import annotations

import argparse
import logging
import pickle
from pathlib import Path

import numpy as np

from agents.wayfinder.perception import PerceptionEncoder
from agents.wayfinder.world_model import WorldModel
from training.replay_buffer import ReplayBuffer

logger = logging.getLogger(__name__)


def train_offline(
    buffer_path: str,
    latent_dim: int = 256,
    epochs: int = 50,
    batch_size: int = 64,
    lr: float = 1e-4,
    device: str = "cpu",
    save_path: str = "models/world_model.pt",
) -> None:
    """Train the world model offline on a pre-collected buffer.

    Args:
        buffer_path: Path to a pickled ReplayBuffer.
        latent_dim: Latent dimension.
        epochs: Number of training epochs.
        batch_size: Training batch size.
        lr: Learning rate.
        device: Torch device.
        save_path: Where to save the trained model.
    """
    logger.info("Loading replay buffer from %s", buffer_path)
    with open(buffer_path, "rb") as f:
        buffer: ReplayBuffer = pickle.load(f)

    logger.info("Buffer loaded: %d transitions, %d unique frames", len(buffer), buffer.num_unique_frames)

    encoder = PerceptionEncoder(latent_dim=latent_dim, device=device)
    world_model = WorldModel(latent_dim=latent_dim, device=device, lr=lr)

    # Pre-encode all unique frames
    logger.info("Encoding unique frames...")
    frame_hashes = list(buffer.frames.keys())
    frame_arrays = np.stack([buffer.frames[h] for h in frame_hashes])
    latents = encoder.encode_batch(frame_arrays)
    hash_to_latent = {h: lat for h, lat in zip(frame_hashes, latents)}

    logger.info("Training for %d epochs...", epochs)
    for epoch in range(epochs):
        batch = buffer.sample_prioritized(batch_size)
        total_loss = 0.0

        for t in batch:
            state_latent = hash_to_latent.get(t.frame_hash)
            next_hash = hash_to_latent.get(
                __import__("hashlib").md5(t.next_frame.tobytes()).hexdigest()
            )
            if state_latent is None or next_hash is None:
                continue

            world_model.add_transition(
                state_latent=state_latent,
                action={"action": t.action, "data": t.action_data},
                next_latent=next_hash,
                frame_changed=t.frame_changed,
            )
            loss = world_model.train_step(batch_size=min(batch_size, len(world_model._buffer)))
            total_loss += loss

        avg_loss = total_loss / max(len(batch), 1)
        if (epoch + 1) % 5 == 0:
            logger.info(
                "Epoch %d/%d: avg_loss=%.4f, buffer=%d, confidence=%.3f",
                epoch + 1, epochs, avg_loss,
                world_model.buffer_size_current,
                world_model.confidence(),
            )

    # Save model
    save_dir = Path(save_path).parent
    save_dir.mkdir(parents=True, exist_ok=True)
    import torch
    torch.save({
        "world_model": world_model.state_dict(),
        "encoder": encoder.state_dict(),
        "latent_dim": latent_dim,
    }, save_path)
    logger.info("Model saved to %s", save_path)


def train_online(
    games: list[str],
    max_actions_per_game: int = 500,
    latent_dim: int = 256,
    device: str = "cpu",
    save_path: str = "models/world_model_online.pt",
) -> None:
    """Train the world model online by playing games.

    Args:
        games: List of game IDs to play.
        max_actions_per_game: Max actions per game.
        latent_dim: Latent dimension.
        device: Torch device.
        save_path: Where to save the model.
    """
    from agents.wayfinder.agent import WayfinderAgent

    agent = WayfinderAgent(
        max_actions=max_actions_per_game,
        latent_dim=latent_dim,
        device=device,
    )

    for game_id in games:
        logger.info("Playing game %s...", game_id)
        agent.reset()

        # In real usage, this would use the SDK to play the game.
        # For now, we simulate with random frames.
        for step in range(max_actions_per_game):
            frame = np.random.randint(0, 16, size=(64, 64), dtype=np.uint8)
            result = agent.act(
                frames=[frame],
                state="NOT_FINISHED",
                score=0.0,
                win_score=1.0,
                available_actions=["ACTION1", "ACTION2", "ACTION3", "ACTION4", "ACTION5"],
            )

            if agent.is_done([frame], "NOT_FINISHED"):
                break

        logger.info(
            "Game %s: %d actions, buffer=%d, confidence=%.3f",
            game_id, agent.action_count,
            agent._world_model.buffer_size_current,
            agent._world_model.confidence(),
        )

    import torch
    torch.save({
        "world_model": agent._world_model.state_dict(),
        "encoder": agent._encoder.state_dict(),
        "latent_dim": latent_dim,
    }, save_path)
    logger.info("Online model saved to %s", save_path)


def main() -> int:
    """CLI entry point for training."""
    parser = argparse.ArgumentParser(description="Train the world model")
    parser.add_argument("--mode", choices=["offline", "online"], default="online")
    parser.add_argument("--buffer", default="data/buffer.pkl", help="Path to replay buffer (offline mode)")
    parser.add_argument("--games", default="ls20,ls21,ls22", help="Comma-separated game IDs (online mode)")
    parser.add_argument("--epochs", type=int, default=50)
    parser.add_argument("--batch-size", type=int, default=64)
    parser.add_argument("--lr", type=float, default=1e-4)
    parser.add_argument("--latent-dim", type=int, default=256)
    parser.add_argument("--device", default="cpu")
    parser.add_argument("--save-path", default="models/world_model.pt")
    parser.add_argument("-v", "--verbose", action="store_true")

    args = parser.parse_args()

    logging.basicConfig(
        level=logging.DEBUG if args.verbose else logging.INFO,
        format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
    )

    if args.mode == "offline":
        train_offline(
            buffer_path=args.buffer,
            latent_dim=args.latent_dim,
            epochs=args.epochs,
            batch_size=args.batch_size,
            lr=args.lr,
            device=args.device,
            save_path=args.save_path,
        )
    else:
        train_online(
            games=args.games.split(","),
            max_actions_per_game=500,
            latent_dim=args.latent_dim,
            device=args.device,
            save_path=args.save_path,
        )

    return 0


if __name__ == "__main__":
    import sys
    sys.exit(main())