KGATE 0.2.3__tar.gz → 0.2.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: KGATE
3
- Version: 0.2.3
3
+ Version: 0.2.5
4
4
  Summary: Knowledge Graph Autoencoder Training Environment, bridging PyG encoders and TorchKGE decoders.
5
5
  License: MIT
6
6
  Keywords: Knowledge Graph,Knowledge Graph Embedding,Autoencoder,Machine Learning,Link Prediction
@@ -15,6 +15,7 @@ Requires-Dist: optuna (>=4.2.1,<5.0.0)
15
15
  Requires-Dist: pytest (>=8.3.4,<9.0.0)
16
16
  Requires-Dist: pytorch-ignite (>=0.5.1,<0.6.0)
17
17
  Requires-Dist: pyyaml (>=6.0.2,<7.0.0)
18
+ Requires-Dist: tomli-w (>=1.2.0,<2.0.0)
18
19
  Requires-Dist: torch-geometric (>=2.6.1,<3.0.0)
19
20
  Requires-Dist: torchkge (>=0.17.7,<0.18.0)
20
21
  Project-URL: Repository, https://github.com/BAUDOTlab/KGATE
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "KGATE"
3
- version = "0.2.3"
3
+ version = "0.2.5"
4
4
  description = "Knowledge Graph Autoencoder Training Environment, bridging PyG encoders and TorchKGE decoders."
5
5
  authors = [
6
6
  {name = "Benjamin Loire", email = "benjamin.loire@univ-amu.fr"},
@@ -41,3 +41,4 @@ pytorch-ignite = "^0.5.1"
41
41
  pyyaml = "^6.0.2"
42
42
  pytest = "^8.3.4"
43
43
  optuna = "^4.2.1"
44
+ tomli-w = "^1.2.0"
@@ -122,7 +122,6 @@ class LinkPredictionEvaluator(eval.LinkPredictionEvaluator):
122
122
  self.filt_rank_true_tails = self.filt_rank_true_tails.to(device)
123
123
  edgelist = knowledge_graph.edgelist.to(device)
124
124
 
125
- embeddings = node_embeddings.weight.data
126
125
 
127
126
  for i, batch in tqdm(enumerate(dataloader), total=len(dataloader),
128
127
  unit="batch", disable=(not verbose),
@@ -143,9 +142,13 @@ class LinkPredictionEvaluator(eval.LinkPredictionEvaluator):
143
142
 
144
143
  input = knowledge_graph.get_encoder_input(edgelist[:, edge_mask], node_embeddings)
145
144
  encoder_output: Dict[str, Tensor] = encoder(input.x_dict, input.edge_index)
146
-
145
+
146
+ embeddings: torch.Tensor = torch.zeros((knowledge_graph.n_ent, decoder.emb_dim), device=device, dtype=torch.float)
147
+
147
148
  for node_type, idx in input.mapping.items():
148
149
  embeddings[idx] = encoder_output[node_type]
150
+ else:
151
+ embeddings = node_embeddings.weight.data
149
152
 
150
153
  h_emb, t_emb, r_emb, candidates = decoder.inference_prepare_candidates(h_idx = h_idx,
151
154
  t_idx = t_idx,
@@ -1,4 +1,5 @@
1
1
  import os
2
+ from glob import glob
2
3
  from inspect import signature
3
4
  from pathlib import Path
4
5
  from torchkge import KnowledgeGraph
@@ -9,7 +10,7 @@ from torch import tensor, long, stack, Tensor
9
10
  from torch.nn import Parameter
10
11
  from torch.nn.functional import normalize
11
12
  from torch.utils.data import DataLoader
12
- from .utils import parse_config, load_knowledge_graph, set_random_seeds, find_best_model, merge_kg, init_embedding, plot_learning_curves
13
+ from .utils import parse_config, load_knowledge_graph, set_random_seeds, find_best_model, merge_kg, init_embedding, plot_learning_curves, save_config
13
14
  from .preprocessing import prepare_knowledge_graph, SUPPORTED_SEPARATORS
14
15
  from .encoders import *
15
16
  from .decoders import *
@@ -564,6 +565,17 @@ class Architect(Model):
564
565
  trainer = trainer
565
566
  )
566
567
 
568
+ # If we find an identical config we resume training from it, otherwise we clean the checkpoints directory.
569
+ existing_config_path: Path = Path(self.config["output_directory"]).joinpath("kgate_conf.toml")
570
+ if existing_config_path.exists():
571
+ existing_config = parse_config(str(existing_config_path), {})
572
+ if existing_config == self.config:
573
+ all_checkpoints = glob(f"{self.checkpoints_dir}/checkpoint_*.pt")
574
+ checkpoint_file = checkpoint_file or Path(max(all_checkpoints, key=os.path.getctime))
575
+ logging.info("Found previous run with the same parameters in the output folder... ")
576
+ elif self.checkpoints_dir.exists() and len(os.listdir(self.checkpoints_dir)) > 0:
577
+ self.checkpoints_dir.unlink()
578
+
567
579
  # trainer.add_event_handler(Events.EPOCH_STARTED, self.encoder_pass)
568
580
 
569
581
  trainer.add_event_handler(Events.EPOCH_COMPLETED, self.log_metrics_to_csv)
@@ -633,6 +645,7 @@ class Architect(Model):
633
645
  to_save
634
646
  )
635
647
 
648
+ save_config(self.config)
636
649
 
637
650
  if checkpoint_file is not None:
638
651
  if Path(checkpoint_file).is_file():
@@ -6,6 +6,7 @@ import pandas as pd
6
6
  import numpy as np
7
7
  from pathlib import Path
8
8
  import tomllib
9
+ import tomli_w
9
10
  import random
10
11
  import logging
11
12
  import pickle
@@ -81,6 +82,23 @@ def set_config_key(key: str, default: dict, config: dict | None = None, inline:
81
82
  else:
82
83
  return inline_value
83
84
 
85
+ def save_config(config:dict, filename:Path | None = None):
86
+ """Saves the Architect configuration as a TOML file.
87
+
88
+ If no filename is given, it will be created as config.output_directory/kgate_config.toml.
89
+
90
+ Parameters
91
+ ----------
92
+ config: dict
93
+ The parsed config as a python dictionnary.
94
+ filename: Path (optional)
95
+ The complete path to the configuration file. If one already exists, it will be overwritten."""
96
+
97
+ config_path = filename or Path(config["output_directory"]).joinpath("kgate_config.toml")
98
+
99
+ with open(config_path, "wb") as f:
100
+ tomli_w.dump(config,f)
101
+
84
102
  def load_knowledge_graph(pickle_filename: Path) -> Tuple[KnowledgeGraph, KnowledgeGraph, KnowledgeGraph]:
85
103
  """Load the knowledge graph from pickle files."""
86
104
  logging.info(f"Will not run the preparation step. Using KG stored in: {pickle_filename}")
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes