
FILE src/utils/metrics_utils.py FUNCTION is_molecule_successful
29: def is_molecule_successful(properties, ranges, preferences):
30:     """
31:     Determine if a molecule is successful based on multiple properties.
32: 
33:     Args:
34:         properties (list of float): List of molecular property values [p1, p2, ..., pk].
35:         ranges (list of tuple): List of desired ranges [(a1, b1), (a2, b2), ..., (ak, bk)].
36:         preferences (list of int): List of preferences for each property [-1, 0, 1].
37: 
38:     Returns:
39:         bool: True if the molecule is successful for all properties, False otherwise.
40:     """
41:     all_props_success = [False]*len(ranges)
42:     for i, (p, (a, b), preference) in enumerate(zip(properties, ranges, preferences)):
43:         if preference == -1:  # Lower values preferred
44:             lower_threshold = a * 0.9 if a > 0 else a * 1.1
45:             upper_threshold = a * 1.1 if a>0 else a *0.9
46:             if (p >= lower_threshold) and (p<=upper_threshold):
47:                 all_props_success[i] = True
48:                 continue
49:             else:
50:                 return False
51:         elif preference == 1:  # Higher values preferred
52:             lower_threshold = b * 0.9 if b > 0 else b * 1.1
53:             upper_threshold = b * 1.1 if b > 0 else b * 0.9
54:             if (p >= lower_threshold) and (p<=upper_threshold):
55:                 all_props_success[i] = True
56:                 continue
57:             else:
58:                 return False
59: 
60:         elif preference == 0:  # Range constraint
61:             lower_threshold = a * 0.9 if a > 0 else a * 1.1
62:             upper_threshold = b * 1.1 if b > 0 else b * 0.9
63:             if (p >= lower_threshold) and (p<=upper_threshold):
64:                 all_props_success[i] = True
65:                 continue
66:             else:
67:                 return False
68:         else:
69:             raise ValueError("Preference must be -1, 0, or 1.")
70:     return all(all_props_success)

FILE src/utils/metrics_utils.py FUNCTION success_percentage
72: def success_percentage(molecules, ranges, preferences):
73:     """
74:     Calculate the success percentage for multiple molecules.
75: 
76:     Args:
77:         molecules (list of list of float): List of molecules, where each molecule is a list of property values.
78:         ranges (list of tuple): List of desired ranges [(a1, b1), (a2, b2), ..., (ak, bk)] for k properties.
79:         preferences (list of int): List of preferences for each property [-1, 0, 1].
80: 
81:     Returns:
82:         float: Success percentage as the fraction of successful molecules multiplied by 100.
83:     """
84:     successful_count = 0
85:     
86:     for properties in molecules:
87:         if is_molecule_successful(properties, ranges, preferences):
88:             successful_count += 1
89:     
90:     success_percentage = (successful_count / len(molecules)) * 100
91:     return success_percentage

FILE src/utils/metrics_utils.py FUNCTION calculate_unique_ratio
425: def calculate_unique_ratio(smiles_list):
426:     unique_molecules = canonicalize_list(smiles_list, include_stereocenters=False)
427:     unique_ratio = len(unique_molecules) / len(smiles_list)
428:     return unique_ratio

FILE src/utils/metrics_utils.py FUNCTION calculate_nmodes
430: def calculate_nmodes(smiles_list, rewards, tanimoto_thresh, reward_threshold):
431:     mols_list = [Chem.MolFromSmiles(smiles) for smiles in smiles_list]
432:     fingerprints = [calculate_fingerprint(mol) for mol in mols_list]
433:     mol_data = [(smiles, reward, fingerprint) for smiles, reward, fingerprint in zip(smiles_list, rewards, fingerprints) if fingerprint is not None]
434:     mol_data.sort(key=lambda x: x[1], reverse=True)
435:     modes = []
436:     for smiles, reward, fingerprint in mol_data:
437:         if reward < reward_threshold:
438:             continue
439:         is_new_mode = True
440:         for mode_smiles, mode_fp in modes:
441:             similarity = tanimoto_similarity(fingerprint, mode_fp)
442:             if similarity > tanimoto_thresh:
443:                 is_new_mode = False
444:                 break
445:         if is_new_mode:
446:             modes.append((smiles, fingerprint))
447:     return len(modes)

FILE src/utils/metrics_utils.py FUNCTION calculate_diversity
449: def calculate_diversity(smiles_list):
450:     mols_list = [Chem.MolFromSmiles(smiles) for smiles in smiles_list]
451:     fingerprints = [calculate_fingerprint(mol) for mol in mols_list]
452:     num_mols = len(mols_list)
453:     tanimoto_similarities = np.zeros((num_mols, num_mols))
454:     for i in range(num_mols):
455:         for j in range(i + 1, num_mols):
456:             similarity = DataStructs.TanimotoSimilarity(fingerprints[i], fingerprints[j])
457:             tanimoto_similarities[i, j] = similarity
458:             tanimoto_similarities[j, i] = similarity
459:     avg_similarity = np.mean(tanimoto_similarities[np.triu_indices(num_mols, k=1)])
460:     diversity = 1 - avg_similarity
461:     return diversity

FILE src/utils/metrics_utils.py FUNCTION calculate_fast_diversity
463: def calculate_fast_diversity(smiles_list):
464:     mols_list = [Chem.MolFromSmiles(smiles) for smiles in smiles_list]
465:     fingerprints = [calculate_fingerprint(mol) for mol in mols_list]
466:     return 1 - np.concatenate([Chem.DataStructs.BulkTanimotoSimilarity(fingerprints[i], fingerprints[i+1:]) for i in range(len(mols_list) - 1)]).mean()

FILE src/utils/metrics_utils.py FUNCTION calculate_normalized_l1_diff
476: def calculate_normalized_l1_diff(smiles_list, conditionals, predictor = None):
477:     '''predictor: test_molopt.TaskPredictor object, needed for TDC tasks
478:     '''
479:     mols_list = [Chem.MolFromSmiles(smiles) for smiles in smiles_list]
480:     properties_list = [calculate_properties(mol, conditionals, predictor) for mol in mols_list]
481:     conditionals_l1 = {}
482:     for prop in conditionals:
483:         l1sum = 0
484:         c_low, c_high = conditionals[prop][0][0], conditionals[prop][0][1]
485:         preference = conditionals[prop][-1]
486:         for i in range(len(mols_list)):
487:             prop_val = properties_list[i][prop]
488:             if preference == 0:
489:                 if (prop_val < c_low) or (prop_val > c_high):
490:                     l1sum += min(abs(prop_val - c_low), abs(prop_val - c_high))
491:             elif preference == 1:
492:                 l1sum += abs(prop_val - c_high)
493:             elif preference == -1:
494:                 l1sum += abs(prop_val - c_low)
495:         conditionals_l1[prop] = l1sum / ((i + 1) * (c_high - c_low))
496:     return conditionals_l1

FILE src/utils/metrics_utils.py FUNCTION binding_evaluate
499: def binding_evaluate(protein, smiles, train_smiles, minimized_docking_scores):
500:     df = pd.DataFrame()
501:     num_mols = len(smiles)
502:     df['smiles'] = smiles
503:     validity = len(df) / num_mols
504:     df['MOL'] = [Chem.MolFromSmiles(s) for s in smiles]
505: 
506:     train_mols = [Chem.MolFromSmiles(smi) for smi in train_smiles]
507:     
508:     if 'sim' not in df.keys():
509:         gen_fps = [AllChem.GetMorganFingerprintAsBitVect((mol), 2, 1024) for mol in df['MOL']]
510:         train_fps = [AllChem.GetMorganFingerprintAsBitVect((mol), 2, 1024) for mol in train_mols]
511:         max_sims = []
512:         for i in range(len(gen_fps)):
513:             sims = DataStructs.BulkTanimotoSimilarity(gen_fps[i], train_fps)
514:             max_sims.append(max(sims))
515:         df['sim'] = max_sims
516: 
517: 
518: 
519:     uniqueness = len(set(df['smiles'])) / len(df)
520:     novelty = len(df[df['sim'] < 0.4]) / len(df)
521: 
522: 
523:     df[protein] = (np.array(minimized_docking_scores)/-1).tolist() 
524:     df['qed'] = [QED.qed(m) for m in df['MOL']]
525:     df['sa'] = [(10 - calculateScore(m)) / 9 for m in df['MOL']]
526: 
527:     df = df.drop_duplicates(subset=['smiles'])
528:     del df['MOL']
529: 
530:     if protein == 'parp1': hit_thr = 10.
531:     elif protein == 'fa7': hit_thr =  8.5
532:     elif protein == '5ht1b': hit_thr = 8.7845
533:     elif protein == 'jak2': hit_thr = 9.1
534:     elif protein == 'braf': hit_thr = 10.3
535:     else: raise ValueError('Unrecognized target protein')
536: 
537:     df = df[df[f'{protein}']!=0]
538:     df = df[df['qed'] > 0.5]
539:     df = df[df['sa'] > (10 - 5) / 9]
540: 
541:     hit_len_df = len(df[df[protein] > hit_thr]) / len(df) 
542:     hit_num_mols = len(df[df[protein] > hit_thr]) / num_mols
543: 
544: 
545:     nov_df = df[df['sim'] < 0.4]
546:     nov_df = nov_df.sort_values(by=[protein], ascending=False)
547: 
548:     num_top5 = int(num_mols * 0.05)
549: 
550:     top_ds = nov_df.iloc[:num_top5][protein].mean(), nov_df.iloc[:num_top5][protein].std()
551:     nov_hit_len_df = len(nov_df[nov_df[protein] > hit_thr]) / len(df) 
552:     nov_hit_num_mols = len(nov_df[nov_df[protein] > hit_thr]) / num_mols
553:     
554:     return {'validity': validity, 'uniqueness': uniqueness,
555:             '0.4Tanimoto_novelty': novelty, 'top_ds': top_ds, 'hit': hit_len_df, 'hit_num_mols': hit_num_mols, 'nov_hit_len_df':nov_hit_len_df, 'nov_hit_num_mols':nov_hit_num_mols}

FILE src/utils/metrics_utils.py FUNCTION get_metrics
557: def get_metrics(generated_smiles_list, gen_smi_overall_rew, pretrain_conditionals, pretrain_smiles_list, task_conditionals, 
558:                 predictor = None, gen_smi_moo_rew = None, hypervolume = True, task_offline_df=None, binding=False, protein=None, docking_scores=None):
559:     '''res_dict_path: path to dfictionary with sampled smiles and corresponding rewards
560:         predictor: test_molopt.TaskPredictor object, needed for TDC tasks
561:     '''
562:     evaluator = Evaluator(name = 'Diversity')
563:     metrics= {}
564:     if task_offline_df:
565:         task_offline_smiles = task_offline_df.smiles.values
566:         training_smiles = pretrain_smiles_list+task_offline_smiles
567:     else:
568:         training_smiles = pretrain_smiles_list
569:     all_conditionals = pretrain_conditionals.copy()
570:     all_conditionals.update(task_conditionals)
571:     gen_mols = [Chem.MolFromSmiles(smiles) for smiles in generated_smiles_list]
572:     gen_df = pd.DataFrame(gen_mols,columns=['MOL'])
573:     metrics['l1dist']= calculate_normalized_l1_diff(generated_smiles_list, all_conditionals, predictor)
574:     metrics['uniqueness'] = calculate_unique_ratio(generated_smiles_list)
575:     metrics['success%'] = calculate_success_percentage(generated_smiles_list, task_conditionals, all_conditionals, predictor=predictor)#, relative_success=False)
576:     metrics['diversity'] = calculate_fast_diversity(generated_smiles_list)
577:     metrics['tdc div']= evaluator(generated_smiles_list)
578:     metrics['novelty'] = guacamol_novelty(generated_smiles_list,training_smiles)
579:     metrics['#modes'] = calculate_nmodes(generated_smiles_list, gen_smi_overall_rew, tanimoto_thresh=0.5, reward_threshold=0.5)
580:     metrics['#scaffold']= bemisMurcoScaffold(generated_smiles_list)
581:     metrics['validity'] = len(gen_mols)/len(generated_smiles_list)
582:     metrics['#Circles'] = get_ncircle(gen_df)
583:     metrics['top-K'] = top_k_scores(gen_smi_overall_rew, generated_smiles_list)
584:     # metrics['IntDiv1'] = internal_diversity(generated_smiles_list)
585:     if hypervolume:
586:         metrics['Hypervolume'] = get_hypervolume(gen_smi_moo_rew)
587:     if binding:
588:         metrics['binding'] = binding_evaluate(protein, generated_smiles_list, training_smiles, docking_scores)
589:     return metrics

FILE src/utils/metrics_utils.py FUNCTION top_k_scores
591: def top_k_scores(gen_smi_overall_rew, generated_smiles_list):
592:     top_smi = sorted(zip(gen_smi_overall_rew, generated_smiles_list), reverse=True)
593:     top_k_avg_rewards = {}
594:     top_k_values = [1, 10, 100]
595:     for k in top_k_values:
596:         top_k_tuples = top_smi[:k]
597:         avg_reward = sum(tup[0] for tup in top_k_tuples) / len(top_k_tuples)
598:         top_k_avg_rewards[f"top-{k}"] = avg_reward
599:     return top_k_avg_rewards

FILE src/utils/metrics_utils.py FUNCTION guacamol_novelty
602: def guacamol_novelty(smiles_list, training_smiles):
603:     training_set_molecules = set(canonicalize_list(training_smiles, include_stereocenters=False))
604:     unique_molecules = canonicalize_list(smiles_list, include_stereocenters=False)
605:     novel_molecules = set(unique_molecules).difference(training_set_molecules)
606:     novel_ratio = len(novel_molecules) / len(smiles_list)
607:     return novel_ratio

FILE src/utils/metrics_utils.py FUNCTION bemisMurcoScaffold
701: def bemisMurcoScaffold(smiles_list):
702:     # Set to store unique scaffolds
703:     unique_scaffolds = set()
704: 
705:     for smiles in smiles_list:
706:         mol = Chem.MolFromSmiles(smiles)
707:         if mol:
708:             # Get the Bemis-Murcko scaffold
709:             scaffold = MurckoScaffold.GetScaffoldForMol(mol)
710:             # Convert scaffold to SMILES to check uniqueness
711:             scaffold_smiles = Chem.MolToSmiles(scaffold)
712:             unique_scaffolds.add(scaffold_smiles)
713: 
714:     # Calculate chemical space coverage
715:     coverage = len(unique_scaffolds)
716: 
717:     return coverage

FILE src/agfn/sampling.py FUNCTION remove_duplicates
30: def remove_duplicates(smiles_list, reference_smiles=None, stereo=False):
31:     """
32:     Remove duplicate SMILES based on their InChI keys.
33: 
34:     Parameters:
35:     smiles_list: list of SMILES strings to process.
36:     reference_smiles: list of reference SMILES (duplicates compared to these will be removed).
37:     stereo: If True, consider stereochemistry and isotopes during duplicate detection.
38: 
39:     Returns:
40:     A tuple of (unique_smiles, duplicates) where:
41:     - unique_smiles: list of unique SMILES
42:     - duplicates: list of tuples (original_smiles, duplicate_smiles)
43:     """
44:     d = dict()  # key: InChI key, value: list of SMILES
45:     unique_smiles = []
46:     duplicates = []
47: 
48:     # Convert reference SMILES to InChI keys if provided
49:     if reference_smiles is not None:
50:         for smiles in reference_smiles:
51:             mol = Chem.MolFromSmiles(smiles)
52:             if mol:
53:                 inchi_key = get_inchi_key(mol, stereo)
54:                 d[inchi_key] = [smiles]
55: 
56:     # Process input SMILES
57:     for smiles in smiles_list:
58:         mol = Chem.MolFromSmiles(smiles)
59:         if mol:
60:             inchi_key = get_inchi_key(mol, stereo)
61:             if inchi_key not in d:
62:                 d[inchi_key] = [smiles]
63:                 unique_smiles.append(smiles)
64:             else:
65:                 d[inchi_key].append(smiles)
66:                 duplicates.append((d[inchi_key][0], smiles))  # Add first encountered SMILES and current duplicate
67: 
68:     return unique_smiles, duplicates

FILE src/agfn/sampling.py FUNCTION sample_smiles
143:     def sample_smiles(self, n_trajs, bs=32, dedup=True, save_dir="./data/gfn_samples/smiles_checkpoints"):
144:         os.makedirs(save_dir, exist_ok=True)
145: 
146:         all_smiles = []
147:         all_mols = []
148:         seen_smiles = set()
149: 
150:         pbar = tqdm(total=n_trajs, desc="Sampling unique SMILES", dynamic_ncols=True)
151: 
152:         # Checkpointing config only if n_trajs > 1000
153:         enable_checkpointing = n_trajs > 1000
154:         percent_interval = 10
155:         next_save_threshold = percent_interval
156:         last_saved_file = None
157: 
158:         while len(all_smiles) < n_trajs:
159:             current_bs = min(bs, n_trajs - len(all_smiles))
160:             cond_info = self.cond_info_cmp.compute_cond_info_forward(current_bs)
161:             cond_info_encoding = self.cond_info_cmp.thermometer_encoding(cond_info).to(self.device)
162: 
163:             cur_result = self.graph_sampler.sample_from_model(
164:                 self.model,
165:                 current_bs,
166:                 cond_info_encoding,
167:                 self.device,
168:                 random_stop_action_prob=self.hps['random_stop_prob'],
169:                 random_action_prob=self.hps['random_action_prob'],
170:                 seed_graph=self.seed_graph
171:             )
172: 
173:             valid_idcs = [
174:                 i for i in range(len(cur_result))
175:                 if cur_result[i]["is_valid"] and "fwd_logprob" in cur_result[i]
176:             ]
177: 
178:             mols = [self.ctx.graph_to_mol(cur_result[i]['traj'][-1][0]) for i in valid_idcs]
179:             smiles = [Chem.MolToSmiles(mol) for mol in mols]
180: 
181:             if dedup:
182:                 unique_smiles, _ = remove_duplicates(smiles, reference_smiles=all_smiles, stereo=False)
183:                 mols = [mol for smi, mol in zip(smiles, mols) if smi in unique_smiles]
184:                 smiles = unique_smiles
185: 
186:             added = 0
187:             for smi, mol in zip(smiles, mols):
188:                 if len(all_smiles) >= n_trajs:
189:                     break
190:                 if smi not in seen_smiles:
191:                     seen_smiles.add(smi)
192:                     all_smiles.append(smi)
193:                     all_mols.append(mol)
194:                     added += 1
195: 
196:             pbar.update(added)
197: 
198:             # Checkpoint saving if enabled
199:             if enable_checkpointing:
200:                 current_percent = int(100 * len(all_smiles) / n_trajs)
201:                 if current_percent >= next_save_threshold:
202:                     checkpoint_path = os.path.join(save_dir, f"smiles_{next_save_threshold}pct.pkl")
203:                     with open(checkpoint_path, "wb") as f:
204:                         pickle.dump(all_smiles, f)
205: 
206:                     if last_saved_file and os.path.exists(last_saved_file):
207:                         os.remove(last_saved_file)
208: 
209:                     last_saved_file = checkpoint_path
210:                     next_save_threshold += percent_interval
211: 
212:         pbar.close()
213: 
214:         # Save final full SMILES list
215:         final_path = os.path.join(save_dir, "smiles_final.pkl")
216:         with open(final_path, "wb") as f:
217:             pickle.dump(all_smiles, f)
218:         print(f'Saved {len(all_smiles)} samples to ./data/gfn_samples/smiles_checkpoints/smiles_final.pkl')
219:         return all_mols, all_smiles

FILE src/agfn/metrics.py FUNCTION metrics_pre_prep
10: def metrics_pre_prep(args):
11:     loaded_dict = torch.load(args.model_path,map_location='cpu')
12:     hps = loaded_dict['hps']
13:     cond_prop_var= {
14:             'tpsa':20,
15:             'num_rings':1,
16:             'sas':1,
17:             'qed':1,
18:             }
19:     conditional_range_dict = dict()
20:     for k in cond_prop_var:
21:         conditional_range_dict[k] = hps[k]
22: 
23:     reward_ft =  RewardFineTune(conditional_range_dict,None, cond_prop_var, hps["reward_aggergation"], hps['atomenv_dictionary'], hps['zinc_rad_scale'], hps)
24: 
25:     sampler = Sampler(args.model_path)
26:     sampled_mols, sampled_smiles = sampler.sample_smiles(args.ntrajs)
27:     
28:     online_rew_tup = reward_ft.molecular_rewards(sampled_mols)
29:     online_rew = torch.Tensor(online_rew_tup[2]).unsqueeze(dim=1)
30:     normalized_task_rew_online, true_task_score_online = reward_ft.task_reward(hps.task, reward_ft.task_model, sampled_mols) #for TDC
31: 
32:     if hps.task_rewards_only:
33:         flat_rewards_online =  torch.Tensor(normalized_task_rew_online)
34:     else:
35:         flat_rewards_online = online_rew*normalized_task_rew_online
36: 
37:     
38:     res = {}
39:     res['normalized_moo_rew']= online_rew_tup[0] if  hps.objective=='property_targeting' else np.hstack([online_rew_tup[0],normalized_task_rew_online]) 
40:     res['overall_rew'] = flat_rewards_online
41:     res['generated_smiles_list'] = sampled_smiles
42:     res['pretrain_conditionals']= conditional_range_dict
43:     res['task_conditionals'] = {hps['task']: [hps.task_possible_range, hps.task_possible_range, hps.pref_dir]} #task_conditional_range_dict if task_conditional_range_dict else {}
44:     res['hps']= hps
45:     
46:     return res

FILE src/gflownet/algo/tb_loss.py FUNCTION compute_batch_losses
4: def compute_batch_losses(algo, gfn_trainer, batch, dev, hps, num_bootstrap: int = 0):
5:         """Compute the losses over trajectories contained in the batch
6: 
7:         Parameters
8:         ----------
9:         model: TrajectoryBalanceModel
10:            A GNN taking in a batch of graphs as input as per constructed by `self.construct_batch`.
11:            Must have a `logZ` attribute, itself a model, which predicts log of Z(cond_info)
12:         batch: gd.Batch
13:           batch of graphs inputs as per constructed by `self.construct_batch`
14:         num_bootstrap: int
15:           the number of trajectories for which the reward loss is computed. Ignored if 0.
16:         t : int
17:           iteration number"""
18:         # A single trajectory is comprised of many graphs
19:         num_trajs = int(batch.traj_lens.shape[0])
20:         # print('tbloss.py num_trajs', num_trajs)
21:         log_rewards = batch.log_rewards
22:         # print('TBloss.py log_rewawrds', log_rewards, log_rewards.shape)
23:         # Clip rewards
24:         assert log_rewards.ndim == 1
25:         clip_log_R = torch.maximum(log_rewards, torch.tensor(algo.illegal_action_logreward, device=dev)).float()
26:         invalid_mask = 1 - batch.is_valid
27:         # This index says which trajectory each graph belongs to, so
28:         # it will look like [0,0,0,0,1,1,1,2,...] if trajectory 0 is
29:         # of length 4, trajectory 1 of length 3, and so on.
30:         batch_idx = torch.arange(num_trajs, device=dev).repeat_interleave(batch.traj_lens)
31:         # The position of the first graph of each trajectory
32:         first_graph_idx = torch.zeros_like(batch.traj_lens)
33:         torch.cumsum(batch.traj_lens[:-1], 0, out=first_graph_idx[1:])
34:         # The position of the last graph of each trajectory
35:         final_graph_idx = torch.cumsum(batch.traj_lens, 0) - 1
36: 
37:         # Forward pass of the model, returns a GraphActionCategorical representing the forward
38:         # policy P_F, optionally a backward policy P_B, and per-graph outputs (e.g. F(s) in SubTB).
39:         if algo.p_b_is_parameterized:
40:             fwd_cat, bck_cat, per_graph_out, logZ_forward = gfn_trainer.model(batch)
41:         else:
42:             fwd_cat, per_graph_out, logZ_forward = gfn_trainer.model(batch)
43: 
44:         # Compute trajectory balance objective
45:         # log_Z = gfn_trainer.model.module.logZ(cond_info)[:, 0]
46:         # print('cond_info ',cond_info.shape, ' module logZ ',gfn_trainer.model.module.logZ(cond_info).shape)
47:         log_Z = logZ_forward[first_graph_idx]  # gfn_trainer.model.logZ_forward#(cond_info)[:, 0]
48:         # Compute the log prob of each action in the trajectory
49:         if algo.correct_idempotent:
50:             # If we want to correct for idempotent actions, we need to sum probabilities
51:             # i.e. to compute P(s' | s) = sum_{a that lead to s'} P(a|s)
52:             # here we compute the indices of the graph that each action corresponds to, ip_lens
53:             # contains the number of idempotent actions for each transition, so we
54:             # repeat_interleave as with batch_idx
55:             ip_batch_idces = torch.arange(batch.ip_lens.shape[0], device=dev).repeat_interleave(batch.ip_lens)
56:             # Indicate that the `batch` corresponding to each action is the above
57:             ip_log_prob = fwd_cat.log_prob(batch.ip_actions, batch=ip_batch_idces)
58:             # take the logsumexp (because we want to sum probabilities, not log probabilities)
59:             # TODO: numerically stable version:
60:             p = scatter(ip_log_prob.exp(), ip_batch_idces, dim=0, dim_size=batch_idx.shape[0], reduce="sum")
61:             # As a (reasonable) band-aid, ignore p < 1e-30, this will prevent underflows due to
62:             # scatter(small number) = 0 on CUDA
63:             log_p_F = p.clamp(1e-30).log()
64: 
65:             if algo.p_b_is_parameterized:
66:                 # Now we repeat this but for the backward policy
67:                 bck_ip_batch_idces = torch.arange(batch.bck_ip_lens.shape[0], device=dev).repeat_interleave(
68:                     batch.bck_ip_lens
69:                 )
70:                 bck_ip_log_prob = bck_cat.log_prob(batch.bck_ip_actions, batch=bck_ip_batch_idces)
71:                 bck_p = scatter(
72:                     bck_ip_log_prob.exp(), bck_ip_batch_idces, dim=0, dim_size=batch_idx.shape[0], reduce="sum"
73:                 )
74:                 log_p_B = bck_p.clamp(1e-30).log()
75:         else:
76:             # Else just naively take the logprob of the actions we took
77:             log_p_F = fwd_cat.log_prob(batch.actions)
78:             if algo.p_b_is_parameterized:
79:                 log_p_B = bck_cat.log_prob(batch.bck_actions)
80: 
81:         if algo.p_b_is_parameterized:
82:             # If we're modeling P_B then trajectories are padded with a virtual terminal state sF,
83:             # zero-out the logP_F of those states
84:             log_p_F[final_graph_idx] = 0
85:             if algo.is_doing_subTB:
86:                 # Force the pad states' F(s) prediction to be R
87:                 per_graph_out[final_graph_idx, 0] = clip_log_R
88: 
89:             # To get the correct P_B we need to shift all predictions by 1 state, and ignore the
90:             # first P_B prediction of every trajectory.
91:             # Our batch looks like this:
92:             # [(s1, a1), (s2, a2), ..., (st, at), (sF, None),   (s1, a1), ...]
93:             #                                                   ^ new trajectory begins
94:             # For the P_B of s1, we need the output of the model at s2.
95: 
96:             # We also have access to the is_sink attribute, which tells us when P_B must = 1, which
97:             # we'll use to ignore the last padding state(s) of each trajectory. This by the same
98:             # occasion masks out the first P_B of the "next" trajectory that we've shifted.
99:             log_p_B = torch.cat([log_p_B[1:], log_p_B[:1]]) * (1 - batch.is_sink)
100:         else:
101:             log_p_B = batch.log_p_B
102:             print('tbloss logpb ', log_p_B, log_p_B.shape)
103:             print('tbloss logpF ', log_p_F, log_p_F.shape)
104:         assert log_p_F.shape == log_p_B.shape
105: 
106:         # This is the log probability of each trajectory
107:         traj_log_p_F = scatter(log_p_F, batch_idx, dim=0, dim_size=num_trajs, reduce="sum")
108:         traj_log_p_B = scatter(log_p_B, batch_idx, dim=0, dim_size=num_trajs, reduce="sum")
109:         
110:         if (gfn_trainer.hps['offline_data']) and (gfn_trainer.hps['MLE_coeff']>0):
111:             mle_loss = -traj_log_p_F[batch.num_sub_online_trajs:]#.mean()  #num_sub_online_trajs: = sub offline trajectories
112:         else:
113:             mle_loss = 0
114: 
115:         if algo.is_doing_subTB:
116:             # SubTB interprets the per_graph_out predictions to predict the state flow F(s)
117:             traj_losses = self.subtb_loss_fast(log_p_F, log_p_B, per_graph_out[:, 0], clip_log_R, batch.traj_lens)
118:             # The position of the first graph of each trajectory
119:             first_graph_idx = torch.zeros_like(batch.traj_lens)
120:             first_graph_idx = torch.cumsum(batch.traj_lens[:-1], 0, out=first_graph_idx[1:])
121:             log_Z = per_graph_out[first_graph_idx, 0]
122:         else:
123:             # Compute log numerator and denominator of the TB objective
124:             # print(f'logZ {logZ.shape} traj_log_p_F {traj_log_p_F.shape}')
125:             numerator = log_Z + traj_log_p_F
126:             denominator = clip_log_R + traj_log_p_B
127: 
128:             if algo.mask_invalid_rewards:
129:                 # Instead of being rude to the model and giving a
130:                 # logreward of -100 what if we say, whatever you think the
131:                 # logprobablity of this trajetcory is it should be smaller
132:                 # (thus the `numerator - 1`). Why 1? Intuition?
133:                 denominator = denominator * (1 - invalid_mask) + invalid_mask * (numerator.detach() - 1)
134: 
135:             if algo.epsilon is not None:
136:                 # Numerical stability epsilon
137:                 epsilon = torch.tensor([algo.epsilon], device=dev).float()
138:                 numerator = torch.logaddexp(numerator, epsilon)
139:                 denominator = torch.logaddexp(denominator, epsilon)
140:             if algo.tb_loss_is_mae:
141:                 traj_losses = abs(numerator - denominator)
142:             elif algo.tb_loss_is_huber:
143:                 pass  # TODO
144:             else:
145:                 traj_losses = (numerator - denominator).pow(2)
146: 
147:         # Normalize losses by trajectory length
148:         if algo.length_normalize_losses:
149:             traj_losses = traj_losses / batch.traj_lens
150:         if algo.reward_normalize_losses:
151:             # multiply each loss by how important it is, using R as the importance factor
152:             # factor = Rp.exp() / Rp.exp().sum()
153:             factor = -clip_log_R.min() + clip_log_R + 1
154:             factor = factor / factor.sum()
155:             assert factor.shape == traj_losses.shape
156:             # * num_trajs because we're doing a convex combination, and a .mean() later, which would
157:             # undercount (by 2N) the contribution of each loss
158:             traj_losses = factor * traj_losses * num_trajs
159: 
160:         if algo.bootstrap_own_reward:
161:             num_bootstrap = num_bootstrap or len(log_rewards)
162:             if algo.reward_loss_is_mae:
163:                 reward_losses = abs(log_rewards[:num_bootstrap] - log_reward_preds[:num_bootstrap])
164:             else:
165:                 reward_losses = (log_rewards[:num_bootstrap] - log_reward_preds[:num_bootstrap]).pow(2)
166:             reward_loss = reward_losses.mean()
167:         else:
168:             reward_loss = 0
169: 
170:         # mle_min, mle_max = 0, 500 #  min(mle_loss), max(mle_loss)
171:         # gfn_min, gfn_max = 0, 120000 #min(traj_losses), max(traj_losses)
172: 
173:         # gfn_scaled = (traj_losses - gfn_min)/(gfn_max - gfn_min)
174:         # mle_scaled = (mle_loss - mle_min)/(mle_max - mle_min)
175: 
176:         # loss = (gfn_trainer.hps['gfn_lambda'])*gfn_scaled.mean()  + (1-gfn_trainer.hps['gfn_lambda'])*mle_scaled.mean()
177:         if gfn_trainer.hps['MLE_coeff']>0:
178:             loss = gfn_trainer.hps['gfn_loss_coeff']*traj_losses.mean() + gfn_trainer.hps['MLE_coeff']*mle_loss.mean()
179:         else:
180:             loss = gfn_trainer.hps['gfn_loss_coeff']*traj_losses.mean() 
181: 
182:         # print('tbloss loss ', loss)
183: 
184:         # loss = gfn_trainer.hps['gfn_loss_coeff']*traj_losses.mean()*t**(0.33) + reward_loss * algo.reward_loss_multiplier + gfn_trainer.hps['MLE_coeff']*mle_loss*t**(-0.33)
185:         # loss = gfn_trainer.hps['gfn_loss_coeff']*traj_losses.mean() + reward_loss * algo.reward_loss_multiplier + gfn_trainer.hps['MLE_coeff']*mle_loss
186: 
187:         # print('tbloss.py fltgfn loss ',traj_losses.mean(), ' flatmle loss ',mle_loss)
188:         info = {
189:             "offline_loss": traj_losses[: batch.num_offline].mean().item() if batch.num_offline > 0 else 0,
190:             "online_loss": traj_losses[batch.num_offline :].mean().item() if batch.num_online > 0 else 0,
191:             # "reward_loss": reward_loss,
192:             "invalid_trajectories": (invalid_mask.sum() / batch.num_online).item() if batch.num_online > 0 else 0,
193:             "invalid_logprob": ((invalid_mask * traj_log_p_F).sum() / (invalid_mask.sum() + 1e-4)).item(),
194:             "invalid_losses": ((invalid_mask * traj_losses).sum() / (invalid_mask.sum() + 1e-4)).item(),
195:             "logZ": log_Z.mean().item(),
196:             "loss": loss.item(),
197:             "mle_loss":mle_loss.mean().item() if gfn_trainer.hps['MLE_coeff']>0 else 0,
198:             "total_gfn_loss":traj_losses.mean().item(),
199:             # "total_gfn_loss_scaled":gfn_scaled.mean().item(),
200:             # "mle_loss_scaled": mle_scaled.mean().item() if gfn_trainer.hps['MLE_coeff']>0 else 0,
201:         }
202:         # print('tb loss.py info ', info)
203: 
204:         return loss, info

FILE src/gflownet/algo/rtb_loss.py FUNCTION compute_batch_losses
4: def compute_batch_losses(algo, gfn_trainer, batch, dev, t, num_bootstrap: int = 0):
5:     num_trajs = int(batch.traj_lens.shape[0])
6:     # print('rtbloss.py compte_batch_loss batch ', batch.__dict__.keys())
7:     log_rewards = batch.log_rewards
8:     # print('TBloss.py log_rewawrds', log_rewards, log_rewards.shape)
9:     # Clip rewards
10:     assert log_rewards.ndim == 1
11:     clip_log_R = torch.maximum(log_rewards, torch.tensor(algo.illegal_action_logreward, device=dev)).float()
12:     invalid_mask = 1 - batch.is_valid
13:     # This index says which trajectory each graph belongs to, so
14:     # it will look like [0,0,0,0,1,1,1,2,...] if trajectory 0 is
15:     # of length 4, trajectory 1 of length 3, and so on.
16:     batch_idx = torch.arange(num_trajs, device=dev).repeat_interleave(batch.traj_lens)
17:     # The position of the first graph of each trajectory
18:     first_graph_idx = torch.zeros_like(batch.traj_lens)
19:     torch.cumsum(batch.traj_lens[:-1], 0, out=first_graph_idx[1:])
20:     # The position of the last graph of each trajectory
21:     final_graph_idx = torch.cumsum(batch.traj_lens, 0) - 1
22: 
23:     # Forward pass of the model, returns a GraphActionCategorical representing the forward
24:     # policy P_F, optionally a backward policy P_B, and per-graph outputs (e.g. F(s) in SubTB).
25:     
26:     fwd_cat_post, logZ_forward_post = gfn_trainer.model(batch)
27:     # logZ_forward_post = logZ_forward_post[:,0]
28:     log_Z = logZ_forward_post[first_graph_idx]
29:     log_p_F = fwd_cat_post.log_prob(batch.actions)  
30: 
31: 
32:     # This is the log probability of each trajectory
33:     traj_log_p_F = scatter(log_p_F, batch_idx, dim=0, dim_size=num_trajs, reduce="sum")
34: 
35:     if (gfn_trainer.hps['offline_data']) and (gfn_trainer.hps['MLE_coeff']>0):
36:         mle_loss = -traj_log_p_F[batch.num_sub_online_trajs:]#.mean()  #num_sub_online_trajs: = sub offline trajectories
37:     else:
38:         mle_loss = 0
39: 
40:     with torch.no_grad():
41:         fwd_cat_prior = gfn_trainer.model_prior(batch)
42:     log_p_F_prior = fwd_cat_prior.log_prob(batch.actions)
43:     traj_log_p_F_prior = scatter(log_p_F_prior, batch_idx, dim=0, dim_size=num_trajs, reduce="sum")
44:     
45:     numerator = log_Z + traj_log_p_F
46:     denominator = traj_log_p_F_prior + clip_log_R
47: 
48:     if gfn_trainer.hps['vargrad']:
49:         numerator = log_Z_hat = -traj_log_p_F + traj_log_p_F_prior + clip_log_R
50:         denominator = log_Z_hat.mean()
51: 
52:     if algo.mask_invalid_rewards:
53:         # Instead of being rude to the model and giving a
54:         # logreward of -100 what if we say, whatever you think the
55:         # logprobablity of this trajetcory is it should be smaller
56:         # (thus the `numerator - 1`). Why 1? Intuition?
57:         denominator = denominator * (1 - invalid_mask) + invalid_mask * (numerator.detach() - 1)
58: 
59:     if algo.epsilon is not None:
60:         # Numerical stability epsilon
61:         epsilon = torch.tensor([algo.epsilon], device=dev).float()
62:         numerator = torch.logaddexp(numerator, epsilon)
63:         denominator = torch.logaddexp(denominator, epsilon)
64:     if algo.tb_loss_is_mae:
65:         traj_losses = abs(numerator - denominator)
66:     elif algo.tb_loss_is_huber:
67:         pass  # TODO
68:     else:
69:         if gfn_trainer.hps['vargrad']:
70:             traj_losses = (numerator - denominator).pow(2)#.mean()
71:         else:
72:             traj_losses = (numerator - denominator).pow(2)
73:         # print('rtbloss.py trajlosses ', traj_losses, traj_losses.shape)
74: 
75:     # Normalize losses by trajectory length
76:     if algo.length_normalize_losses:
77:         traj_losses = traj_losses / batch.traj_lens
78:     if algo.reward_normalize_losses:
79:         # multiply each loss by how important it is, using R as the importance factor
80:         # factor = Rp.exp() / Rp.exp().sum()
81:         factor = -clip_log_R.min() + clip_log_R + 1
82:         factor = factor / factor.sum()
83:         assert factor.shape == traj_losses.shape
84:         # * num_trajs because we're doing a convex combination, and a .mean() later, which would
85:         # undercount (by 2N) the contribution of each loss
86:         traj_losses = factor * traj_losses * num_trajs
87: 
88:     if (gfn_trainer.hps['offline_data']) and (gfn_trainer.hps['MLE_coeff']>0):
89:         loss = gfn_trainer.hps['gfn_loss_coeff']*traj_losses.mean() + gfn_trainer.hps['MLE_coeff']*mle_loss.mean()
90:     else:
91:         loss = gfn_trainer.hps['gfn_loss_coeff']*traj_losses.mean() 
92: 
93:     info = {
94:             "offline_loss": traj_losses[: batch.num_offline].mean().item() if batch.num_offline > 0 else 0,
95:             "online_loss": traj_losses[batch.num_offline :].mean().item() if batch.num_online > 0 else 0,
96:             # "reward_loss": reward_loss,
97:             "invalid_trajectories": (invalid_mask.sum() / batch.num_online).item() if batch.num_online > 0 else 0,
98:             "invalid_logprob": ((invalid_mask * traj_log_p_F).sum() / (invalid_mask.sum() + 1e-4)).item(),
99:             "invalid_losses": ((invalid_mask * traj_losses).sum() / (invalid_mask.sum() + 1e-4)).item(),
100:             "logZ": log_Z.mean(),#.item(),
101:             "loss": loss.item(),
102:             "mle_loss":mle_loss.mean().item() if (gfn_trainer.hps['offline_data']) and (gfn_trainer.hps['MLE_coeff']>0) else 0,
103:             "total_gfn_loss":traj_losses.mean().item(),
104: 
105:         }
106: 
107:     return loss, info