-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearchbot_agent.py
2191 lines (1914 loc) · 91.6 KB
/
searchbot_agent.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 (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
from collections import defaultdict
import math
from typing import Callable, DefaultDict, Dict, List, Set, Tuple, Optional, Any
import collections
import copy
import functools
import itertools
import json
import logging
import random
import tabulate
import time
from termcolor import colored
import numpy as np
from fairdiplomacy.utils.agent_interruption import raise_if_should_stop
from fairdiplomacy.utils.typedefs import get_last_message
from parlai_diplomacy.utils.game2seq.format_helpers.misc import INF_SLEEP_TIME
import torch
from conf import agents_cfgs
from fairdiplomacy.pydipcc import Game, CFRStats
from fairdiplomacy.agents.base_agent import AgentState
from fairdiplomacy.agents.base_search_agent import (
BaseSearchAgent,
SearchResult,
make_set_orders_dicts,
sample_orders_from_policy,
)
from fairdiplomacy.agents.bilateral_stats import BilateralStats
from fairdiplomacy.pseudo_orders import PseudoOrders
from fairdiplomacy.utils.temp_redefine import temp_redefine
from parlai_diplomacy.utils.misc import last_dict_key
from parlai.utils.logging import _is_interactive
# fairdiplomacy.action_generation and fairdiplomacy.action_exploration
# both circularly refer fairdiplomacy.agents, so we import those modules whole
# instead of from "fairdiplomacy.action_generation import blah".
# That way, we break the circular initialization issue by not requiring the symbols
# *within* those modules to exist at import time, since they very well might not exist
# if we were only halfway through importing those when we began importing this file.
import fairdiplomacy.action_generation
import fairdiplomacy.action_exploration
from fairdiplomacy.agents.base_strategy_model_rollouts import (
BaseStrategyModelRollouts,
RolloutResultsCache,
)
from fairdiplomacy.agents.base_strategy_model_wrapper import BaseStrategyModelWrapper
from fairdiplomacy.agents.plausible_order_sampling import (
PlausibleOrderSampler,
cutoff_policy,
renormalize_policy,
)
from fairdiplomacy.agents.br_corr_bilateral_search import (
BRCorrBilateralSearchResult,
compute_payoff_matrix_for_all_opponents,
extract_bp_policy_for_powers,
)
from fairdiplomacy.models.consts import POWER2IDX, POWERS
from fairdiplomacy.utils.game import game_from_two_party_view, get_last_message_from, next_M_phase
from fairdiplomacy.utils.parse_device import device_id_to_str
from fairdiplomacy.utils.sampling import sample_p_dict, argmax_p_dict
from fairdiplomacy.utils.timing_ctx import TimingCtx
from fairdiplomacy.utils.order_idxs import is_action_valid
from fairdiplomacy.utils.base_strategy_model_multi_gpu_wrappers import (
MultiProcessBaseStrategyModelExecutor,
)
from fairdiplomacy.viz.meta_annotations import api as meta_annotations
from fairdiplomacy.typedefs import (
Action,
BilateralConditionalValueTable,
JointAction,
MessageDict,
MessageHeuristicResult,
ConditionalValueTable,
Phase,
PlausibleOrders,
PlayerRating,
Policy,
Power,
PowerPolicies,
Timestamp,
)
from parlai_diplomacy.wrappers.dialogue import TOKEN_DETAILS_TAG
from parlai_diplomacy.wrappers.factory import load_order_wrapper
from parlai_diplomacy.wrappers.orders import ParlAIPlausiblePseudoOrdersWrapper
from parlai_diplomacy.wrappers.base_wrapper import RolloutType
from fairdiplomacy.agents.parlai_message_handler import (
ParlaiMessageHandler,
ParlaiMessagePseudoOrdersCache,
SleepSixTimesCache,
pseudoorders_initiate_sleep_heuristics_should_trigger,
joint_action_contains_xpower_support_or_convoy,
)
ActionDict = Dict[Tuple[Power, Action], float]
def color_order_logprobs(a: Action, lp: Optional[Dict[Action, List[float]]]) -> str:
if not _is_interactive() or lp is None:
return ", ".join(a)
alp = lp[a]
assert len(a) == len(alp)
ret = []
for o, olp in zip(a, alp):
op = math.exp(olp)
if op < 1e-2:
o = colored(o, "red")
elif op < 1e-1:
o = colored(o, "yellow")
elif op < 0.5:
o = colored(o, "green")
ret.append(o)
return ", ".join(ret)
def filter_logprob_ratio(action_logprobs: Policy, min_ratio: float) -> Set[Action]:
"""Returns the set of actions in the logprobs whose probability is at least
min_ratio times the probability of the most likely action"""
assert all(
p <= 1e-8 for p in action_logprobs.values()
), f"action_logprobs should be negative; got {action_logprobs}"
assert 0 < min_ratio < 1, min_ratio
max_logprob = max(action_logprobs.values())
return {a for a, p in action_logprobs.items() if p - max_logprob >= math.log(min_ratio)}
class CFRResult(SearchResult):
def __init__(
self,
bp_policies: PowerPolicies,
avg_policies: PowerPolicies,
final_policies: PowerPolicies,
cfr_data: Optional["CFRData"],
use_final_iter: bool,
bilateral_stats: Optional[BilateralStats] = None,
):
self.bp_policies = bp_policies
self.avg_policies = avg_policies
self.final_policies = final_policies
self.cfr_data = cfr_data # type: ignore
self.use_final_iter = use_final_iter
self.bilateral_stats = bilateral_stats
def get_agent_policy(self) -> PowerPolicies:
return self.avg_policies
def get_population_policy(self) -> PowerPolicies:
return self.avg_policies
def get_bp_policy(self) -> PowerPolicies:
return self.bp_policies
def sample_action(self, power) -> Action:
policies = self.final_policies if self.use_final_iter else self.avg_policies
return sample_p_dict(policies[power])
def avg_utility(self, pwr: Power) -> float:
return self.cfr_data.avg_utility(pwr) if self.cfr_data is not None else 0
def avg_action_utility(self, pwr: Power, a: Action) -> float:
return self.cfr_data.avg_action_utility(pwr, a) if self.cfr_data is not None else 0
def get_bilateral_stats(self) -> BilateralStats:
assert self.bilateral_stats is not None
return self.bilateral_stats
def is_early_exit(self) -> bool:
return self.cfr_data is None
def _early_quit_cfr_result(power: Power, *, action: Action = tuple()) -> CFRResult:
policies = {power: {action: 1.0}}
return CFRResult(
bp_policies=policies,
avg_policies=policies,
final_policies=policies,
cfr_data=None,
use_final_iter=False,
)
def sorted_policy(plausible_orders: List[Action], probs: List[float]) -> Policy:
return dict(sorted(zip(plausible_orders, probs), key=lambda ac_p: -ac_p[1]))
class CFRData:
def __init__(
self,
bp_policy: PowerPolicies,
use_optimistic_cfr: bool,
qre: Optional[agents_cfgs.SearchBotAgent.QRE] = None,
agent_power=None,
scale_lambdas_by_power: Optional[Dict[Power, float]] = None,
):
# Make sure that all powers have some actions. This guarantees that
# we run utility computation for every power and so state values will
# be computed correctly. In theory, only alive powers should have
# non-zero utility, ano so we only need to augment alive powers without
# orders. But in practice as the state values are computed by a value
# network some dead power may have non-zero utilities.
# Note, that the plausible order sampler by default adds empty policies
# for all powers.
for power in bp_policy:
assert bp_policy[
power
], f"Power {power} doesn't have policy. Add an empty action policy."
self.use_optimistic_cfr = use_optimistic_cfr
use_linear_weighting = True
if qre:
use_qre = True
qre_target_blueprint = qre.target_pi == "BLUEPRINT"
qre_eta = qre.eta
assert qre.qre_lambda is not None, "qre_lambda must be set."
qre_lambda = qre.qre_lambda
power_qre_lambda = {p: qre_lambda for p in POWERS}
if qre.agent_qre_lambda is not None:
assert (
qre.agent_qre_lambda != -1
), "Use None for specifying unset agent_qre_lambda, rather than -1"
assert agent_power is not None, "agent_power must be set"
power_qre_lambda[agent_power] = qre.agent_qre_lambda
qre_entropy_factor = qre.qre_entropy_factor
power_qre_entropy_factor = {p: qre_entropy_factor for p in POWERS}
if qre.agent_qre_entropy_factor is not None:
assert (
qre.agent_qre_entropy_factor != -1
), "Use None for specifying unset agent_qre_entropy_factor, rather than -1"
assert agent_power is not None, "agent_power must be set"
power_qre_entropy_factor[agent_power] = qre.agent_qre_entropy_factor
else:
use_qre = False
qre_target_blueprint = False
qre_eta = 0.0
qre_lambda = 0.0
qre_entropy_factor = 1.0
power_qre_lambda = {p: qre_lambda for p in POWERS}
power_qre_entropy_factor = {p: qre_entropy_factor for p in POWERS}
if scale_lambdas_by_power is not None:
for power in scale_lambdas_by_power:
power_qre_lambda[power] *= scale_lambdas_by_power[power]
self.power_qre_lambda = power_qre_lambda
self.power_plausible_orders: PlausibleOrders = {p: sorted(v) for p, v in bp_policy.items()}
power_plausible_action_probs = {
p: [bp_policy[p][a] for a in self.power_plausible_orders[p]] for p in POWERS
}
self.stats = CFRStats(
use_linear_weighting,
use_optimistic_cfr,
use_qre,
qre_target_blueprint,
qre_eta,
power_qre_lambda,
power_qre_entropy_factor,
power_plausible_action_probs,
)
def cur_iter_strategy(self, pwr: Power) -> List[float]:
return self.stats.cur_iter_strategy(pwr)
def cur_iter_policy(self, pwr: Power) -> Policy:
return sorted_policy(self.power_plausible_orders[pwr], self.cur_iter_strategy(pwr))
def avg_strategy(self, pwr: Power) -> List[float]:
return self.stats.avg_strategy(pwr)
def avg_policy(self, pwr: Power) -> Policy:
return sorted_policy(self.power_plausible_orders[pwr], self.avg_strategy(pwr))
def avg_utility(self, pwr: Power) -> float:
return self.stats.avg_utility(pwr)
def avg_action_utilities(self, pwr: Power) -> List[float]:
return self.stats.avg_action_utilities(pwr)
def avg_action_utility(self, pwr: Power, a: Action) -> float:
return self.stats.avg_action_utility(pwr, self.power_plausible_orders[pwr].index(a))
def avg_action_regret(self, pwr: Power, a: Action) -> float:
return self.stats.avg_action_regret(pwr, self.power_plausible_orders[pwr].index(a))
def avg_action_prob(self, pwr: Power, a: Action) -> float:
return self.stats.avg_action_prob(pwr, self.power_plausible_orders[pwr].index(a))
def cur_iter_action_prob(self, pwr: Power, a: Action) -> float:
return self.stats.cur_iter_action_prob(pwr, self.power_plausible_orders[pwr].index(a))
def bp_strategy(self, pwr: Power, temperature=1.0) -> List[float]:
return self.stats.bp_strategy(pwr, temperature)
def bp_policy(self, pwr: Power, temperature=1.0) -> Policy:
return sorted_policy(self.power_plausible_orders[pwr], self.bp_strategy(pwr, temperature))
def update(
self,
pwr: Power,
actions: List[Action],
state_utility: float,
action_utilities: List[float],
which_strategy_to_accumulate: int,
cfr_iter: int,
) -> None:
self.stats.update(
pwr, state_utility, action_utilities, which_strategy_to_accumulate, cfr_iter
)
PhaseKey = Tuple[Phase, Phase] # (dialogue_phase, rollout_phase)
class SearchBotAgentState(AgentState):
"""Cached state for a particular agent power."""
def __init__(self, agent_power):
self.last_ts: Timestamp = Timestamp.from_seconds(-1)
self.agent_power = agent_power
# hide these because we have to check that we're on the same phase!
self._last_search_result: Dict[PhaseKey, Optional[SearchResult]] = {}
self._last_pseudo_orders: Dict[PhaseKey, Optional[JointAction]] = {}
self._value_table_cache: DefaultDict[
PhaseKey, DefaultDict[Power, BilateralConditionalValueTable]
] = defaultdict(functools.partial(defaultdict, dict))
self.pseudo_orders_cache = ParlaiMessagePseudoOrdersCache()
def _get_phase_key(self, game: Game) -> PhaseKey:
return (
game.get_metadata("last_dialogue_phase") or game.current_short_phase,
game.current_short_phase,
)
def update(
self,
game: Game,
agent_power: Power,
search_result: Optional[SearchResult],
pseudo_orders: Optional[JointAction],
) -> None:
assert self.agent_power == agent_power
self.last_ts = (
last_dict_key(game.messages) if game.messages else Timestamp.from_seconds(-1)
)
self.agent_power = agent_power
if search_result and search_result.is_early_exit():
# don't include early-exit search results, because they
# don't have the actual search policies for anyone
search_result = None
phase_key = self._get_phase_key(game)
self._last_search_result[phase_key] = search_result
self._last_pseudo_orders[phase_key] = pseudo_orders
def get_last_search_result(self, game: Game) -> Optional[SearchResult]:
phase_key = self._get_phase_key(game)
return self._last_search_result.get(phase_key, None)
def get_last_pseudo_orders(self, game: Game) -> Optional[JointAction]:
phase_key = self._get_phase_key(game)
return self._last_pseudo_orders.get(phase_key, None)
def get_new_messages(self, game: Game):
"""Return all new messages in the game since this state"""
return [m for m in game.messages.values() if m["time_sent"] > self.last_ts]
def get_sleepsix_cache(self) -> SleepSixTimesCache:
# backwards compatibility
if not hasattr(self, "sleepsix_cache"):
self.sleepsix_cache = SleepSixTimesCache()
return self.sleepsix_cache
def get_cached_value_tables(
self, game: Game
) -> DefaultDict[Power, BilateralConditionalValueTable]:
phase_key = self._get_phase_key(game)
return self._value_table_cache[phase_key]
class SearchBotAgent(BaseSearchAgent):
"""One-ply cfr with base_strategy_model-policy rollouts"""
def __init__(self, cfg: agents_cfgs.SearchBotAgent, *, skip_base_strategy_model_cache=False):
super().__init__(cfg)
base_strategy_model_wrapper_kwargs = dict(
device=device_id_to_str(cfg.device),
max_batch_size=cfg.max_batch_size,
half_precision=cfg.half_precision,
skip_base_strategy_model_cache=skip_base_strategy_model_cache,
)
self.base_strategy_model = BaseStrategyModelWrapper(
cfg.rollout_model_path or cfg.model_path,
value_model_path=cfg.value_model_path,
force_disable_all_power=True,
**base_strategy_model_wrapper_kwargs,
)
self.cfg = cfg
self.has_press = cfg.dialogue is not None
self.set_player_rating = cfg.set_player_rating
self.player_rating = cfg.player_rating
if self.set_player_rating:
if cfg.cache_rollout_results:
logging.warning("Undefined behaviour if searchbot.cache_rollout_results is set")
assert (
self.player_rating is not None and 0 <= self.player_rating <= 1.0
), "Player rating needs to be a float between 0 and 1.0"
logging.info(f"Setting player rating to {self.player_rating}")
else:
if self.player_rating is not None:
logging.warning(
"searchbot.player_rating is set but searchbot.set_player_rating is not set"
)
self.player_rating = None
self.base_strategy_model_rollouts = BaseStrategyModelRollouts(
self.base_strategy_model,
cfg=cfg.rollouts_cfg,
has_press=self.has_press,
set_player_ratings=self.set_player_rating,
)
self.bilateral_cfg = cfg.bilateral_dialogue
assert cfg.n_rollouts >= 0, "Set searchbot.n_rollouts"
self.qre = cfg.qre
if self.qre is not None:
logging.info(
f"Performing qre regret minimization with eta={self.qre.eta} "
f"and lambda={self.qre.qre_lambda} with target pi={self.qre.target_pi}"
)
if self.qre.qre_lambda == 0.0:
logging.info("Using lambda 0.0 simplifies qre to regular hedge")
self.n_rollouts = cfg.n_rollouts
self.cache_rollout_results = cfg.cache_rollout_results
self.precompute_cache = cfg.precompute_cache
self.enable_compute_nash_conv = cfg.enable_compute_nash_conv
self.n_plausible_orders = cfg.plausible_orders_cfg.n_plausible_orders
self.use_optimistic_cfr = cfg.use_optimistic_cfr
self.use_final_iter = cfg.use_final_iter
self.bp_iters = cfg.bp_iters
self.bp_prob = cfg.bp_prob
self.loser_bp_iter = cfg.loser_bp_iter
self.loser_bp_value = cfg.loser_bp_value
self.reset_seed_on_rollout = cfg.reset_seed_on_rollout
self.max_seconds = cfg.max_seconds
self.br_corr_bilateral_search_cfg = cfg.br_corr_bilateral_search
self.message_search_cfg = cfg.message_search
self.human_power_po = None
self.all_power_base_strategy_model_executor = None
if self.br_corr_bilateral_search_cfg is not None:
assert (
self.base_strategy_model.model.is_all_powers()
), "br_corr_bilateral_search requires an all-powers base_strategy_model model."
allpower_wrapper_kwargs = {
**base_strategy_model_wrapper_kwargs,
"model_path": self.base_strategy_model.model_path,
"value_model_path": cfg.value_model_path,
}
allpower_rollouts_kwargs = {
"cfg": cfg.rollouts_cfg,
"has_press": self.has_press,
"set_player_ratings": self.set_player_rating,
}
# if we allow multi gpu for plausible orders,
# then we also allow multi gpu for the base_strategy_model to avoid adding redundant flags
self.all_power_base_strategy_model_executor = MultiProcessBaseStrategyModelExecutor(
allow_multi_gpu=cfg.plausible_orders_cfg.allow_multi_gpu,
base_strategy_model_wrapper_kwargs=allpower_wrapper_kwargs,
base_strategy_model_rollouts_kwargs=allpower_rollouts_kwargs,
)
if cfg.parlai_model_orders.model_path:
if cfg.rescoring_blueprint_model_path is not None:
raise RuntimeError(
"You probably don't want to rescore parlai policy with a base_strategy_model BP"
)
logging.info("Setting up parlai orders model...")
self.parlai_model_orders = load_order_wrapper(cfg.parlai_model_orders)
else:
self.parlai_model_orders = None
self.cfr_messages = cfg.cfr_messages
if cfg.dialogue is not None:
self.message_handler = ParlaiMessageHandler(
cfg.dialogue,
model_orders=self.parlai_model_orders,
base_strategy_model=self.base_strategy_model,
)
else:
self.message_handler = None
assert not self.cfr_messages
if cfg.rollout_model_path and cfg.model_path != cfg.rollout_model_path:
self.proposal_base_strategy_model = BaseStrategyModelWrapper(
cfg.model_path, **base_strategy_model_wrapper_kwargs
)
else:
self.proposal_base_strategy_model = self.base_strategy_model
self.order_sampler = PlausibleOrderSampler(
cfg.plausible_orders_cfg,
base_strategy_model=self.proposal_base_strategy_model,
parlai_model_cfg=cfg.parlai_model_orders,
)
self.order_aug_cfg = cfg.order_aug
if cfg.rescoring_blueprint_model_path:
assert self.parlai_model_orders is None
assert (
cfg.order_aug.do is None
), "Cannot use DO with rescoring_blueprint_model_path. Use multibp rescoring instead"
self.rescoring_blueprint_model = BaseStrategyModelWrapper(
cfg.rescoring_blueprint_model_path, **base_strategy_model_wrapper_kwargs
)
else:
self.rescoring_blueprint_model = None
self.exploited_agent = None
self.exploited_agent_power = None
self.exploited_agent_num_samples = 1
if cfg.exploited_searchbot_cfg is not None and cfg.exploited_agent_power:
# When exploiting an agent, we run a one-sided regret minimization with full knowledge of the fixed exploited
# policy. So we need to make sure we have their actual policy.
exploited_searchbot_cfg = cfg.exploited_searchbot_cfg.to_editable()
logging.info(
f"Replacing exploited agent device {exploited_searchbot_cfg.device} -> {cfg.device}"
)
exploited_searchbot_cfg.device = cfg.device
exploited_searchbot_cfg = exploited_searchbot_cfg.to_frozen()
assert not exploited_searchbot_cfg.use_final_iter
assert cfg.exploited_agent_power in POWERS, cfg.exploited_agent_power
self.exploited_agent = SearchBotAgent(exploited_searchbot_cfg)
self.exploited_agent_power = cfg.exploited_agent_power
self.exploited_agent_num_samples = cfg.exploited_agent_num_samples
logging.info(
f"Exploited agent: {self.exploited_agent_power} {exploited_searchbot_cfg}"
)
self.log_intermediate_iterations = cfg.log_intermediate_iterations
self.log_bilateral_values = cfg.log_bilateral_values
self.do_incremental_search = cfg.do_incremental_search
logging.info(f"Initialized SearchBot Agent: {self.__dict__}")
def initialize_state(self, power: Power) -> AgentState:
return SearchBotAgentState(power)
def get_exploited_agent_power(self) -> Optional[Power]:
return self.exploited_agent_power
def override_has_press(self, has_press: bool):
self.has_press = has_press
self.base_strategy_model_rollouts.override_has_press(has_press)
# Overrides BaseAgent
def can_share_strategy(self) -> bool:
# It's only safe to share strategy if the strategy is not conditional on dialogue.
# If qre uses different params per power, then its not symmetric or safe
search_can_share_strategy = (self.qre is None) or (
self.qre is not None
and self.qre.agent_qre_lambda is None
and self.qre.agent_qre_entropy_factor is None
)
return self.parlai_model_orders is None and search_can_share_strategy
# Overrides BaseAgent
def get_orders(self, game: Game, power: Power, state: AgentState) -> Action:
assert isinstance(state, SearchBotAgentState)
cfr_result = self.try_get_cached_search_result(game, state)
if not cfr_result:
bp_policy = self.maybe_get_incremental_bp(game, agent_power=power, agent_state=state)
if self.use_br_correlated_search(game.phase, "final_order"):
cfr_result = self.run_best_response_against_correlated_bilateral_search(
game,
bp_policy=bp_policy,
agent_power=power,
early_exit_for_power=power,
agent_state=state,
)
else:
cfr_result = self.run_search(
game,
bp_policy=bp_policy,
agent_power=power,
early_exit_for_power=power,
agent_state=state,
)
state.update(game, power, cfr_result, None)
return cfr_result.sample_action(power)
# Overrides BaseAgent
def get_orders_many_powers(self, game: Game, powers: List[Power],) -> JointAction:
assert (
self.message_handler is None
), "This searchbot agent appears to be a full-press agent. Do not use get_orders_many_powers in full-press since not all agents see the same info."
assert not self.use_final_iter, "unsafe: use_final_iter"
cfr_result = self.run_search(game, agent_state=None,)
return {power: cfr_result.sample_action(power) for power in powers}
# Overrides BaseSearchAgent
def get_plausible_orders_policy(
self,
game: Game,
*,
agent_power: Optional[Power] = None,
agent_state: Optional[AgentState],
player_rating: Optional[PlayerRating] = None,
allow_augment: bool = True,
) -> PowerPolicies:
"""Compute blueprint policy for all agents.
If exploiting an agent, the blueprint will be the agent's computed average policy.
If allow_augment is false, will not attempt to apply augmentations like double oracle.
"""
# Determine the set of plausible actions to consider for each power
policy = self.order_sampler.sample_orders(
game, agent_power=agent_power, speaking_power=agent_power, player_rating=player_rating
)
if self.rescoring_blueprint_model is not None:
policy = self.order_sampler.rescore_actions_base_strategy_model(
game,
has_press=self.has_press,
agent_power=agent_power,
input_policy=policy,
model=self.rescoring_blueprint_model.model,
)
self.order_sampler.log_orders(game, policy, label="AFTER BP-rescoring")
# If we are exploiting an agent, compute their policy and replace the blueprint
# with their known average policy.
if self.exploited_agent_power is not None:
exploited_policy = collections.defaultdict(float)
per_sample_weight = 1.0 / self.exploited_agent_num_samples
for i in range(self.exploited_agent_num_samples):
# ahh this is terrible!
assert self.exploited_agent is not None
assert not self.exploited_agent.use_final_iter
sample_policy = self.exploited_agent.run_search(
game, agent_power=self.exploited_agent_power, agent_state=None
).avg_policies[self.exploited_agent_power]
for action in sample_policy:
exploited_policy[action] += per_sample_weight * sample_policy[action]
# Convert defaultdict -> ordinary dict
exploited_policy = dict(exploited_policy)
# Replace the blueprint for the power being exploited
policy[self.exploited_agent_power] = exploited_policy
# Inference time double oracle or other augmentation.
if allow_augment:
with temp_redefine(self.base_strategy_model_rollouts, "max_rollout_length", 0):
with temp_redefine(self, "cache_rollout_results", True):
original_policy, policy = (
policy,
augment_plausible_orders(
game,
policy,
self,
self.order_aug_cfg,
agent_power=agent_power,
limits=self.order_sampler.get_plausible_order_limits(game),
),
)
for power in sorted(policy):
new_actions = set(policy[power]).difference(original_policy[power])
for i, action in enumerate(sorted(new_actions)):
logging.info(
"Order augmentation. New order for %s (%d/%d): %s",
power,
i + 1,
len(new_actions),
action,
)
return policy
def use_br_correlated_search(self, phase: str, mode: str):
assert mode in ["final_order", "pseudo_order"], mode
if self.br_corr_bilateral_search_cfg is None:
return False
if "MOVEMENT" not in phase:
return False
if mode == "final_order" and self.br_corr_bilateral_search_cfg.enable_for_final_order:
return True
if mode == "pseudo_order" and self.br_corr_bilateral_search_cfg.enable_for_pseudo_order:
return True
return False
def run_search(
self,
game: Game,
*,
bp_policy: Optional[PowerPolicies] = None,
early_exit_for_power: Optional[Power] = None,
timings: Optional[TimingCtx] = None,
extra_plausible_orders: Optional[PlausibleOrders] = None,
agent_power: Optional[Power] = None,
agent_state: Optional[AgentState],
) -> CFRResult:
"""Computes an equilibrium policy for all powers.
Arguments:
- game: Game object encoding current game state.
- bp_policy: If set, overrides the plausible order set and blueprint policy for initialization.
Values should be probabilities, but can be set to -1 to simply specify plausible orders;
in that case, this function will raise an error if any feature uses the BP distribution (e.g. bp_iters > 0)
- early_exit_for_power: If set, then if this power has <= 1 plausible order, will exit early without computing a full equilibrium.
- timings: A TimingCtx object to measure timings
- extra_plausible_orders: Extra plausible orders to add to the base_strategy_model-computed set.
- agent_power: Optionally, specify which agent is computing the equilibrium.
Used by parlai plausible order generation, as well as advanced features like bilateral strategy.
Returns:
- CFRResult object:
- avg_policies: {pwr: avg_policy} for each power
- final_policies: {pwr: avg_policy} for each power
- cfr_data: detailed internal information from the CFR procedure
"""
if timings is None:
timings = TimingCtx()
timings.start("one-time")
deadline: Optional[float] = (
time.monotonic() + self.max_seconds if self.max_seconds > 0 else None
)
# If there are no locations to order, bail
if early_exit_for_power and len(game.get_orderable_locations()[early_exit_for_power]) == 0:
if agent_power is not None:
assert early_exit_for_power == agent_power
return _early_quit_cfr_result(early_exit_for_power)
logging.info(f"BEGINNING CFR run_search, agent_power={agent_power}")
maybe_rollout_results_cache = (
self.base_strategy_model_rollouts.build_cache() if self.cache_rollout_results else None
)
if bp_policy is None:
bp_policy = self.get_plausible_orders_policy(
game,
agent_power=agent_power,
agent_state=agent_state,
player_rating=self.player_rating if self.set_player_rating else None,
)
if extra_plausible_orders:
for p, orders in extra_plausible_orders.items():
for order in orders:
bp_policy[p].setdefault(order, 0.0)
logging.info(f"Adding extra plausible orders {p}: {orders}")
cfr_data = CFRData(
bp_policy,
use_optimistic_cfr=self.use_optimistic_cfr,
qre=self.qre,
agent_power=agent_power,
)
# If there a single plausible action, no need to search.
if (
early_exit_for_power
and len(cfr_data.power_plausible_orders[early_exit_for_power]) == 1
):
[the_action] = cfr_data.power_plausible_orders[early_exit_for_power]
return _early_quit_cfr_result(early_exit_for_power, action=the_action)
# run rollouts or get from cache
if self.cache_rollout_results and self.precompute_cache:
num_active_powers = sum(
len(actions) > 1 for actions in cfr_data.power_plausible_orders.values()
)
if num_active_powers > 2:
logging.warning(
"Disabling precomputation of the CFR cache as have %d > 2 active powers",
num_active_powers,
)
else:
joint_orders = sample_all_joint_orders(cfr_data.power_plausible_orders)
self.base_strategy_model_rollouts.do_rollouts_maybe_cached(
game,
agent_power=agent_power,
set_orders_dicts=joint_orders,
cache=maybe_rollout_results_cache,
timings=timings,
)
if agent_power is not None:
bilateral_stats = BilateralStats(game, agent_power, cfr_data.power_plausible_orders)
else:
bilateral_stats = None
logging.info("Starting CFR iters...")
last_search_iter = False
for cfr_iter in range(self.n_rollouts):
if last_search_iter:
logging.info(f"Early exit from CFR after {cfr_iter} iterations by timeout")
break
elif deadline is not None and time.monotonic() >= deadline:
last_search_iter = True
timings.start("start")
# do verbose logging on 2^x iters
verbose_log_iter = self.is_verbose_log_iter(cfr_iter) or last_search_iter
timings.start("query_policy")
# get policy probs for all powers
power_action_ps = self.get_cur_iter_strategies(cfr_data, cfr_iter)
timings.start("apply_orders")
# sample policy for all powers
_, power_sampled_orders = sample_orders_from_policy(
cfr_data.power_plausible_orders, power_action_ps
)
if bilateral_stats is not None:
bilateral_stats.accum_bilateral_probs(power_sampled_orders, weight=cfr_iter)
set_orders_dicts = make_set_orders_dicts(
cfr_data.power_plausible_orders, power_sampled_orders
)
timings.stop()
all_rollout_results = self.base_strategy_model_rollouts.do_rollouts_maybe_cached(
game,
agent_power=agent_power,
set_orders_dicts=set_orders_dicts,
cache=maybe_rollout_results_cache,
timings=timings,
player_rating=self.player_rating,
)
timings.start("cfr")
for pwr, actions in cfr_data.power_plausible_orders.items():
# pop this power's results
results, all_rollout_results = (
all_rollout_results[: len(actions)],
all_rollout_results[len(actions) :],
)
if bilateral_stats is not None:
bilateral_stats.accum_bilateral_values(pwr, cfr_iter, results)
# logging.info(f"Results {pwr} = {results}")
# calculate regrets
action_utilities: List[float] = [r[1][pwr] for r in results]
state_utility: float = np.dot(power_action_ps[pwr], action_utilities) # type: ignore
# log some action values
if verbose_log_iter:
self.log_cfr_iter_state(
game=game,
pwr=pwr,
actions=actions,
cfr_data=cfr_data,
cfr_iter=cfr_iter,
state_utility=state_utility,
action_utilities=action_utilities,
power_sampled_orders=power_sampled_orders,
)
# update cfr data structures
cfr_data.update(
pwr=pwr,
actions=actions,
state_utility=state_utility,
action_utilities=action_utilities,
which_strategy_to_accumulate=CFRStats.ACCUMULATE_PREV_ITER,
cfr_iter=cfr_iter,
)
if self.enable_compute_nash_conv and verbose_log_iter:
logging.info(f"Computing nash conv for iter {cfr_iter}")
self.compute_nash_conv(
cfr_data,
f"cfr iter {cfr_iter}",
game,
cfr_data.avg_strategy,
maybe_rollout_results_cache,
agent_power=agent_power,
)
if maybe_rollout_results_cache is not None and verbose_log_iter:
logging.info(f"{maybe_rollout_results_cache}")
timings.start("to_dict")
# return prob. distributions for each power
avg_ret, final_ret = {}, {}
power_is_loser = self.get_power_loser_dict(cfr_data, self.n_rollouts)
for p in POWERS:
if power_is_loser[p] or p == self.exploited_agent_power:
avg_ret[p] = final_ret[p] = cfr_data.bp_policy(p)
else:
avg_ret[p] = cfr_data.avg_policy(p)
final_ret[p] = cfr_data.cur_iter_policy(p)
if agent_power is not None:
logging.info(f"Final avg strategy: {avg_ret[agent_power]}")
logging.info(
"Raw Values: %s",
{
p: f"{x:.3f}"
for p, x in zip(
POWERS,
self.base_strategy_model.get_values(
game, has_press=self.has_press, agent_power=agent_power
),
)
},
)
logging.info("CFR Values: %s", {p: f"{cfr_data.avg_utility(p):.3f}" for p in POWERS})
timings.stop()
if bilateral_stats is not None and self.log_bilateral_values:
bilateral_stats.log(cfr_data, min_order_prob=self.bilateral_cfg.min_order_prob)
timings.pprint(logging.getLogger("timings").info)
return CFRResult(
bp_policies=bp_policy,
avg_policies=avg_ret,
final_policies=final_ret,
cfr_data=cfr_data,
use_final_iter=self.use_final_iter,
bilateral_stats=bilateral_stats,
)
def run_bilateral_search_with_conditional_evs(
self, game: Game, *args, **kwargs,
):
raise NotImplementedError
def run_best_response_against_correlated_bilateral_search(
self, game: Game, *args, **kwargs,
):
raise NotImplementedError
def _eval_action_under_bilateral_search(
self,
game: Game,
agent_power: Power,
agent_state: SearchBotAgentState,
agent_action: Action,
recipient_power: Power,
bp_policy: PowerPolicies,
pair_value_table: BilateralConditionalValueTable,
timings: Optional[TimingCtx] = None,
) -> float:
if timings is None:
timings = TimingCtx()
timings.start("run_search")
eq_policy = self.run_bilateral_search_with_conditional_evs(
game,
bp_policy=bp_policy,
agent_power=agent_power,
other_power=recipient_power,
agent_state=agent_state,
conditional_evs=pair_value_table,
).get_population_policy()
for policy_name, policy in [("bp_policy", bp_policy), ("eq_policy", eq_policy)]:
policy_str = "\n".join(
f"{power}\n{tabulate.tabulate(list(policy[power].items())[:6], tablefmt='plain')}"
for power in (agent_power, recipient_power)
)
logging.info(f"\n{policy_name}:\n{policy_str}")
payoffs = torch.zeros((len(POWERS), 1)) # type: ignore
for recipient_action, prob in eq_policy[recipient_power].items():
payoffs += prob * pair_value_table[(agent_action, recipient_action)]
agent_payoff = float(payoffs[POWER2IDX[agent_power]])
recipient_payoff = float(payoffs[POWER2IDX[recipient_power]])
logging.info(
f"_eval_action_under_bilateral_search payoffs:\n"
f"{agent_power}: {float(agent_payoff)}\n"
f"{recipient_power}: {float(recipient_payoff)}"
)