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
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 | class Visualizer:
def __init__(
self,
final_model_dir: Path,
dataset: EconomicDataset,
data_batch: EconomicModelInput,
final_model: EconomicNetwork | None = None,
training_animation: bool = False,
num_checkpoints: int = None,
load_checkpoints_evenly: bool = True,
min_epoch: int | None = None,
max_epoch: int | None = None,
additional_tracker_names: list[
Literal[CONVERGNCE_TRACKER_NAME, HISTOGRAMS_TRACKER_NAME, IMPACTS_CONVERGENCE_TRACKER_NAME]
]
| Literal["all"]
| None = None,
curve_settings: dict | None = None,
):
self.ckpt_dirs = (
get_checkpoint_paths(final_model_dir, num_checkpoints, load_checkpoints_evenly, min_epoch, max_epoch)
if training_animation
else None
)
self.training_animation = training_animation
self.model_dir = final_model_dir
self.dataset = dataset
self.temp_dir = tempfile.TemporaryDirectory()
self.trackers_built = False
self.additional_tracker_names = additional_tracker_names or []
self.curve_settings = curve_settings
if final_model is None:
self._final_model = self._build_model(dataset)
self._final_model.restore(
self.model_dir,
no_trackers=False,
catch_exceptions=False,
partial_restore=False,
)
else:
self._final_model = final_model
self._build_and_write_trackers(data_batch)
def _build_and_write_trackers(self, data_batch: EconomicModelInput):
try:
if self.training_animation:
for i, ckpt_dir in tqdm(enumerate(self.ckpt_dirs)):
if i == 0:
ckpt_model = ModelWithTrackedDataSubset(
temp_dir=Path(self.temp_dir.name),
model=self._final_model,
dataset=self.dataset,
data_batch=data_batch,
additional_tracker_names=self.additional_tracker_names,
curve_settings=self.curve_settings,
)
ckpt_model.restore_and_write_trackers(ckpt_dir)
else:
final_model = ModelWithTrackedDataSubset(
temp_dir=Path(self.temp_dir.name),
model=self._final_model,
dataset=self.dataset,
data_batch=data_batch,
additional_tracker_names=self.additional_tracker_names,
curve_settings=self.curve_settings,
)
final_model.restore_and_write_trackers(self.model_dir)
self.trackers_built = True
except Exception as e:
self.clean_up()
raise e
def _build_model(self, dataset: EconomicDataset) -> EconomicNetwork:
with open(Path(__file__).parent.parent.parent / "cml" / "hyperparameters.yml", "r") as fp:
hyperparameters = yaml.safe_load(fp)
model = build_model(
dataset=dataset,
hyperparameters=hyperparameters,
net_combination=copy.deepcopy(DEFAULT_NETWORK_COMBINATION),
include_trackers=False,
_disable_model_compile_cache=True,
)
_ = model(next(iter(dataset)))
return model
@cached_property
def all_trackers(self) -> DataForViz:
_all_trackers = {}
for dir_path in Path(self.temp_dir.name).iterdir():
trackers = load_model_trackers(dir_path)
_all_trackers = merge_trackers(_all_trackers, trackers)
return _all_trackers
def visualize(
self,
data_creator: Callable[[Intermediary, dict], DataForViz],
plot_creator: Callable[DataForViz, go.Figure | dict[str, go.Figure]],
tracker_name: str,
data_kwargs: dict | None = None,
plot_kwargs: dict | None = None,
show_plot=True,
file_name: str | None = None,
out_dir: str | Path | None = None,
plot_title: str | None = None,
) -> go.Figure:
"""
Visualize the data from the model using the registered functions
"""
data_kwargs = data_kwargs or {}
plot_kwargs = plot_kwargs or {}
slider_label = sorted(list(self.all_trackers[f"all_{tracker_name}"].keys()))
tracker_intermediaries = [self.all_trackers[f"all_{tracker_name}"][label] for label in slider_label]
tracker_intermediaries = [
intermediary["temporalnet"] if tracker_name == "intermediaries" else intermediary
for intermediary in tracker_intermediaries
if intermediary
]
if self.training_animation:
if data_creator.__name__ == get_impact_for_viz.__name__:
data_list = [
data_creator(intermediary, is_animation_call=True, data_kwargs=data_kwargs)
for intermediary in tracker_intermediaries
]
elif data_creator.__name__ in (
get_convergence_for_viz.__name__,
get_histograms_for_viz.__name__,
get_impacts_convergence_for_viz.__name__,
):
data_list = data_creator(tracker_intermediaries, data_kwargs)
else:
data_list = [
data_creator(intermediary, data_kwargs=data_kwargs) for intermediary in tracker_intermediaries
]
if plot_creator.__name__ == viz_impacts.__name__:
final_plot = plot_creator(pd.concat(data_list, axis=0), is_animation_call=True, viz_kwargs=plot_kwargs)
elif plot_creator.__name__ == viz_convergence.__name__:
final_plot = plot_creator(data_list, viz_kwargs=plot_kwargs | {"return_figure_flag": show_plot})
elif plot_creator.__name__ in (viz_histograms.__name__, viz_impacts_convergence.__name__):
final_plot = plot_creator(data_list, viz_kwargs=plot_kwargs)
else:
final_plot = get_animated_plot([plot_creator(data, plot_kwargs) for data in data_list], slider_label)
else:
data = data_creator(tracker_intermediaries[-1], data_kwargs=data_kwargs)
final_plot = plot_creator(data, viz_kwargs=plot_kwargs)
show_or_save_plots(final_plot, show_plot, file_name, plot_title, out_dir)
def __del__(self):
self.clean_up()
def clean_up(self):
self.temp_dir.cleanup()
|