boltzmann9 0.1.3__py3-none-any.whl → 0.1.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
boltzmann9/pipeline.py DELETED
@@ -1,216 +0,0 @@
1
- """RBM training and evaluation pipelines."""
2
-
3
- from __future__ import annotations
4
-
5
- from pathlib import Path
6
- from typing import Any, Dict
7
-
8
- import torch
9
-
10
- from .config import load_config
11
- from .data import BMDataset, split_rbm_loaders
12
- from .model import RBM
13
- from .tester import RBMTester
14
- from .utils import resolve_device, resolve_pin_memory
15
-
16
-
17
- def create_dataloaders(cfg: Dict[str, Any]) -> Dict[str, Any]:
18
- """Create dataset and dataloaders from config.
19
-
20
- Args:
21
- cfg: Configuration dictionary with 'data' and 'dataloader' sections.
22
-
23
- Returns:
24
- Dictionary with 'dataset', 'train', 'val', 'test' loaders, and 'device'.
25
- """
26
- device = resolve_device(cfg.get("device", "auto"))
27
-
28
- data_cfg = cfg.get("data", {})
29
- csv_path = data_cfg.get("csv_path")
30
- if not csv_path:
31
- raise ValueError("csv_path must be specified in config['data']")
32
-
33
- drop_cols = data_cfg.get("drop_cols", [])
34
- dataset = BMDataset(csv_path, drop_cols=drop_cols)
35
-
36
- dl = cfg.get("dataloader", {})
37
- pin_memory = resolve_pin_memory(dl.get("pin_memory", "auto"), device)
38
-
39
- loaders = split_rbm_loaders(
40
- dataset,
41
- batch_size=dl.get("batch_size", 256),
42
- split=tuple(dl.get("split", (0.8, 0.1, 0.1))),
43
- seed=dl.get("seed", 42),
44
- shuffle_train=dl.get("shuffle_train", True),
45
- num_workers=dl.get("num_workers", 0),
46
- pin_memory=pin_memory,
47
- drop_last_train=dl.get("drop_last_train", True),
48
- )
49
-
50
- return {
51
- "dataset": dataset,
52
- "train": loaders["train"],
53
- "val": loaders["val"],
54
- "test": loaders["test"],
55
- "device": device,
56
- }
57
-
58
-
59
- def train_rbm(config_path: str | Path) -> Dict[str, Any]:
60
- """Train an RBM model.
61
-
62
- Args:
63
- config_path: Path to configuration .py file.
64
-
65
- Returns:
66
- Dictionary containing:
67
- - model: Trained RBM model.
68
- - history: Training history.
69
- - device: Device used for training.
70
- - config: The loaded configuration dictionary.
71
- """
72
- cfg = load_config(config_path)
73
-
74
- # Setup
75
- loaders = create_dataloaders(cfg)
76
- device = loaders["device"]
77
-
78
- print(f"Using device: {device}")
79
- print(f"Loaded dataset: {len(loaders['dataset'])} samples")
80
- print(f" Columns: {loaders['dataset'].columns}")
81
-
82
- # Model
83
- model_cfg = dict(cfg.get("model", {}))
84
- model = RBM(model_cfg).to(device)
85
-
86
- # Train
87
- train_cfg = dict(cfg.get("train", {}))
88
- history = model.fit(
89
- loaders["train"],
90
- val_loader=loaders["val"],
91
- **train_cfg,
92
- )
93
-
94
- return {
95
- "model": model,
96
- "history": history,
97
- "device": device,
98
- "config": cfg,
99
- }
100
-
101
-
102
- def evaluate_rbm(
103
- model: RBM,
104
- config_path: str | Path,
105
- ) -> Dict[str, Any]:
106
- """Evaluate a trained RBM model.
107
-
108
- Args:
109
- model: Trained RBM model.
110
- config_path: Path to configuration .py file.
111
-
112
- Returns:
113
- Dictionary containing:
114
- - test_metrics: Basic test metrics (free energy, reconstruction).
115
- - conditional_results: Conditional NLL evaluation results.
116
- """
117
- cfg = load_config(config_path)
118
-
119
- loaders = create_dataloaders(cfg)
120
- device = loaders["device"]
121
- model = model.to(device)
122
-
123
- print(f"Using device: {device}")
124
- print(f"Evaluating on {len(loaders['test'].dataset)} test samples")
125
-
126
- # Basic metrics
127
- eval_cfg = cfg.get("eval", {})
128
- test_metrics = model.evaluate(loaders["test"], recon_k=eval_cfg.get("recon_k", 1))
129
- print("Test metrics:", test_metrics)
130
-
131
- # Conditional NLL
132
- cond_cfg = cfg.get("conditional", {})
133
- tester = RBMTester(
134
- model=model,
135
- test_dataloader=loaders["test"],
136
- clamp_idx=cond_cfg["clamp_idx"],
137
- target_idx=cond_cfg["target_idx"],
138
- )
139
- conditional_results = tester.conditional_nll(
140
- n_samples=cond_cfg.get("n_samples", 100),
141
- burn_in=cond_cfg.get("burn_in", 500),
142
- thin=cond_cfg.get("thin", 10),
143
- )
144
-
145
- return {
146
- "test_metrics": test_metrics,
147
- "conditional_results": conditional_results,
148
- }
149
-
150
-
151
- def save_model(
152
- model: RBM,
153
- path: str | Path,
154
- config_path: str | Path | None = None,
155
- ) -> None:
156
- """Save model checkpoint.
157
-
158
- Args:
159
- model: RBM model to save.
160
- path: Path to save checkpoint.
161
- config_path: Optional path to config file (will be saved as reference).
162
- """
163
- path = Path(path)
164
- checkpoint = {
165
- "model_state_dict": model.state_dict(),
166
- "nv": model.nv,
167
- "nh": model.nh,
168
- }
169
-
170
- if config_path is not None:
171
- # Load and save the actual config dict for portability
172
- cfg = load_config(config_path)
173
- checkpoint["config"] = cfg
174
- checkpoint["config_path"] = str(config_path)
175
-
176
- torch.save(checkpoint, path)
177
- print(f"Model saved to: {path}")
178
-
179
-
180
- def load_model(
181
- path: str | Path,
182
- device: str | None = None,
183
- ) -> tuple[RBM, Dict[str, Any] | None]:
184
- """Load model from checkpoint.
185
-
186
- Args:
187
- path: Path to checkpoint file.
188
- device: Device to load model to. If None, uses CPU.
189
-
190
- Returns:
191
- Tuple of (model, config) where config may be None if not saved.
192
- """
193
- path = Path(path)
194
- checkpoint = torch.load(path, map_location="cpu", weights_only=False)
195
-
196
- # Reconstruct config for model initialization
197
- cfg = checkpoint.get("config")
198
- if cfg is not None:
199
- model_cfg = cfg.get("model", {})
200
- else:
201
- # Fallback: create minimal config from saved dimensions
202
- nv = checkpoint.get("nv", checkpoint["model_state_dict"]["W"].shape[0])
203
- nh = checkpoint.get("nh", checkpoint["model_state_dict"]["W"].shape[1])
204
- model_cfg = {
205
- "visible_blocks": {"v": nv},
206
- "hidden_blocks": {"h": nh},
207
- }
208
-
209
- model = RBM(model_cfg)
210
- model.load_state_dict(checkpoint["model_state_dict"])
211
-
212
- if device:
213
- model = model.to(device)
214
-
215
- print(f"Model loaded from: {path}")
216
- return model, cfg