File size: 4,212 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
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
#!/usr/bin/env python3
"""Run the prespecified five-stock hyperparameter sensitivity grid."""

from __future__ import annotations

import argparse
import copy
import json
import sys
from pathlib import Path


ROOT = Path(__file__).resolve().parents[3]
SCRIPT_DIR = ROOT / "experiments/tbd_revision/scripts"
if str(SCRIPT_DIR) not in sys.path:
    sys.path.insert(0, str(SCRIPT_DIR))

from train_representation_baselines import run_one, summarize  # noqa: E402


STOCKS = ("asset_001", "asset_002", "asset_017", "asset_005", "asset_033")
METHODS = ("timae", "lobgrid_timae", "simlob2026")
SEEDS = (2026, 2027, 2028)

# Each axis changes one value from the retained configuration. The baseline
# additionally supplies the three label-budget conditions used elsewhere.
VARIANTS: dict[str, dict[str, float | int]] = {
    "baseline": {},
    "latent64": {"latent_dim": 64},
    "latent256": {"latent_dim": 256},
    "width64": {"d_model": 64},
    "width128": {"d_model": 128},
    "heads2": {"nhead": 2},
    "heads8": {"nhead": 8},
    "mask20": {"mask_ratio": 0.2},
    "mask60": {"mask_ratio": 0.6},
    "lr100": {"learning_rate": 0.0001},
    "lr1000": {"learning_rate": 0.001},
    "batch64": {"batch_size": 64},
    "batch256": {"batch_size": 256},
    "wd0": {"weight_decay": 0.0},
    "wd1e4": {"weight_decay": 0.0001},
}


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--base-config", type=Path, required=True)
    parser.add_argument("--output-root", type=Path, required=True)
    parser.add_argument(
        "--variants",
        nargs="+",
        choices=tuple(VARIANTS),
        required=True,
    )
    parser.add_argument("--force", action="store_true")
    return parser.parse_args()


def resolved(path: Path) -> Path:
    return path if path.is_absolute() else ROOT / path


def main() -> None:
    args = parse_args()
    base = json.loads(resolved(args.base_config).read_text(encoding="utf-8"))
    output_root = resolved(args.output_root)
    output_root.mkdir(parents=True, exist_ok=True)

    for variant in args.variants:
        config = copy.deepcopy(base)
        config["training"].setdefault("nhead", 4)
        config["training"].setdefault("mask_ratio", 0.4)
        config["training"].update(VARIANTS[variant])
        result_dir = output_root / variant
        config["results_dir"] = str(result_dir)
        config["pretrain_id"] = f"final_revision_hp_{variant}"
        config["stocks"] = list(STOCKS)
        config["methods"] = list(METHODS)
        config["settings"] = ["from_scratch", "fine_tune"]
        config["seeds"] = list(SEEDS)
        config["label_budgets"] = (
            [0.25, 0.5, 1.0] if variant == "baseline" else [0.5]
        )
        config["purpose"] = (
            "Prespecified five-stock, three-seed, one-factor-at-a-time "
            f"sensitivity condition: {variant}."
        )
        result_dir.mkdir(parents=True, exist_ok=True)
        (result_dir / "resolved_config.json").write_text(
            json.dumps(config, indent=2) + "\n",
            encoding="utf-8",
        )

        total = (
            len(STOCKS)
            * len(METHODS)
            * len(SEEDS)
            * len(config["label_budgets"])
        )
        completed = 0
        for stock in STOCKS:
            for method in METHODS:
                for seed in SEEDS:
                    for label_budget in config["label_budgets"]:
                        completed += 1
                        print(
                            f"VARIANT {variant} {completed}/{total} "
                            f"{stock} {method} seed={seed} "
                            f"budget={label_budget}",
                            flush=True,
                        )
                        run_one(
                            config,
                            stock,
                            method,
                            seed,
                            label_budget,
                            config["settings"],
                            force=args.force,
                        )
        summarize(config, f"hyperparameter_{variant}")


if __name__ == "__main__":
    main()