dicee.models.graph_model
Shared graph-conditioned model support, extracted from the DICE ULTRA implementation.
Architecture and graph construction adapted from https://github.com/DeepGraphLearning/ULTRA at commit 427966ad8ed60420eef034063d44f3153addff90. Reference fixtures and the grouped sampling and adversarial loss implementations also follow this upstream work. Graphs are runtime context, excluded from the transferable state dictionary.
MIT License
Copyright (c) 2023 MilaGraph
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Classes
Shared graph lifecycle and entity-scoring interfaces for graph foundation models. |
|
Shared relation prediction API with (head, tail) query pairs. |
Module Contents
- class dicee.models.graph_model.GraphKGE(args)[source]
Bases:
dicee.models.base_model.BaseKGEShared graph lifecycle and entity-scoring interfaces for graph foundation models.
- name = 'GraphKGE'
- config_prefix = 'graph'
- graph_filename = 'graph.pt'
- checkpoint_hint = 'all keys and shapes must match'
- deterministic_inference = False
- query_batch_size
- num_direct_relations = 0
- train(mode=True)[source]
Set the module in training mode.
This has an effect only on certain modules. See the documentation of particular modules for details of their behaviors in training/evaluation mode, i.e., whether they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- init_entity_embeddings(embedding_dim=None)[source]
Create (or re-create) the entity embedding table.
This is the single place that honours
defer_large_embeddings: when entity rows are sharded across FSDP ranks the table must stayNoneuntil the trainer allocates the sharded adapter. Subclasses that need an entity table of a non-default width must call this method instead of assigningself.entity_embeddingsdirectly, so the deferral is never silently undone.- Parameters:
embedding_dim (Optional[int]) – Width of the table. Defaults to
embedding_dim.
- init_relation_embeddings(embedding_dim=None)[source]
Create (or re-create) the relation embedding table.
Relation tables are never deferred - they are small enough to be replicated on every rank.
- Parameters:
embedding_dim (Optional[int]) – Width of the table. Defaults to
embedding_dim.
- abstractmethod get_embeddings()[source]
Return the entity and relation embedding matrices as numpy arrays.
- Returns:
entity_embeddings (numpy.ndarray) – Shape
(num_entities, embedding_dim).relation_embeddings (numpy.ndarray) – Shape
(num_relations, embedding_dim).
- set_graph(triples, num_entities=None, num_relations=None, inverse_relations=None)[source]
Attach training facts; inverse_relations maps direct DICE IDs to inverse IDs.
Without a mapping every supplied relation is treated as a direct relation. Repeated facts and explicitly supplied inverse facts are deduplicated.
- forward_triples(x)[source]
Score a batch of
(head, relation, tail)index triples.- Parameters:
x (torch.LongTensor) – Shape
(batch_size, 3)integer tensor where each row is[head_idx, relation_idx, tail_idx].- Returns:
Shape
(batch_size,)triple scores.- Return type:
torch.FloatTensor
- forward_k_vs_sample(x, target_entity_idx)[source]
Score a
(head, relation)batch against a sampled subset of entities.Used by
KvsSampleand1vsSampledatasets. Sub-classes that support sample-based labelling must override this method.- Returns:
Shape
(batch_size, k)score matrix where k is the number of sampled target entities.- Return type:
torch.FloatTensor
- forward_k_vs_all(x)[source]
Score a
(head, relation)batch against every entity.Sub-classes must override this method. The default implementation raises
ValueErrorto make missing overrides obvious at runtime.- Returns:
Shape
(batch_size, num_entities)score matrix.- Return type:
torch.FloatTensor
- forward_k_vs_all_heads(x, target_entity_idx=None)[source]
Score head candidates for DICE pairs (relation, tail).
- forward(x, y_idx=None)[source]
Route the forward pass to the appropriate scoring method.
Inspects the shape and type of x to decide which low-level scorer to call:
Tuple
(x, y_idx)→forward_k_vs_sample()(batch, 3)tensor →forward_triples()(batch, 2)tensor →forward_k_vs_all()BPE triple tensor →
forward_byte_pair_encoded_triple()BPE pair tensor →
forward_byte_pair_encoded_k_vs_all()
- Parameters:
x (torch.LongTensor or Tuple[torch.LongTensor, torch.LongTensor]) – Either a plain index tensor or a
(triple_idx, target_idx)tuple for sample-based labelling.y_idx (torch.LongTensor, optional) – Target entity indices used by
forward_k_vs_sample(). Ignored when x is a plain tensor.
- Returns:
Score tensor whose shape depends on the selected scorer.
- Return type:
torch.FloatTensor
- class dicee.models.graph_model.RelationGraphKGE(args)[source]
Bases:
GraphKGEShared relation prediction API with (head, tail) query pairs.
- forward_triples(x)[source]
Score a batch of
(head, relation, tail)index triples.- Parameters:
x (torch.LongTensor) – Shape
(batch_size, 3)integer tensor where each row is[head_idx, relation_idx, tail_idx].- Returns:
Shape
(batch_size,)triple scores.- Return type:
torch.FloatTensor
- forward_k_vs_sample(x, target_entity_idx)[source]
Score relation candidates [K] or [B,K] for (head, tail) pairs.
- forward_k_vs_all(x)[source]
Score a
(head, relation)batch against every entity.Sub-classes must override this method. The default implementation raises
ValueErrorto make missing overrides obvious at runtime.- Returns:
Shape
(batch_size, num_entities)score matrix.- Return type:
torch.FloatTensor
- forward_k_vs_all_relations