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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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
#!/usr/bin/env python3
"""Train end-to-end, frozen-probe, and fine-tuned downstream classifiers."""

from __future__ import annotations

import argparse
import copy
import json
import random
import time
from pathlib import Path

import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

from models import AutoEncoder, Classifier, build_encoder


def load_npz(path: Path):
    import numpy as np  # noqa: PLC0415

    with np.load(path, allow_pickle=False) as data:
        x = torch.tensor(data["x"], dtype=torch.float32)
        y = torch.tensor(data["y"] + 1, dtype=torch.long)
        train_key = "train_idx" if "train_idx" in data else "natural_train_idx"
        keys = {"train": train_key, "val": "val_idx", "test": "test_idx"}
        splits = {name: torch.tensor(data[key], dtype=torch.long) for name, key in keys.items()}
    return x, y, splits


def make_loader(x, y, idx, batch_size, shuffle, num_workers=0, pin_memory=False):
    return DataLoader(
        TensorDataset(x[idx], y[idx]),
        batch_size=batch_size,
        shuffle=shuffle,
        num_workers=num_workers,
        pin_memory=pin_memory,
    )


def sample_label_budget(y, train_idx, budget: float, seed: int):
    if budget >= 0.999:
        return train_idx
    if budget <= 0:
        raise ValueError("label budget must be positive.")

    import numpy as np  # noqa: PLC0415

    rng = np.random.default_rng(seed)
    train_np = train_idx.cpu().numpy()
    y_np = y.cpu().numpy()
    chosen = []
    for cls in sorted(set(y_np[train_np].tolist())):
        cls_idx = train_np[y_np[train_np] == cls]
        if len(cls_idx) == 0:
            continue
        n = max(1, int(round(len(cls_idx) * budget)))
        chosen.append(rng.choice(cls_idx, size=min(n, len(cls_idx)), replace=False))
    if not chosen:
        raise ValueError("label budget produced an empty training split.")
    return torch.tensor(np.sort(np.concatenate(chosen)), dtype=torch.long)


def count_parameters(model):
    total = sum(p.numel() for p in model.parameters())
    trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
    return {"total": total, "trainable": trainable}


def classification_metrics(logits, y):
    pred = logits.argmax(dim=1)
    acc = (pred == y).float().mean().item()
    precisions = []
    recalls = []
    f1s = []
    for cls in range(3):
        tp = ((pred == cls) & (y == cls)).sum().item()
        fp = ((pred == cls) & (y != cls)).sum().item()
        fn = ((pred != cls) & (y == cls)).sum().item()
        recall = tp / max(tp + fn, 1)
        precision = tp / max(tp + fp, 1)
        precisions.append(precision)
        recalls.append(recall)
        f1s.append(2 * precision * recall / max(precision + recall, 1e-12))
    class_names = ("down", "stationary", "up")
    details = {
        f"precision_{name}": float(precisions[index])
        for index, name in enumerate(class_names)
    }
    details.update(
        {
            f"recall_{name}": float(recalls[index])
            for index, name in enumerate(class_names)
        }
    )
    details.update(
        {
            f"f1_{name}": float(f1s[index])
            for index, name in enumerate(class_names)
        }
    )
    return {
        "accuracy": acc,
        "balanced_accuracy": sum(recalls) / 3,
        "macro_f1": sum(f1s) / 3,
        **details,
    }


def evaluate(model, loader, device):
    model.eval()
    logits_all = []
    y_all = []
    with torch.no_grad():
        for x, y in loader:
            logits_all.append(model(x.to(device)).cpu())
            y_all.append(y)
    return classification_metrics(torch.cat(logits_all), torch.cat(y_all))


def train_epoch(model, loader, optimizer, device, criterion):
    model.train()
    total = 0.0
    n = 0
    for x, y in loader:
        x, y = x.to(device), y.to(device)
        optimizer.zero_grad(set_to_none=True)
        loss = criterion(model(x), y)
        loss.backward()
        optimizer.step()
        total += float(loss.item()) * len(y)
        n += len(y)
    return total / max(n, 1)


def level_weights(device: torch.device, dtype: torch.dtype, decay: float = 0.85) -> torch.Tensor:
    near_to_far = torch.pow(
        torch.full((10,), decay, device=device, dtype=dtype),
        torch.arange(10, device=device, dtype=dtype),
    )
    weights = torch.cat([near_to_far.flip(0), near_to_far, near_to_far.flip(0), near_to_far])
    return weights / weights.mean()


def structure_regularizer(recon: torch.Tensor) -> torch.Tensor:
    prices = recon[:, :, :20]
    bid = prices[:, :, :10]
    ask = prices[:, :, 10:20]
    bid_order = torch.relu(bid[:, :, :-1] - bid[:, :, 1:]).mean()
    ask_order = torch.relu(ask[:, :, :-1] - ask[:, :, 1:]).mean()
    spread = torch.relu(bid[:, :, -1] - ask[:, :, 0]).mean()
    return bid_order + ask_order + spread


def reconstruction_loss(pred: torch.Tensor, target: torch.Tensor, loss_name: str, structure_weight: float) -> torch.Tensor:
    mse = torch.mean((pred - target) ** 2)
    if loss_name == "mse":
        return mse
    if loss_name == "wmse":
        weights = level_weights(pred.device, pred.dtype)
        return torch.mean((pred - target) ** 2 * weights)
    if loss_name == "mse_structure":
        return mse + structure_weight * structure_regularizer(pred)
    if loss_name in {"lobench", "wmse_structure"}:
        weights = level_weights(pred.device, pred.dtype)
        wmse = torch.mean((pred - target) ** 2 * weights)
        return wmse + structure_weight * structure_regularizer(pred)
    raise ValueError(f"unknown pretrain_loss: {loss_name}")


def pretrain_encoder(model_name, latent_dim, train_loader, val_loader, cfg, device, ckpt_path):
    meta_path = ckpt_path.with_suffix(".pretrain.json")
    if ckpt_path.exists() and meta_path.exists():
        return json.loads(meta_path.read_text(encoding="utf-8")) | {"cached": True}

    encoder = build_encoder(model_name, latent_dim)
    decoder_name = cfg.get("pretrain_decoder", "mlp")
    ae = AutoEncoder(
        encoder,
        latent_dim=latent_dim,
        decoder_name=decoder_name,
        decoder_layers=int(cfg.get("pretrain_decoder_layers", 2)),
        decoder_heads=int(cfg.get("pretrain_decoder_heads", 8)),
        decoder_d_model=int(cfg.get("pretrain_decoder_d_model", latent_dim)),
    ).to(device)
    opt = torch.optim.AdamW(ae.parameters(), lr=cfg["learning_rate"], weight_decay=cfg["weight_decay"])
    loss_name = cfg.get("pretrain_loss", "mse")
    structure_weight = float(cfg.get("pretrain_structure_weight", 0.1))
    best = float("inf")
    best_epoch = 0
    history = []
    epochs_without_improvement = 0
    patience = int(cfg.get("pretrain_patience", 0))
    started = time.perf_counter()
    for epoch in range(1, int(cfg["pretrain_epochs"]) + 1):
        epoch_started = time.perf_counter()
        ae.train()
        train_loss = 0.0
        train_mse = 0.0
        train_n = 0
        for x, _ in train_loader:
            x = x.to(device)
            opt.zero_grad(set_to_none=True)
            pred = ae(x)
            loss = reconstruction_loss(pred, x, loss_name, structure_weight)
            loss.backward()
            opt.step()
            train_loss += float(loss.item()) * len(x)
            train_mse += float(torch.mean((pred.detach() - x) ** 2).item()) * len(x)
            train_n += len(x)
        val = 0.0
        val_mse = 0.0
        n = 0
        ae.eval()
        with torch.no_grad():
            for x, _ in val_loader:
                x = x.to(device)
                pred = ae(x)
                batch_loss = reconstruction_loss(pred, x, loss_name, structure_weight).item()
                batch_mse = torch.mean((pred - x) ** 2).item()
                val += batch_loss * len(x)
                val_mse += batch_mse * len(x)
                n += len(x)
        val /= max(n, 1)
        val_mse /= max(n, 1)
        history.append(
            {
                "epoch": epoch,
                "train_loss": train_loss / max(train_n, 1),
                "val_loss": val,
                "train_mse": train_mse / max(train_n, 1),
                "val_mse": val_mse,
                f"train_{loss_name}": train_loss / max(train_n, 1),
                f"val_{loss_name}": val,
                "epoch_seconds": time.perf_counter() - epoch_started,
            }
        )
        if val < best:
            best = val
            best_epoch = epoch
            torch.save(ae.encoder.state_dict(), ckpt_path)
            epochs_without_improvement = 0
        else:
            epochs_without_improvement += 1
        if patience and epochs_without_improvement >= patience:
            break
    meta = {
        "decoder": decoder_name,
        "pretrain_loss": loss_name,
        "pretrain_structure_weight": structure_weight,
        "best_val_loss": best,
        f"best_val_{loss_name}": best,
        "best_val_mse": history[best_epoch - 1]["val_mse"] if best_epoch else None,
        "best_epoch": best_epoch,
        "seconds": time.perf_counter() - started,
        "history": history,
        "cached": False,
    }
    meta_path.write_text(json.dumps(meta, indent=2), encoding="utf-8")
    return meta


def set_seed(seed: int) -> None:
    import os  # noqa: PLC0415

    os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
    random.seed(seed)
    torch.manual_seed(seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.benchmark = False
    torch.backends.cudnn.deterministic = True
    # Fail loudly if a final evidence run reaches a nondeterministic CUDA
    # kernel. Repeated seeds are meaningful only when the execution policy is
    # itself recorded and enforced.
    torch.use_deterministic_algorithms(True, warn_only=False)
    try:
        import numpy as np  # noqa: PLC0415

        np.random.seed(seed)
    except Exception:
        pass


def run(args):
    cfg = json.loads(Path(args.config).read_text(encoding="utf-8"))
    train_cfg = cfg["training"]
    out_dir = Path(cfg["results_dir"])
    out_dir.mkdir(parents=True, exist_ok=True)
    pretrain_stock = args.pretrain_stock or args.stock
    windows = Path(cfg["processed_dir"]) / f"{args.stock}_pilot.npz"
    x, y, splits = load_npz(windows)

    set_seed(args.seed)
    device = torch.device(train_cfg["device"] if torch.cuda.is_available() else "cpu")
    batch_size = int(train_cfg["batch_size"])
    num_workers = int(train_cfg.get("num_workers", 0))
    pin_memory = device.type == "cuda"
    label_budget = float(args.label_budget)
    downstream_train_idx = sample_label_budget(y, splits["train"], label_budget, args.seed)
    pretrain_train_loader = make_loader(x, y, splits["train"], batch_size, shuffle=True, num_workers=num_workers, pin_memory=pin_memory)
    train_loader = make_loader(x, y, downstream_train_idx, batch_size, shuffle=True, num_workers=num_workers, pin_memory=pin_memory)
    val_loader = make_loader(x, y, splits["val"], batch_size, shuffle=False, num_workers=num_workers, pin_memory=pin_memory)
    test_loader = make_loader(x, y, splits["test"], batch_size, shuffle=False, num_workers=num_workers, pin_memory=pin_memory)

    latent_dim = int(train_cfg["latent_dim"])
    decoder_name = train_cfg.get("pretrain_decoder", "mlp")
    pretrain_loss_name = train_cfg.get("pretrain_loss", "mse")
    encoder = build_encoder(args.model, latent_dim)
    loss_tag = "" if pretrain_loss_name == "mse" else f"_loss{pretrain_loss_name}"
    ckpt = out_dir / f"{pretrain_stock}_{args.model}_{decoder_name}{loss_tag}_seed{args.seed}_encoder.pt"
    pretrain = None

    if args.setting in {"frozen_probe", "fine_tune"}:
        source_train_loader = pretrain_train_loader
        source_val_loader = val_loader
        if pretrain_stock != args.stock:
            source_windows = Path(cfg["processed_dir"]) / f"{pretrain_stock}_pilot.npz"
            sx, sy, source_splits = load_npz(source_windows)
            source_train_loader = make_loader(
                sx,
                sy,
                source_splits["train"],
                batch_size,
                shuffle=True,
                num_workers=num_workers,
                pin_memory=pin_memory,
            )
            source_val_loader = make_loader(
                sx,
                sy,
                source_splits["val"],
                batch_size,
                shuffle=False,
                num_workers=num_workers,
                pin_memory=pin_memory,
            )
        pretrain = pretrain_encoder(args.model, latent_dim, source_train_loader, source_val_loader, train_cfg, device, ckpt)
        encoder.load_state_dict(torch.load(ckpt, map_location="cpu"))

    if args.setting in {"frozen_probe", "random_frozen"}:
        for p in encoder.parameters():
            p.requires_grad = False

    model = Classifier(encoder, latent_dim=latent_dim).to(device)
    parameters = count_parameters(model)
    opt = torch.optim.AdamW(
        [p for p in model.parameters() if p.requires_grad],
        lr=train_cfg["learning_rate"],
        weight_decay=train_cfg["weight_decay"],
    )
    criterion = nn.CrossEntropyLoss()
    history = []
    train_started = time.perf_counter()
    best_val_macro_f1 = -1.0
    best_epoch = 0
    best_state = copy.deepcopy(model.state_dict())
    epochs_without_improvement = 0
    patience = int(train_cfg.get("downstream_patience", 0))
    for epoch in range(1, int(train_cfg["downstream_epochs"]) + 1):
        epoch_started = time.perf_counter()
        loss = train_epoch(model, train_loader, opt, device, criterion)
        metrics = evaluate(model, val_loader, device)
        if metrics["macro_f1"] > best_val_macro_f1:
            best_val_macro_f1 = metrics["macro_f1"]
            best_epoch = epoch
            best_state = copy.deepcopy(model.state_dict())
            epochs_without_improvement = 0
        else:
            epochs_without_improvement += 1
        history.append(
            {
                "epoch": epoch,
                "loss": loss,
                "epoch_seconds": time.perf_counter() - epoch_started,
                **{f"val_{k}": v for k, v in metrics.items()},
            }
        )
        if patience and epochs_without_improvement >= patience:
            break
    downstream_seconds = time.perf_counter() - train_started
    model.load_state_dict(best_state)

    result = {
        "stock": args.stock,
        "pretrain_stock": pretrain_stock,
        "model": args.model,
        "setting": args.setting,
        "seed": args.seed,
        "label_budget": label_budget,
        "label_horizon": cfg.get("data", {}).get("label_horizon"),
        "label_threshold": cfg.get("data", {}).get("label_threshold"),
        "train_samples": int(len(downstream_train_idx)),
        "full_train_samples": int(len(splits["train"])),
        "pretrain_decoder": decoder_name,
        "pretrain": pretrain,
        "pretrain_cached": bool(pretrain.get("cached")) if pretrain else False,
        "parameters": parameters,
        "best_val_macro_f1": best_val_macro_f1,
        "best_epoch": best_epoch,
        "downstream_seconds": downstream_seconds,
        "total_seconds": downstream_seconds + (pretrain["seconds"] if pretrain else 0.0),
        "val": evaluate(model, val_loader, device),
        "test": evaluate(model, test_loader, device),
        "history": history,
    }
    budget_tag = f"_budget{int(round(label_budget * 100)):03d}" if label_budget < 0.999 else ""
    source_tag = f"_from{pretrain_stock}" if pretrain_stock != args.stock else ""
    out_file = out_dir / f"{args.stock}_{args.model}_{args.setting}{source_tag}_seed{args.seed}{budget_tag}.json"
    out_file.write_text(json.dumps(result, indent=2), encoding="utf-8")
    print(json.dumps(result["test"], indent=2))
    print(f"wrote {out_file}")


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--config", required=True)
    parser.add_argument("--stock", required=True)
    parser.add_argument("--model", required=True)
    parser.add_argument("--setting", choices=["end_to_end", "random_frozen", "frozen_probe", "fine_tune"], required=True)
    parser.add_argument("--seed", type=int, required=True)
    parser.add_argument("--label-budget", type=float, default=1.0)
    parser.add_argument("--pretrain-stock", default=None)
    return parser.parse_args()


if __name__ == "__main__":
    run(parse_args())