LOBench-A-share-processed / code /experiments /tbd_revision /scripts /profile_final_revision_complexity.py
Download code/experiments/tbd_revision/scripts/profile_final_revision_complexity.py from mythezone/LOBench-A-share-processed: direct link, hf CLI and curl.
- Browser
- Download file 12.8 kB
-
https://huggingface.co/datasets/mythezone/LOBench-A-share-processed/resolve/main/code/experiments/tbd_revision/scripts/profile_final_revision_complexity.py
- Command line
-
hf download hf://datasets/mythezone/LOBench-A-share-processed/code/experiments/tbd_revision/scripts/profile_final_revision_complexity.py
-
curl -L -o profile_final_revision_complexity.py https://huggingface.co/datasets/mythezone/LOBench-A-share-processed/resolve/main/code/experiments/tbd_revision/scripts/profile_final_revision_complexity.py
12.8 kB
| #!/usr/bin/env python3 | |
| """Profile the three frozen controlled implementations used in the final revision.""" | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import json | |
| import platform | |
| import statistics | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import torch | |
| ROOT = Path(__file__).resolve().parents[3] | |
| MODEL_SRC = ROOT / "experiments/adma2026_representation/src" | |
| SCRIPT_DIR = ROOT / "experiments/tbd_revision/scripts" | |
| for import_dir in (MODEL_SRC, SCRIPT_DIR): | |
| if str(import_dir) not in sys.path: | |
| sys.path.insert(0, str(import_dir)) | |
| from models import Classifier # noqa: E402 | |
| from train_representation_baselines import build_method # noqa: E402 | |
| METHODS = { | |
| "Ti-MAE-style": "timae", | |
| "LOBGrid--Ti-MAE-style": "lobgrid_timae", | |
| "SimLOB-style": "simlob2026", | |
| } | |
| CORE_STOCKS = ( | |
| "asset_001", | |
| "asset_002", | |
| "asset_017", | |
| "asset_005", | |
| "asset_033", | |
| ) | |
| CORE_SEEDS = (2026, 2027, 2028) | |
| def parameter_count(module: torch.nn.Module) -> int: | |
| return sum(parameter.numel() for parameter in module.parameters()) | |
| def synchronized_forward_seconds( | |
| model: torch.nn.Module, | |
| sample: torch.Tensor, | |
| *, | |
| warmup: int, | |
| repeats: int, | |
| ) -> list[float]: | |
| device = sample.device | |
| model.eval() | |
| with torch.inference_mode(): | |
| for _ in range(warmup): | |
| model(sample) | |
| if device.type == "cuda": | |
| torch.cuda.synchronize(device) | |
| observations: list[float] = [] | |
| for _ in range(repeats): | |
| started = time.perf_counter() | |
| model(sample) | |
| if device.type == "cuda": | |
| torch.cuda.synchronize(device) | |
| observations.append(time.perf_counter() - started) | |
| return observations | |
| def peak_forward_gib(model: torch.nn.Module, sample: torch.Tensor) -> float | None: | |
| if sample.device.type != "cuda": | |
| return None | |
| torch.cuda.empty_cache() | |
| torch.cuda.reset_peak_memory_stats(sample.device) | |
| with torch.inference_mode(): | |
| model(sample) | |
| torch.cuda.synchronize(sample.device) | |
| return torch.cuda.max_memory_allocated(sample.device) / (1024**3) | |
| def result_costs( | |
| results_dir: Path, | |
| method: str, | |
| *, | |
| stocks: set[str], | |
| seeds: set[int], | |
| ) -> dict[str, float | int]: | |
| pretrain_paths = [] | |
| for path in sorted(results_dir.glob(f"*_{method}_seed*_encoder.pretrain.json")): | |
| payload = json.loads(path.read_text(encoding="utf-8")) | |
| if payload.get("method") != method: | |
| continue | |
| if any(f"_seed{seed}_encoder.pretrain.json" in path.name for seed in seeds): | |
| pretrain_paths.append(path) | |
| if not pretrain_paths: | |
| raise FileNotFoundError(f"No pooled pretraining metadata for {method}.") | |
| pretrain_seconds = [ | |
| float(json.loads(path.read_text(encoding="utf-8"))["seconds"]) | |
| for path in pretrain_paths | |
| ] | |
| # Do not filter by a filename fragment such as ``*_timae_*``: that | |
| # fragment also matches ``lobgrid_timae``. The serialized method key is | |
| # authoritative, and every stock/seed pair must occur exactly once. | |
| adapt_cases: dict[tuple[str, int], tuple[Path, dict[str, object]]] = {} | |
| for path in sorted(results_dir.glob("*_fine_tune_seed*_budget050.json")): | |
| payload = json.loads(path.read_text(encoding="utf-8")) | |
| if ( | |
| payload.get("method") != method | |
| or payload.get("setting") != "fine_tune" | |
| or str(payload.get("stock")) not in stocks | |
| or int(payload.get("seed", -1)) not in seeds | |
| or abs(float(payload.get("label_budget", -1.0)) - 0.5) >= 1e-9 | |
| ): | |
| continue | |
| key = (str(payload["stock"]), int(payload["seed"])) | |
| if key in adapt_cases: | |
| raise ValueError( | |
| f"Duplicate 50%-budget adaptation case for {method}/{key}: " | |
| f"{adapt_cases[key][0]} and {path}" | |
| ) | |
| adapt_cases[key] = (path, payload) | |
| expected_adapt_cases = { | |
| (stock, seed) for stock in stocks for seed in seeds | |
| } | |
| if set(adapt_cases) != expected_adapt_cases: | |
| missing = sorted(expected_adapt_cases - set(adapt_cases)) | |
| extra = sorted(set(adapt_cases) - expected_adapt_cases) | |
| raise ValueError( | |
| f"Incomplete 50%-budget adaptations for {method}: " | |
| f"missing={missing}, extra={extra}" | |
| ) | |
| adapt_seconds = [ | |
| float(adapt_cases[key][1]["downstream_seconds"]) | |
| for key in sorted(adapt_cases) | |
| ] | |
| return { | |
| "pretrain_runs": len(pretrain_seconds), | |
| "pretrain_minutes_mean": statistics.fmean(pretrain_seconds) / 60.0, | |
| "pretrain_minutes_sd": statistics.stdev(pretrain_seconds) | |
| / 60.0 | |
| if len(pretrain_seconds) > 1 | |
| else 0.0, | |
| "adapt_runs": len(adapt_seconds), | |
| "adapt_seconds_mean": statistics.fmean(adapt_seconds), | |
| "adapt_seconds_sd": statistics.stdev(adapt_seconds) | |
| if len(adapt_seconds) > 1 | |
| else 0.0, | |
| } | |
| def write_csv(path: Path, rows: list[dict[str, object]]) -> None: | |
| with path.open("w", newline="", encoding="utf-8") as handle: | |
| writer = csv.DictWriter(handle, fieldnames=list(rows[0])) | |
| writer.writeheader() | |
| writer.writerows(rows) | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument( | |
| "--results-dir", | |
| type=Path, | |
| default=ROOT | |
| / "experiments/tbd_revision/outputs/results_final_revision_ashare5_pooled_3seed", | |
| ) | |
| parser.add_argument( | |
| "--out-dir", | |
| type=Path, | |
| default=ROOT | |
| / "experiments/tbd_revision/outputs/summary_final_revision_complexity", | |
| ) | |
| parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu") | |
| parser.add_argument("--warmup", type=int, default=30) | |
| parser.add_argument("--repeats", type=int, default=100) | |
| parser.add_argument("--throughput-batch-size", type=int, default=128) | |
| parser.add_argument( | |
| "--training-hardware", | |
| default="single NVIDIA RTX 5880 Ada", | |
| ) | |
| parser.add_argument("--stocks", nargs="+", default=list(CORE_STOCKS)) | |
| parser.add_argument("--seeds", nargs="+", type=int, default=list(CORE_SEEDS)) | |
| return parser.parse_args() | |
| def main() -> None: | |
| args = parse_args() | |
| device = torch.device(args.device) | |
| if device.type == "cuda": | |
| hardware = ( | |
| f"{torch.cuda.get_device_name(device)}; PyTorch {torch.__version__}; " | |
| f"CUDA {torch.version.cuda}" | |
| ) | |
| else: | |
| hardware = f"CPU; PyTorch {torch.__version__}" | |
| rows: list[dict[str, object]] = [] | |
| for display_name, method in METHODS.items(): | |
| encoder = build_method(method, latent_dim=128, d_model=96) | |
| model = Classifier(encoder, latent_dim=128, num_classes=3).to(device) | |
| sample_b1 = torch.randn(1, 100, 40, device=device) | |
| sample_bn = torch.randn(args.throughput_batch_size, 100, 40, device=device) | |
| latency = synchronized_forward_seconds( | |
| model, | |
| sample_b1, | |
| warmup=args.warmup, | |
| repeats=args.repeats, | |
| ) | |
| throughput_times = synchronized_forward_seconds( | |
| model, | |
| sample_bn, | |
| warmup=args.warmup, | |
| repeats=args.repeats, | |
| ) | |
| costs = result_costs( | |
| args.results_dir, | |
| method, | |
| stocks=set(args.stocks), | |
| seeds=set(args.seeds), | |
| ) | |
| rows.append( | |
| { | |
| "implementation": display_name, | |
| "method_key": method, | |
| "trainable_parameters": parameter_count(model), | |
| "peak_forward_gib_b128": peak_forward_gib(model, sample_bn), | |
| "batch1_latency_ms_mean": statistics.fmean(latency) * 1000.0, | |
| "batch1_latency_ms_sd": statistics.stdev(latency) * 1000.0 | |
| if len(latency) > 1 | |
| else 0.0, | |
| "throughput_batch_size": args.throughput_batch_size, | |
| "samples_per_second": args.throughput_batch_size | |
| / statistics.fmean(throughput_times), | |
| **costs, | |
| } | |
| ) | |
| args.out_dir.mkdir(parents=True, exist_ok=True) | |
| write_csv(args.out_dir / "complexity_profile.csv", rows) | |
| (args.out_dir / "complexity_profile.json").write_text( | |
| json.dumps( | |
| { | |
| "hardware": hardware, | |
| "software": { | |
| "python": sys.version, | |
| "platform": platform.platform(), | |
| "pytorch": torch.__version__, | |
| "cuda_runtime": torch.version.cuda, | |
| "cudnn": ( | |
| torch.backends.cudnn.version() | |
| if torch.backends.cudnn.is_available() | |
| else None | |
| ), | |
| }, | |
| "input_shape": "[batch, 100, 40]", | |
| "dtype": "float32", | |
| "float32_matmul_precision": torch.get_float32_matmul_precision(), | |
| "latency_scope": "classifier forward pass under torch.inference_mode", | |
| "measurement_protocol": { | |
| "cuda_synchronized": device.type == "cuda", | |
| "warmup_iterations": args.warmup, | |
| "measured_repetitions": args.repeats, | |
| "latency_batch_size": 1, | |
| "throughput_batch_size": args.throughput_batch_size, | |
| "peak_memory_batch_size": args.throughput_batch_size, | |
| "peak_memory_metric": ( | |
| "process-local torch.cuda.max_memory_allocated" | |
| if device.type == "cuda" | |
| else None | |
| ), | |
| }, | |
| "cost_scope": { | |
| "training_hardware": args.training_hardware, | |
| "stocks": args.stocks, | |
| "seeds": args.seeds, | |
| "label_budget": 0.5, | |
| "pooled_pretraining_aggregation": ( | |
| "mean and sample SD over three seed-specific pooled runs" | |
| ), | |
| "adaptation_aggregation": ( | |
| "mean and sample SD over five stocks x three seeds" | |
| ), | |
| "included_in_training_wall_time": ( | |
| "in-memory batch iteration, host-to-device transfer, " | |
| "optimization, validation, checkpointing, and final evaluation" | |
| ), | |
| "excluded": ( | |
| "raw-data preparation, external market-data/network I/O, " | |
| "exchange connectivity, and order execution" | |
| ), | |
| }, | |
| "rows": rows, | |
| }, | |
| indent=2, | |
| ), | |
| encoding="utf-8", | |
| ) | |
| lines = [ | |
| "# Final-revision model-side cost profile", | |
| "", | |
| f"Forward-profile hardware: {hardware}", | |
| f"Training-time hardware: {args.training_hardware}", | |
| "", | |
| "All model-side measurements use FP32. Latency and throughput are synchronized " | |
| f"classifier-forward measurements after {args.warmup} warm-up iterations and " | |
| f"{args.repeats} measured repetitions. Peak memory is process-local allocated " | |
| f"memory for a batch of {args.throughput_batch_size}. " | |
| "Pooled pretraining is counted once per method and seed; adaptation is " | |
| "averaged over the five-stock x three-seed 50%-label cases. " | |
| "Pretraining time is summarized over three seed-specific pooled runs. " | |
| "Training wall time includes in-memory batch iteration, host-to-device " | |
| "transfer, optimization, validation, checkpointing, and final evaluation. " | |
| "Raw-data preparation and external market-data/network or execution-system " | |
| "I/O are excluded.", | |
| "", | |
| "| implementation | params | peak GiB | B1 ms | samples/s | pretrain min | adapt s |", | |
| "|---|---:|---:|---:|---:|---:|---:|", | |
| ] | |
| for row in rows: | |
| peak = row["peak_forward_gib_b128"] | |
| lines.append( | |
| f"| {row['implementation']} | {int(row['trainable_parameters']):,} | " | |
| f"{float(peak):.3f} | {float(row['batch1_latency_ms_mean']):.3f} | " | |
| f"{float(row['samples_per_second']):.1f} | " | |
| f"{float(row['pretrain_minutes_mean']):.2f} | " | |
| f"{float(row['adapt_seconds_mean']):.1f} |" | |
| ) | |
| (args.out_dir / "complexity_profile.md").write_text( | |
| "\n".join(lines) + "\n", | |
| encoding="utf-8", | |
| ) | |
| print(f"wrote final cost profile to {args.out_dir}") | |
| if __name__ == "__main__": | |
| main() | |