forked from facebookresearch/diplomacy_cicero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase_strategy_model.py
2053 lines (1802 loc) · 82.4 KB
/
base_strategy_model.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 enum import Enum
from typing import TYPE_CHECKING, Tuple, Optional, Union
import inspect
import logging
import math
import os
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torch.distributions.categorical import Categorical
import conf.conf_cfgs
from fairdiplomacy.models.consts import POWERS, LOCS, LOGIT_MASK_VAL, MAX_SEQ_LEN, N_SCS
from fairdiplomacy.utils.cat_pad_sequences import cat_pad_sequences
from fairdiplomacy.utils.padded_embedding import PaddedEmbedding
from fairdiplomacy.utils.timing_ctx import TimingCtx
from fairdiplomacy.utils.order_idxs import LOC_IDX_OF_ORDER_IDX, local_order_idxs_to_global
from fairdiplomacy.utils.thread_pool_encoding import get_board_state_size
from fairdiplomacy.models.state_space import (
get_order_vocabulary,
EOS_IDX,
)
from fairdiplomacy.models.base_strategy_model.decoders import TransfDecoder
from fairdiplomacy.models.base_strategy_model.util import he_init, top_p_filtering
from fairdiplomacy import pydipcc
EOS_TOKEN = get_order_vocabulary()[EOS_IDX]
# If teacher forcing orders have this id, then a sampled order will be used for
# this position.
NO_ORDER_ID = -2
# Indices for encoding scoring systems for x_scoring_system
class Scoring(Enum):
SOS = 0 # sum of squares
DSS = 1 # draw size scoring
class BaseStrategyModelV2(nn.Module):
def __init__(
self,
*,
inter_emb_size, # 120
board_map_size, # number of diplomacy map locations, i.e. 81
order_emb_size, # 80
prev_order_emb_size, # 20
orders_vocab_size, # 13k
lstm_size, # 200
lstm_dropout=0,
lstm_layers=1,
value_dropout,
value_decoder_init_scale=1.0,
value_decoder_activation="relu",
value_decoder_use_weighted_pool: bool,
value_decoder_extract_from_encoder: bool,
featurize_output=False,
relfeat_output=False,
featurize_prev_orders=False,
value_softmax=False,
encoder_cfg: conf.conf_cfgs.Encoder,
pad_spatial_size_to_multiple=1,
all_powers: bool,
has_single_chances: bool,
has_double_chances: bool,
has_policy=True,
has_value=True,
use_player_ratings=False,
use_year=False,
use_agent_power=False,
num_scoring_systems=1, # Uses the first N of the scoring systems
input_version=1,
training_permute_powers=False,
with_order_conditioning=False,
transformer_decoder=Optional[conf.conf_cfgs.TrainTask.TransformerDecoder],
):
super().__init__()
self.input_version = input_version
self.board_state_size = get_board_state_size(input_version)
self.orders_vocab_size = orders_vocab_size
# Make the type checker understand what self.order_feats is
if TYPE_CHECKING:
self.order_feats = torch.tensor([])
self.featurize_prev_orders = featurize_prev_orders
self.prev_order_enc_size = prev_order_emb_size
if featurize_prev_orders:
order_feats, _srcs, _dsts = compute_order_features()
self.register_buffer("order_feats", order_feats)
self.prev_order_enc_size += self.order_feats.shape[-1]
# Register a buffer that maps global order index to source location
# of that order. We register this as a buffer to make sure it's always
# on the same device as the base_strategy_model itself.
srcloc_idx_of_global_order_idx_plus_one = compute_srcloc_idx_of_global_order_idx_plus_one()
self.register_buffer(
"srcloc_idx_of_global_order_idx_plus_one",
srcloc_idx_of_global_order_idx_plus_one,
persistent=False,
)
# Make the type checker understand what self.srcloc_idx_of_global_order_idx is
if TYPE_CHECKING:
self.srcloc_idx_of_global_order_idx_plus_one = torch.tensor([])
self.has_policy = has_policy
self.has_value = has_value
self.num_scoring_systems = num_scoring_systems
# Use os.urandom so as to explicitly be different on different distributed data
# parallel processes and not share seeds.
self.training_permute_powers = training_permute_powers
self.permute_powers_rand = np.random.default_rng(seed=list(os.urandom(16))) # type:ignore
self.board_map_size = board_map_size
self.transformer_sequence_len = board_map_size + len(POWERS) + 1
encoder_kind = encoder_cfg.WhichOneof("encoder")
assert encoder_kind == "transformer"
# Note:Due to historical accident the actual size we use everywhere is inter_emb_size*2
self.inter_emb_size = inter_emb_size
# These are linear maps we use to embed every input into the tensor we feed to the transformer.
# Location-keyed inputs
self.board_emb_linear = nn.Linear(self.board_state_size, inter_emb_size * 2)
self.prev_board_emb_linear = nn.Linear(self.board_state_size, inter_emb_size * 2)
self.prev_order_emb_linear = nn.Linear(self.prev_order_enc_size, inter_emb_size * 2)
if with_order_conditioning:
self.this_order_emb_linear = nn.Linear(self.prev_order_enc_size, inter_emb_size * 2)
else:
self.this_order_emb_linear = None
# Power-keyed inputs
self.build_numbers_emb_linear = nn.Linear(1, inter_emb_size * 2)
self.player_ratings_emb_linear = None
if use_player_ratings:
self.player_ratings_emb_linear = nn.Linear(1, inter_emb_size * 2)
self.agent_power_emb_linear = None
if use_agent_power:
self.agent_power_emb_linear = nn.Linear(1, inter_emb_size * 2)
# Global inputs
self.season_emb_linear = nn.Linear(3, inter_emb_size * 2)
self.in_adj_phase_emb_linear = nn.Linear(1, inter_emb_size * 2)
self.has_press_emb_linear = nn.Linear(1, inter_emb_size * 2)
self.scoring_system_emb_linear = None
if self.num_scoring_systems > 1:
self.scoring_system_emb_linear = nn.Linear(num_scoring_systems, inter_emb_size * 2)
self.year_emb_linear = None
if use_year:
self.year_emb_linear = nn.Linear(1, inter_emb_size * 2)
if pad_spatial_size_to_multiple > 1:
self.transformer_sequence_len = (
(self.transformer_sequence_len + pad_spatial_size_to_multiple - 1)
// pad_spatial_size_to_multiple
* pad_spatial_size_to_multiple
)
trans_encoder_cfg = getattr(encoder_cfg, encoder_kind)
assert isinstance(trans_encoder_cfg, conf.conf_cfgs.Encoder.Transformer)
self.encoder = TransformerEncoder(
total_input_size=inter_emb_size * 2,
spatial_size=self.transformer_sequence_len,
inter_emb_size=inter_emb_size,
encoder_cfg=trans_encoder_cfg,
)
if has_policy:
if transformer_decoder is not None:
self.policy_decoder = TransfDecoder(
inter_emb_size=inter_emb_size, cfg=transformer_decoder,
)
else:
self.policy_decoder = LSTMBaseStrategyModelDecoder(
inter_emb_size=inter_emb_size,
spatial_size=self.transformer_sequence_len,
orders_vocab_size=orders_vocab_size,
lstm_size=lstm_size,
order_emb_size=order_emb_size,
lstm_dropout=lstm_dropout,
lstm_layers=lstm_layers,
master_alignments=None,
use_simple_alignments=True,
power_emb_size=0,
featurize_output=featurize_output,
relfeat_output=relfeat_output,
)
if has_value:
self.value_decoder = ValueDecoder(
inter_emb_size=inter_emb_size,
spatial_size=self.transformer_sequence_len,
init_scale=value_decoder_init_scale,
dropout=value_dropout,
softmax=value_softmax,
activation=value_decoder_activation,
use_weighted_pool=value_decoder_use_weighted_pool,
extract_from_encoder=value_decoder_extract_from_encoder,
)
self.prev_order_embedding = nn.Embedding(
orders_vocab_size, prev_order_emb_size, padding_idx=0
)
self.all_powers = all_powers
self.has_single_chances = has_single_chances
self.has_double_chances = has_double_chances
def get_input_version(self) -> int:
return self.input_version
def get_training_permute_powers(self) -> bool:
return self.training_permute_powers
def set_training_permute_powers(self, b: bool):
self.training_permute_powers = b
def is_all_powers(self) -> bool:
return self.all_powers
def supports_single_power_decoding(self) -> bool:
return not self.all_powers or self.has_single_chances
def supports_double_power_decoding(self) -> bool:
return self.all_powers and self.has_double_chances
def get_srcloc_idx_of_global_order_idx_plus_one(self) -> torch.Tensor:
"""Return a tensor mapping (global order idx+1) -> location idx of src of order.
EOS_IDX+1 is mapped to a value larger than any location idx.
"""
return self.srcloc_idx_of_global_order_idx_plus_one
def _embed_orders(self, orders: torch.Tensor, x_board_state: torch.Tensor):
B, NUM_LOCS, _ = x_board_state.shape
order_emb = self.prev_order_embedding(orders[:, 0])
if self.featurize_prev_orders:
order_emb = torch.cat((order_emb, self.order_feats[orders[:, 0]]), dim=-1)
# insert the prev orders into the correct board location
order_exp = x_board_state.new_zeros(B, NUM_LOCS, self.prev_order_enc_size)
prev_order_loc_idxs = torch.arange(B, device=x_board_state.device).repeat_interleave(
orders.shape[-1]
) * NUM_LOCS + orders[:, 1].reshape(-1)
order_exp.view(-1, self.prev_order_enc_size).index_add_(
0, prev_order_loc_idxs, order_emb.view(-1, self.prev_order_enc_size)
)
return order_exp
def encode_state(
self,
*,
x_board_state,
x_prev_state,
x_prev_orders,
x_season,
x_year_encoded,
x_in_adj_phase,
x_build_numbers,
x_has_press=None,
x_player_ratings=None,
x_scoring_system=None,
x_agent_power=None,
x_current_orders: Optional[torch.Tensor] = None,
) -> torch.Tensor:
"""Runs encoder."""
# following https://arxiv.org/pdf/2006.04635.pdf , Appendix C
B, NUM_LOCS, _ = x_board_state.shape
assert NUM_LOCS == self.board_map_size
# Preemptively make sure that dtypes of things match, to try to limit the chance of bugs
# if the inputs were built in an ad-hoc way when are trying to run in fp16.
assert x_board_state.dtype == x_prev_state.dtype
assert x_board_state.dtype == x_build_numbers.dtype
assert x_board_state.dtype == x_season.dtype
if x_has_press is not None:
assert x_board_state.dtype == x_has_press.dtype
# B. insert the prev orders into the correct board location (which is in the second column of x_po)
x_prev_order_exp = self._embed_orders(x_prev_orders, x_board_state)
# The final tensor we feed to the encoder for all board-location-keyed data.
# [B, 81, inter_emb_size*2]
assert len(x_board_state.shape) == 3
encoder_input_by_location = self.board_emb_linear(x_board_state)
assert len(x_prev_state.shape) == 3
encoder_input_by_location += self.prev_board_emb_linear(x_prev_state)
assert len(x_prev_order_exp.shape) == 3
encoder_input_by_location += self.prev_order_emb_linear(x_prev_order_exp)
if self.this_order_emb_linear is not None:
if x_current_orders is None:
# Feed zeroes. This is how we encode conditioning on empty order in
# FeatureEncoder.encode_orders_single.
x_current_orders = x_prev_orders.new_zeros(x_prev_orders.shape)
assert x_current_orders is not None
this_order_exp = self._embed_orders(x_current_orders, x_board_state)
encoder_input_by_location += self.this_order_emb_linear(this_order_exp)
else:
assert (
x_current_orders is None
), "Got x_current_orders parameter for a model that does not support conditional sampling"
# The final tensor we feed to the encoder for all power-keyed data.
# [B, 7, inter_emb_size*2]
assert x_build_numbers is not None and len(x_build_numbers.shape) == 2
encoder_input_by_power = self.build_numbers_emb_linear(x_build_numbers.unsqueeze(-1))
if self.player_ratings_emb_linear:
if x_player_ratings is not None:
assert len(x_player_ratings.shape) == 2
encoder_input_by_power += self.player_ratings_emb_linear(
x_player_ratings.unsqueeze(-1)
)
else:
encoder_input_by_power += self.player_ratings_emb_linear(
x_board_state.new_ones(B, len(POWERS), 1)
)
if self.agent_power_emb_linear:
if x_agent_power is not None:
assert len(x_agent_power.shape) == 2
encoder_input_by_power += self.agent_power_emb_linear(x_agent_power.unsqueeze(-1))
else:
encoder_input_by_power += self.agent_power_emb_linear(
x_board_state.new_zeros(B, len(POWERS), 1)
)
# The final tensor we feed to the encoder for all global singleton data.
# [B, 1, inter_emb_size*2]
assert len(x_season.shape) == 2
encoder_input_global = self.season_emb_linear(x_season.unsqueeze(1))
assert len(x_in_adj_phase.shape) == 1
encoder_input_global += self.in_adj_phase_emb_linear(
x_in_adj_phase.unsqueeze(-1).unsqueeze(-1)
)
if x_has_press is not None:
assert len(x_has_press.shape) == 2
encoder_input_global += self.has_press_emb_linear(x_has_press.unsqueeze(1))
else:
# If not provided, default to treating it as no press
encoder_input_global += self.has_press_emb_linear(x_board_state.new_zeros(B, 1, 1))
if self.scoring_system_emb_linear is not None:
if x_scoring_system is not None:
assert len(x_scoring_system.shape) == 2
encoder_input_global += self.scoring_system_emb_linear(
x_scoring_system.unsqueeze(1)
)
else:
# If we're training a model that supports scoring systems but is not provided
# at inference time, then assume it's sos, at training fail
assert (
not self.training
), "Training a model with scoring systems but not providing it as input"
encoder_input_global += self.scoring_system_emb_linear(
F.one_hot(
x_board_state.new_full(
(B, 1), fill_value=Scoring.SOS.value, dtype=torch.long
),
num_classes=self.num_scoring_systems,
).to(x_board_state.dtype)
)
if self.year_emb_linear is not None:
encoder_input_global += self.year_emb_linear(x_year_encoded.unsqueeze(1))
# Concat everything.
# [B, 81+7+1, inter_emb_size*2]
encoder_input = torch.cat(
[encoder_input_by_location, encoder_input_by_power, encoder_input_global], dim=1
)
if self.transformer_sequence_len != encoder_input.shape[1]:
# pad -> (batch, transformer_sequence_len, channels)
assert self.transformer_sequence_len > encoder_input.shape[1]
assert len(encoder_input.shape) == 3
encoder_input = F.pad(
encoder_input, (0, 0, 0, self.transformer_sequence_len - encoder_input.shape[1])
)
encoded = self.encoder(encoder_input)
return encoded
def forward(
self,
*,
x_board_state,
x_prev_state,
x_prev_orders,
x_season,
x_year_encoded,
x_in_adj_phase,
x_build_numbers,
x_loc_idxs,
x_possible_actions,
temperature,
top_p=1.0,
batch_repeat_interleave=None,
teacher_force_orders=None,
x_power=None,
x_has_press=None,
x_player_ratings=None,
x_scoring_system=None,
x_agent_power=None,
need_policy=True,
need_value=True,
pad_to_max=False,
x_current_orders: Optional[torch.Tensor] = None,
encoded: Optional[torch.Tensor] = None,
) -> Tuple[
Optional[torch.Tensor],
Optional[torch.Tensor],
Optional[torch.Tensor],
Optional[torch.Tensor],
]:
"""
B indexes independent elements of a batch.
S indexes orderable locations.
Arguments:
- x_board_state: [B, 81, board_state_size]
- x_prev_state: [B, 2, 100], long
- x_prev_orders: [B, 81, 40]
- x_season: [B, 3]
- x_year_encoded: [B, 1]
- x_in_adj_phase: [B], bool
- x_build_numbers: [B, 7]
- x_loc_idxs: int8, [B, 81] or [B, 7, 81]
The sequence of location idxs to decode, or the sequence of location idxs to decode
for each of the 7 powers, by numbering the locations in order by 0, 1, 2, ...
and marking locations that don't have a unit to be ordered with EOS_IDX.
On builds and disbands and retreats, the build and disband and retreat locations must be marked with "-2".
Models are generally only trained on location idxs decoding in sorted order.
- x_possible_actions: long, [B, S, 469] or [B, 7, S, 469]
For each sequence idx (or for each power for each seq idx), the list of (up to 469)
possible global_order_idxs that can be legally issued for that unit,
On builds, the 0th sequence idx just lists the possible combined builds.
On adjustment-disbands, the successive sequence idxs are each one disband, and we have a hack
to resample duplicate disbands.
On retreats, the successive sequence idxs are the location-sorted places needing to retreat.
The position at which an order is in this list oof 469 is known as "local" order idx.
- temperature: softmax temp, lower = more deterministic; must be either
a float or a tensor of [B, 1]
- top_p: probability mass to samples from, lower = more spiky; must
be either a float or a tensor of [B, 1]
- batch_repeat_interleave: if set to a value k, will behave as if [B] dimension was
was actually [B*k] in size, with each element repeated k times
(e.g. [1,2,3] k=2 -> [1,1,2,2,3,3]), on all tensors EXCEPT teacher_force_orders
- teacher_force_orders: [B, S] or [B, 7, S] long or None,
global ORDER idxs, NOT local idxs. This is 0-padded.
If batch_repeat_interleave is provided, then the shape must be
[B*batch_repeat_interleave, S] or [B*batch_repeat_interleave, 7, S].
- x_power: [B, S] long, [B, 7, S] long, or None.
Labels which power idx is being decoded for each item in the sequence, or for each item
in the sequence for each of the 7 sequences for the different powers.
On movement phases, generally this tensor will just be constant, or constant per
each power.
On all powers, the [B,7,S] form or None must be used, S is expected to be equal to 34.
Only [:,0,:] is used on movement phases and retreat phases, and the sequence simply
walks through all the orderable locations in order, labeling which power.
Build and adjustment-disband are still encoded non-jointly and use all 7 sequences separately
per power.
- x_has_press: [B, 1] or None
- x_player_ratings: [B, 7] player rating percentile (0 - 1) for each player, or None
- x_agent_power: [B, 7] one-hot indicator of agent power or None
- x_scoring_system: [B, num_scoring_systems] or None - for each scoring system, the weight
on that scoring system, weights should add up to 1 for each batch element.
- need_policy: if not set, global_order_idxs, local_order_idxs, and logits will be None.
- need_value: if not set, final_sos in Result will be None
- pad_to_max, if set, will pad all output tensors to [..., MAX_SEQ_LEN, 469]. Use that
to make torch.nn.DataPatallel to work.
- x_current_orders: [B, 81, 40]: orders for this phase to condition on. Only
possible if with_order_conditioning is True
if x_power is None or [B, 7, 34] Long, the model will decode for all 7 powers.
- loc_idxs, all_cand_idxs (i.e. x_possible_actions), and teacher_force_orders must have an
extra axis at dim=1 with size 7
- global_order_idxs and order_scores will be returned with an extra axis
at dim=1 with size 7
- if x_power is [B, 7, 34] Long, non-A phases are expected to be encoded in [:,0,:]
else x_power must be [B, S] Long and only one power's sequence will be decoded
Returns:
- global_order_idxs [B, S] or [B, 7, S]: idx in ORDER_VOCABULARY of sampled
orders for each power
- local_order_idxs [B, S] or [B, 7, S]: idx in all_cand_idxs of sampled
orders for each power
- logits [B, S, C] or [B, 7, S, C]: masked pre-softmax logits of each
candidate order, 0 < S <= 17, 0 < C <= 469
- final_sos [B, 7]: estimated sum of squares share for each power
"""
assert not (need_policy and not self.has_policy)
assert not (need_value and not self.has_value)
assert need_policy or need_value
power_permutation_matrix = None
if self.training and self.training_permute_powers:
(
x_board_state,
x_prev_state,
(x_build_numbers, x_player_ratings, x_agent_power),
power_permutation_matrix,
) = _apply_permute_powers(
input_version=self.input_version,
permute_powers_rand=self.permute_powers_rand,
x_board_state=x_board_state,
x_prev_state=x_prev_state,
per_power_tensors=(x_build_numbers, x_player_ratings, x_agent_power),
)
if encoded is None:
encoded = self.encode_state(
x_board_state=x_board_state,
x_prev_state=x_prev_state,
x_prev_orders=x_prev_orders,
x_season=x_season,
x_year_encoded=x_year_encoded,
x_in_adj_phase=x_in_adj_phase,
x_build_numbers=x_build_numbers,
x_has_press=x_has_press,
x_player_ratings=x_player_ratings,
x_scoring_system=x_scoring_system,
x_agent_power=x_agent_power,
x_current_orders=x_current_orders,
)
if not need_value:
final_sos = None
else:
final_sos = self.value_decoder(encoded)
if batch_repeat_interleave is not None:
final_sos = torch.repeat_interleave(final_sos, batch_repeat_interleave, dim=0)
if power_permutation_matrix is not None and final_sos is not None:
final_sos = torch.matmul(
power_permutation_matrix.to(final_sos.device), final_sos.unsqueeze(2),
).squeeze(2)
if not need_policy:
global_order_idxs = local_order_idxs = logits = None
else:
# NOTE - "all_powers" here indicates whether we are decoding as an
# model trained to predict the joint action distribution instead of
# decoding powers only individually.
# This is NOT the same thing as _forward_all_powers, because
# _forward_all_powers simply means whether we are decoding all 7
# powers (whether jointly or individually).
# So, for example, it is not a bug that we may call
# _forward_all_powers even when all_powers is False.
all_powers = x_power is not None and len(x_power.shape) == 3
if all_powers:
assert (
self.all_powers
), "BaseStrategyModel got all_powers query but model is not all_powers"
if x_power is None or all_powers:
global_order_idxs, local_order_idxs, logits = _forward_all_powers(
policy_decoder=self.policy_decoder,
enc=encoded,
loc_idxs=x_loc_idxs,
cand_idxs=x_possible_actions,
temperature=temperature,
top_p=top_p,
batch_repeat_interleave=batch_repeat_interleave,
teacher_force_orders=teacher_force_orders,
power=x_power,
)
else:
global_order_idxs, local_order_idxs, logits = _forward_one_power(
policy_decoder=self.policy_decoder,
enc=encoded,
loc_idxs=x_loc_idxs,
cand_idxs=x_possible_actions,
temperature=temperature,
top_p=top_p,
batch_repeat_interleave=batch_repeat_interleave,
teacher_force_orders=teacher_force_orders,
power=x_power,
)
if pad_to_max:
global_order_idxs, local_order_idxs, logits = _pad_to_max(
global_order_idxs, local_order_idxs, logits, all_powers
)
return global_order_idxs, local_order_idxs, logits, final_sos
class BaseStrategyModel(nn.Module):
def __init__(
self,
*,
board_state_size, # fairdiplomacy.utils.thread_pool_encoding.get_board_state_size
# prev_orders_size, # 40
inter_emb_size, # 120
power_emb_size, # 60
season_emb_size, # 20,
num_blocks, # 16
A, # 81x81
master_alignments,
orders_vocab_size, # 13k
lstm_size, # 200
order_emb_size, # 80
prev_order_emb_size, # 20
lstm_dropout=0,
lstm_layers=1,
encoder_dropout=0,
value_dropout,
use_simple_alignments=False,
value_decoder_init_scale=1.0,
featurize_output=False,
relfeat_output=False,
featurize_prev_orders=False,
residual_linear=False,
merged_gnn=False,
encoder_layerdrop=0,
value_softmax=False,
encoder_cfg=None,
pad_spatial_size_to_multiple=1,
all_powers,
has_policy=True,
has_value=True,
use_player_ratings=False,
input_version=1,
training_permute_powers=False,
):
super().__init__()
assert board_state_size == get_board_state_size(
input_version
), f"Board state size {board_state_size} does not match expected for version {input_version}"
self.input_version = input_version
self.board_state_size = board_state_size
self.orders_vocab_size = orders_vocab_size
# Make the type checker understand what self.order_feats is
if TYPE_CHECKING:
self.order_feats = torch.tensor([])
self.featurize_prev_orders = featurize_prev_orders
self.prev_order_enc_size = prev_order_emb_size
if has_policy and featurize_prev_orders:
order_feats, _srcs, _dsts = compute_order_features()
self.register_buffer("order_feats", order_feats)
self.prev_order_enc_size += self.order_feats.shape[-1]
# Register a buffer that maps global order index to source location
# of that order
srcloc_idx_of_global_order_idx_plus_one = compute_srcloc_idx_of_global_order_idx_plus_one()
self.register_buffer(
"srcloc_idx_of_global_order_idx_plus_one",
srcloc_idx_of_global_order_idx_plus_one,
persistent=False,
)
# Make the type checker understand what self.srcloc_idx_of_global_order_idx_plus_one is
if TYPE_CHECKING:
self.srcloc_idx_of_global_order_idx_plus_one = torch.tensor([])
self.has_policy = has_policy
self.has_value = has_value
self.use_player_ratings = use_player_ratings
self.use_agent_power = False
# Use os.urandom so as to explicitly be different on different distributed data
# parallel processes and not share seeds.
self.training_permute_powers = training_permute_powers
self.permute_powers_rand = np.random.default_rng(seed=list(os.urandom(16))) # type:ignore
self.spatial_size = A.size()[0]
encoder_kind = encoder_cfg.WhichOneof("encoder")
extra_input_size = len(POWERS) + season_emb_size + 1
if self.use_player_ratings:
extra_input_size += len(POWERS) + 1
board_state_input_dim = board_state_size + extra_input_size
prev_orders_input_dim = board_state_size + self.prev_order_enc_size + extra_input_size
if encoder_kind == "transformer":
if pad_spatial_size_to_multiple > 1:
self.spatial_size = (
(self.spatial_size + pad_spatial_size_to_multiple - 1)
// pad_spatial_size_to_multiple
* pad_spatial_size_to_multiple
)
encoder_cfg = getattr(encoder_cfg, encoder_kind)
self.encoder = TransformerEncoder(
total_input_size=board_state_input_dim + prev_orders_input_dim,
spatial_size=self.spatial_size,
inter_emb_size=inter_emb_size,
encoder_cfg=encoder_cfg,
)
elif encoder_kind is None: # None == graph encoder
if pad_spatial_size_to_multiple > 1:
raise ValueError(
"pad_spatial_size_to_multiple > 1 not supported for graph conv encoder"
)
self.encoder = BaseStrategyModelEncoder(
board_state_size=board_state_input_dim,
prev_orders_size=prev_orders_input_dim,
inter_emb_size=inter_emb_size,
num_blocks=num_blocks,
A=A,
dropout=encoder_dropout,
residual_linear=residual_linear,
merged_gnn=merged_gnn,
layerdrop=encoder_layerdrop,
)
else:
assert False
if has_policy:
self.policy_decoder = LSTMBaseStrategyModelDecoder(
inter_emb_size=inter_emb_size,
spatial_size=self.spatial_size,
orders_vocab_size=orders_vocab_size,
lstm_size=lstm_size,
order_emb_size=order_emb_size,
lstm_dropout=lstm_dropout,
lstm_layers=lstm_layers,
master_alignments=master_alignments,
use_simple_alignments=use_simple_alignments,
power_emb_size=power_emb_size,
featurize_output=featurize_output,
relfeat_output=relfeat_output,
)
if has_value:
self.value_decoder = ValueDecoder(
inter_emb_size=inter_emb_size,
spatial_size=self.spatial_size,
init_scale=value_decoder_init_scale,
dropout=value_dropout,
softmax=value_softmax,
use_weighted_pool=False,
extract_from_encoder=False,
)
self.season_lin = nn.Linear(3, season_emb_size)
self.prev_order_embedding = nn.Embedding(
orders_vocab_size, prev_order_emb_size, padding_idx=0
)
self.all_powers = all_powers
def get_input_version(self) -> int:
return self.input_version
def get_training_permute_powers(self) -> bool:
return self.training_permute_powers
def set_training_permute_powers(self, b: bool):
self.training_permute_powers = b
def is_all_powers(self) -> bool:
return self.all_powers
def supports_single_power_decoding(self) -> bool:
return not self.all_powers
def supports_double_power_decoding(self) -> bool:
return False
def get_srcloc_idx_of_global_order_idx_plus_one(self) -> torch.Tensor:
"""Return a tensor mapping (global order idx+1) -> location idx of src of order.
EOS_IDX+1 is mapped to a value larger than any location idx.
"""
return self.srcloc_idx_of_global_order_idx_plus_one
def forward(
self,
*,
x_board_state,
x_prev_state,
x_prev_orders,
x_season,
x_year_encoded,
x_in_adj_phase, # Unused
x_build_numbers,
x_loc_idxs,
x_possible_actions,
temperature,
top_p=1.0,
batch_repeat_interleave=None,
teacher_force_orders=None,
x_power=None,
x_has_press=None,
x_player_ratings=None,
x_scoring_system=None,
x_agent_power=None,
need_policy=True,
need_value=True,
pad_to_max=False,
x_current_orders=None,
encoded=None,
) -> Tuple[
Optional[torch.Tensor],
Optional[torch.Tensor],
Optional[torch.Tensor],
Optional[torch.Tensor],
]:
"""
See docs for base_strategy_modelv2
"""
del encoded # Not supported.
# following https://arxiv.org/pdf/2006.04635.pdf , Appendix C
B, NUM_LOCS, _ = x_board_state.shape
# Preemptively make sure that dtypes of things match, to try to limit the chance of bugs
# if the inputs were built in an ad-hoc way when are trying to run in fp16.
assert x_board_state.dtype == x_prev_state.dtype
assert x_board_state.dtype == x_build_numbers.dtype
assert x_board_state.dtype == x_season.dtype
if x_has_press is not None:
assert x_board_state.dtype == x_has_press.dtype
assert not (need_policy and not self.has_policy)
assert not (need_value and not self.has_value)
assert need_policy or need_value
assert (
x_current_orders is None
), "Old base_strategy_model does not support x_current_orders"
power_permutation_matrix = None
if self.training and self.training_permute_powers:
(
x_board_state,
x_prev_state,
(x_build_numbers, x_player_ratings, x_agent_power),
power_permutation_matrix,
) = _apply_permute_powers(
input_version=self.input_version,
permute_powers_rand=self.permute_powers_rand,
x_board_state=x_board_state,
x_prev_state=x_prev_state,
per_power_tensors=(x_build_numbers, x_player_ratings, x_agent_power),
)
assert x_build_numbers is not None
# A. get season and prev order embs
x_season_emb = self.season_lin(x_season)
x_prev_order_emb = self.prev_order_embedding(x_prev_orders[:, 0])
if self.featurize_prev_orders:
x_prev_order_emb = torch.cat(
(x_prev_order_emb, self.order_feats[x_prev_orders[:, 0]]), dim=-1
)
# B. insert the prev orders into the correct board location (which is in the second column of x_po)
x_prev_order_exp = x_board_state.new_zeros(B, NUM_LOCS, self.prev_order_enc_size)
prev_order_loc_idxs = torch.arange(B, device=x_board_state.device).repeat_interleave(
x_prev_orders.shape[-1]
) * NUM_LOCS + x_prev_orders[:, 1].reshape(-1)
x_prev_order_exp.view(-1, self.prev_order_enc_size).index_add_(
0, prev_order_loc_idxs, x_prev_order_emb.view(-1, self.prev_order_enc_size)
)
# concatenate the subcomponents into board state and prev state, following the paper
x_build_numbers_exp = x_build_numbers[:, None].expand(-1, NUM_LOCS, -1)
x_season_emb_exp = x_season_emb[:, None].expand(-1, NUM_LOCS, -1)
if x_has_press is not None:
x_has_press_exp = x_has_press[:, None].expand(-1, NUM_LOCS, 1)
else:
x_has_press_exp = x_board_state.new_zeros(B, NUM_LOCS, 1)
if self.use_player_ratings:
if x_player_ratings is not None:
x_player_ratings_exp = x_player_ratings[:, None].expand(-1, NUM_LOCS, len(POWERS))
else:
# assume player have top rating if not supplied
x_player_ratings_exp = x_board_state.new_ones((B, NUM_LOCS, len(POWERS)))
# assert that the encoding of the ownership of units of powers is contiguous
encoding_unit_ownership_idxs = pydipcc.encoding_unit_ownership_idxs(self.input_version)
assert tuple(
x - encoding_unit_ownership_idxs[0] for x in encoding_unit_ownership_idxs
) == tuple(range(len(POWERS)))
# add in the rating for the controlling power at each loc
loc_power_idx = encoding_unit_ownership_idxs[0]
loc_power = x_board_state[:, :, loc_power_idx : loc_power_idx + len(POWERS)]
# assert each location controlled by at most one power
# assert loc_power.sum(-1).max() <= 1 # this assert is too slow
unit_player_ratings = (x_player_ratings_exp * loc_power).sum(-1, keepdim=True)
x_player_ratings_exp = torch.cat((x_player_ratings_exp, unit_player_ratings), dim=-1)
else:
# append an empty tensor for ratings (noop)
x_player_ratings_exp = x_board_state.new_zeros((B, NUM_LOCS, 0))
assert x_player_ratings_exp.dtype == x_board_state.dtype
x_bo_hat = torch.cat(
(
x_board_state,
x_build_numbers_exp,
x_season_emb_exp,
x_has_press_exp,
x_player_ratings_exp,
),
dim=-1,
)
x_po_hat = torch.cat(
(
x_prev_state,
x_prev_order_exp,
x_build_numbers_exp,
x_season_emb_exp,
x_has_press_exp,
x_player_ratings_exp,
),
dim=-1,
)
assert x_bo_hat.size()[1] == x_po_hat.size()[1]
if self.spatial_size != x_bo_hat.size()[1]:
# pad (batch, 81, channels) -> (batch, spatial_size, channels)
assert self.spatial_size > x_bo_hat.size()[1]
assert len(x_bo_hat.size()) == 3
x_bo_hat = F.pad(x_bo_hat, (0, 0, 0, self.spatial_size - x_bo_hat.size()[1]))
if self.spatial_size != x_po_hat.size()[1]:
# pad (batch, 81, channels) -> (batch, spatial_size, channels)
assert self.spatial_size > x_po_hat.size()[1]
assert len(x_po_hat.size()) == 3
x_po_hat = F.pad(x_po_hat, (0, 0, 0, self.spatial_size - x_po_hat.size()[1]))
if isinstance(self.encoder, TransformerEncoder):
encoded = self.encoder(torch.cat([x_bo_hat, x_po_hat], -1))
else:
encoded = self.encoder(x_bo_hat, x_po_hat)
if need_value:
final_sos = self.value_decoder(encoded)
if batch_repeat_interleave is not None:
final_sos = torch.repeat_interleave(final_sos, batch_repeat_interleave, dim=0)
if power_permutation_matrix is not None and final_sos is not None:
final_sos = torch.matmul(
power_permutation_matrix.to(final_sos.device), final_sos.unsqueeze(2),
).squeeze(2)
else:
final_sos = None
all_powers = x_power is not None and len(x_power.shape) == 3
if not need_policy:
global_order_idxs = local_order_idxs = logits = None
else:
if x_power is None or all_powers:
global_order_idxs, local_order_idxs, logits = _forward_all_powers(
policy_decoder=self.policy_decoder,
enc=encoded,
loc_idxs=x_loc_idxs,
cand_idxs=x_possible_actions,
temperature=temperature,
top_p=top_p,
batch_repeat_interleave=batch_repeat_interleave,
teacher_force_orders=teacher_force_orders,
power=x_power,
)
else:
global_order_idxs, local_order_idxs, logits = _forward_one_power(
policy_decoder=self.policy_decoder,
enc=encoded,
loc_idxs=x_loc_idxs,
cand_idxs=x_possible_actions,
temperature=temperature,
top_p=top_p,
batch_repeat_interleave=batch_repeat_interleave,
teacher_force_orders=teacher_force_orders,
power=x_power,
)
if pad_to_max:
global_order_idxs, local_order_idxs, logits = _pad_to_max(
global_order_idxs, local_order_idxs, logits, all_powers
)
return global_order_idxs, local_order_idxs, logits, final_sos
def check_permute_powers():
# This is a safeguard so that if base_strategy_model is modified,
# we don't forget to update apply_permute_powers
# If you are updating this function, please consider whether the new base_strategy_model input you
# are adding needs to also have permutations of the powers applied to it.
# Please update apply_permute_powers if it does.
expected_keys = {
"x_possible_actions",
"batch_repeat_interleave",
"teacher_force_orders",