|
| 1 | +"""Diversity injection for RL policy networks. |
| 2 | +
|
| 3 | +When reward gradients vanish (stuck in local minima or flat regions), this module |
| 4 | +automatically expands exploration of nearby representational variants by injecting |
| 5 | +agent-specific random perturbations into the encoder output. |
| 6 | +
|
| 7 | +Key insight: when PPO loss → 0 (stuck), the diversity loss term automatically |
| 8 | +dominates, pushing α higher and increasing representational spread across agents. |
| 9 | +""" |
| 10 | + |
| 11 | +from __future__ import annotations |
| 12 | + |
| 13 | +import torch |
| 14 | +import torch.nn as nn |
| 15 | +from tensordict import TensorDict |
| 16 | + |
| 17 | +from metta.agent.components.component_config import ComponentConfig |
| 18 | + |
| 19 | + |
| 20 | +class DiversityInjectionConfig(ComponentConfig): |
| 21 | + """Configuration for diversity injection layer.""" |
| 22 | + |
| 23 | + in_key: str |
| 24 | + out_key: str |
| 25 | + name: str = "diversity_injection" |
| 26 | + |
| 27 | + # Number of agent slots to support (should match max agents in training) |
| 28 | + num_agents: int = 256 |
| 29 | + |
| 30 | + # Low-rank approximation rank for memory efficiency |
| 31 | + # W = U @ V.T where U, V are (hidden_dim, rank) |
| 32 | + projection_rank: int = 32 |
| 33 | + |
| 34 | + # Initial value for log_alpha (α = exp(log_alpha)) |
| 35 | + # -1.0 means α starts at ~0.37 |
| 36 | + log_alpha_init: float = -1.0 |
| 37 | + |
| 38 | + # Maximum value for α to prevent explosion |
| 39 | + alpha_max: float = 5.0 |
| 40 | + |
| 41 | + # Whether to apply LayerNorm after injection for stability |
| 42 | + use_layer_norm: bool = True |
| 43 | + |
| 44 | + # Key in TensorDict containing agent IDs (training_env_ids by default) |
| 45 | + agent_id_key: str = "training_env_ids" |
| 46 | + |
| 47 | + def make_component(self, env=None) -> nn.Module: |
| 48 | + return DiversityInjection(config=self) |
| 49 | + |
| 50 | + |
| 51 | +class DiversityInjection(nn.Module): |
| 52 | + """Applies agent-specific random perturbations to encoder output. |
| 53 | +
|
| 54 | + Architecture: |
| 55 | + obs → [shared encoder] → h → h + α * perturbation → [policy_head] → logits |
| 56 | + → [value_head] → value |
| 57 | +
|
| 58 | + Where perturbation = W_rand[agent_id] @ h using low-rank factorization. |
| 59 | + """ |
| 60 | + |
| 61 | + def __init__(self, config: DiversityInjectionConfig): |
| 62 | + super().__init__() |
| 63 | + self.config = config |
| 64 | + self.in_key = config.in_key |
| 65 | + self.out_key = config.out_key |
| 66 | + self.agent_id_key = config.agent_id_key |
| 67 | + self.alpha_max = config.alpha_max |
| 68 | + |
| 69 | + # Learned scalar controlling perturbation strength |
| 70 | + self.log_alpha = nn.Parameter(torch.tensor(config.log_alpha_init)) |
| 71 | + |
| 72 | + # Lazy initialization - we don't know hidden_dim until first forward |
| 73 | + self._hidden_dim: int | None = None |
| 74 | + |
| 75 | + # Register placeholder buffers (will be replaced on first forward) |
| 76 | + self.register_buffer("_projection_u", None) |
| 77 | + self.register_buffer("_projection_v", None) |
| 78 | + |
| 79 | + self.layer_norm: nn.LayerNorm | None = None |
| 80 | + |
| 81 | + def _initialize_projections(self, hidden_dim: int, device: torch.device, dtype: torch.dtype) -> None: |
| 82 | + """Initialize random projection matrices on first forward pass.""" |
| 83 | + if self._hidden_dim == hidden_dim and self._projection_u is not None: |
| 84 | + # Already initialized, just ensure device matches |
| 85 | + if self._projection_u.device != device: |
| 86 | + self._projection_u = self._projection_u.to(device) |
| 87 | + self._projection_v = self._projection_v.to(device) |
| 88 | + if self.layer_norm is not None: |
| 89 | + self.layer_norm = self.layer_norm.to(device) |
| 90 | + return |
| 91 | + |
| 92 | + self._hidden_dim = hidden_dim |
| 93 | + rank = self.config.projection_rank |
| 94 | + num_agents = self.config.num_agents |
| 95 | + |
| 96 | + # Create low-rank factorization: W = U @ V.T |
| 97 | + # Scale by 1/sqrt(rank) for stable initialization |
| 98 | + scale = 1.0 / (rank**0.5) |
| 99 | + |
| 100 | + # Generate deterministic random projections per agent using seeded generators |
| 101 | + projection_u = torch.zeros(num_agents, hidden_dim, rank, dtype=dtype, device=device) |
| 102 | + projection_v = torch.zeros(num_agents, rank, hidden_dim, dtype=dtype, device=device) |
| 103 | + |
| 104 | + for agent_idx in range(num_agents): |
| 105 | + gen = torch.Generator() |
| 106 | + gen.manual_seed(agent_idx * 31337) # Deterministic per-agent seed |
| 107 | + projection_u[agent_idx] = ( |
| 108 | + torch.randn(hidden_dim, rank, generator=gen, dtype=dtype, device="cpu").to(device) * scale |
| 109 | + ) |
| 110 | + projection_v[agent_idx] = ( |
| 111 | + torch.randn(rank, hidden_dim, generator=gen, dtype=dtype, device="cpu").to(device) * scale |
| 112 | + ) |
| 113 | + |
| 114 | + # Update buffers in-place |
| 115 | + self._projection_u = projection_u |
| 116 | + self._projection_v = projection_v |
| 117 | + |
| 118 | + # Initialize LayerNorm if enabled |
| 119 | + if self.config.use_layer_norm and self.layer_norm is None: |
| 120 | + self.layer_norm = nn.LayerNorm(hidden_dim).to(device) |
| 121 | + |
| 122 | + @property |
| 123 | + def alpha(self) -> torch.Tensor: |
| 124 | + """Current perturbation strength coefficient.""" |
| 125 | + return self.log_alpha.exp().clamp(max=self.alpha_max) |
| 126 | + |
| 127 | + def forward(self, td: TensorDict) -> TensorDict: |
| 128 | + h = td[self.in_key] # (batch, hidden_dim) or (batch, time, hidden_dim) |
| 129 | + |
| 130 | + # Initialize on first forward |
| 131 | + self._initialize_projections(h.shape[-1], h.device, h.dtype) |
| 132 | + |
| 133 | + # Get agent IDs - handle both (batch,) and (batch, time) shapes |
| 134 | + if self.agent_id_key in td.keys(): |
| 135 | + agent_ids = td[self.agent_id_key] |
| 136 | + # Flatten to 1D if needed, take first element per batch item if (batch, time) |
| 137 | + if agent_ids.dim() > 1: |
| 138 | + agent_ids = agent_ids[:, 0] if agent_ids.shape[1] > 0 else agent_ids.squeeze(-1) |
| 139 | + agent_ids = agent_ids.long() % self.config.num_agents |
| 140 | + else: |
| 141 | + # Default to agent 0 if no agent IDs provided (e.g., during eval) |
| 142 | + agent_ids = torch.zeros(h.shape[0], dtype=torch.long, device=h.device) |
| 143 | + |
| 144 | + # Compute perturbation using low-rank factorization |
| 145 | + # h @ U @ V.T = (h @ U) @ V.T |
| 146 | + original_shape = h.shape |
| 147 | + if h.dim() == 3: |
| 148 | + # (batch, time, hidden) -> (batch * time, hidden) |
| 149 | + batch, time, hidden = h.shape |
| 150 | + h_flat = h.reshape(batch * time, hidden) |
| 151 | + # Expand agent_ids to match flattened batch |
| 152 | + agent_ids = agent_ids.unsqueeze(1).expand(batch, time).reshape(batch * time) |
| 153 | + else: |
| 154 | + h_flat = h |
| 155 | + batch, time = h.shape[0], 1 |
| 156 | + |
| 157 | + # Gather projection matrices for each sample's agent |
| 158 | + # _projection_u: (num_agents, hidden_dim, rank) |
| 159 | + # _projection_v: (num_agents, rank, hidden_dim) |
| 160 | + u = self._projection_u[agent_ids] # (batch, hidden_dim, rank) |
| 161 | + v = self._projection_v[agent_ids] # (batch, rank, hidden_dim) |
| 162 | + |
| 163 | + # Compute perturbation: h @ U @ V.T |
| 164 | + # (batch, hidden) @ (batch, hidden, rank) -> (batch, rank) |
| 165 | + intermediate = torch.einsum("bh,bhr->br", h_flat, u) |
| 166 | + # (batch, rank) @ (batch, rank, hidden) -> (batch, hidden) |
| 167 | + perturbation = torch.einsum("br,brh->bh", intermediate, v) |
| 168 | + |
| 169 | + # Apply perturbation with learned coefficient |
| 170 | + alpha = self.alpha |
| 171 | + h_div = h_flat + alpha * perturbation |
| 172 | + |
| 173 | + # Apply LayerNorm for stability when α is large |
| 174 | + if self.layer_norm is not None: |
| 175 | + h_div = self.layer_norm(h_div) |
| 176 | + |
| 177 | + # Reshape back if needed |
| 178 | + if len(original_shape) == 3: |
| 179 | + h_div = h_div.reshape(original_shape) |
| 180 | + |
| 181 | + td[self.out_key] = h_div |
| 182 | + |
| 183 | + return td |
| 184 | + |
| 185 | + def get_diversity_loss(self) -> torch.Tensor: |
| 186 | + """Return diversity loss term: -log_alpha. |
| 187 | +
|
| 188 | + This encourages α to grow when other losses are small. |
| 189 | + """ |
| 190 | + return -self.log_alpha |
| 191 | + |
| 192 | + def extra_repr(self) -> str: |
| 193 | + return ( |
| 194 | + f"in_key={self.in_key}, out_key={self.out_key}, " |
| 195 | + f"num_agents={self.config.num_agents}, rank={self.config.projection_rank}, " |
| 196 | + f"alpha_max={self.alpha_max}, use_layer_norm={self.config.use_layer_norm}" |
| 197 | + ) |
0 commit comments