forked from Refefer/cloverleaf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
4694 lines (4232 loc) · 142 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! This is the main interface for Cloverleaf
//! It has tight coupling to python, specifically as the lingua franca of the machine learning
//! world. Consequently, this coupling has a couple of nuances that limit cloverleaf's ability
//! as a standalone module but that's ok :)
/// Main interface for defining graphs
pub mod graph;
/// We define all the algorithms within this module
pub mod algos;
/// How can we efficiently sample from the graph?
mod sampler;
/// Maps node types, node names to internal IDs and back
mod vocab;
/// Where we store embeddings. These are both node and feature embeddings
mod embeddings;
/// Simple bitset
mod bitset;
/// Stores optimized distances
mod distance;
/// This interface allows us to update embeddings (and other structures) in multiple threads
/// without having to gain exclusive write access. Do _not_ clone hogwild structures as they
/// will still point to the underlying data
mod hogwild;
/// Who doesn't like progress bars?
mod progress;
/// Mapping from nodes -> features
mod feature_store;
/// Beginnings of refactoring out IO operations for efficient loading/writing of different data
/// structures
mod io;
use std::sync::Arc;
use std::ops::Deref;
use std::fs::File;
use std::io::{Write,BufWriter,BufReader,BufRead};
use std::collections::HashSet;
use rayon::prelude::*;
use float_ord::FloatOrd;
use pyo3::prelude::*;
use pyo3::exceptions::{PyValueError,PyIOError,PyKeyError,PyIndexError,PyTypeError};
use itertools::Itertools;
use rand::prelude::*;
use rand_xorshift::XorShiftRng;
use rand_distr::Uniform;
use crate::graph::{CSR,CumCSR,Graph as CGraph,NodeID,CDFtoP};
use crate::vocab::Vocab;
use crate::sampler::{Weighted,Unweighted};
use crate::distance::{Distance as EDist};
use crate::embeddings::{EmbeddingStore,Entity};
use crate::feature_store::FeatureStore;
use crate::io::{EmbeddingWriter,EmbeddingReader,GraphReader,open_file_for_reading,open_file_for_writing};
use crate::algos::aggregator::{WeightedAggregator,UnigramProbability,AvgAggregator,AttentionAggregator, EmbeddingBuilder};
use crate::algos::alignment::{NeighborhoodAligner as NA};
use crate::algos::ann::Ann;
use crate::algos::connected::{find_connected_components,prune_graph_components};
use crate::algos::ep::attention::{AttentionType,MultiHeadedAttention};
use crate::algos::ep::{EmbeddingPropagation,LossWeighting as EPLW};
use crate::algos::ep::loss::Loss;
use crate::algos::ep::model::{AveragedFeatureModel,AttentionFeatureModel};
use crate::algos::feat_propagation::propagate_features;
use crate::algos::graph_ann::NodeDistance;
use crate::algos::grwr::{Steps as GSteps,GuidedRWR};
use crate::algos::instantembedding::{InstantEmbeddings as IE,Estimator};
use crate::algos::lsr::{LSR as ALSR};
use crate::algos::pprembed::PPREmbed;
use crate::algos::pprrank::{PprRank, Loss as PprLoss};
use crate::algos::reweighter::{Reweighter};
use crate::algos::rwr::{RWR,ppr_estimate,rollout};
use crate::algos::smci::SupervisedMCIteration;
use crate::algos::utils::Sample;
use crate::algos::vpcg::{VPCG, FeatureWeight as VFeatureWeight};
/// Defines a constant seed for use when a seed is not provided. This is specifically hardcoded to
/// allow for deterministic performance across all algorithms using any stochasticity.
const SEED: u64 = 20222022;
/// Simplifies a lot of the type signatures
type FQNode = (String, String);
/// Maps an iterator of node ids and scores back to their pretty names with optional top K and
/// filtering by node types.
fn convert_scores(
vocab: &Vocab,
scores: impl Iterator<Item=(NodeID, f32)>,
k: Option<usize>,
filtered_node_type: Option<HashSet<String>>
) -> Vec<(FQNode, f32)> {
let mut scores: Vec<_> = scores.collect();
scores.sort_by_key(|(_k, v)| FloatOrd(-*v));
// Convert the list to named
let k = k.unwrap_or(scores.len());
scores.into_iter()
.map(|(node_id, w)| {
let (node_type, name) = vocab.get_name(node_id).unwrap();
(((*node_type).clone(), name.to_string()), w)
})
.filter(|((node_type, _node_name), _w)| {
filtered_node_type.as_ref()
.map(|nts| nts.contains(node_type))
.unwrap_or(true)
})
.take(k)
.collect()
}
fn convert_node_id_to_fqn(
vocab: &Vocab,
node_id: NodeID
) -> FQNode {
let (node_type, name) = vocab.get_name(node_id).unwrap();
((*node_type).clone(), name.to_string())
}
/// Convenience method for getting an internal node id from pretty name
fn get_node_id<A: AsRef<str>, B: AsRef<str>>(
vocab: &Vocab,
node_type: A,
node_name:B
) -> PyResult<NodeID> {
if let Some(node_id) = vocab.get_node_id(node_type.as_ref(), node_name.as_ref()) {
Ok(node_id)
} else {
Err(PyKeyError::new_err(format!(" Node '{}:{}' does not exist!", node_type.as_ref(), node_name.as_ref())))
}
}
#[derive(Clone)]
enum QueryType {
Node(String,String),
Embedding(Vec<f32>)
}
/// Type of Query to issue: a direct node lookup or an embedding
#[pyclass]
#[derive(Clone)]
pub struct Query {
qt: QueryType
}
#[pymethods]
impl Query {
/// Creates a query using a node type and name as lookup.
///
/// Parameters
/// ----------
/// node_type : str
/// The type of node.
/// node_name : str
/// The name of the node
///
/// Returns
/// -------
/// Query
#[staticmethod]
pub fn node(
node_type: String,
node_name: String
) -> Self {
Query { qt: QueryType::Node(node_type, node_name) }
}
/// Creates a query using a provided embedding.
///
/// Parameters
/// ----------
/// emb : List[float]
/// A list of floating point numbers to lookup.
///
/// Returns
/// -------
/// Query
#[staticmethod]
pub fn embedding(
emb: Vec<f32>
) -> Self {
Query { qt: QueryType::Embedding(emb) }
}
}
/// Contains the set of distance metrics used by NodeEmbeddings, typically application
/// dependent.
///
#[pyclass]
#[derive(Clone)]
pub enum Distance {
/// Uses Cosine distance - useful for general embedding problems.
Cosine,
/// Euclidean distance
Euclidean,
/// Simple un-normalized dot products.
Dot,
/// Landmark triangulation distance, useful for Distance embeddingsji
ALT,
/// Computes the jaccard between embeddings, treating each value as a discrete class
Jaccard,
/// Computes the hamming distance between embeddings, treating each value as a discrete class
Hamming
}
impl Distance {
fn to_edist(&self) -> EDist {
match self {
Distance::Cosine => EDist::Cosine,
Distance::Dot => EDist::Dot,
Distance::Euclidean => EDist::Euclidean,
Distance::ALT => EDist::ALT,
Distance::Hamming => EDist::Hamming,
Distance::Jaccard => EDist::Jaccard
}
}
fn from_edist(dist: EDist) -> Distance {
match dist {
EDist::Cosine => Distance::Cosine,
EDist::Dot => Distance::Dot,
EDist::Euclidean => Distance::Euclidean,
EDist::ALT => Distance::ALT,
EDist::Hamming => Distance::Hamming,
EDist::Jaccard => Distance::Jaccard
}
}
}
#[pymethods]
impl Distance {
pub fn compute(
&self,
e1: Vec<f32>,
e2: Vec<f32>
) -> f32 {
self.to_edist().compute(e1.as_slice(), e2.as_slice())
}
}
///
/// Core Graph library in Cloverleaf.
///
/// Graphs contain a list of nodes, defined by their type and their name, and a list of directional edges
/// and corresponding weights that describe node connections.
///
/// Graphs are encoded using Compressed Sparse Row Format to minimize
/// memory costs and allow for large graphs to be constructed on commodity systems. Further, edge
/// weights are encoded using CDF format to optimizes certain access patterns, such as weighted
/// random walks.The downside is this makes graphs immutable: there are no update or delete methods available
/// for defined graphs.
#[pyclass]
pub struct Graph {
graph: Arc<CumCSR>,
vocab: Arc<Vocab>
}
#[pymethods]
impl Graph {
/// Checks if a node is defined within the graph.
///
/// Parameters
/// ----------
/// name : FQNode
/// A tuple containing the (node_type, node_name) to lookup.
///
/// Returns
/// -------
/// bool
/// Returns True if the node is defined in the graph, False otherwise
pub fn contains_node(&self, name: FQNode) -> bool {
get_node_id(self.vocab.deref(), name.0, name.1).is_ok()
}
/// Returns the number of nodes that are defined in the graph
///
/// Parameters
/// ----------
///
/// Returns
/// -------
/// Int
pub fn nodes(&self) -> usize {
self.graph.len()
}
/// Returns the number of edges defined in the graph.
///
/// Parameters
/// ----------
///
/// Returns
/// -------
/// Int
///
pub fn edges(&self) -> usize {
self.graph.edges()
}
/// Returns the set of outbound nodes and corresponding edge weights for a given node in the Graph.
///
/// Parameters
/// ----------
/// node: FQNode
/// A tuple containing the (node_type, node_name) to lookup.
///
/// normalized: Bool - optional:
/// If provided, returns transition probability. If omitted, returns in CDF format
/// which allows for fast weighted random sampling.
///
/// Returns
/// -------
/// (List[(str, str)], List[float])
/// Set of edges and the corresponding set of weights.
///
/// Throws a KeyError if the node doesn't exist in the graph
///
pub fn get_edges(&self, node: FQNode, normalized: Option<bool>) -> PyResult<(Vec<FQNode>, Vec<f32>)> {
let node_id = get_node_id(self.vocab.deref(), node.0, node.1)?;
let (edges, weights) = self.graph.get_edges(node_id);
let names = edges.into_iter()
.map(|node_id| {
let (nt, n) = self.vocab.get_name(*node_id).unwrap();
((*nt).clone(), n.to_string())
}).collect();
if let Some(true) = normalized {
Ok((names, CDFtoP::new(weights).collect()))
} else {
Ok((names, weights.to_vec()))
}
}
/// Returns an interator to the nodes defined in the graph
///
/// Parameters
/// ----------
///
/// Returns
/// -------
/// Iterator[(str, str)]
/// An iterator emitting node types and node names defined in the graph.
///
pub fn vocab(&self) -> VocabIterator {
VocabIterator::new(self.vocab.clone())
}
/// Saves a graph to disk at the provided path.
///
/// Parameters
/// ----------
/// path : String
/// Where to save the the graph.
///
/// Returns
/// -------
///
pub fn save(&self, path: &str, comp_level: Option<u32>) -> PyResult<()> {
let mut bw = open_file_for_writing(path, comp_level)?;
for node in 0..self.graph.len() {
let (f_node_type, f_name) = self.vocab.get_name(node)
.expect("Programming error!");
let (edges, weights) = self.graph.get_edges(node);
for (out_node, weight) in edges.iter().zip(CDFtoP::new(weights)) {
let (t_node_type, t_name) = self.vocab.get_name(*out_node)
.expect("Programming error!");
writeln!(&mut bw, "{}\t{}\t{}\t{}\t{}", f_node_type, f_name, t_node_type, t_name, weight)
.map_err(|e| PyIOError::new_err(format!("{:?}", e)))?;
}
}
Ok(())
}
/// Returns the number of nodes in the graph
pub fn __len__(&self) -> PyResult<usize> {
Ok(self.nodes())
}
/// Simple represetnation of the Graph
pub fn __repr__(&self) -> String {
format!("Graph<Nodes={}, Edges={}>", self.graph.len(), self.graph.edges())
}
#[staticmethod]
/// Loads a graph from disk
///
/// Parameters
/// ----------
/// path : str
/// Path to load graph from, in graph format.
///
/// edge_type : EdgeType
/// EdgeType to use, either Directed or Undirected
///
/// Returns
/// -------
/// Self - Can throw exception
///
pub fn load(
py: Python<'_>,
path: &str,
edge_type: EdgeType,
chunk_size: Option<usize>,
skip_rows: Option<usize>,
weighted: Option<bool>,
deduplicate: Option<bool>
) -> PyResult<Self> {
py.allow_threads(move || {
let (vocab, csr) = GraphReader::load(
path,
edge_type,
chunk_size.unwrap_or(1),
skip_rows.unwrap_or(0),
weighted.unwrap_or(true),
deduplicate.unwrap_or(false)
)?;
let g = Graph {
graph: Arc::new(csr),
vocab: Arc::new(vocab)
};
Ok(g)
})
}
}
/// Basic RP3b walker
#[pyclass]
#[derive(Clone)]
struct RandomWalker {
restarts: Sample,
walks: usize,
beta: Option<f32>
}
#[pymethods]
impl RandomWalker {
/// Instantiates a random walker instance which can perform random walks on a graph.
///
/// Parameters
/// ----------
/// restarts : Float
/// If restarts is ~ (0,1), performs probabalistic termination (ie. pagewalk). If
/// restarts is [1,inf], performs fixed length walks (ie. rp3b, pixie).
///
/// walks : Int
/// Number of random walks to perform. The higher the number, the higher the fidelity
/// of local neighborhood at the expense of more compute. 100_000 is usually a good
/// number to start with.
///
/// beta : Float - Optional
/// If provided, beta ~ [0,1] specifes how much to discount node impact as a function of its degree.
/// Higher betas discount popular nodes more, biasing toward rarer nodes. Lower betas
/// reinforce popular nodes more.
///
/// Returns
/// -------
/// Self
///
#[new]
fn new(restarts: f32, walks: usize, beta: Option<f32>) -> PyResult<Self> {
Sample::new(restarts)
.map_err(|_err| PyValueError::new_err("restarts must be between (0, 1)"))
.map(|restarts| RandomWalker { restarts, walks, beta })
}
/// Simple representation of the RandomWalker
pub fn __repr__(&self) -> String {
format!("RandomWalker<restarts={:?}, walks={}, beta={:?}>", self.restarts, self.walks, self.beta)
}
/// Performs a random walk on a graph, returning a list of nodes and their approxmiate
/// scores where higher scores indicate a higher likelihood to terminate on those nodes.
///
/// Parameters
/// ----------
/// graph : Graph
/// Graph to perform random walks on
///
/// node : FQNode
/// Fully qualified node: (NodeType, NodeName)
///
/// seed : Int - Optional
/// If provided, sets the random seed. Otherwise, uses a global fixed seed.
///
/// k : Int - Optional
/// If provided, truncates the list to the top K.
///
/// filter_type : String or List[String] - Optional
/// If provided, only returns nodes that match the provided node type.
///
/// weighted : Bool - Optional
/// Whether to perform a weighted random walk. Default is True.
///
/// Returns
/// -------
/// List[(FQNode, Float)] - Can throw exception
/// List of fully qualified nodes and their fractional scores.
///
pub fn walk(
&self,
graph: &Graph,
node: FQNode,
seed: Option<u64>,
k: Option<usize>,
filter_type: Option<&PyAny>,
single_threaded: Option<bool>,
weighted: Option<bool>
) -> PyResult<Vec<(FQNode, f32)>> {
let node_id = get_node_id(graph.vocab.deref(), node.0, node.1)?;
let rwr = RWR {
steps: self.restarts,
walks: self.walks,
beta: self.beta.unwrap_or(0.5),
single_threaded: single_threaded.unwrap_or(false),
seed: seed.unwrap_or(SEED)
};
let results = if weighted.unwrap_or(true) {
rwr.sample_bfs(graph.graph.as_ref(), node_id)
} else {
rwr.sample(graph.graph.as_ref(), &Unweighted, node_id)
};
let fts = convert_filter_type(filter_type)?;
Ok(convert_scores(&graph.vocab, results.into_iter(), k, fts))
}
}
/// Rp3b walker with the ability to bias walks according to a provided embedding set.
#[pyclass]
#[derive(Clone)]
struct BiasedRandomWalker {
restarts: f32,
walks: usize,
beta: Option<f32>,
blend: Option<f32>,
}
#[pymethods]
impl BiasedRandomWalker {
#[new]
/// Creates a BiasedRandomWalker instance.
///
/// BiasedRandomWalkers perform random walks while allowing external embeddings to influence
/// the direction a random walker takes. When two nodes have a closer distance, the
/// randomwalker will reweight scores to explore in that direction more often. This is
/// helpful when wanting to perform a random walk but also have it focus on areas compatible
/// with embeddings - for example, random walks between queries and products, where the
/// embeddings represent user preferences.
///
/// Parameters
/// ----------
/// restarts : Float
/// If restarts is ~ (0,1), performs probabalistic termination (ie. pagewalk). If
/// restarts is [1,inf], performs fixed length walks (ie. rp3b, pixie).
///
/// walks : Int
/// Number of random walks to perform. The higher the number, the higher the fidelity
/// of local neighborhood at the expense of more compute. 100_000 is usually a good
/// number to start with.
///
/// beta : Float - Optional
/// If provided, beta ~ [0,1] specifes how much to discount node impact as a function of its degree.
/// Higher betas discount popular nodes more, biasing toward rarer nodes. Lower betas
/// reinforce popular nodes more.
///
/// blend : Float - Optional
/// If provided, determines how much the embedding influences the direction of the
/// random walk
///
/// Returns
/// -------
/// Self
///
fn new(restarts: f32, walks: usize, beta: Option<f32>, blend: Option<f32>) -> Self {
BiasedRandomWalker { restarts, walks, beta, blend }
}
/// Simple representation of the BiasedRandomWalker
pub fn __repr__(&self) -> String {
format!("BiasedRandomWalker<restarts={}, walks={}, beta={:?}, blend={:?}>", self.restarts, self.walks, self.beta, self.blend)
}
/// Performs the random walk with both starting node and bias context. Further, a rerank
/// context can be provided to rerank the final results by yet an additional context.
///
/// Parameters
/// ----------
/// graph : Graph
/// Graph to perform random walks on
///
/// embeddings : NodeEmbeddings
/// Set of embeddings which reference nodes within the graph.
///
/// node : FQNode
/// Fully qualified node: (NodeType, NodeName)
///
/// context : Query
/// Context, which can be either an embedding or a node lookup, for which to perform
/// distances against.
///
/// seed : Int - Optional
/// If provided, sets the random seed. Otherwise, uses a global fixed seed.
///
/// k : Int - Optional
/// If provided, truncates the list to the top K.
///
/// rerank_context : Query - Optional
/// If provided, reranks the final result set by the rerank context.
///
/// filter_type : String or List[String] - Optional
/// If provided, only returns nodes that match the provided node type.
///
///
/// Returns
/// -------
/// List[(FQNode, Float)] - Can throw exception
/// List of fully qualified nodes and their fractional scores.
///
pub fn walk(
&self,
graph: &Graph,
embeddings: &NodeEmbeddings,
node: FQNode,
context: &Query,
k: Option<usize>,
seed: Option<u64>,
rerank_context: Option<&Query>,
filter_type: Option<&PyAny>
) -> PyResult<Vec<(FQNode, f32)>> {
let node_id = get_node_id(graph.vocab.deref(), node.0, node.1)?;
let g_emb = lookup_embedding(context, embeddings)?;
let steps = if self.restarts >= 1. {
GSteps::Fixed(self.restarts as usize)
} else if self.restarts > 0. {
let one_percent = 0.01f32.ln() / (1. - self.restarts).ln();
GSteps::Probability(self.restarts, (one_percent).ceil() as usize)
} else {
return Err(PyValueError::new_err("Alpha must be between [0, inf)"))
};
let grwr = GuidedRWR {
steps: steps,
walks: self.walks,
alpha: self.blend.unwrap_or(0.5),
beta: self.beta.unwrap_or(0.5),
seed: seed.unwrap_or(SEED)
};
let node_embeddings = &embeddings.embeddings;
let mut results = grwr.sample(graph.graph.as_ref(),
&Weighted, node_embeddings, node_id, g_emb);
// Reweight results if requested
if let Some(cn) = rerank_context {
println!("Reranking...");
let c_emb = lookup_embedding(cn, embeddings)?;
Reweighter::new(self.blend.unwrap_or(0.5))
.reweight(&mut results, node_embeddings, c_emb);
}
let fts = convert_filter_type(filter_type)?;
Ok(convert_scores(&graph.vocab, results.into_iter(), k, fts))
}
}
/// Computes a SparsePPR
#[pyclass]
#[derive(Clone)]
struct SparsePPR {
restarts: f32,
eps: f32
}
#[pymethods]
impl SparsePPR {
/// Creates a Sparse Personalized Page Rank. Unlike sampling approaches used by
/// RandomWalker, this uses a different personalized page rank estimator controllable by a
/// provided error. In general, it's less flexible than sampling based approaches but can
/// be substantially faster for graphs with low degree counts.
///
/// In cases where degree count can be high, can be substantially slower than estimate based
/// approaches.
///
/// Parameters
/// ----------
/// restarts : Float
/// restarts ~ (0,1), determines the probability a random walk will terminate with
/// lower restarts resulting in longer walks.
///
/// eps : Float - Optional
/// If provided, specifies the tolerable error rate allowed for the estimation. Default
/// is 1e-5.
///
/// Returns
/// -------
/// Self - Can throw exception
///
///
#[new]
fn new(restarts: f32, eps: Option<f32>) -> PyResult<Self> {
if restarts <= 0f32 || restarts >= 1f32 {
return Err(PyValueError::new_err("restarts must be between (0, 1)"))
}
Ok(SparsePPR { restarts, eps: eps.unwrap_or(1e-5) })
}
/// Simple representation of the SparsePPR
pub fn __repr__(&self) -> String {
format!("SparsePPR<restarts={}, eps={}>", self.restarts, self.eps)
}
/// Computes the personalized page rank estimate for a given node
///
/// Parameters
/// ----------
/// graph : Graph
/// Graph to perform the PPR on
///
/// node : FQNode
/// Starting node for PPR.
///
/// k : Int - Optional
/// If provided, returns only the top K nodes and scores; otherwise provides all.
///
/// filter_type : String or List[String] - Optional
/// If provided, filters out nodes that do not match the provided filter_type.
///
/// Returns
/// -------
/// List[(FQNode, f32)] - Can throw exception
/// List of fully qualified nodes and their fractional scores
///
pub fn compute(
&self,
graph: &Graph,
node: FQNode,
k: Option<usize>,
filter_type: Option<&PyAny>
) -> PyResult<Vec<(FQNode, f32)>> {
let node_id = get_node_id(graph.vocab.deref(), node.0, node.1)?;
let results = ppr_estimate(graph.graph.as_ref(), node_id, self.restarts, self.eps);
let fts = convert_filter_type(filter_type)?;
Ok(convert_scores(&graph.vocab, results.into_iter(), k, fts))
}
}
/// Type of edge. Undirected edges internally get converted to two directed edges.
#[pyclass]
#[derive(Clone)]
pub enum EdgeType {
Directed,
Undirected
}
/// Allows the user to build a graph incrementally before converting it into a proper CSR graph
#[pyclass]
struct GraphBuilder {
vocab: Vocab,
edges: Vec<(NodeID, NodeID, f32)>
}
#[pymethods]
impl GraphBuilder {
/// Creates a new graph builder instance. This allows for the programatic construction of
/// graphs, creating a fully fledged and optimized graph at the end.
///
/// Returns
/// -------
/// Self
///
///
#[new]
pub fn new() -> Self {
GraphBuilder {
vocab: Vocab::new(),
edges: Vec::new()
}
}
/// Simple representation of the GraphBuilder
pub fn __repr__(&self) -> String {
format!("GraphBuilder<Nodes={}, Edges={}>", self.vocab.len(), self.edges.len())
}
/// Adds an edge to the graph.
///
/// Parameters
/// ----------
/// from_node : FQNode
/// Originating node.
///
/// to_node : FQNode
/// Destination Node
///
/// weight : Float
/// Associated Edge weight, if application
///
/// node_type : EdgeType
/// If Directed, only creates the edge in one direction. If undirected, creates two
/// edges from from_node -> to_node and to_node -> from_node, each with the same weight.
///
pub fn add_edge(
&mut self,
from_node: FQNode,
to_node: FQNode,
weight: f32,
node_type: EdgeType
) {
let f_id = self.vocab.get_or_insert(from_node.0, from_node.1);
let t_id = self.vocab.get_or_insert(to_node.0, to_node.1);
self.edges.push((f_id, t_id, weight));
if matches!(node_type, EdgeType::Undirected) {
self.edges.push((t_id, f_id, weight));
}
}
/// Constructs the graph
///
/// Returns
/// -------
/// Graph - Optional
/// Creates a Graph for usage. If no edges have been specified, returns None.
///
pub fn build_graph(&mut self, deduplicate: Option<bool>) -> Option<Graph> {
if self.edges.len() == 0 {
return None
}
// We swap the internal buffers with new buffers; we do this to preserve memory whenever
// possible.
let mut vocab = Vocab::new();
let mut edges = Vec::new();
std::mem::swap(&mut vocab, &mut self.vocab);
std::mem::swap(&mut edges, &mut self.edges);
let graph = CSR::construct_from_edges(edges, deduplicate.unwrap_or(true));
Some(Graph {
graph: Arc::new(CumCSR::convert(graph)),
vocab: Arc::new(vocab)
})
}
}
#[pyclass]
#[derive(Clone)]
struct LossWeighting {
loss: EPLW
}
#[pymethods]
impl LossWeighting {
#[allow(non_snake_case)]
#[staticmethod]
pub fn Log() -> Self {
LossWeighting { loss: EPLW::DegreeLog }
}
#[allow(non_snake_case)]
#[staticmethod]
pub fn Exponential(weight: f32) -> Self {
LossWeighting { loss: EPLW::DegreeExponential(weight) }
}
}
/// A python wrapper for the internal ADT used for defining losses
#[pyclass]
#[derive(Clone)]
struct EPLoss {
loss: Loss
}
#[pymethods]
impl EPLoss {
/// Uses thresholded Margin loss for Embedding Propagation. This is equivalent to the loss
/// used in the Embedding Propagation paper.
///
/// Parameters
/// ----------
/// gamma : Float
/// Threshold for which to ignore distance computation.
///
/// negatives : Int - Optional
/// If provided, the number of negatives samples to use. Default is 1
///
/// Returns
/// -------
/// Self
///
///
#[staticmethod]
pub fn margin(gamma: f32, negatives: Option<usize>) -> Self {
EPLoss { loss: Loss::MarginLoss(gamma, negatives.unwrap_or(1)) }
}
/// Uses temperature controlled contrastive loss with cosine similarity for optimization.
///
/// Parameters
/// ----------
/// positive_margin : Float
/// Margin threshold for positives.
///
/// negative_margin : Float
/// Margin threshold for negatives.
///
/// negatives : Int
/// If provided, the number of negatives samples to use. Default is 1.
///
/// Returns
/// -------
/// Self
///
///
#[staticmethod]
pub fn contrastive(positive_margin: f32, negative_margin: f32, negatives: usize) -> Self {
EPLoss { loss: Loss::Contrastive(positive_margin, negative_margin, negatives.max(1)) }
}
/// Uses the Starspace loss for optimization, as seen in the Starspace paper.
///
/// Parameters
/// ----------
/// gamma : Float
/// Margin threshold. Higher values spend less time optimizing scores which are
/// relatively close to the margin
///
/// negatives : Int
/// If provided, the number of negatives samples to use. Default is 1.
///
/// Returns
/// -------
/// Self
///
///
#[staticmethod]
pub fn starspace(gamma: f32, negatives: usize) -> Self {
EPLoss { loss: Loss::StarSpace(gamma, negatives.max(1)) }
}
/// Optimizes for the NLL of a 1-N classification task. This is also known as ListNet,
/// except with a margin. Uses dot products for similarity.
///
/// Parameters
/// ----------
/// tau : Float
/// Tau serves as the margin threshold parameter
///
/// negatives : Int
/// If provided, the number of negatives samples to use. Default is 1.
///
/// Returns