routing-nar/rl4co/models/zoo/ngs/ga.py SHA256 4a88192cae9952ea634d4d9bb9bc278f68e3346a12ad078fadb3dcb74903e4a9
1: from functools import cached_property
2: from typing import Optional, Tuple, cast
3: 
4: import torch
5: 
6: from tensordict import TensorDict
7: from torch import Tensor
8: from tqdm import trange
9: 
10: from rl4co.envs import RL4COEnvBase
11: from rl4co.models.common.constructive.nonautoregressive.decoder import (
12:     NonAutoregressiveDecoder,
13: )
14: from rl4co.utils.decoding import Sampling
15: from rl4co.utils.ops import batchify, get_distance_matrix, unbatchify
16: 
17: 
18: SAVE_MEMORY = True
19: 
20: 
21: class GA:
22:     """Implements the Genetic Algorithm (GA) under the NGS framework.
23: 
24:     Args:
25:         log_heuristic: Logarithm of the heuristic matrix.
26:         n_population: Number of individuals in the population. Defaults to 100.
27:         n_offspring: Number of offspring to be generated. Defaults to 100.
28:             Note that each pair of parents generates only one offspring.
29:         n_parents: Number of parents to be selected for mating. Defaults to 2.
30:         mutation_rate: Rate of mutation. Defaults to 0.01.
31:         rank_coefficient: Coefficient to be used for the rank-based selection. Defaults to 0.01.
32:         novelty_rank_w: Weight for novelty to be used for weighted rank-based selection. Defaults to 0.0.
33:         use_local_search: Whether to use local_search provided by the env. Default to False.
34:         use_nls: Whether to use neural-guided local search provided by the env. Default to False.
35:         n_perturbations: Number of perturbations to be used for nls. Defaults to 5.
36:         local_search_params: Arguments to be passed to the local_search.
37:         perturbation_params: Arguments to be passed to the perturbation used for nls.
38:     """
39: 
40:     def __init__(
41:         self,
42:         log_heuristic: Tensor,
43:         n_population: int = 100,
44:         n_offspring: int = 100,
45:         n_parents: int = 2,
46:         mutation_rate: float = 0.01,
47:         rank_coefficient: float = 0.001,
48:         novelty_rank_w: float = 0.0,
49:         use_local_search: bool = False,
50:         use_nls: bool = False,
51:         n_perturbations: int = 1,
52:         local_search_params: dict = {},
53:         perturbation_params: dict = {},
54:     ):
55:         self.log_heuristic = log_heuristic
56:         self.n_nodes = log_heuristic.shape[1]
57:         self.batch_size = log_heuristic.shape[0]
58: 
59:         self.n_population = n_population
60:         self.n_offspring = n_offspring
61:         self.n_parents = n_parents
62:         self.mutation_rate = mutation_rate
63:         self.rank_coefficient = rank_coefficient
64:         self.novelty_rank_w = novelty_rank_w
65: 
66:         self.final_actions = self.final_reward = None
67:         self.final_reward_cache: dict = {}
68: 
69:         self.use_local_search = use_local_search
70:         assert not (use_nls and not use_local_search), "use_nls requires use_local_search"
71:         self.use_nls = use_nls
72:         self.n_perturbations = n_perturbations
73:         self.local_search_params = local_search_params.copy()
74:         self.perturbation_params = perturbation_params.copy()
75: 
76:         self._batchindex = torch.arange(self.batch_size, device=log_heuristic.device)
77:         self._batchnoffindex = torch.arange(
78:             self.batch_size * self.n_offspring, device=log_heuristic.device
79:         )
80: 
81:     @cached_property
82:     def heuristic_dist(self) -> torch.Tensor:
83:         heuristic = self.log_heuristic.exp().detach().cpu() + 1e-10
84:         heu_dist = 1 / (heuristic / heuristic.max(-1, keepdim=True)[0] + 1e-5)
85:         heu_dist[:, torch.arange(heu_dist.shape[1]), torch.arange(heu_dist.shape[2])] = 0
86:         return heu_dist
87: 
88:     def run(
89:         self,
90:         td_initial: TensorDict,
91:         env: RL4COEnvBase,
92:         n_iterations: int,
93:         decoding_kwargs: dict,
94:         disable_tqdm: bool = True,
95:     ) -> Tuple[Tensor, dict[int, Tensor]]:
96:         """Run the NGS algorithm for a specified number of iterations.
97: 
98:         Args:
99:             td_initial: Initial state of the problem.
100:             env: Environment representing the problem.
101:             n_iterations: Number of iterations to run the algorithm.
102:             decoding_kwargs: Keyword arguments for decoding strategy.
103:             disable_tqdm: Whether to disable the tqdm progress bar. Defaults to False.
104: 
105:         Returns:
106:             td: The final state of the problem.
107:             actions: The final actions chosen by the algorithm.
108:             reward: The final reward achieved by the algorithm.
109:         """
110: 
111:         population = {
112:             "actions": torch.zeros(0, dtype=torch.long, device=td_initial.device),
113:             "edge_mask": torch.zeros(0, dtype=torch.bool, device=td_initial.device),
114:             "reward": torch.zeros(0, dtype=torch.float, device=td_initial.device),
115:             "novelty": torch.zeros(0, dtype=torch.float, device=td_initial.device),
116:         }
117: 
118:         pbar = trange(
119:             n_iterations, dynamic_ncols=True, desc="Running GA", disable=disable_tqdm
120:         )
121:         for i in pbar:
122:             # reset environment
123:             td = td_initial.clone()
124:             _, _, population = self._one_step(td, env, population, decoding_kwargs)
125:             self.final_reward_cache[i] = self.final_reward.clone()  # type: ignore
126:             pbar.set_postfix({"reward": f"{self.final_reward.mean().item():.3f}"})  # type: ignore
127: 
128:         action_matrix = self._convert_final_action_to_matrix()
129:         return action_matrix, self.final_reward_cache
130: 
131:     def run_for_training(
132:         self,
133:         td_initial: TensorDict,
134:         env: RL4COEnvBase,
135:         n_iterations: int,
136:         decoding_kwargs: dict,
137:         actions: Optional[Tensor] = None,
138:         reward: Optional[Tensor] = None,
139:     ) -> Tuple[Tensor, Tensor]:
140:         """Run the NGS algorithm for a specified number of iterations.
141: 
142:         Args:
143:             td_initial: Initial state of the problem.
144:             env: Environment representing the problem.
145:             n_iterations: Number of iterations to run the algorithm.
146:             decoding_kwargs: Keyword arguments for decoding strategy.
147:             actions: Actions to be used for training. Defaults to None.
148:             reward: Reward to be used for training. Defaults to None.
149: 
150:         Returns:
151:             actions: The final actions chosen by the algorithm.
152:             reward: The final reward achieved by the algorithm.
153:         """
154: 
155:         population = {
156:             "actions": torch.zeros(0, dtype=torch.long, device=td_initial.device),
157:             "edge_mask": torch.zeros(0, dtype=torch.bool, device=td_initial.device),
158:             "reward": torch.zeros(0, dtype=torch.float, device=td_initial.device),
159:             "novelty": torch.zeros(0, dtype=torch.float, device=td_initial.device),
160:         }
161:         if actions is not None:
162:             assert (
163:                 actions.size(0) == reward.size(0) == self.batch_size * self.n_offspring  # type: ignore
164:             )
165: 
166:             # reshape from (batch_size * n_offspring, ...) to (batch_size, n_offspring, ...)
167:             reward = unbatchify(reward, self.n_offspring)  # type: ignore
168:             actions = unbatchify(actions, self.n_offspring)  # type: ignore
169:             # update final actions and rewards
170:             self._update_results(actions, reward)
171:             # update population
172:             population = self._update_population(env.name, actions, reward, population)
173: 
174:         for _ in range(n_iterations):
175:             # reset environment
176:             td = td_initial.clone()
177:             _, _, population = self._one_step(td, env, population, decoding_kwargs)
178: 
179:         return population["actions"], population["reward"]
180: 
181:     def _one_step(
182:         self,
183:         td: TensorDict,
184:         env: RL4COEnvBase,
185:         population: dict[str, torch.Tensor],
186:         decoding_kwargs: dict,
187:     ) -> Tuple[Tensor, Tensor, dict[str, torch.Tensor]]:
188:         """Run one step of the Neural Genetic Operator
189: 
190:         Args:
191:             td: Current state of the problem.
192:             env: Environment representing the problem.
193:             population: Population of individuals.
194:                 population["actions"].shape == (batch_size, n_population, max_seq_len)
195:                 population["edge_mask"].shape == (batch_size, n_population, max_seq_len, max_seq_len)
196:                 population["reward"].shape == (batch_size, n_population)
197:                 population["novelty"].shape == (batch_size, n_population)
198:             decoding_kwargs: Keyword arguments for decoding strategy.
199: 
200:         Returns:
201:             actions: The actions chosen by the algorithm.
202:             reward: The reward achieved by the algorithm.
203:         """
204:         # sampling
205:         parents_mask = self._get_parents_mask(population)
206:         td, env, actions, reward = self._sampling(td, env, parents_mask, decoding_kwargs)
207:         # local search, reserved for extensions
208:         if self.use_local_search:
209:             actions, reward = self.local_search(td, env, actions, decoding_kwargs)
210: 
211:         # reshape from (batch_size * n_offspring, ...) to (batch_size, n_offspring, ...)
212:         reward = unbatchify(reward, self.n_offspring)
213:         actions = unbatchify(actions, self.n_offspring)
214:         # update final actions and rewards
215:         self._update_results(actions, reward)
216:         # update population
217:         population = self._update_population(env.name, actions, reward, population)
218: 
219:         return actions, reward, population  # type: ignore
220: 
221:     def _sampling(
222:         self,
223:         td: TensorDict,
224:         env: RL4COEnvBase,
225:         parents_mask: Optional[Tensor],
226:         decoding_kwargs: dict,
227:     ):
228:         decode_strategy = Sampling(**decoding_kwargs)
229: 
230:         td, env, num_starts = decode_strategy.pre_decoder_hook(td, env)
231:         while not td["done"].all():
232:             logits, mask = NonAutoregressiveDecoder.heatmap_to_logits(
233:                 td, self.log_heuristic, num_starts
234:             )
235: 
236:             # NGS masking
237:             if parents_mask is not None:
238:                 new_mask = mask * parents_mask[
239:                     self._batchnoffindex, td["current_node"].squeeze(-1)
240:                 ]
241:                 # Mutation here
242:                 invalid_indices = new_mask.sum(-1) == 0  # invalid case
243:                 mutation_indices = torch.rand(  # stochastic mutation
244:                     parents_mask.size(0), device=invalid_indices.device
245:                 ) < self.mutation_rate
246:                 unmask_indices = invalid_indices | mutation_indices
247:                 new_mask[unmask_indices] = mask[unmask_indices]
248:                 mask = new_mask
249: 
250:             td = decode_strategy.step(logits, mask, td)
251:             td = env.step(td)["next"]
252: 
253:         logprobs, actions, td, env = decode_strategy.post_decoder_hook(td, env)
254:         reward = env.get_reward(td, actions)
255: 
256:         return td, env, actions, reward
257: 
258:     def local_search(
259:         self, td: TensorDict, env: RL4COEnvBase, actions: Tensor, decoding_kwargs: dict
260:     ) -> Tuple[Tensor, Tensor]:
261:         """Perform local search on the actions and reward obtained.
262: 
263:         Args:
264:             td: Current state of the problem.
265:             env: Environment representing the problem.
266:             actions: Actions chosen by the algorithm.
267: 
268:         Returns:
269:             actions: The modified actions
270:             reward: The modified reward
271:         """
272:         device = td.device
273:         if env.name in ["tsp", "cvrp"]:
274:             # Convert to CPU in advance to minimize the overhead from device transfer
275:             td = td.detach().cpu()
276:             # TODO: avoid or generalize this, e.g., pre-compute for local search in each env
277:             td["distances"] = get_distance_matrix(td["locs"])
278:             actions = actions.detach().cpu()
279:         elif env.name in ["pctsp", "op"]:  # destroy & repair local search
280:             self.local_search_params.update(
281:                 {
282:                     "decoding_kwargs": decoding_kwargs,
283:                     "heatmap": batchify(self.log_heuristic, self.n_offspring),
284:                 }
285:             )
286:         else:
287:             raise NotImplementedError(f"Local search not implemented for {env.name}")
288: 
289:         best_actions = env.local_search(
290:             td=td, actions=actions, **self.local_search_params
291:         )
292:         best_rewards = env.get_reward(td, best_actions)
293: 
294:         if self.use_nls:
295:             td_perturb = td.clone()
296:             td_perturb["distances"] = torch.tile(
297:                 self.heuristic_dist, (self.n_offspring, 1, 1)
298:             )
299:             new_actions = best_actions.clone()
300: 
301:             for _ in range(self.n_perturbations):
302:                 perturbed_actions = env.local_search(
303:                     td=td_perturb, actions=new_actions, **self.perturbation_params
304:                 )
305:                 new_actions = env.local_search(
306:                     td=td, actions=perturbed_actions, **self.local_search_params
307:                 )
308:                 new_rewards = env.get_reward(td, new_actions)
309: 
310:                 improved_indices = new_rewards > best_rewards
311:                 best_actions = env.replace_selected_actions(
312:                     best_actions, new_actions, improved_indices
313:                 )
314:                 best_rewards[improved_indices] = new_rewards[improved_indices]
315: 
316:         best_actions = best_actions.to(device)
317:         best_rewards = best_rewards.to(device)
318: 
319:         return best_actions, best_rewards
320: 
321:     def _update_results(self, actions, reward):
322:         # update the best-trails recorded in self.final_actions
323:         best_index = reward.argmax(-1)
324:         best_reward = reward[self._batchindex, best_index]
325:         best_actions = actions[self._batchindex, best_index]
326: 
327:         if self.final_actions is None or self.final_reward is None:
328:             self.final_actions = list(iter(best_actions.clone()))
329:             self.final_reward = best_reward.clone()
330:         else:
331:             require_update = self._batchindex[self.final_reward <= best_reward]
332:             for index in require_update:
333:                 self.final_actions[index] = best_actions[index].clone()
334:             self.final_reward[require_update] = best_reward[require_update].clone()
335: 
336:         return best_index
337: 
338:     def _convert_final_action_to_matrix(self) -> Tensor:
339:         assert self.final_actions is not None
340:         action_count = max(len(actions) for actions in self.final_actions)
341:         mat_actions = torch.zeros(
342:             (self.batch_size, action_count),
343:             device=self.final_actions[0].device,
344:             dtype=self.final_actions[0].dtype,
345:         )
346:         for index, action in enumerate(self.final_actions):
347:             mat_actions[index, : len(action)] = action
348: 
349:         return mat_actions
350: 
351:     ###############################
352:     ##### GA specific methods #####
353:     ###############################
354: 
355:     def _update_population(
356:         self, env_name, actions, reward, population: dict[str, Tensor]
357:     ) -> dict[str, Tensor]:
358:         assert actions.size(1) == self.n_offspring
359: 
360:         if env_name == "tsp" or len(population["actions"]) == 0:
361:             concated_actions = torch.cat([population["actions"], actions], dim=1)
362:         else:  # for other envs, we may need to pad the actions
363:             diff_length = actions.size(-1) - population["actions"].size(-1)
364:             if diff_length > 0:
365:                 population["actions"] = torch.nn.functional.pad(
366:                     population["actions"], (0, diff_length), value=0
367:                 )
368:             elif diff_length < 0:
369:                 actions = torch.nn.functional.pad(actions, (0, -diff_length), value=0)
370:             concated_actions = torch.cat([population["actions"], actions], dim=1)
371:         # concated_actions.shape == (batch_size, n_population + n_offspring, max_seq_len)
372: 
373:         new_n = concated_actions.size(1)  # new_n = n_population + n_offspring
374:         concated_edge_mask = self._get_edge_mask(concated_actions)
375:         # edge_mask.shape == (batch_size, new_n, n_nodes, n_nodes)
376:         pairwise_distance = self._pairwise_distance(concated_edge_mask)
377:         # pairwise_distance.shape == (batch_size, new_n, new_n)
378: 
379:         concated_reward = torch.cat([population["reward"], reward], dim=1)
380:         # concated_reward.shape == (batch_size, new_n)
381:         concated_novelty = pairwise_distance.mean(-1)
382:         # concated_novelty.shape == (batch_size, new_n)
383: 
384:         if new_n <= self.n_population:
385:             population["actions"] = concated_actions
386:             population["edge_mask"] = concated_edge_mask
387:             population["reward"] = concated_reward
388:             population["novelty"] = concated_novelty
389:         else:
390:             # remove redundant individuals
391:             triu_indices = torch.triu_indices(new_n, new_n)
392:             pairwise_distance[:, triu_indices[0], triu_indices[1]] = 1.0
393:             # pairwise_distance.shape == (batch_size, new_n, new_n)
394:             redundant_indices = torch.where(pairwise_distance < 1e-5)
395: 
396:             uniqueness_weights = torch.ones_like(concated_reward)
397:             if len(redundant_indices[0]) > 0:
398:                 concated_reward[redundant_indices[:2]] = -1e5
399:                 concated_novelty[redundant_indices[:2]] = -1e5
400:                 uniqueness_weights[redundant_indices[:2]] = 0.0
401: 
402:             # rank-based selection
403:             score_ranks = torch.argsort(torch.argsort(-concated_reward, dim=1), dim=1)
404:             novelty_ranks = torch.argsort(torch.argsort(-concated_novelty, dim=1), dim=1)
405:             weighted_ranks = (
406:                 (1 - self.novelty_rank_w) * score_ranks
407:                 + self.novelty_rank_w * novelty_ranks
408:             )
409:             weights = 1.0 / (self.rank_coefficient * new_n + weighted_ranks)
410:             weights *= uniqueness_weights
411:             indices_to_keep = torch.multinomial(
412:                 weights, self.n_population, replacement=False
413:             )
414:             batch_indices = self._batchindex.unsqueeze(1).expand(-1, self.n_population)
415:             population["actions"] = concated_actions[batch_indices, indices_to_keep]
416:             population["edge_mask"] = concated_edge_mask[batch_indices, indices_to_keep]
417:             population["reward"] = concated_reward[batch_indices, indices_to_keep]
418:             population["novelty"] = concated_novelty[batch_indices, indices_to_keep]
419: 
420:         return population
421: 
422:     def _get_edge_mask(self, actions: Tensor) -> Tensor:
423:         batch_size, n, max_seq_len = actions.size()
424:         n_nodes = self.n_nodes
425: 
426:         actions_flat = actions.reshape(batch_size * n, max_seq_len)
427:         # actions_flat.shape == (batch_size * n, max_seq_len)
428:         edge_index = torch.stack(
429:             [actions_flat, torch.roll(actions_flat, shifts=-1, dims=1)], dim=2
430:         )
431:         row = edge_index[:, :, 0]
432:         col = edge_index[:, :, 1]
433:         batch_indices = (
434:             torch.arange(batch_size * n, device=actions.device)
435:             .view(-1, 1)
436:             .expand(-1, max_seq_len)
437:         )
438:         flat_indices_forward = batch_indices * (n_nodes * n_nodes) + row * n_nodes + col
439:         flat_indices_backward = batch_indices * (n_nodes * n_nodes) + col * n_nodes + row
440:         flat_indices = torch.cat(
441:             [flat_indices_forward, flat_indices_backward], dim=1
442:         ).reshape(-1)
443:         total_elements = batch_size * n * n_nodes * n_nodes
444:         edge_mask_flat = torch.zeros(
445:             total_elements, dtype=torch.bool, device=actions.device
446:         )
447:         edge_mask_flat[flat_indices] = True
448:         edge_mask = edge_mask_flat.view(batch_size, n, n_nodes, n_nodes)
449:         # edge_mask.shape == (batch_size, n, n_nodes, n_nodes)
450: 
451:         return edge_mask
452: 
453:     def _pairwise_distance(self, edge_mask: Tensor) -> Tensor:
454:         batch_size, n, n_nodes, _ = edge_mask.size()
455:         if SAVE_MEMORY:  # For-loop Version (to avoid OOM)
456:             pairwise_sum = torch.zeros(
457:                 (batch_size, n, n), dtype=torch.float, device=edge_mask.device
458:             )
459:             for b in range(batch_size):
460:                 _edges = edge_mask[b].view(n, -1).to(torch.float)
461:                 pairwise_sum[b] = torch.mm(_edges, _edges.transpose(0, 1))
462:         else:  # Batch Version
463:             mask_flat = edge_mask.view(batch_size, n, -1).float()
464:             # mask_flat.shape == (batch_size, n, n_nodes * n_nodes)
465:             pairwise_sum = torch.matmul(mask_flat, mask_flat.transpose(1, 2))
466: 
467:         pairwise_distance = 1 - (pairwise_sum / (2 * n_nodes))
468:         # pairwise_distance.shape == (batch_size, n, n)
469:         return pairwise_distance
470: 
471:     def _get_parents_mask(self, population: dict[str, Tensor]) -> Optional[Tensor]:
472:         reward = population["reward"]
473:         novelty = population["novelty"]
474:         if len(reward) == 0 or reward.size(1) < self.n_population:
475:             return None
476: 
477:         # rank-based selection
478:         score_ranks = torch.argsort(torch.argsort(-reward, dim=1), dim=1)
479:         novelty_ranks = torch.argsort(torch.argsort(-novelty, dim=1), dim=1)
480:         weighted_ranks = (
481:             (1 - self.novelty_rank_w) * score_ranks + self.novelty_rank_w * novelty_ranks
482:         )
483:         weights = 1.0 / (self.rank_coefficient * self.n_population + weighted_ranks)
484:         # weights.shape == (batch_size, n_population)
485: 
486:         if SAVE_MEMORY:  # For-loop & Sparse Version (to avoid OOM)
487:             weights_expanded = cast(Tensor, batchify(weights, self.n_offspring))
488:             parents_indices = torch.multinomial(
489:                 weights_expanded, self.n_parents, replacement=False
490:             )
491:             parents_indices_batched = unbatchify(parents_indices, self.n_offspring)
492:             # parents_indices.shape == (batch_size, n_offspring, n_parents)
493: 
494:             parents_edge_masks = torch.cat(
495:                 [
496:                     (
497:                         population["edge_mask"][b, parents_indices_batched[b]]
498:                         .unsqueeze(1)
499:                         .to_sparse_coo()
500:                     )
501:                     for b in range(self.batch_size)
502:                 ],
503:                 dim=1,
504:             )  # parents_edge_masks.shape == (n_offspring, batch_size, n_parents, n_nodes, n_nodes)
505:             out = parents_edge_masks.sum(2).bool().to_dense().flatten(0, 1)
506: 
507:         else:  # Batch & Dense Version
508:             weights_expanded = cast(Tensor, batchify(weights, self.n_offspring))
509:             parents_indices = torch.multinomial(
510:                 weights_expanded, self.n_parents, replacement=False
511:             )
512: 
513:             parents_edge_masks = cast(
514:                 Tensor, batchify(population["edge_mask"], self.n_offspring)
515:             )
516:             batch_indices = torch.arange(
517:                 parents_edge_masks.size(0), device=parents_edge_masks.device
518:             ).unsqueeze(1).expand(-1, self.n_parents)
519:             parents_edge_masks = parents_edge_masks[batch_indices, parents_indices]
520:             out = parents_edge_masks.sum(1).bool()
521:         return out  # out.shape == (batch_size * n_offspring, n_nodes, n_nodes)