Models API¶
The models package exposes all neural network policy architectures.
Quick-start¶
from models import BattalionMlpPolicy, MAPPOPolicy, WFM1Policy, ScenarioCard
from stable_baselines3 import PPO
from envs import BattalionEnv
# Standard MLP policy with SB3
env = BattalionEnv()
model = PPO(BattalionMlpPolicy, env)
# Multi-agent MAPPO (obs_dim/state_dim taken from MultiBattalionEnv 2v2 defaults)
from models import MAPPOPolicy
policy = MAPPOPolicy(obs_dim=22, action_dim=3, state_dim=25, n_agents=2)
# WFM-1 foundation model
from models import WFM1Policy, ScenarioCard, ECHELON_BATTALION, TERRAIN_PROCEDURAL
card = ScenarioCard(echelon=ECHELON_BATTALION, terrain_type=TERRAIN_PROCEDURAL)
wfm1 = WFM1Policy()
MLP policy (SB3-compatible)¶
models.mlp_policy.BattalionMlpPolicy
¶
Bases: ActorCriticPolicy
MLP actor-critic policy for BattalionEnv.
A configurable fully-connected network with separate actor and critic
heads, designed for the 12-dimensional observation space of
:class:~envs.battalion_env.BattalionEnv.
Architecture (default)::
obs(12) → Linear(128) → Tanh → Linear(128) → Tanh
↓ ↓
actor head → action(3) + log_std critic head → value(1)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
observation_space
|
Space
|
Gymnasium observation space. |
required |
action_space
|
Space
|
Gymnasium action space. |
required |
lr_schedule
|
Schedule
|
Learning-rate schedule passed in by the SB3 algorithm. |
required |
net_arch
|
Optional[List[int]]
|
Hidden-layer sizes shared by actor and critic. Defaults to
|
None
|
activation_fn
|
Type[Module]
|
Activation function class applied after each hidden layer.
Defaults to :class: |
Tanh
|
**kwargs
|
Any
|
Forwarded to
:class: |
{}
|
Source code in models/mlp_policy.py
MAPPO multi-agent policy¶
models.mappo_policy.MAPPOActor
¶
Bases: Module
Shared actor network for homogeneous MAPPO agents.
Takes a local observation vector and produces a diagonal Gaussian
action distribution. The log_std parameters are learned but shared
across the batch (not conditioned on the observation).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obs_dim
|
int
|
Dimensionality of the per-agent local observation. |
required |
action_dim
|
int
|
Dimensionality of the continuous action space. |
required |
hidden_sizes
|
Tuple[int, ...]
|
Sizes of the hidden layers in the shared trunk MLP. |
(128, 64)
|
Source code in models/mappo_policy.py
evaluate_actions(obs, actions)
¶
Evaluate log-probabilities and entropy for given (obs, action) pairs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obs
|
Tensor
|
Local observations of shape |
required |
actions
|
Tensor
|
Actions of shape |
required |
Returns:
| Name | Type | Description |
|---|---|---|
log_probs |
torch.Tensor — shape ``(batch,)``
|
|
entropy |
torch.Tensor — shape ``(batch,)``
|
|
Source code in models/mappo_policy.py
forward(obs)
¶
Return (action_mean, action_std) tensors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obs
|
Tensor
|
Local observation of shape |
required |
Returns:
| Name | Type | Description |
|---|---|---|
mean |
torch.Tensor — shape ``(..., action_dim)``
|
|
std |
torch.Tensor — shape ``(..., action_dim)``
|
|
Source code in models/mappo_policy.py
get_distribution(obs)
¶
models.mappo_policy.MAPPOCritic
¶
Bases: Module
Centralized critic conditioned on the global state tensor.
Receives the global state (all agents' positions, headings, strengths and morale) and produces a scalar value estimate used for advantage computation in MAPPO.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_dim
|
int
|
Dimensionality of the global state vector (output of
:meth: |
required |
hidden_sizes
|
Tuple[int, ...]
|
Sizes of the hidden layers in the critic MLP. |
(128, 64)
|
Source code in models/mappo_policy.py
forward(state)
¶
Return value estimates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
Tensor
|
Global state tensor of shape |
required |
Returns:
| Name | Type | Description |
|---|---|---|
values |
torch.Tensor — shape ``(...)``
|
|
Source code in models/mappo_policy.py
models.mappo_policy.MAPPOPolicy
¶
Bases: Module
MAPPO policy: shared actor(s) plus a centralized critic.
Supports two parameter-sharing modes for the actor:
share_parameters=True(default) — all n_agents agents use the same :class:MAPPOActorweights. Memory scales as O(actor_params + critic_params) instead of O(n_agents * actor_params).share_parameters=False— each agent gets its own :class:MAPPOActor; useful for ablation studies.
In both cases there is a single :class:MAPPOCritic that all
agents share.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obs_dim
|
int
|
Per-agent local observation dimensionality. |
required |
action_dim
|
int
|
Per-agent action dimensionality (continuous). |
required |
state_dim
|
int
|
Global state dimensionality. |
required |
n_agents
|
int
|
Number of controlled agents (used only when
|
1
|
share_parameters
|
bool
|
Whether all agents share one actor. Defaults to |
True
|
actor_hidden_sizes
|
Tuple[int, ...]
|
Hidden layer sizes for the actor trunk. |
(128, 64)
|
critic_hidden_sizes
|
Tuple[int, ...]
|
Hidden layer sizes for the critic trunk. |
(128, 64)
|
Source code in models/mappo_policy.py
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 | |
act(obs, agent_idx=0, deterministic=False)
¶
Sample actions for a batch of observations.
A batch dimension is added internally when obs is 1-D so that
the return shapes are always (batch, action_dim) and
(batch,) regardless of whether the caller passes a single
observation or a batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obs
|
Tensor
|
Local observations of shape |
required |
agent_idx
|
int
|
Index of the agent whose actor should be used. Ignored when
|
0
|
deterministic
|
bool
|
When |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
actions |
torch.Tensor — shape ``(batch, action_dim)``
|
|
log_probs |
torch.Tensor — shape ``(batch,)``
|
|
Source code in models/mappo_policy.py
evaluate_actions(obs, actions, state, agent_idx=0)
¶
Evaluate actions under the current policy for the PPO update.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obs
|
Tensor
|
Local observations of shape |
required |
actions
|
Tensor
|
Actions of shape |
required |
state
|
Tensor
|
Global states of shape |
required |
agent_idx
|
int
|
Actor index (ignored when sharing parameters). |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
log_probs |
torch.Tensor — shape ``(batch,)``
|
|
entropy |
torch.Tensor — shape ``(batch,)``
|
|
values |
torch.Tensor — shape ``(batch,)``
|
|
Source code in models/mappo_policy.py
get_actor(agent_idx=0)
¶
Return the actor for agent_idx.
When share_parameters=True the same actor is returned
regardless of agent_idx.
Source code in models/mappo_policy.py
get_value(state)
¶
Return value estimate(s) for the given global state(s).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
Tensor
|
Global state tensor of shape |
required |
Returns:
| Name | Type | Description |
|---|---|---|
values |
torch.Tensor — scalar or shape ``(batch,)``
|
|
Source code in models/mappo_policy.py
parameter_count()
¶
Return a dict with actor and critic parameter counts.
Source code in models/mappo_policy.py
Entity encoder (transformer)¶
models.entity_encoder.EntityEncoder
¶
Bases: Module
Multi-head self-attention encoder over a variable-length entity sequence.
Architecture::
entity tokens (B, N, token_dim)
│
token_embed: Linear(token_dim → d_model)
│ + SpatialPositionalEncoding(x, y) [optional]
│
TransformerEncoder (n_layers × TransformerEncoderLayer)
└── MultiheadAttention (n_heads, d_model)
└── FFN (dim_feedforward = 4 * d_model)
└── LayerNorm + residual
│
mean-pool over non-padded entities → (B, d_model)
│
output projection: Linear(d_model → d_model) [identity-initialised]
Padding is handled via src_key_padding_mask: a boolean tensor of shape
(B, N) where True marks padded (ignored) positions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_dim
|
int
|
Dimensionality of each input entity token. Defaults to
|
ENTITY_TOKEN_DIM
|
d_model
|
int
|
Internal transformer dimension. |
64
|
n_heads
|
int
|
Number of attention heads. Must evenly divide |
4
|
n_layers
|
int
|
Number of transformer encoder layers. |
2
|
dim_feedforward
|
Optional[int]
|
Feed-forward sublayer width. Defaults to |
None
|
dropout
|
float
|
Dropout probability inside the transformer. |
0.0
|
use_spatial_pe
|
bool
|
When |
True
|
n_freq_bands
|
int
|
Number of Fourier frequency bands used by
:class: |
8
|
Source code in models/entity_encoder.py
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 | |
output_dim
property
¶
Dimensionality of the pooled output vector.
forward(tokens, pad_mask=None, return_attention=False)
¶
Encode a batch of entity sequences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Tensor
|
Entity token tensor of shape |
required |
pad_mask
|
Optional[Tensor]
|
Boolean mask of shape |
None
|
return_attention
|
bool
|
When |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
encoding |
torch.Tensor — shape ``(B, d_model)``
|
Mean-pooled sequence encoding. |
attn_weights |
torch.Tensor — shape ``(B, N, N)``
|
Averaged attention weights from the last layer.
Only returned when |
Source code in models/entity_encoder.py
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 | |
make_padding_mask(n_valid, max_n)
staticmethod
¶
Create a padding mask from per-sample entity counts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_valid
|
Tensor
|
Integer tensor of shape |
required |
max_n
|
int
|
Total number of positions in the padded sequence. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
pad_mask |
torch.BoolTensor — shape ``(B, max_n)``
|
|
Source code in models/entity_encoder.py
models.entity_encoder.EntityActorCriticPolicy
¶
Bases: Module
Actor-critic policy that uses an :class:EntityEncoder as the backbone.
Both the actor and the centralized critic share a single entity encoder
(weight-sharing is optional and controlled by shared_encoder).
Actor head
Takes the pooled entity encoding (B, d_model) and produces a diagonal
Gaussian action distribution.
Critic head
Takes the pooled encoding of the global entity sequence (all units from both teams) and produces a scalar value estimate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_dim
|
int
|
Entity token dimensionality. Defaults to |
ENTITY_TOKEN_DIM
|
action_dim
|
int
|
Continuous action space dimensionality. |
3
|
d_model
|
int
|
Transformer internal dimension. |
64
|
n_heads
|
int
|
Number of attention heads. |
4
|
n_layers
|
int
|
Number of transformer encoder layers. |
2
|
actor_hidden_sizes
|
Tuple[int, ...]
|
MLP hidden sizes applied on top of the entity encoding for the actor. |
(128, 64)
|
critic_hidden_sizes
|
Tuple[int, ...]
|
MLP hidden sizes applied on top of the entity encoding for the critic. |
(128, 64)
|
shared_encoder
|
bool
|
When |
True
|
dropout
|
float
|
Dropout probability in the transformer layers. |
0.0
|
use_spatial_pe
|
bool
|
Enable 2-D Fourier positional encoding. |
True
|
Source code in models/entity_encoder.py
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 | |
act(tokens, pad_mask=None, deterministic=False)
¶
Sample (or select deterministically) actions for a batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Tensor
|
Shape |
required |
pad_mask
|
Optional[Tensor]
|
Padding mask of shape |
None
|
deterministic
|
bool
|
Return the distribution mean instead of sampling. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
actions |
torch.Tensor — shape ``(B, action_dim)``
|
|
log_probs |
torch.Tensor — shape ``(B,)``
|
|
Source code in models/entity_encoder.py
evaluate_actions(tokens, actions, pad_mask=None)
¶
Evaluate log-probs and entropy for given token sequences and actions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Tensor
|
Shape |
required |
actions
|
Tensor
|
Shape |
required |
pad_mask
|
Optional[Tensor]
|
Padding mask of shape |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
log_probs |
torch.Tensor — shape ``(B,)``
|
|
entropy |
torch.Tensor — shape ``(B,)``
|
|
Source code in models/entity_encoder.py
get_distribution(tokens, pad_mask=None)
¶
Compute the action distribution for a batch of entity sequences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Tensor
|
Shape |
required |
pad_mask
|
Optional[Tensor]
|
Boolean padding mask of shape |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dist |
:class:`~torch.distributions.Normal`
|
|
Source code in models/entity_encoder.py
get_value(tokens, pad_mask=None)
¶
Return value estimates for a batch of global entity sequences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Tensor
|
Global entity sequences of shape |
required |
pad_mask
|
Optional[Tensor]
|
Padding mask of shape |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
values |
torch.Tensor — shape ``(B,)``
|
|
Source code in models/entity_encoder.py
parameter_count()
¶
Return a dict with actor and critic parameter counts.
Source code in models/entity_encoder.py
models.entity_encoder.SpatialPositionalEncoding
¶
Bases: Module
Additive 2-D Fourier positional encoding for entity (x, y) positions.
Computes:
.. code-block:: text
PE(x, y) = concat([sin(2π k x), cos(2π k x),
sin(2π k y), cos(2π k y)] for k in 1..n_freqs)
and projects the resulting 4 * n_freqs-dimensional vector to
d_model via a single linear layer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d_model
|
int
|
Output dimension (must match the transformer d_model). |
required |
n_freqs
|
int
|
Number of frequency bands per axis. Defaults to |
8
|
Source code in models/entity_encoder.py
forward(xy)
¶
Compute positional embeddings for a batch of (x, y) pairs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xy
|
Tensor
|
Positions of shape |
required |
Returns:
| Name | Type | Description |
|---|---|---|
pe |
torch.Tensor — shape ``(..., d_model)``
|
|
Source code in models/entity_encoder.py
Recurrent policy (LSTM)¶
models.recurrent_policy.RecurrentActorCriticPolicy
¶
Bases: Module
Actor-critic policy with LSTM temporal memory.
Both actor and critic run through the same :class:RecurrentEntityEncoder
(weight-sharing optional). Hidden states are passed in/out explicitly so
the caller controls episode boundaries and checkpointing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_dim
|
int
|
Entity token dimensionality. |
ENTITY_TOKEN_DIM
|
action_dim
|
int
|
Continuous action space dimensionality. |
3
|
d_model
|
int
|
Transformer internal dimension. |
64
|
n_heads
|
int
|
Attention heads in the entity encoder. |
4
|
n_layers
|
int
|
Transformer encoder layers. |
2
|
lstm_hidden_size
|
int
|
LSTM hidden state dimensionality. |
128
|
lstm_num_layers
|
int
|
Number of stacked LSTM layers. |
1
|
actor_hidden_sizes
|
Tuple[int, ...]
|
MLP hidden sizes on top of the LSTM output for the actor head. |
(128, 64)
|
critic_hidden_sizes
|
Tuple[int, ...]
|
MLP hidden sizes on top of the LSTM output for the critic head. |
(128, 64)
|
shared_encoder
|
bool
|
When |
True
|
dropout
|
float
|
Dropout probability. |
0.0
|
use_spatial_pe
|
bool
|
Enable 2-D Fourier positional encoding. |
True
|
Source code in models/recurrent_policy.py
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 | |
act(tokens, hx, pad_mask=None, deterministic=False)
¶
Sample (or select deterministically) an action for a single step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Tensor
|
Shape |
required |
hx
|
LSTMHiddenState
|
Current LSTM hidden state. |
required |
pad_mask
|
Optional[Tensor]
|
Padding mask. |
None
|
deterministic
|
bool
|
Return the distribution mean instead of sampling. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
actions |
torch.Tensor — shape ``(B, action_dim)``
|
|
log_probs |
torch.Tensor — shape ``(B,)``
|
|
new_hx |
:class:`LSTMHiddenState` — updated hidden state
|
|
Source code in models/recurrent_policy.py
evaluate_actions(tokens_seq, hx, actions_seq, pad_mask_seq=None)
¶
Evaluate log-probs, entropy and values for a sequence of actions.
Used during PPO update to compute the ratio π_new / π_old.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens_seq
|
Tensor
|
Entity token sequences of shape |
required |
hx
|
LSTMHiddenState
|
Initial LSTM hidden state at the start of the sequence. |
required |
actions_seq
|
Tensor
|
Actions to evaluate, shape |
required |
pad_mask_seq
|
Optional[Tensor]
|
Padding mask of shape |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
log_probs |
torch.Tensor — shape ``(B, T)``
|
|
entropy |
torch.Tensor — shape ``(B, T)``
|
|
values |
torch.Tensor — shape ``(B, T)``
|
|
Source code in models/recurrent_policy.py
get_distribution(tokens, hx, pad_mask=None)
¶
Compute action distribution for a single timestep.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Tensor
|
Shape |
required |
hx
|
LSTMHiddenState
|
Current LSTM hidden state. |
required |
pad_mask
|
Optional[Tensor]
|
Boolean padding mask |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dist |
:class:`~torch.distributions.Normal`
|
|
new_hx |
:class:`LSTMHiddenState`
|
|
Source code in models/recurrent_policy.py
get_value(tokens, hx, pad_mask=None)
¶
Compute value estimates for a single timestep.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Tensor
|
Shape |
required |
hx
|
LSTMHiddenState
|
Current LSTM hidden state. |
required |
pad_mask
|
Optional[Tensor]
|
Padding mask. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
values |
torch.Tensor — shape ``(B,)``
|
|
new_hx |
:class:`LSTMHiddenState`
|
|
Source code in models/recurrent_policy.py
initial_state(batch_size=1, device=None)
¶
Return a zero-initialised LSTM hidden state.
Call at the start of each episode to reset temporal memory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size
|
int
|
Number of parallel environments / samples. |
1
|
device
|
Optional[device]
|
Target device. |
None
|
Source code in models/recurrent_policy.py
load_checkpoint(path, device=None, **kwargs)
classmethod
¶
Restore a policy from a checkpoint created by :meth:save_checkpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the checkpoint file. |
required |
device
|
Optional[device]
|
Device to load weights onto. |
None
|
**kwargs
|
Constructor arguments — must match those used when the checkpoint was saved. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
policy |
:class:`RecurrentActorCriticPolicy`
|
|
Source code in models/recurrent_policy.py
parameter_count()
¶
Return a dict with actor and critic parameter counts.
Source code in models/recurrent_policy.py
save_checkpoint(path)
¶
Persist model weights to path (torch.save format).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Destination file path. Parent directories are created if needed. |
required |
Source code in models/recurrent_policy.py
models.recurrent_policy.RecurrentEntityEncoder
¶
Bases: Module
Entity encoder followed by a multi-layer LSTM for temporal memory.
The entity encoder reduces a variable-length set of entity tokens to a fixed-size pooled vector. The LSTM then integrates this encoding across timesteps, maintaining an internal model of unobserved unit positions.
Architecture::
tokens (B, N, token_dim)
│
EntityEncoder → enc (B, d_model)
│
nn.LSTM(d_model → hidden_size, num_layers)
│ ← (h_t, c_t) in / out
lstm_out (B, hidden_size)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_dim
|
int
|
Entity token dimensionality. |
ENTITY_TOKEN_DIM
|
d_model
|
int
|
Transformer internal dimension (EntityEncoder output). |
64
|
n_heads
|
int
|
Attention heads for the entity encoder. |
4
|
n_layers
|
int
|
Transformer encoder layers. |
2
|
lstm_hidden_size
|
int
|
LSTM hidden state dimensionality. |
128
|
lstm_num_layers
|
int
|
Number of stacked LSTM layers. |
1
|
dropout
|
float
|
Dropout probability applied inside transformer and LSTM. |
0.0
|
use_spatial_pe
|
bool
|
Enable 2-D Fourier positional encoding on entity tokens. |
True
|
Source code in models/recurrent_policy.py
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 | |
output_dim
property
¶
Dimensionality of the LSTM output vector.
forward(tokens, hx, pad_mask=None)
¶
Encode a single timestep of entity tokens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Tensor
|
Shape |
required |
hx
|
LSTMHiddenState
|
Current LSTM hidden state. |
required |
pad_mask
|
Optional[Tensor]
|
Boolean padding mask of shape |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
out |
torch.Tensor — shape ``(B, lstm_hidden_size)``
|
LSTM output for this timestep. |
new_hx |
LSTMHiddenState
|
Updated hidden and cell states. |
Source code in models/recurrent_policy.py
forward_sequence(tokens_seq, hx, pad_mask_seq=None)
¶
Encode a sequence of timesteps for BPTT during training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens_seq
|
Tensor
|
Shape |
required |
hx
|
LSTMHiddenState
|
Initial hidden state at the start of the sequence. |
required |
pad_mask_seq
|
Optional[Tensor]
|
Padding mask of shape |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
out_seq |
torch.Tensor — shape ``(B, T, lstm_hidden_size)``
|
LSTM outputs for every timestep. |
new_hx |
LSTMHiddenState
|
Hidden state after the last timestep. |
Source code in models/recurrent_policy.py
initial_state(batch_size=1, device=None)
¶
Return a zero-initialised hidden state for batch_size samples.
Source code in models/recurrent_policy.py
models.recurrent_policy.LSTMHiddenState
dataclass
¶
Container for LSTM (h, c) states with episode-reset utilities.
Both tensors have shape (num_layers, batch, hidden_size).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h
|
Tensor
|
Hidden state tensor. |
required |
c
|
Tensor
|
Cell state tensor. |
required |
Source code in models/recurrent_policy.py
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 | |
as_tuple()
¶
detach()
¶
reset_at(done_mask)
¶
Zero out hidden states for episodes that have ended.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
done_mask
|
Tensor
|
Boolean tensor of shape |
required |
Returns:
| Type | Description |
|---|---|
LSTMHiddenState with states zeroed at ``done_mask`` positions.
|
|
Source code in models/recurrent_policy.py
to(device)
¶
zeros(num_layers, hidden_size, batch_size=1, device=None)
classmethod
¶
Create a zero-initialised hidden state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_layers
|
int
|
Number of LSTM layers. |
required |
hidden_size
|
int
|
LSTM hidden dimension. |
required |
batch_size
|
int
|
Batch dimension. |
1
|
device
|
Optional[device]
|
Target device (defaults to CPU). |
None
|
Source code in models/recurrent_policy.py
models.recurrent_policy.RecurrentRolloutBuffer
¶
On-policy rollout buffer that stores LSTM hidden states for BPTT.
Stores per-step hidden states alongside the usual rollout data so that PPO updates can re-run the LSTM through consecutive sequences (truncated BPTT) starting from the exact hidden state present during collection.
Note
This buffer does not automatically reset LSTM hidden states at episode
boundaries. When done=True at step t, the caller is responsible for
providing an appropriately reset (typically zeroed) hidden state for
step t+1 via :meth:~models.recurrent_policy.RecurrentActorCriticPolicy.initial_state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_steps
|
int
|
Number of environment steps per rollout. |
required |
max_entities
|
int
|
Maximum number of entity tokens per step (pad shorter observations). |
required |
token_dim
|
int
|
Entity token dimensionality. |
ENTITY_TOKEN_DIM
|
action_dim
|
int
|
Action space dimensionality. |
3
|
lstm_hidden_size
|
int
|
LSTM hidden state dimensionality. |
128
|
lstm_num_layers
|
int
|
Number of LSTM layers. |
1
|
gamma
|
float
|
Discount factor for GAE. |
0.99
|
gae_lambda
|
float
|
GAE smoothing parameter λ. |
0.95
|
Source code in models/recurrent_policy.py
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 | |
add(tokens, hx, action, log_prob, reward, done, value, pad_mask=None)
¶
Store one environment transition.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
ndarray
|
Entity tokens of shape |
required |
hx
|
LSTMHiddenState
|
LSTM hidden state at the start of this step (before feeding tokens through the encoder). |
required |
action
|
ndarray
|
Action taken, shape |
required |
log_prob
|
float
|
Log-probability of action under the collection policy. |
required |
reward
|
float
|
Scalar reward received. |
required |
done
|
bool
|
Whether the episode ended after this step. |
required |
value
|
float
|
Critic value estimate for this step. |
required |
pad_mask
|
Optional[ndarray]
|
Boolean padding mask of shape |
None
|
Source code in models/recurrent_policy.py
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 | |
compute_returns_and_advantages(last_value, last_done)
¶
Compute GAE advantages and discounted returns.
Must be called once the buffer is full (all n_steps transitions have been added).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
last_value
|
float
|
Critic value estimate for the state after the last stored step
(bootstrap value). Set to |
required |
last_done
|
bool
|
Whether the last step was terminal. |
required |
Source code in models/recurrent_policy.py
get_sequences(seq_len, device, normalize_advantages=True)
¶
Split the buffer into non-overlapping sequences for BPTT.
Each returned batch is a dict with keys:
"tokens"— shape(n_seqs, seq_len, max_entities, token_dim)"pad_masks"— shape(n_seqs, seq_len, max_entities)"hx_h"— shape(lstm_num_layers, n_seqs, lstm_hidden_size)"hx_c"— shape(lstm_num_layers, n_seqs, lstm_hidden_size)"actions"— shape(n_seqs, seq_len, action_dim)"log_probs"— shape(n_seqs, seq_len)"advantages"— shape(n_seqs, seq_len)"returns"— shape(n_seqs, seq_len)"values"— shape(n_seqs, seq_len)
The initial hidden states hx_h / hx_c are taken from the
first step of each sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seq_len
|
int
|
Length of each sub-sequence. Must evenly divide |
required |
device
|
device
|
Destination device for returned tensors. |
required |
normalize_advantages
|
bool
|
Normalise advantages to zero mean, unit variance (recommended). |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
batches |
list of dicts (each dict is one sequence batch)
|
|
Source code in models/recurrent_policy.py
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 | |
memory_bytes()
¶
Approximate memory usage of stored arrays in bytes.
Source code in models/recurrent_policy.py
WFM-1 foundation model¶
models.wfm1.WFM1Policy
¶
Bases: Module
WFM-1 hierarchical transformer policy.
A single policy that operates across battalion, brigade, division, and corps echelons. Multi-echelon information is fused via cross-echelon attention. A lightweight ScenarioCard FiLM adapter conditions the policy on scenario metadata, enabling efficient fine-tuning.
Architecture::
For each active echelon e ∈ {battalion, brigade, division, corps}:
tokens_e (B, N_e, token_dim)
│
EchelonEncoder(echelon=e) → enc_e (B, d_model)
Stack: echelon_encs = [enc_e₁, enc_e₂, …] shape (B, E, d_model)
│
CrossEchelonTransformer → fused (B, d_model)
│
FiLM(ScenarioCard) : fused ← fused × γ + β
│
actor head → Gaussian action distribution
critic head → scalar value
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_dim
|
int
|
Entity token dimensionality. Defaults to :data: |
ENTITY_TOKEN_DIM
|
action_dim
|
int
|
Continuous action space dimensionality. |
3
|
d_model
|
int
|
Transformer hidden dimension. |
128
|
n_heads
|
int
|
Attention heads for both echelon encoder and cross-echelon transformer. |
8
|
n_echelon_layers
|
int
|
Transformer depth for each :class: |
4
|
n_cross_layers
|
int
|
Transformer depth for :class: |
2
|
actor_hidden_sizes
|
Tuple[int, ...]
|
MLP hidden sizes for the actor head. |
(256, 128)
|
critic_hidden_sizes
|
Tuple[int, ...]
|
MLP hidden sizes for the critic head. |
(256, 128)
|
dropout
|
float
|
Dropout probability (transformer only). |
0.0
|
use_spatial_pe
|
bool
|
Enable 2-D Fourier positional encoding in the echelon encoders. |
True
|
share_echelon_encoders
|
bool
|
When |
True
|
card_hidden_size
|
int
|
Width of the FiLM adapter MLP. |
64
|
Source code in models/wfm1.py
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 | |
act(tokens, pad_mask=None, echelon=ECHELON_BATTALION, card=None, card_vec=None, tokens_per_echelon=None, pad_masks=None, deterministic=False)
¶
Sample actions (no gradient).
Can be called with a single-echelon tokens tensor or with a
full tokens_per_echelon dict for multi-echelon inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Optional[Tensor]
|
Single-echelon entity tokens |
required |
pad_mask
|
Optional[Tensor]
|
Padding mask for |
None
|
echelon
|
int
|
Active echelon level for single-echelon mode. |
ECHELON_BATTALION
|
card
|
Optional[ScenarioCard]
|
Scenario conditioning card. |
None
|
card_vec
|
Optional[Tensor]
|
Pre-computed scenario card tensor (alternative to |
None
|
tokens_per_echelon
|
Optional[Dict[int, Tensor]]
|
Multi-echelon input dict; overrides |
None
|
pad_masks
|
Optional[Dict[int, Tensor]]
|
Padding masks for multi-echelon mode. |
None
|
deterministic
|
bool
|
When |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
actions |
torch.Tensor — shape ``(B, action_dim)``
|
|
log_probs |
torch.Tensor — shape ``(B,)``
|
|
Source code in models/wfm1.py
adapter_parameters()
¶
Return only the FiLM adapter parameters.
Call this to get a parameter group for lightweight scenario-specific fine-tuning (adapter-only gradient updates leave the base transformer frozen).
Returns:
| Type | Description |
|---|---|
list of :class:`torch.nn.Parameter`
|
|
Source code in models/wfm1.py
base_parameters()
¶
Return all non-adapter (base model) parameters.
evaluate_actions(tokens, actions, pad_mask=None, echelon=ECHELON_BATTALION, card=None, card_vec=None)
¶
Evaluate log-probs, entropy, and values for given actions.
Used during PPO update.
Returns:
| Name | Type | Description |
|---|---|---|
log_probs |
torch.Tensor — shape ``(B,)``
|
|
entropy |
torch.Tensor — shape ``(B,)``
|
|
values |
torch.Tensor — shape ``(B,)``
|
|
Source code in models/wfm1.py
finetune_loss(batch)
¶
Compute a supervised fine-tuning loss from a demonstration batch.
The batch dict must contain:
* "tokens" — shape (B, N, token_dim)
* "actions" — shape (B, action_dim)
Optional keys:
* "pad_mask" — shape (B, N)
* "echelon" — scalar int (default: ECHELON_BATTALION)
* "card_vec" — shape (B, card_raw_dim) or (card_raw_dim,)
Returns:
| Name | Type | Description |
|---|---|---|
loss |
torch.Tensor — scalar behaviour-cloning MSE loss
|
|
Source code in models/wfm1.py
freeze_base()
¶
get_value(tokens, pad_mask=None, echelon=ECHELON_BATTALION, card=None, card_vec=None, tokens_per_echelon=None, pad_masks=None)
¶
Compute scalar value estimates.
Returns:
| Name | Type | Description |
|---|---|---|
values |
torch.Tensor — shape ``(B,)``
|
|
Source code in models/wfm1.py
load_checkpoint(path, map_location=None, **kwargs)
classmethod
¶
Load a WFM-1 checkpoint produced by :meth:save_checkpoint.
Extra keyword arguments override the saved configuration.
Source code in models/wfm1.py
save_checkpoint(path)
¶
Save model state dict to path (.pt).
Source code in models/wfm1.py
models.wfm1.ScenarioCard
dataclass
¶
Metadata descriptor for a training/evaluation scenario.
Used to condition WFM-1 via FiLM modulation. All numeric fields are expected to be pre-normalised to reasonable ranges; the policy encodes them into a conditioning vector via a small MLP.
Attributes:
| Name | Type | Description |
|---|---|---|
map_scale |
float
|
Map area normalised to |
echelon_level |
int
|
Primary echelon of the scenario. One of :data: |
weather_code |
int
|
Active weather condition. One of :data: |
n_blue_units |
float
|
Number of blue (friendly) units, normalised to |
n_red_units |
float
|
Number of red (enemy) units, similarly normalised. |
terrain_type |
int
|
Integer terrain identifier. 0 = procedural; 1–4 = GIS sites. |
cavalry_fraction |
float
|
Fraction of units that are cavalry ( |
artillery_fraction |
float
|
Fraction of units that are artillery ( |
supply_pressure |
float
|
Supply depletion index ( |
time_of_day |
float
|
Normalised time in |
max_units |
float
|
Normalisation constant for unit counts. Not encoded — used only
during the :meth: |
Source code in models/wfm1.py
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 | |
to_tensor(device=None)
¶
Encode the card as a 1-D float tensor of shape (_SCENARIO_CARD_RAW_DIM,).
Encoding layout (12 dims): * [0] map_scale float [0, 1] * [1:5] echelon one-hot 4 dims * [5:9] weather one-hot 4 dims * [9] n_blue_units / max_units float [0, 1] * [10] n_red_units / max_units float [0, 1] * [11] terrain_type / 4 float [0, 1]
Unit counts (n_blue_units, n_red_units) are normalised
internally by dividing by max_units; callers do not need to
pre-normalise them.
Note: the remaining floating-point fields (cavalry_fraction,
artillery_fraction, supply_pressure, time_of_day) are
stored on the dataclass but are not included in this 12-dim
vector. They can be appended manually for experimental extensions.
Source code in models/wfm1.py
models.wfm1.EchelonEncoder
¶
Bases: Module
Per-echelon entity encoder based on :class:~models.entity_encoder.EntityEncoder.
Wraps an :class:~models.entity_encoder.EntityEncoder and optionally
adds an echelon embedding that is summed into the token embeddings before
the transformer layers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_dim
|
int
|
Entity token dimensionality. |
ENTITY_TOKEN_DIM
|
d_model
|
int
|
Transformer hidden dimension. |
128
|
n_heads
|
int
|
Number of attention heads. |
8
|
n_layers
|
int
|
Number of transformer encoder layers. |
4
|
dropout
|
float
|
Dropout probability in transformer layers. |
0.0
|
use_spatial_pe
|
bool
|
Whether to add 2-D Fourier positional encoding. |
True
|
n_freq_bands
|
int
|
Fourier frequency bands for the spatial PE. |
8
|
use_echelon_embedding
|
bool
|
When |
True
|
Source code in models/wfm1.py
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 | |
output_dim
property
¶
Dimensionality of the pooled output.
forward(tokens, echelon, pad_mask=None)
¶
Encode entity tokens for a given echelon level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
Tensor
|
Entity token tensor of shape |
required |
echelon
|
int
|
Integer echelon identifier (0–3). |
required |
pad_mask
|
Optional[Tensor]
|
Boolean padding mask |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
enc |
torch.Tensor — shape ``(B, d_model)``
|
|
Source code in models/wfm1.py
models.wfm1.CrossEchelonTransformer
¶
Bases: Module
Transformer that integrates encodings from multiple echelon levels.
Takes a sequence of echelon encodings (B, E, d_model) where E is the
number of active echelons, and applies multi-head self-attention to fuse
information across echelon boundaries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d_model
|
int
|
Hidden dimension (must match the echelon encoder output). |
128
|
n_heads
|
int
|
Number of attention heads. |
8
|
n_layers
|
int
|
Depth of the cross-echelon transformer. |
2
|
dropout
|
float
|
Dropout probability. |
0.0
|
Source code in models/wfm1.py
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 | |
forward(echelon_encs, echelon_ids)
¶
Fuse multi-echelon encodings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
echelon_encs
|
Tensor
|
Stacked echelon encodings of shape |
required |
echelon_ids
|
Tensor
|
Integer echelon identifiers of shape |
required |
Returns:
| Name | Type | Description |
|---|---|---|
fused |
torch.Tensor — shape ``(B, d_model)``
|
Mean-pooled fused representation. |