-
Notifications
You must be signed in to change notification settings - Fork 25
/
run.py
2155 lines (1991 loc) · 93.4 KB
/
run.py
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
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2022 The Balsa Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Balsa.
Usage:
# Experiment configs are declared in experiments.py.
# Look up the name and pass --run <name>.
python -u run.py --run <name> 2>&1 | tee run.log
Use Main() to modify hparams for debugging.
"""
import collections
import copy
import logging
import os
import pickle
import pprint
import signal
import time
from absl import app
from absl import flags
import numpy as np
import pandas as pd
import psycopg2
import pytorch_lightning as pl
from pytorch_lightning import loggers as pl_loggers
import ray
import ray.util
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import lr_scheduler
import torch.utils.data
from torch.utils.tensorboard import SummaryWriter
import wandb
import balsa
from balsa import costing
from balsa import envs
from balsa import execution
from balsa import plan_analysis
from balsa.experience import Experience
from balsa.models.transformer import ReportModel
from balsa.models.transformer import Transformer
from balsa.models.transformer import TransformerV2
from balsa.models.treeconv import TreeConvolution
import balsa.optimizer as optim
from balsa.util import dataset as ds
from balsa.util import plans_lib
from balsa.util import postgres
import sim as sim_lib
import pg_executor
from pg_executor import dbmsx_executor
import train_utils
import experiments # noqa # pylint: disable=unused-import
FLAGS = flags.FLAGS
flags.DEFINE_string('run', 'Balsa_JOBRandSplit', 'Experiment config to run.')
flags.DEFINE_boolean('local', False,
'Whether to use local engine for query execution.')
def GetDevice():
return 'cuda' if torch.cuda.is_available() else 'cpu'
def Save(obj, path):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, 'wb') as f:
pickle.dump(obj, f)
return path
def SaveText(text, path):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path + '.tmp', 'w') as f:
f.write(text)
f.write('\n')
os.replace(path + '.tmp', path)
return path
def MakeModel(p, exp, dataset):
dev = GetDevice()
num_label_bins = int(
dataset.costs.max().item()) + 2 # +1 for 0, +1 for ceil(max cost).
query_feat_size = len(exp.query_featurizer(exp.nodes[0]))
batch = exp.featurizer(exp.nodes[0])
assert batch.ndim == 1
plan_feat_size = batch.shape[0]
if p.tree_conv:
labels = num_label_bins if p.cross_entropy else 1
return TreeConvolution(feature_size=query_feat_size,
plan_size=plan_feat_size,
label_size=labels,
version=p.tree_conv_version).to(dev)
else:
plan_vocab_size = exp.featurizer.pad() + 1 # +1 for PAD.
parent_pos_vocab_size = exp.pos_featurizer.pad() + 1
d_model = 256
d_ff = 1024
num_layers = 4
num_heads = 4
clazz = TransformerV2 if p.v2 else Transformer
return clazz(
plan_vocab_size,
parent_pos_vocab_size,
d_model,
num_heads,
d_ff,
num_layers,
d_query_feat=query_feat_size,
plan_pad_idx=exp.featurizer.pad(),
parent_pos_pad_idx=exp.pos_featurizer.pad(),
use_pos_embs=p.pos_embs,
dropout=p.dropout,
cross_entropy=p.cross_entropy,
max_label_bins=num_label_bins,
).to(dev)
@ray.remote
def ExecuteSql(query_name,
sql_str,
hint_str,
hinted_plan,
query_node,
predicted_latency,
curr_timeout_ms=None,
found_plans=None,
predicted_costs=None,
silent=False,
is_test=False,
use_local_execution=True,
plan_physical=True,
repeat=1,
engine='postgres'):
"""Executes a query.
Returns:
If use_local_execution:
A (pg_executor, dbmsx_executor).Result.
Else:
A ray.ObjectRef of the above.
"""
# Unused args.
del query_name, hinted_plan, query_node, predicted_latency, found_plans,\
predicted_costs, silent, is_test, plan_physical
assert engine in ('postgres', 'dbmsx'), engine
if engine == 'postgres':
return postgres.ExplainAnalyzeSql(sql_str,
comment=hint_str,
verbose=False,
geqo_off=True,
timeout_ms=curr_timeout_ms,
remote=not use_local_execution)
else:
return DbmsxExecuteSql(sql_str,
comment=hint_str,
timeout_ms=curr_timeout_ms,
remote=not use_local_execution,
repeat=repeat)
def AddCommentToSql(sql_str, comment, engine):
"""Adds a comment (hint string) to a SQL string."""
fns = {
'postgres': PostgresAddCommentToSql,
'dbmsx': DbmsxAddCommentToSql,
}
return fns[engine](sql_str, comment)
def PostgresAddCommentToSql(sql_str, comment=None):
"""Postgres: <comment> <SELECT ...>."""
return comment + '\n' + sql_str
def DbmsxAddCommentToSql(sql_str, comment=None):
raise NotImplementedError
def DbmsxExecuteSql(sql_str,
comment=None,
timeout_ms=None,
remote=True,
repeat=1):
raise NotImplementedError
def DbmsxNodeToHintStr(node, with_physical_hints=False):
"""Converts a plans_lib.Node plan into Dbmsx-compatible hint string."""
raise NotImplementedError
def HintStr(node, with_physical_hints, engine):
if engine == 'postgres':
return node.hint_str(with_physical_hints=with_physical_hints)
assert engine == 'dbmsx', engine
return DbmsxNodeToHintStr(node, with_physical_hints=with_physical_hints)
def ParseExecutionResult(result_tup,
query_name,
sql_str,
hint_str,
hinted_plan,
query_node,
predicted_latency,
curr_timeout_ms=None,
found_plans=None,
predicted_costs=None,
silent=False,
is_test=False,
use_local_execution=True,
plan_physical=True,
repeat=None,
engine='postgres'):
del repeat # Unused.
messages = []
result = result_tup.result
has_timeout = result_tup.has_timeout
server_ip = result_tup.server_ip
if has_timeout:
assert not result, result
if engine == 'dbmsx':
real_cost = -1 if has_timeout else result_tup.latency
else:
if has_timeout:
real_cost = -1
else:
json_dict = result[0][0][0]
real_cost = json_dict['Execution Time']
if hint_str is not None:
# Check that the hint has been respected. No need to check if running
# baseline.
do_hint_check = True
if engine == 'dbmsx':
raise NotImplementedError
else:
if not has_timeout:
executed_node = postgres.ParsePostgresPlanJson(json_dict)
else:
# Timeout has occurred & 'result' is empty. Fallback to
# checking against local Postgres.
print('Timeout occurred; checking the hint against local PG.')
executed_node, _ = postgres.SqlToPlanNode(sql_str,
comment=hint_str,
verbose=False)
executed_node = plans_lib.FilterScansOrJoins(executed_node)
executed_hint_str = executed_node.hint_str(
with_physical_hints=plan_physical)
if do_hint_check and hint_str != executed_hint_str:
print('initial\n', hint_str)
print('after\n', executed_hint_str)
msg = 'Hint not respected for {}; server_ip={}'.format(
query_name, server_ip)
try:
assert False, msg
except Exception as e:
print(e, flush=True)
import ipdb
ipdb.set_trace()
if not silent:
messages.append('{}Running {}: hinted plan\n{}'.format(
'[Test set] ' if is_test else '', query_name, hinted_plan))
messages.append('filters')
messages.append(pprint.pformat(query_node.info['all_filters']))
messages.append('')
messages.append('q{},{:.1f},{}'.format(query_node.info['query_name'],
real_cost, hint_str))
messages.append(
'{} Execution time: {:.1f} (predicted {:.1f}) curr_timeout_ms={}'.
format(query_name, real_cost, predicted_latency, curr_timeout_ms))
if hint_str is None or silent:
# Running baseline: don't print debug messages below.
return result_tup, real_cost, server_ip, '\n'.join(messages)
messages.append('Expert plan: latency, predicted, hint')
expert_hint_str = query_node.hint_str()
expert_hint_str_physical = query_node.hint_str(with_physical_hints=True)
messages.append(' {:.1f} (predicted {:.1f}) {}'.format(
query_node.cost, query_node.info['curr_predicted_latency'],
expert_hint_str))
if found_plans:
if predicted_costs is None:
predicted_costs = [None] * len(found_plans)
messages.append('SIM-predicted costs, predicted latency, plan: ')
min_p_latency = np.min([p_latency for p_latency, _ in found_plans])
for p_cost, found in zip(predicted_costs, found_plans):
p_latency, found_plan = found
found_hint_str = found_plan.hint_str()
found_hint_str_physical = HintStr(found_plan,
with_physical_hints=True,
engine=engine)
extras = [
'cheapest' if p_latency == min_p_latency else '',
'[expert plan]'
if found_hint_str_physical == expert_hint_str_physical else '',
'[picked]' if found_hint_str_physical == hint_str else ''
]
extras = ' '.join(filter(lambda s: s, extras)).strip()
if extras:
extras = '<-- {}'.format(extras)
if p_cost:
messages.append(' {:.1f} {:.1f} {} {}'.format(
p_cost, p_latency, found_hint_str, extras))
else:
messages.append(' {:.1f} {} {}'.format(
p_latency, found_hint_str, extras))
messages.append('-' * 80)
return result_tup, real_cost, server_ip, '\n'.join(messages)
def _GetQueryFeaturizerClass(p):
return {
True: sim_lib.SimQueryFeaturizer,
False: plans_lib.QueryFeaturizer,
'SimQueryFeaturizerV2': sim_lib.SimQueryFeaturizerV2,
'SimQueryFeaturizerV3': sim_lib.SimQueryFeaturizerV3,
'SimQueryFeaturizerV4': sim_lib.SimQueryFeaturizerV4,
}[p.sim_query_featurizer]
def TrainSim(p, loggers=None):
sim_p = sim_lib.Sim.Params()
# Copy over relevant params.
sim_p.workload.query_dir = p.query_dir
sim_p.workload.query_glob = p.query_glob
sim_p.workload.test_query_glob = p.test_query_glob
sim_p.workload.search_space_join_ops = p.search_space_join_ops
sim_p.workload.search_space_scan_ops = p.search_space_scan_ops
sim_p.skip_data_collection_geq_num_rels = 12
if p.cost_model == 'mincardcost':
sim_p.search.cost_model = costing.MinCardCost.Params()
else:
sim_p.search.cost_model = costing.PostgresCost.Params()
sim_p.query_featurizer_cls = _GetQueryFeaturizerClass(p)
sim_p.plan_featurizer_cls = plans_lib.TreeNodeFeaturizer
sim_p.infer_search_method = p.search_method
sim_p.infer_beam_size = p.beam
sim_p.infer_search_until_n_complete_plans = p.search_until_n_complete_plans
if p.plan_physical:
sim_p.plan_physical = True
# Use a physical-aware plan featurizer.
sim_p.plan_featurizer_cls = plans_lib.PhysicalTreeNodeFeaturizer
sim_p.generic_ops_only_for_min_card_cost = \
p.generic_ops_only_for_min_card_cost
sim_p.label_transforms = p.label_transforms
sim_p.tree_conv_version = p.tree_conv_version
sim_p.loss_type = p.loss_type
sim_p.gradient_clip_val = p.gradient_clip_val
sim_p.bs = p.bs
sim_p.epochs = p.epochs
sim_p.perturb_query_features = p.perturb_query_features
sim_p.validate_fraction = p.validate_fraction
# Instantiate.
sim = sim_lib.Sim(sim_p)
if p.sim_checkpoint is None:
sim.CollectSimulationData()
sim.Train(load_from_checkpoint=p.sim_checkpoint, loggers=loggers)
sim.model.freeze()
sim.EvaluateCost()
sim.FreeData()
return sim
def InitializeModel(p,
model,
sim,
soft_assign_tau=0.0,
soft_assign_use_ema=False,
ema_source_tm1=None):
"""Initializes model weights.
Given model_(t-1), sim, ..., ema_source_tm1, initializes model_t as follows.
If soft_assign_use_ema is False:
model := soft_assign_tau*model + (1-soft_assign_tau)*sim.
In particular:
- soft_assign_tau = 0 means always reinitializes 'model' with 'sim'.
- soft_assign_tau = 1 means don't reinitialize 'model'; keep training it
across value iterations.
A value of 0.1 seems to perform well.
Otherwise, use an exponential moving average of "source networks":
source_t = soft_assign_tau * source_(t-1)
+ (1-soft_assign_tau) model_(t-1)
model_t := source_t
In particular:
- soft_assign_tau = 0 means don't reinitialize 'model'; keep training it
across value iterations.
- soft_assign_tau = 1 means always reinitializes 'model' with 'sim'.
A value of 0.05 seems to perform well.
For both schemes, before training 'model' for the very first time it is
always initialized with the simulation model 'sim'.
Args:
p: params.
model: current iteration's value model.
sim: the trained-in-sim model.
soft_assign_tau: if positive, soft initializes 'model' using the formula
described above.
soft_assign_use_ema: whether to use an exponential moving average of
"source networks".
ema_source_tm1: the EMA of source networks at iteration t-1.
"""
def Rename(state_dict):
new_state_dict = collections.OrderedDict()
for key, value in state_dict.items():
new_key = key
if key.startswith('tree_conv.'):
new_key = key.replace('tree_conv.', '')
new_state_dict[new_key] = value
return new_state_dict
sim_weights = sim.model.state_dict()
sim_weights_renamed = copy.deepcopy(Rename(sim_weights))
model_weights = model.state_dict()
assert model_weights.keys() == sim_weights_renamed.keys()
tau = soft_assign_tau
if tau:
if not soft_assign_use_ema:
print('Assigning real model := {}*SIM + {}*previous real model'.
format(1 - tau, tau))
for key, param in model_weights.items():
param.requires_grad = False
param = param * tau + sim_weights_renamed[key] * (1.0 - tau)
param.requires_grad = True
else:
# Use an exponential moving average of source networks.
if ema_source_tm1 is None:
ema_source_tm1 = sim_weights_renamed
assert isinstance(ema_source_tm1,
collections.OrderedDict), ema_source_tm1
assert ema_source_tm1.keys() == model_weights.keys()
# Calculates source_t for current iteration t:
# source_t = tau * source_(t-1) + (1-tau) model_(t-1)
with torch.no_grad():
ema_source_t = copy.deepcopy(ema_source_tm1)
for key, param in model_weights.items():
ema_source_t[key] = tau * ema_source_tm1[key] + (
1.0 - tau) * param
# Assign model_t := source_t.
model.load_state_dict(ema_source_t)
print('Initialized from EMA source network: tau={}'.format(tau))
# Return source_t for next iter's use.
return ema_source_t
else:
model.load_state_dict(sim_weights_renamed)
print('Initialized from SIM weights.')
if p.finetune_out_mlp_only:
for name, param in model.named_parameters():
if 'out_mlp' not in name:
param.detach_()
param.requires_grad = False
print('Freezing', name)
if p.param_noise:
for layer in model.out_mlp:
if isinstance(layer, nn.Linear):
print('Adding N(0, {}) to out_mlp\'s {}.'.format(
p.param_noise, layer))
def _Add(w):
w.requires_grad = False
w.add_(
torch.normal(mean=0.0,
std=p.param_noise,
size=w.shape,
device=w.device))
w.requires_grad = True
_Add(layer.weight)
class BalsaModel(pl.LightningModule):
"""Wraps an nn.Module into a pl.LightningModule."""
def __init__(self,
params,
model,
loss_type=None,
torch_invert_cost=None,
query_featurizer=None,
perturb_query_features=None,
l2_lambda=0,
learning_rate=None,
optimizer_state_dict=None,
reduce_lr_within_val_iter=False):
super().__init__()
self.logging_prefix = ''
self.params = params.Copy()
self.model = model
assert loss_type in [None, 'mean_qerror'], loss_type
self.loss_type = loss_type
self.torch_invert_cost = torch_invert_cost
self.query_featurizer = query_featurizer
self.perturb_query_features = perturb_query_features
self.l2_lambda = l2_lambda
self.optimizer_state_dict = optimizer_state_dict
# Assume constant LR within each value iter. Reasonable for on-pol but
# probably need tuning for off-pol.
self.learning_rate = learning_rate
# Optionally, reduce within each trainer.fit() call (i.e., an iter).
self.reduce_lr_within_val_iter = reduce_lr_within_val_iter
def SetLoggingPrefix(self, prefix):
"""Useful for prepending value iteration numbers."""
self.logging_prefix = prefix
def forward(self, query_feat, plan_feat, indexes):
return self.model(query_feat, plan_feat, indexes)
def configure_optimizers(self):
p = self.params
if p.adamw:
optimizer = torch.optim.AdamW(self.parameters(),
lr=self.learning_rate,
weight_decay=p.adamw)
else:
optimizer = torch.optim.Adam(
self.parameters(),
lr=self.learning_rate,
)
if self.optimizer_state_dict is not None:
# Checks the params are the same.
# 'params': [139581476513104, ...]
curr = optimizer.state_dict()['param_groups'][0]['params']
prev = self.optimizer_state_dict['param_groups'][0]['params']
assert curr == prev, (curr, prev)
print('Loading last iter\'s optimizer state.')
# Prev optimizer state's LR may be stale.
optimizer.load_state_dict(self.optimizer_state_dict)
for param_group in optimizer.param_groups:
param_group['lr'] = self.learning_rate
assert optimizer.state_dict(
)['param_groups'][0]['lr'] == self.learning_rate
print('LR', self.learning_rate)
if not self.reduce_lr_within_val_iter:
return optimizer
print('returning optimizer + scheduler')
scheduler = {
'scheduler': lr_scheduler.ReduceLROnPlateau(optimizer,
'min',
patience=5,
verbose=True),
'interval': 'epoch',
'frequency': 1,
'monitor': 'val_early_stop_on', # Bug: cannot use 'val_loss'.
}
return [optimizer], [scheduler]
def on_train_epoch_start(self):
self.latest_per_iter_lr = self.trainer.optimizers[0].state_dict(
)['param_groups'][0]['lr']
def training_step(self, batch, batch_idx):
loss, l2_loss = self._ComputeLoss(batch)
result = pl.TrainResult(minimize=loss)
# Log both a per-iter metric and an overall metric for comparison.
result.log('{}loss'.format(self.logging_prefix), loss, prog_bar=False)
result.log('train_loss', loss, prog_bar=True)
if self.l2_lambda > 0:
result.log('l2_loss', l2_loss, prog_bar=False)
return result
def validation_step(self, batch, batch_idx):
val_loss, l2_loss = self._ComputeLoss(batch)
result = pl.EvalResult(checkpoint_on=val_loss, early_stop_on=val_loss)
result.log('{}val_loss'.format(self.logging_prefix),
val_loss,
prog_bar=False)
result.log('val_loss', val_loss, prog_bar=True)
if self.l2_lambda > 0:
result.log('val_l2_loss', l2_loss, prog_bar=False)
return result
def _ComputeLoss(self, batch):
p = self.params
dev = GetDevice()
query_feat = batch.query_feats
if self.training and self.perturb_query_features is not None:
# No-op for non-enabled featurizers.
query_feat = self.query_featurizer.PerturbQueryFeatures(
query_feat, distribution=self.perturb_query_features)
query_feat, plan_feat, indexes, target = (query_feat.to(dev),
batch.plans.to(dev),
batch.indexes.to(dev),
batch.costs.to(dev))
output = self.forward(query_feat, plan_feat, indexes)
if p.cross_entropy:
log_probs = output.log_softmax(-1)
target_dist = torch.zeros_like(log_probs)
# Scalar 46.25 represented as: 0.75 * 46 + 0.25 * 47.
ceil = torch.ceil(target)
w_ceil = ceil - target
floor = torch.floor(target)
w_floor = 1 - w_ceil
target_dist.scatter_(1,
ceil.long().unsqueeze(1), w_ceil.unsqueeze(1))
target_dist.scatter_(1,
floor.long().unsqueeze(1),
w_floor.unsqueeze(1))
loss = (-target_dist * log_probs).sum(-1).mean()
else:
if self.loss_type == 'mean_qerror':
output_inverted = self.torch_invert_cost(output.reshape(-1,))
target_inverted = self.torch_invert_cost(target.reshape(-1,))
loss = train_utils.QErrorLoss(output_inverted, target_inverted)
else:
loss = F.mse_loss(output.reshape(-1,), target.reshape(-1,))
if self.l2_lambda > 0:
l2_loss = torch.tensor(0., device=loss.device, requires_grad=True)
for param in self.parameters():
l2_loss = l2_loss + torch.norm(param).pow(2)
l2_loss = self.l2_lambda * 0.5 * l2_loss
loss += l2_loss
return loss, l2_loss
return loss, None
def on_after_backward(self):
if self.global_step % 10 == 0:
norm_dict = self.grad_norm(norm_type=2)
total_grad_norm = norm_dict['grad_2.0_norm_total']
total_norm = torch.stack([
torch.norm(param) for param in self.parameters()
]).sum().detach()
self.logger.log_metrics(
{
'total_grad_norm': total_grad_norm,
'total_norm': total_norm,
},
step=self.global_step)
class BalsaAgent(object):
"""The Balsa agent."""
def __init__(self, params):
self.params = params.Copy()
p = self.params
print('BalsaAgent params:\n{}'.format(p))
self.sim = None
self.ema_source_net = None
self.timeout_controller = execution.PerQueryTimeoutController(
timeout_slack=p.timeout_slack,
no_op=not p.use_timeout,
relax_timeout_factor=p.relax_timeout_factor,
relax_timeout_on_n_timeout_iters=p.relax_timeout_on_n_timeout_iters,
initial_timeout_ms=p.initial_timeout_ms)
self.query_execution_cache = execution.QueryExecutionCache()
self.best_plans = execution.QueryExecutionCache()
self.trainer = None
self.loggers = None
# Labels.
self.label_mean = None
self.label_std = None
self.label_running_stats = envs.RunningStats()
# EMA/SWA.
# average name -> dict
self.moving_average_model_state_dict = collections.defaultdict(dict)
# average name -> counter
self.moving_average_counter_dict = collections.defaultdict(int)
# LR schedule.
self.lr_schedule = train_utils.GetLrSchedule(p)
# Optimizer state.
self.prev_optimizer_state_dict = None
# Ray.
if p.use_local_execution:
ray.init(resources={'pg': 1})
else:
# Cluster access: make sure the cluster has been launched.
import uuid
ray.init(address='auto',
namespace=f'{uuid.uuid4().hex[:4]}',
logging_level=logging.ERROR)
try:
print('Connected to ray! Resources:', ray.available_resources())
except RuntimeError as e:
if 'dictionary changed size during iteration' not in str(e):
raise e
print('Connected to ray but ray.available_resources() failed, '
'likely indicating issues with the cluster.\nTry running '
'1 run only and see if tasks go through or get stuck.'
' Exception:\n {}'.format(e))
# Workload.
self.workload = self._MakeWorkload()
self.all_nodes = self.workload.Queries(split='all')
self.train_nodes = self.workload.Queries(split='train')
self.test_nodes = self.workload.Queries(split='test')
print(len(self.train_nodes), 'train queries:',
[node.info['query_name'] for node in self.train_nodes])
print(len(self.test_nodes), 'test queries:',
[node.info['query_name'] for node in self.test_nodes])
if p.test_query_glob is None:
print('Consider all queries as training nodes.')
# Rewrite ops if physical plan is not used.
if not p.plan_physical:
plans_lib.RewriteAsGenericJoinsScans(self.all_nodes)
# If the target engine has a dialect != Postgres, overwrite
# node.info['sql_str'] with the dialected SQL.
if p.engine_dialect_query_dir is not None:
self.workload.UseDialectSql(p)
# Unused.
assert p.use_adaptive_lr is None
self.adaptive_lr_schedule = None
if p.linear_decay_to_zero:
self.adaptive_lr_schedule = (
train_utils.AdaptiveMetricPiecewiseDecayToZero(
[(0, p.lr)],
metric_max_value=0, # Does not matter.
total_steps=p.val_iters))
# Logging.
self._InitLogging()
self.timer = train_utils.Timer()
# Experience (replay) buffer.
self.exp, self.exp_val = self._MakeExperienceBuffer()
self._latest_replay_buffer_path = None
# Cleanup handlers. Ensures that the Ray cluster state remains healthy
# even if this driver program is killed.
signal.signal(signal.SIGTERM, self.Cleanup)
signal.signal(signal.SIGINT, self.Cleanup)
def Cleanup(self, signum, frame):
"""Calls ray.shutdown() on cleanup."""
print('Received signal {}; calling ray.shutdown().'.format(
signal.Signals(signum).name))
ray.shutdown()
def _MakeWorkload(self):
p = self.params
if os.path.isfile(p.init_experience):
# Load the expert optimizer experience.
with open(p.init_experience, 'rb') as f:
workload = pickle.load(f)
# Filter queries based on the current query_glob.
workload.FilterQueries(p.query_dir, p.query_glob, p.test_query_glob)
else:
wp = envs.JoinOrderBenchmark.Params()
wp.query_dir = p.query_dir
wp.query_glob = p.query_glob
wp.test_query_glob = None
workload = wp.cls(wp)
# Requires baseline to run in this scenario.
p.run_baseline = True
return workload
def _InitLogging(self):
p = self.params
self.loggers = [
pl_loggers.TensorBoardLogger(save_dir=os.getcwd(),
version=None,
name='tensorboard_logs'),
pl_loggers.WandbLogger(save_dir=os.getcwd(), project='balsa'),
]
self.summary_writer = SummaryWriter()
self.wandb_logger = self.loggers[-1]
p_dict = balsa.utils.SanitizeToText(dict(p))
for logger in self.loggers:
logger.log_hyperparams(p_dict)
with open(os.path.join(self.wandb_logger.experiment.dir, 'params.txt'),
'w') as f:
# Files saved to wandb's rundir are auto-uploaded.
f.write(p.ToText())
if not p.run_baseline:
self.LogExpertExperience(self.train_nodes, self.test_nodes)
def _MakeExperienceBuffer(self):
p = self.params
if not p.run_baseline and p.sim:
wi = self.GetOrTrainSim().training_workload_info
else:
# E.g., if sim is disabled, we just use the overall workload info
# (thus, this covers both train & test queries).
wi = self.workload.workload_info
if p.tree_conv:
plan_feat_cls = plans_lib.TreeNodeFeaturizer
if p.plan_physical:
# Physical-aware plan featurizer.
plan_feat_cls = plans_lib.PhysicalTreeNodeFeaturizer
else:
plan_feat_cls = plans_lib.PreOrderSequenceFeaturizer
query_featurizer_cls = _GetQueryFeaturizerClass(p)
if self.sim is not None:
# Use the already instantiated query featurizer, which may contain
# computed normalization stats.
query_featurizer_cls = self.GetOrTrainSim().query_featurizer
exp = Experience(self.train_nodes,
p.tree_conv,
workload_info=wi,
query_featurizer_cls=query_featurizer_cls,
plan_featurizer_cls=plan_feat_cls)
if p.prev_replay_buffers_glob is not None:
exp.Load(p.prev_replay_buffers_glob,
p.prev_replay_keep_last_fraction)
pa = plan_analysis.PlanAnalysis.Build(exp.nodes[exp.initial_size:])
pa.Print()
if p.prev_replay_buffers_glob_val is not None:
print('Building validation experience buffer...')
exp_val = Experience(self.train_nodes,
p.tree_conv,
workload_info=wi,
query_featurizer_cls=query_featurizer_cls,
plan_featurizer_cls=plan_feat_cls)
exp_val.Load(p.prev_replay_buffers_glob_val)
pa = plan_analysis.PlanAnalysis.Build(
exp_val.nodes[exp_val.initial_size:])
pa.Print()
else:
exp_val = None
return exp, exp_val
def _MakeDatasetAndLoader(self, log=True):
p = self.params
do_replay_training = (p.prev_replay_buffers_glob is not None and
p.agent_checkpoint is None)
if do_replay_training or (p.skip_training_on_expert and
self.curr_value_iter > 0):
# The first 'n' nodes are expert experience. Optionally, skip
# training on those. At iter 0, we don't skip (impl convenience)
# but we don't train on those data.
skip_first_n = len(self.train_nodes)
else:
# FIXME: ideally, let's make sure expert nodes are not added to the
# replay buffer all together. This was just to make sure iter=0
# code doesn't break (e.g., that we calculate a label mean/std).
skip_first_n = 0
# Use only the latest round of executions?
on_policy = p.on_policy
if do_replay_training and self.curr_value_iter == 0:
# Reloading replay buffers: let's train on all data.
on_policy = False
# TODO: avoid repeatedly featurizing already-featurized nodes.
tup = self.exp.featurize(
rewrite_generic=not p.plan_physical,
verbose=False,
skip_first_n=skip_first_n,
deduplicate=p.dedup_training_data,
physical_execution_hindsight=p.physical_execution_hindsight,
on_policy=on_policy,
use_last_n_iters=p.use_last_n_iters,
use_new_data_only=p.use_new_data_only,
skip_training_on_timeouts=p.skip_training_on_timeouts)
# [np.ndarray], torch.Tensor, torch.Tensor, [float].
all_query_vecs, all_feat_vecs, all_pos_vecs, all_costs = tup[:4]
num_new_datapoints = None
if len(tup) == 5:
num_new_datapoints = tup[-1]
if p.label_transform_running_stats and skip_first_n > 0:
# Use running stats to stabilize.
assert p.label_transforms in [
['log1p', 'standardize'],
['standardize'],
['sqrt', 'standardize'],
], p.label_transforms
assert not p.physical_execution_hindsight
labels = np.asarray([
executed_node.cost
for executed_node in self.exp.nodes[-skip_first_n:]
])
if p.label_transforms[0] == 'log1p':
labels = np.log(1 + labels)
elif p.label_transforms[0] == 'sqrt':
labels = np.sqrt(1 + labels)
for label in labels:
self.label_running_stats.Record(label)
# PlansDataset would use these as-is, when supplied.
self.label_mean = self.label_running_stats.Mean()
self.label_std = self.label_running_stats.Std(epsilon_guard=False)
dataset = ds.PlansDataset(all_query_vecs,
all_feat_vecs,
all_pos_vecs,
all_costs,
tree_conv=p.tree_conv,
transform_cost=p.label_transforms,
label_mean=self.label_mean,
label_std=self.label_std,
cross_entropy=p.cross_entropy)
if do_replay_training and self.curr_value_iter == 0:
self.label_mean = dataset.mean
self.label_std = dataset.std
print("Set label mean/std to offline set!")
if (not p.update_label_stats_every_iter and self.label_mean is None and
len(self.exp.nodes) > len(self.query_nodes)):
# Update the stats once, as soon as some experience is collected.
self.label_mean = dataset.mean
self.label_std = dataset.std
if self.exp_val is None:
assert 0 <= p.validate_fraction <= 1, p.validate_fraction
num_train = int(len(dataset) * (1 - p.validate_fraction))
num_validation = len(dataset) - num_train
assert num_train > 0 and num_validation >= 0, len(dataset)
print('num_train={} num_validation={}'.format(
num_train, num_validation))
train_ds, val_ds = torch.utils.data.random_split(
dataset, [num_train, num_validation])
train_labels = np.asarray(all_costs)[train_ds.indices]
else:
tup = self.exp_val.featurize(
rewrite_generic=not p.plan_physical,
verbose=False,
skip_first_n=skip_first_n,
deduplicate=p.dedup_training_data,
physical_execution_hindsight=p.physical_execution_hindsight,
on_policy=False,
use_last_n_iters=-1,
use_new_data_only=False,
skip_training_on_timeouts=p.skip_training_on_timeouts)
(all_query_vecs_val, all_feat_vecs_val, all_pos_vecs_val,
all_costs_val) = tup[:4]
dataset_val = ds.PlansDataset(all_query_vecs_val,
all_feat_vecs_val,
all_pos_vecs_val,
all_costs_val,
tree_conv=p.tree_conv,
transform_cost=p.label_transforms,
label_mean=self.label_mean,
label_std=self.label_std,
cross_entropy=p.cross_entropy)
train_ds, val_ds = dataset, dataset_val
train_labels = all_costs
if p.tree_conv:
collate_fn = ds.InputBatch
else:
collate_fn = lambda xs: ds.InputBatch(
xs,
plan_pad_idx=self.exp.featurizer.pad(),
parent_pos_pad_idx=self.exp.pos_featurizer.pad())
train_loader = torch.utils.data.DataLoader(train_ds,
batch_size=p.bs,
shuffle=True,
collate_fn=collate_fn,
pin_memory=True)
if p.validate_fraction > 0:
val_loader = torch.utils.data.DataLoader(val_ds,
batch_size=p.bs,
collate_fn=collate_fn)
else:
val_loader = None
if log:
self._LogDatasetStats(train_labels, num_new_datapoints)
return train_ds, train_loader, val_ds, val_loader
def _LogDatasetStats(self, train_labels, num_new_datapoints):
# Track # of training trees that are not timeouts.
num_normal_trees = (np.asarray(train_labels) !=
self.timeout_label()).sum()
data = [
('train/iter-{}-num-trees'.format(self.curr_value_iter),
len(train_labels), self.curr_value_iter),
('train/num-trees', len(train_labels), self.curr_value_iter),
('train/iter-{}-num-normal-trees'.format(self.curr_value_iter),
num_normal_trees, self.curr_value_iter),
('train/num-normal-trees', num_normal_trees, self.curr_value_iter),