File size: 4,271 Bytes
3f316da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Run a small CPU check using one downloaded public asset; no paper scores."""

import argparse
import json
import math
import sys
import tempfile
from pathlib import Path

import numpy as np
import torch

ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT / "experiments/tbd_revision/scripts"))

from run_architecture_task_coverage import MODEL_ORDER, build_encoder
from run_representation_task_suite import load_normalization, task_loss
from train_downstream import load_npz
from train_representation_baselines import (
    ReconstructionPretrainer,
    build_method,
    completed_result,
    result_path_for,
    run_one,
)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--data-dir", type=Path, default=ROOT.parent / "deidentified_50stock_panel")
    args = parser.parse_args()
    torch.set_num_threads(2)
    normalization = load_normalization(args.data_dir, "asset_001")
    with np.load(args.data_dir / "asset_001.npz", allow_pickle=False) as original:
        parts = [original[key][:count] for key, count in
                 [("natural_train_idx", 12), ("val_idx", 6), ("test_idx", 6)]]
        selected = np.concatenate(parts)
        assert len(set(selected.tolist())) == 24, "smoke partitions overlap or are too small"
        arrays = {key: original[key][selected] for key in
                  ["x", "y", "future_returns", "relative_day_id", "seconds_since_midnight"]}
    assert arrays["x"].shape == (24, 100, 40)
    assert np.isfinite(arrays["x"]).all()
    arrays.update(natural_train_idx=np.arange(12), val_idx=np.arange(12, 18),
                  test_idx=np.arange(18, 24))
    with tempfile.TemporaryDirectory(prefix="lobench-smoke-") as directory:
        work = Path(directory)
        np.savez_compressed(work / "asset_001.npz", **arrays)
        (work / "manifest.json").write_text(json.dumps({"assets": [
            {"alias": "asset_001", "normalization_training_only": normalization}
        ]}))
        x, _, splits = load_npz(work / "asset_001.npz")
        assert len(splits["train"]) == 12
        config = {
            "processed_dir": str(work), "dataset_manifest": str(work / "manifest.json"),
            "data_file_template": "{stock}.npz", "results_dir": str(work / "results"),
            "pretrain_scope": "local", "pretrain_index_key": "natural_train_idx",
            "downstream_index_key": "natural_train_idx",
            "training": {"batch_size": 6, "pretrain_epochs": 1, "pretrain_patience": 0,
                         "downstream_epochs": 1, "downstream_patience": 0,
                         "learning_rate": 3e-4, "weight_decay": 1e-5,
                         "latent_dim": 16, "d_model": 16, "nhead": 4,
                         "mask_ratio": 0.4, "device": "cpu", "num_workers": 0,
                         "class_weights": "balanced", "log_epochs": False},
        }
        settings = ["from_scratch", "frozen_probe", "fine_tune"]
        for method in ["timae", "lobgrid_timae", "simlob2026"]:
            run_one(config, "asset_001", method, 2026, 1.0, settings)
            for setting in settings:
                output = result_path_for(config, "asset_001", method, setting, 2026, 1.0)
                assert completed_result(output), output
                result = json.loads(output.read_text())
                assert math.isfinite(result["test"]["macro_f1"])
            model = ReconstructionPretrainer(build_method(method, 16, 16), d_model=16)
            for task in ["reconstruction", "imputation"]:
                loss = task_loss(model, x[:2], task, method, structure_weight=0)
                assert torch.isfinite(loss), (method, task)
                loss.backward()
                model.zero_grad()
        for name in MODEL_ORDER:
            encoder = build_encoder(name, latent_dim=16, hidden_dim=16).eval()
            with torch.no_grad():
                output = encoder(x[:2])
            assert output.shape == (2, 16) and torch.isfinite(output).all(), name
    print("PASS: public data loading; 3 encoders × 3 prediction settings; recovery losses; 9 architecture adapters.")
    print("This smoke test uses 24 windows and one epoch; it does not reproduce paper scores.")


if __name__ == "__main__":
    main()