humancompatible-train 0.1.0__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.
Files changed (32) hide show
  1. experiments/__init__.py +0 -0
  2. experiments/calculate_iteration_values.py +310 -0
  3. experiments/run_folktables.py +408 -0
  4. experiments/run_folktables_torchalgs.py +956 -0
  5. humancompatible/__init__.py +0 -0
  6. humancompatible/train/__init__.py +3 -0
  7. humancompatible/train/algorithms/Algorithm.py +25 -0
  8. humancompatible/train/algorithms/__init__.py +8 -0
  9. humancompatible/train/algorithms/ghost.py +250 -0
  10. humancompatible/train/algorithms/sgd.py +107 -0
  11. humancompatible/train/algorithms/ssl_alm.py +311 -0
  12. humancompatible/train/algorithms/switching_subgradient.py +192 -0
  13. humancompatible/train/algorithms/torch/__init__.py +4 -0
  14. humancompatible/train/algorithms/torch/ssl_alm.py +212 -0
  15. humancompatible/train/algorithms/torch/ssw.py +155 -0
  16. humancompatible/train/algorithms/utils.py +61 -0
  17. humancompatible/train/constraints/__init__.py +11 -0
  18. humancompatible/train/constraints/constraint.py +87 -0
  19. humancompatible/train/constraints/constraint_fns.py +118 -0
  20. humancompatible/train/fairness/__init__.py +0 -0
  21. humancompatible/train/fairness/constraints/__init__.py +15 -0
  22. humancompatible/train/fairness/constraints/constraint.py +97 -0
  23. humancompatible/train/fairness/constraints/constraint_fns.py +244 -0
  24. humancompatible/train/fairness/constraints/torch/__init__.py +1 -0
  25. humancompatible/train/fairness/constraints/torch/constraints.py +36 -0
  26. humancompatible/train/fairness/utils/__init__.py +1 -0
  27. humancompatible/train/fairness/utils/balanced_batch_sampler.py +65 -0
  28. humancompatible_train-0.1.0.dist-info/METADATA +188 -0
  29. humancompatible_train-0.1.0.dist-info/RECORD +32 -0
  30. humancompatible_train-0.1.0.dist-info/WHEEL +5 -0
  31. humancompatible_train-0.1.0.dist-info/licenses/LICENCE.txt +201 -0
  32. humancompatible_train-0.1.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,408 @@
1
+ import importlib
2
+ from itertools import combinations
3
+ import os
4
+ import timeit
5
+ import warnings
6
+ import hydra
7
+ import numpy as np
8
+ import pandas as pd
9
+ import torch
10
+ from torch.utils.data import TensorDataset
11
+ from omegaconf import DictConfig, OmegaConf
12
+ from torch import nn, tensor
13
+ from utils.load_folktables import prepare_folktables_multattr
14
+ from utils.network import SimpleNet
15
+ from humancompatible.train.algorithms.utils import net_grads_to_tensor
16
+ from itertools import combinations
17
+ from humancompatible.train.fairness.constraints import FairnessConstraint
18
+
19
+
20
+
21
+ @hydra.main(version_base=None, config_path="conf", config_name="experiment")
22
+ def run(cfg: DictConfig) -> None:
23
+ warnings.filterwarnings("ignore", category=FutureWarning)
24
+
25
+ print(OmegaConf.to_yaml(cfg))
26
+ N_RUNS = cfg.n_runs
27
+ FT_STATE = cfg.data.state
28
+ FT_TASK = cfg.data.task
29
+ DOWNLOAD_DATA = cfg.data.download
30
+ DATA_PATH = cfg.data.path
31
+
32
+ if "constraint" in cfg.keys():
33
+ CONSTRAINT = cfg.constraint.import_name
34
+ LOSS_BOUND = cfg.constraint.bound
35
+ else:
36
+ CONSTRAINT = "unconstr"
37
+ LOSS_BOUND = 0
38
+
39
+ if cfg.device == "cpu":
40
+ device = "cpu"
41
+ elif cfg.alg == "ghost":
42
+ device = "cpu"
43
+ print("CUDA not supported for Stochastic Ghost")
44
+ elif torch.cuda.is_available():
45
+ device = "cuda"
46
+ print("CUDA found")
47
+ else:
48
+ device = "cpu"
49
+ print("CUDA not found")
50
+
51
+ print(f"{device = }")
52
+ torch.set_default_device(device)
53
+
54
+ DTYPE = torch.float32
55
+
56
+ ## load data ##
57
+
58
+ torch.set_default_dtype(DTYPE)
59
+ DATASET_NAME = FT_TASK + "_" + FT_STATE
60
+
61
+ (
62
+ X_train,
63
+ y_train,
64
+ group_ind_train,
65
+ _,
66
+ _,
67
+ X_test,
68
+ y_test,
69
+ group_ind_test,
70
+ _,
71
+ _,
72
+ _
73
+ ) = prepare_folktables_multattr(
74
+ FT_TASK,
75
+ state=FT_STATE.upper(),
76
+ random_state=42,
77
+ onehot=False,
78
+ download=DOWNLOAD_DATA,
79
+ path=DATA_PATH,
80
+ sens_cols=cfg.data.sens_attr,
81
+ binarize=cfg.data.binarize,
82
+ stratify=False,
83
+ )
84
+ print('Groups:')
85
+ print(len(group_ind_train))
86
+ X_train_tensor = tensor(X_train, dtype=DTYPE)
87
+ y_train_tensor = tensor(y_train, dtype=DTYPE)
88
+ train_ds = TensorDataset(X_train_tensor, y_train_tensor)
89
+
90
+ print(f"Train data loaded: {(FT_TASK, FT_STATE)}")
91
+ print(f"Data shape: {X_train_tensor.shape}")
92
+
93
+ ## prepare to save results ##
94
+
95
+ if "save_name" in cfg["alg"].keys():
96
+ alg_save_name = cfg.alg.save_name
97
+ else:
98
+ alg_save_name = cfg.alg.import_name
99
+
100
+ saved_models_path = os.path.abspath(
101
+ os.path.join(os.path.dirname(__file__), "utils", "saved_models")
102
+ )
103
+ directory = os.path.join(
104
+ saved_models_path, DATASET_NAME, CONSTRAINT, f"{LOSS_BOUND:.0E}"
105
+ )
106
+
107
+ model_name = os.path.join(directory, f"{alg_save_name}_{LOSS_BOUND}")
108
+
109
+ if not os.path.exists(directory):
110
+ os.makedirs(directory)
111
+
112
+ ## run experiments ##
113
+ histories = []
114
+ for EXP_IDX in range(N_RUNS):
115
+
116
+ net = SimpleNet(in_shape=X_test.shape[1], out_shape=1, dtype=DTYPE).to(device)
117
+
118
+ ## define constraints ##
119
+ loss_fn = nn.BCEWithLogitsLoss()
120
+ constraint_fn_module = importlib.import_module("humancompatible.train.fairness.constraints")
121
+ constraint_fn = getattr(constraint_fn_module, cfg.constraint.import_name)
122
+
123
+ if cfg.constraint.type == 'one_vs_mean':
124
+ c = [
125
+ FairnessConstraint(
126
+ train_ds,
127
+ [group_ind, np.concat(group_ind_train)],
128
+ fn=lambda net, inputs: constraint_fn(loss_fn, net, inputs) - cfg.constraint.bound,
129
+ batch_size=cfg.constraint.c_batch_size,
130
+ seed=EXP_IDX
131
+ )
132
+ for group_ind in group_ind_train
133
+ ]
134
+ if cfg.constraint.add_negative:
135
+ c.extend(
136
+ [
137
+ FairnessConstraint(
138
+ train_ds,
139
+ [group_ind, np.concat(group_ind_train)],
140
+ fn=lambda net, inputs: -constraint_fn(loss_fn, net, inputs) - cfg.constraint.bound,
141
+ batch_size=cfg.constraint.c_batch_size,
142
+ seed=EXP_IDX
143
+ )
144
+ for group_ind in group_ind_train
145
+ ]
146
+ )
147
+ elif cfg.constraint.type == 'one_vs_each':
148
+ c = [
149
+ FairnessConstraint(
150
+ train_ds,
151
+ group_idx,
152
+ fn=lambda net, inputs: constraint_fn(loss_fn, net, inputs) - cfg.constraint.bound,
153
+ batch_size=cfg.constraint.c_batch_size,
154
+ device=device,
155
+ seed=EXP_IDX,
156
+ )
157
+ for group_idx in combinations(group_ind_train, 2)
158
+ ]
159
+ if cfg.constraint.add_negative:
160
+ c.extend(
161
+ [
162
+ FairnessConstraint(
163
+ train_ds,
164
+ group_idx,
165
+ fn=lambda net, inputs: -constraint_fn(loss_fn, net, inputs) - cfg.constraint.bound,
166
+ batch_size=cfg.constraint.c_batch_size,
167
+ device=device,
168
+ seed=EXP_IDX,
169
+ )
170
+ for group_idx in combinations(group_ind_train, 2)
171
+ ]
172
+ )
173
+
174
+ torch.manual_seed(EXP_IDX)
175
+ model_path = model_name + f"_trial{EXP_IDX}.pt"
176
+
177
+ net = SimpleNet(in_shape=X_test.shape[1], out_shape=1, dtype=DTYPE).to(device)
178
+
179
+ optimizer_name = cfg.alg.import_name
180
+ module = importlib.import_module("humancompatible.train.algorithms")
181
+ Optimizer = getattr(module, optimizer_name)
182
+
183
+ optimizer = Optimizer(net, train_ds, loss_fn, c)
184
+ history = optimizer.optimize(
185
+ **cfg.alg.params,
186
+ max_iter=cfg.run_maxiter,
187
+ max_runtime=cfg.run_maxtime,
188
+ device=device,
189
+ seed=EXP_IDX,
190
+ verbose=True,
191
+ )
192
+
193
+ ## SAVE RESULTS ##
194
+ params = pd.DataFrame(history["params"])
195
+ values = pd.DataFrame(history["values"])
196
+ t = pd.Series(history["time"], name="time")
197
+ histories.append(values.join(params, how="outer").join(t, how="outer"))
198
+
199
+
200
+ ## SAVE MODEL ##
201
+ print(f"Model saved to: {model_path}")
202
+ torch.save(net.state_dict(), model_path)
203
+ print("")
204
+
205
+ # Save DataFrames to CSV files
206
+ c_name = cfg.constraint.import_name
207
+ utils_path = os.path.abspath(
208
+ os.path.join(os.path.dirname(__file__), "utils", "exp_results", c_name)
209
+ )
210
+ if not os.path.exists(utils_path):
211
+ os.makedirs(utils_path)
212
+
213
+ if cfg.save_checkpoint_df:
214
+ fname = f"{alg_save_name}_{DATASET_NAME}_{LOSS_BOUND}.csv"
215
+ save_path = os.path.join(utils_path, fname)
216
+ print(f"Saving to: {save_path}")
217
+ histories = pd.concat(histories, keys=range(N_RUNS), names=["trial", "iteration"])
218
+ histories.to_pickle(save_path)
219
+ print("Saved!")
220
+
221
+ ####################################################
222
+ ### CALCULATE STATS ON EVERY ALGORITHM ITERATION ###
223
+ ####################################################
224
+
225
+ loss_fn = nn.BCEWithLogitsLoss()
226
+ constraint_fn_module = importlib.import_module("humancompatible.train.fairness.constraints")
227
+ constraint_fn = getattr(constraint_fn_module, cfg.constraint.import_name)
228
+
229
+ print("----")
230
+ print("")
231
+
232
+ exp_iter_indices = [
233
+ histories.loc[exp_idx, :]
234
+ .index.get_level_values("iteration")[histories.loc[exp_idx]["w"].notna()]
235
+ .to_list()
236
+ for exp_idx in histories.index.get_level_values("trial").unique()
237
+ ]
238
+ exp_maxiter = np.argmax([ind[-1] for ind in exp_iter_indices])
239
+ longest_exp_indices = exp_iter_indices[exp_maxiter]
240
+ longest_exp_indices.extend(
241
+ [ei[-1] for ei in exp_iter_indices if ei[-1] not in longest_exp_indices]
242
+ )
243
+ longest_exp_indices = list(set(longest_exp_indices))
244
+ longest_exp_indices.sort()
245
+
246
+ index = pd.MultiIndex.from_product(
247
+ [longest_exp_indices, range(N_RUNS)],
248
+ names=("iteration", "trial"),
249
+ )
250
+ full_eval_train = pd.DataFrame(
251
+ index=index, columns=["G", "f", "fg", "c", "cg"]
252
+ ).sort_index()
253
+ full_eval_test = pd.DataFrame(
254
+ index=index, columns=["G", "f", "fg", "c", "cg"]
255
+ ).sort_index()
256
+
257
+ loss_fn = nn.BCEWithLogitsLoss()
258
+ X_test_tensor = tensor(X_test, dtype=DTYPE).to(device)
259
+ y_test_tensor = tensor(y_test, dtype=DTYPE).to(device)
260
+ X_train_tensor = X_train_tensor.to(device=device)
261
+ y_train_tensor = y_train_tensor.to(device=device)
262
+
263
+ save_train = True
264
+ save_test = True
265
+ histories.dropna(subset=["w"], inplace=True)
266
+
267
+ for exp_idx in range(N_RUNS):
268
+ for alg_iteration in histories.loc[exp_idx, :].index:
269
+ print(f"{exp_idx} | {alg_iteration}", end="\r")
270
+
271
+ w = histories["w"].loc[exp_idx, alg_iteration]
272
+ net.load_state_dict(w)
273
+ net = net.to(device)
274
+ if save_train:
275
+ if cfg.constraint.type=="one_vs_mean":
276
+ data_c = [
277
+ (
278
+ (X_train_tensor[g_idx], y_train_tensor[g_idx]),
279
+ (X_train_tensor, y_train_tensor)
280
+ )
281
+ for g_idx in group_ind_train
282
+ ]
283
+ elif cfg.constraint.type=="one_vs_each":
284
+ data_c = [
285
+ (
286
+ (X_train_tensor[g_idx_1], y_train_tensor[g_idx_1]),
287
+ (X_train_tensor[g_idx_2], y_train_tensor[g_idx_2]),
288
+ )
289
+ for g_idx_1, g_idx_2 in combinations(group_ind_train, 2)
290
+ ]
291
+ calculate_iteration_values(
292
+ alg=cfg.alg.import_name,
293
+ full_eval=full_eval_train,
294
+ index_to_save=[alg_iteration, exp_idx],
295
+ c=c,
296
+ loss_fn=loss_fn,
297
+ data_f=[X_train_tensor, y_train_tensor],
298
+ data_c=data_c,
299
+ net=net,
300
+ device=device,
301
+ add_negative=cfg.constraint.add_negative,
302
+ **params,
303
+ )
304
+
305
+
306
+ if save_test:
307
+ if cfg.constraint.type=="one_vs_mean":
308
+ data_c = [
309
+ (
310
+ (X_test_tensor[g_idx], y_test_tensor[g_idx]),
311
+ (X_test_tensor, y_test_tensor)
312
+ )
313
+ for g_idx in group_ind_test
314
+ ]
315
+ elif cfg.constraint.type=="one_vs_each":
316
+ data_c = [
317
+ (
318
+ (X_test_tensor[g_idx_1], y_test_tensor[g_idx_1]),
319
+ (X_test_tensor[g_idx_2], y_test_tensor[g_idx_2]),
320
+ )
321
+ for g_idx_1, g_idx_2 in combinations(group_ind_test, 2)
322
+ ]
323
+ calculate_iteration_values(
324
+ alg=cfg.alg.import_name,
325
+ full_eval=full_eval_test,
326
+ index_to_save=[alg_iteration, exp_idx],
327
+ c=c,
328
+ loss_fn=loss_fn,
329
+ data_f=[X_test_tensor, y_test_tensor],
330
+ data_c=data_c,
331
+ net=net,
332
+ device=device,
333
+ add_negative=cfg.constraint.add_negative,
334
+ **params,
335
+ )
336
+
337
+ net.zero_grad()
338
+
339
+ fname = f"AFTER_{alg_save_name}_{DATASET_NAME}_{LOSS_BOUND}"
340
+ fext = ".csv"
341
+ if save_train:
342
+ fname_train = fname + "_train" + fext
343
+ save_path = os.path.join(utils_path, fname_train)
344
+ print(f"Saving to: {save_path}")
345
+ full_eval_train.to_pickle(save_path)
346
+
347
+ if save_test:
348
+ fname_test = fname + "_test" + fext
349
+ save_path = os.path.join(utils_path, fname_test)
350
+ print(f"Saving to: {save_path}")
351
+ full_eval_test.to_pickle(save_path)
352
+
353
+
354
+ # helper function to calculate relevant values on full dataset (e.g. constraint gradient, AL function, etc)
355
+ # used to calculate those values at different points during algorithms run
356
+ def calculate_iteration_values(
357
+ alg,
358
+ full_eval,
359
+ index_to_save,
360
+ c,
361
+ loss_fn,
362
+ data_f,
363
+ data_c,
364
+ net,
365
+ device,
366
+ add_negative,
367
+ **params,
368
+ ):
369
+ c_val_vec, c_grads_mat = [], []
370
+
371
+ for i, c_i in enumerate(c):
372
+ cv = c_i.eval(net, data_c[i // 2 if add_negative else i])
373
+ c_val_vec.append(cv)
374
+ cv.backward()
375
+ cg = net_grads_to_tensor(net, flatten=True, device=device)
376
+ net.zero_grad()
377
+ c_grads_mat.append(cg)
378
+ c_val_vec = torch.tensor(c_val_vec)
379
+ c_grads_mat = torch.stack(c_grads_mat)
380
+ full_eval.loc[*index_to_save]["c"] = [c_val_vec.detach().cpu().numpy()]
381
+ full_eval.loc[*index_to_save]["cg"] = [c_grads_mat.detach().cpu().numpy()]
382
+
383
+ X_tensor, y_tensor = data_f
384
+ outs = net(X_tensor)
385
+ if y_tensor.ndim < outs.ndim:
386
+ y_tensor = y_tensor.unsqueeze(1)
387
+ loss = loss_fn(outs, y_tensor)
388
+ loss.backward()
389
+ fg = net_grads_to_tensor(net, flatten=True, device=device)
390
+ net.zero_grad()
391
+
392
+ full_eval.loc[*index_to_save]["f"] = loss.detach().cpu().numpy()
393
+ full_eval.loc[*index_to_save]["fg"] = [fg.detach().cpu().numpy()]
394
+
395
+
396
+ def sample_or_restart_iterloader(loader):
397
+ try:
398
+ item = next(loader)
399
+ return item
400
+ except StopIteration:
401
+ loader._reset(loader)
402
+ # loader.gen
403
+ item = next(loader)
404
+ return item
405
+
406
+
407
+ if __name__ == "__main__":
408
+ run()