-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathlib.rs
2074 lines (1746 loc) · 61.8 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;
/// 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 rayon::prelude::*;
use float_ord::FloatOrd;
use pyo3::prelude::*;
use pyo3::exceptions::{PyValueError,PyIOError,PyKeyError};
use pyo3::types::PyList;
use itertools::Itertools;
use fast_float::parse;
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;
use crate::embeddings::{EmbeddingStore,Distance as EDist,Entity};
use crate::feature_store::FeatureStore;
use crate::io::EmbeddingWriter;
use crate::algos::rwr::{Steps,RWR};
use crate::algos::grwr::{Steps as GSteps,GuidedRWR};
use crate::algos::reweighter::{Reweighter};
use crate::algos::ep::EmbeddingPropagation;
use crate::algos::ep::loss::Loss;
use crate::algos::ep::model::{AveragedFeatureModel,AttentionFeatureModel};
use crate::algos::ep::attention::{AttentionType,MultiHeadedAttention};
use crate::algos::graph_ann::NodeDistance;
use crate::algos::aggregator::{WeightedAggregator,UnigramProbability,AvgAggregator,AttentionAggregator, EmbeddingBuilder};
use crate::algos::feat_propagation::propagate_features;
use crate::algos::alignment::{NeighborhoodAligner as NA};
use crate::algos::smci::SupervisedMCIteration;
use crate::algos::pprrank::PprRank;
use crate::algos::ann::Ann;
/// 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;
/// Simple method for taking an iterator of edges and constructing a CSR graph and associated vocab
fn build_csr(edges: impl Iterator<Item=((String,String),(String,String),f32)>) -> (CSR, Vocab) {
// Convert to NodeIDs
let mut vocab = Vocab::new();
eprintln!("Constructing vocab...");
let edges: Vec<_> = edges.map(|((f_nt, f_n), (t_nt, t_n), w)| {
let f_id = vocab.get_or_insert(f_nt, f_n);
let t_id = vocab.get_or_insert(t_nt, t_n);
(f_id, t_id, w)
}).collect();
eprintln!("Constructing CSR...");
let csr = CSR::construct_from_edges(edges);
(csr, vocab)
}
/// 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<String>
) -> Vec<((String,String), 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).clone()), w)
})
.filter(|((node_type, _node_name), _w)| {
filtered_node_type.as_ref().map(|nt| nt == node_type).unwrap_or(true)
})
.take(k)
.collect()
}
/// Convenience method for getting an internal node id from pretty name
fn get_node_id(vocab: &Vocab, node_type: String, node: String) -> PyResult<NodeID> {
if let Some(node_id) = vocab.get_node_id(node_type.clone(), node.clone()) {
Ok(node_id)
} else {
Err(PyKeyError::new_err(format!(" Node '{}:{}' does not exist!", node_type, node)))
}
}
#[derive(Clone)]
enum QueryType {
Node(String, String),
Embedding(Vec<f32>)
}
#[pyclass]
#[derive(Clone)]
pub struct Query {
qt: QueryType
}
#[pymethods]
impl Query {
#[staticmethod]
pub fn node(
node_type: String,
node_name: String
) -> Self {
Query { qt: QueryType::Node(node_type, node_name) }
}
#[staticmethod]
pub fn embedding(
emb: Vec<f32>
) -> Self {
Query { qt: QueryType::Embedding(emb) }
}
}
/// This maps our python definition to an internal ADT for embedding distnaces
#[pyclass]
#[derive(Clone)]
pub enum Distance {
Cosine,
Euclidean,
Dot,
ALT,
Jaccard,
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
}
}
}
/// Main python wrapper for graphs
#[pyclass]
pub struct Graph {
graph: Arc<CumCSR>,
vocab: Arc<Vocab>
}
#[pymethods]
impl Graph {
#[new]
fn new(edges: Vec<((String,String),(String,String),f32)>) -> Self {
let (graph, vocab) = build_csr(edges.into_iter());
eprintln!("Converting to CDF format...");
Graph {
graph: Arc::new(CumCSR::convert(graph)),
vocab: Arc::new(vocab)
}
}
pub fn contains_node(&self, name: (String, String)) -> bool {
get_node_id(self.vocab.deref(), name.0, name.1).is_ok()
}
pub fn nodes(&self) -> usize {
self.graph.len()
}
pub fn edges(&self) -> usize {
self.graph.edges()
}
pub fn get_edges(&self, node: (String,String)) -> PyResult<(Vec<(String, String)>, 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).clone())
}).collect();
Ok((names, weights.to_vec()))
}
pub fn vocab(&self) -> VocabIterator {
VocabIterator::new(self.vocab.clone())
}
/// Saves a graph to disk
pub fn save(&self, path: &str) -> PyResult<()> {
let f = File::create(path)
.map_err(|e| PyIOError::new_err(format!("{:?}", e)))?;
let mut bw = BufWriter::new(f);
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(())
}
/// Loads a graph from disk
#[staticmethod]
pub fn load(path: &str, edge_type: EdgeType) -> PyResult<Self> {
let f = File::open(path)
.map_err(|e| PyIOError::new_err(format!("{:?}", e)))?;
let br = BufReader::new(f);
let mut vocab = Vocab::new();
let mut edges = Vec::new();
for (i, line) in br.lines().enumerate() {
let line = line.unwrap();
let pieces: Vec<_> = line.split('\t').collect();
if pieces.len() != 5 {
return Err(PyValueError::new_err(format!("{}: Malformed graph file: Expected 5 fields!", i)))
}
let f_id = vocab.get_or_insert(pieces[0].to_string(), pieces[1].to_string());
let t_id = vocab.get_or_insert(pieces[2].to_string(), pieces[3].to_string());
let w: f32 = pieces[4].parse()
.map_err(|e| PyValueError::new_err(format!("{}: Malformed graph file! {} - {:?}", i, e, pieces[4])))?;
edges.push((f_id, t_id, w));
if matches!(edge_type, EdgeType::Undirected) {
edges.push((t_id, f_id, w));
}
}
eprintln!("Read {} nodes, {} edges...", vocab.len(), edges.len());
let csr = CSR::construct_from_edges(edges);
let g = Graph {
graph: Arc::new(CumCSR::convert(csr)),
vocab: Arc::new(vocab)
};
Ok(g)
}
}
/// Basic RP3b walker
#[pyclass]
#[derive(Clone)]
struct RandomWalker {
restarts: f32,
walks: usize,
beta: Option<f32>
}
#[pymethods]
impl RandomWalker {
#[new]
fn new(restarts: f32, walks: usize, beta: Option<f32>) -> Self {
RandomWalker { restarts, walks, beta }
}
pub fn walk(
&self,
graph: &Graph,
node: (String, String),
seed: Option<u64>,
k: Option<usize>,
filter_type: Option<String>
) -> PyResult<Vec<((String,String), f32)>> {
let node_id = get_node_id(graph.vocab.deref(), node.0, node.1)?;
let steps = if self.restarts >= 1. {
Steps::Fixed(self.restarts as usize)
} else if self.restarts > 0. {
Steps::Probability(self.restarts)
} else {
return Err(PyValueError::new_err("Alpha must be between [0, inf)"))
};
let rwr = RWR {
steps: steps,
walks: self.walks,
beta: self.beta.unwrap_or(0.5),
seed: seed.unwrap_or(SEED)
};
let results = rwr.sample(graph.graph.as_ref(), &Weighted, node_id);
Ok(convert_scores(&graph.vocab, results.into_iter(), k, filter_type))
}
}
/// 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]
fn new(restarts: f32, walks: usize, beta: Option<f32>, blend: Option<f32>) -> Self {
BiasedRandomWalker { restarts, walks, beta, blend }
}
pub fn walk(
&self,
graph: &Graph,
embeddings: &NodeEmbeddings,
node: (String,String),
context: &Query,
k: Option<usize>,
seed: Option<u64>,
rerank_context: Option<&Query>,
filter_type: Option<String>
) -> PyResult<Vec<((String,String), 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);
}
Ok(convert_scores(&graph.vocab, results.into_iter(), k, filter_type))
}
}
/// 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 {
#[new]
pub fn new() -> Self {
GraphBuilder {
vocab: Vocab::new(),
edges: Vec::new()
}
}
pub fn add_edge(
&mut self,
from_node: (String, String),
to_node: (String,String),
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));
}
}
pub fn build_graph(&mut self) -> Graph {
// 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);
Graph {
graph: Arc::new(CumCSR::convert(graph)),
vocab: Arc::new(vocab)
}
}
}
/// A python wrapper for the internal ADT used for defining losses
#[pyclass]
#[derive(Clone)]
struct EPLoss {
loss: Loss
}
#[pymethods]
impl EPLoss {
#[staticmethod]
pub fn margin(gamma: f32, negatives: Option<usize>) -> Self {
EPLoss { loss: Loss::MarginLoss(gamma, negatives.unwrap_or(1)) }
}
#[staticmethod]
pub fn contrastive(temperature: f32, negatives: usize) -> Self {
EPLoss { loss: Loss::Contrastive(temperature, negatives.max(1)) }
}
#[staticmethod]
pub fn starspace(gamma: f32, negatives: usize) -> Self {
EPLoss { loss: Loss::StarSpace(gamma, negatives.max(1)) }
}
#[staticmethod]
pub fn rank(tau: f32, negatives: usize) -> Self {
EPLoss { loss: Loss::RankLoss(tau, negatives.max(1)) }
}
#[staticmethod]
pub fn rankspace(tau: f32, negatives: usize) -> Self {
EPLoss { loss: Loss::RankSpace(tau, negatives.max(1)) }
}
#[staticmethod]
pub fn ppr(gamma: f32, negatives: usize, restart_p: f32) -> Self {
EPLoss { loss: Loss::PPR(gamma, negatives.max(1), restart_p) }
}
}
/// A wrapper for model types
enum ModelType {
Averaged(AveragedFeatureModel),
Attention(AttentionFeatureModel)
}
/// The main embedding class. Flexible with loads of options.
#[pyclass]
struct EmbeddingPropagator {
ep: EmbeddingPropagation,
model: ModelType
}
#[pymethods]
impl EmbeddingPropagator {
#[new]
pub fn new(
// Learning rate
alpha: Option<f32>,
// Optimization loss
loss: Option<EPLoss>,
// Batch size
batch_size: Option<usize>,
// Node embedding size
dims: Option<usize>,
// Number of passes to run
passes: Option<usize>,
// Random seed to use
seed: Option<u64>,
// Max neighbors to use for reconstructions
max_nodes: Option<usize>,
// Max features to use for optimization
max_features: Option<usize>,
// Percentage of nodes to use for validation
valid_pct: Option<f32>,
// Number of hard negatives, produced from random walks. The quality of these deeply
// depend on the quality of the graph
hard_negatives: Option<usize>,
// Whether to have a pretty indicator.
indicator: Option<bool>,
// Number of dims to use for attention. If missing, uses the Averaged model
attention: Option<usize>,
// Number of heads to use. Defaults to one, but only used if attention dims are set
attention_heads: Option<usize>,
// Use sliding window context.
context_window: Option<usize>,
// Use gradient noise where we sample from the normal distribution and blend with `noise`
noise: Option<f32>
) -> Self {
let ep = EmbeddingPropagation {
alpha: alpha.unwrap_or(0.9),
batch_size: batch_size.unwrap_or(50),
d_model: dims.unwrap_or(100),
passes: passes.unwrap_or(100),
loss: loss.map(|l|l.loss).unwrap_or(Loss::MarginLoss(1f32,1)),
hard_negs: hard_negatives.unwrap_or(0),
valid_pct: valid_pct.unwrap_or(0.1),
seed: seed.unwrap_or(SEED),
indicator: indicator.unwrap_or(true),
noise: noise.unwrap_or(0.0)
};
let model = if let Some(d_k) = attention {
let num_heads = attention_heads.unwrap_or(1);
let at = if let Some(size) = context_window {
AttentionType::Sliding{window_size: size}
} else if let Some(k) = max_features {
AttentionType::Random { num_features: k }
} else {
AttentionType::Full
};
let mha = MultiHeadedAttention::new(num_heads, d_k, at);
ModelType::Attention(AttentionFeatureModel::new(mha, None, max_nodes))
} else {
ModelType::Averaged(AveragedFeatureModel::new(max_features, max_nodes))
};
EmbeddingPropagator{ ep, model }
}
/// The big one - kicks off learning the features used to construct nodes.
pub fn learn_features(
&mut self,
graph: &Graph,
features: &mut FeatureSet,
feature_embeddings: Option<&mut NodeEmbeddings>
) -> NodeEmbeddings {
features.features.fill_missing_nodes();
// Pull out the EmbeddingStore
let feature_embeddings = feature_embeddings.map(|fes| {
let mut sfes = EmbeddingStore::new(fes.vocab.len(), 0, EDist::Cosine);
std::mem::swap(&mut sfes, &mut fes.embeddings);
sfes
});
let feat_embeds = match &self.model {
ModelType::Averaged(model) => {
self.ep.learn(
graph.graph.as_ref(),
&mut features.features,
feature_embeddings,
model
)
},
ModelType::Attention(model) => {
self.ep.learn(
graph.graph.as_ref(),
&mut features.features,
feature_embeddings,
model
)
}
};
let vocab = features.features.clone_vocab();
let feature_embeddings = NodeEmbeddings {
vocab: Arc::new(vocab),
embeddings: feat_embeds};
feature_embeddings
}
}
/// Defines the FeatureSet class, which allows setting discrete features for a node
#[pyclass]
pub struct FeatureSet {
vocab: Arc<Vocab>,
features: FeatureStore
}
impl FeatureSet {
fn read_vocab_from_file(path: &str) -> PyResult<Vocab> {
let mut vocab = Vocab::new();
let f = File::open(path)
.map_err(|e| PyIOError::new_err(format!("{:?}", e)))?;
let br = BufReader::new(f);
for line in br.lines() {
let line = line.unwrap();
let pieces: Vec<_> = line.split('\t').collect();
if pieces.len() != 3 {
return Err(PyValueError::new_err("Malformed feature line! Need node_type<TAB>name<TAB>f1 f2 ..."))
}
vocab.get_or_insert(pieces[0].into(), pieces[1].into());
}
Ok(vocab)
}
}
#[pymethods]
impl FeatureSet {
// Loads features tied to a graph
#[staticmethod]
pub fn new_from_graph(graph: &Graph, path: Option<String>, namespace: Option<String>) -> PyResult<Self> {
let ns = namespace.unwrap_or_else(|| "feat".to_string());
let mut fs = FeatureSet {
vocab: graph.vocab.clone(),
features: FeatureStore::new(graph.graph.len(), ns)
};
if let Some(path) = path {
fs.load_into(path)?;
}
Ok(fs)
}
// Loads features tied to a graph
#[staticmethod]
pub fn new_from_file(path: String, namespace: Option<String>) -> PyResult<Self> {
// Build the vocab from the file first, get the length of the feature set
let vocab = Arc::new(FeatureSet::read_vocab_from_file(&path)?);
let ns = namespace.unwrap_or_else(|| "feat".to_string());
let feats = FeatureStore::new(vocab.len(), ns);
let mut fs = FeatureSet {
vocab: vocab,
features: feats
};
fs.load_into(path)?;
Ok(fs)
}
pub fn set_features(&mut self, node: (String,String), features: Vec<String>) -> PyResult<()> {
let node_id = get_node_id(self.vocab.deref(), node.0, node.1)?;
self.features.set_features(node_id, features);
Ok(())
}
pub fn get_features(&self, node: (String,String)) -> PyResult<Vec<String>> {
let node_id = get_node_id(self.vocab.deref(), node.0, node.1)?;
Ok(self.features.get_pretty_features(node_id))
}
/// Loads features from a graph, constructing a new vocabulary
pub fn load_into(&mut self, path: String) -> PyResult<()> {
let f = File::open(path)
.map_err(|e| PyIOError::new_err(format!("{:?}", e)))?;
let br = BufReader::new(f);
for line in br.lines() {
let line = line.unwrap();
let pieces: Vec<_> = line.split('\t').collect();
if pieces.len() != 3 {
return Err(PyValueError::new_err("Malformed feature line! Need node_type<TAB>name<TAB>f1 f2 ..."))
}
let bow = pieces[2].split_whitespace()
.map(|s| s.to_string()).collect();
self.set_features((pieces[0].to_string(), pieces[1].to_string()), bow);
}
Ok(())
}
pub fn nodes(&self) -> usize {
self.vocab.len()
}
pub fn num_features(&self) -> usize {
self.features.num_features()
}
pub fn vocab(&self) -> VocabIterator {
VocabIterator::new(self.vocab.clone())
}
pub fn prune_min_count(&self, count: usize) -> Self {
FeatureSet {
features: self.features.prune_min_count(count),
vocab: self.vocab.clone()
}
}
}
/// Propagates features within a feature set, using a graph to find neighbors.
#[pyclass]
pub struct FeaturePropagator {
/// Max number of features for each node
k: usize,
/// Filters out feature which don't meet the minimum feature count
threshold: f32,
/// Number of passes to run. In practice, this should be pretty small.
max_iters: usize
}
#[pymethods]
impl FeaturePropagator {
#[new]
pub fn new(k: usize, threshold: Option<f32>, max_iters: Option<usize>) -> Self {
FeaturePropagator {
k: k,
threshold: threshold.unwrap_or(0.),
max_iters: max_iters.unwrap_or(20)
}
}
pub fn propagate(&self,
graph: &Graph,
features: &mut FeatureSet
) {
propagate_features(
graph.graph.deref(),
&mut features.features,
self.max_iters,
self.k,
self.threshold);
}
}
/// After we train a set of features using EP, we need to use an aggregator to take a set of
/// features and glue them into a new NodeEmbedding
#[derive(Clone)]
enum AggregatorType {
Averaged,
Weighted {
alpha: f32,
vocab: Arc<Vocab>,
unigrams: Arc<UnigramProbability>
},
Attention {
num_heads: usize,
d_k: usize,
window: Option<usize>
}
}
/// This constructs node embeddings based on the AggregatorType and a set of FeatureEmbeddings.
#[pyclass]
#[derive(Clone)]
pub struct FeatureAggregator {
at: AggregatorType
}
#[pymethods]
impl FeatureAggregator {
#[staticmethod]
pub fn Averaged() -> Self {
FeatureAggregator { at: AggregatorType::Averaged }
}
#[staticmethod]
pub fn Attention(num_heads: usize, d_k: usize, window: Option<usize>) -> Self {
FeatureAggregator { at: AggregatorType::Attention {num_heads, d_k, window} }
}
#[staticmethod]
pub fn Weighted(alpha: f32, fs: &FeatureSet) -> Self {
let unigrams = Arc::new(UnigramProbability::new(&fs.features));
let vocab = fs.vocab.clone();
FeatureAggregator { at: AggregatorType::Weighted {alpha, vocab, unigrams} }
}
/// Write the details to disk. We should use a proper serialization library instead of the hot
/// non-sense currently used.
pub fn save(&self, path: &str) -> PyResult<()> {
let f = File::create(path)
.map_err(|e| PyIOError::new_err(format!("{:?}", e)))?;
let mut bw = BufWriter::new(f);
match &self.at {
AggregatorType::Averaged => {
writeln!(&mut bw, "Averaged")
.map_err(|e| PyIOError::new_err(format!("{:?}", e)))?;
},
AggregatorType::Attention { num_heads, d_k, window } => {
writeln!(&mut bw, "Attention")
.map_err(|e| PyIOError::new_err(format!("{:?}", e)))?;
writeln!(&mut bw, "{}", num_heads)
.map_err(|e| PyIOError::new_err(format!("{:?}", e)))?;
writeln!(&mut bw, "{}", d_k)
.map_err(|e| PyIOError::new_err(format!("{:?}", e)))?;
writeln!(&mut bw, "{}", window.unwrap_or(0))
.map_err(|e| PyIOError::new_err(format!("{:?}", e)))?;
},
AggregatorType::Weighted { alpha, vocab, unigrams } => {
writeln!(&mut bw, "Weighted")
.map_err(|e| PyIOError::new_err(format!("{:?}", e)))?;
writeln!(&mut bw, "{}", alpha)
.map_err(|e| PyIOError::new_err(format!("{:?}", e)))?;
for (node, p_wi) in unigrams.iter().enumerate() {
if let Some((f_node_type, f_name)) = vocab.get_name(node) {
writeln!(&mut bw, "{}\t{}\t{}", f_node_type, f_name, *p_wi as f64)
.map_err(|e| PyIOError::new_err(format!("{:?}", e)))?;
} else {
// We've moved to node individual embeddings
break
}
}
}
}
Ok(())
}
#[staticmethod]
pub fn load(path: String) -> PyResult<Self> {
let f = File::open(path)
.map_err(|e| PyIOError::new_err(format!("{:?}", e)))?;
let mut br = BufReader::new(f);
// Find the type
let mut line = String::new();
br.read_line(&mut line)
.map_err(|e| PyIOError::new_err(format!("{:?}", e)))?;
match line.trim_end() {
"Averaged" => Ok(FeatureAggregator::Averaged()),
"Attention" => {
line.clear();
br.read_line(&mut line)
.map_err(|e| PyIOError::new_err(format!("{:?}", e)))?;
let num_heads = line.trim_end().parse::<usize>()
.map_err(|_e| PyValueError::new_err(format!("invalid dim! {:?}", line)))?;
line.clear();
br.read_line(&mut line)
.map_err(|e| PyIOError::new_err(format!("{:?}", e)))?;
let d_k = line.trim_end().parse::<usize>()
.map_err(|_e| PyValueError::new_err(format!("invalid dim! {:?}", line)))?;
line.clear();
br.read_line(&mut line)
.map_err(|e| PyIOError::new_err(format!("{:?}", e)))?;
let window = line.trim_end().parse::<usize>()
.map_err(|_e| PyValueError::new_err(format!("invalid dim! {:?}", line)))?;
let window = if window == 0 {
None
} else {
Some(window)
};
Ok(FeatureAggregator::Attention(num_heads, d_k, window))
},
"Weighted" => {
// get alpha
line.clear();
br.read_line(&mut line)
.map_err(|e| PyIOError::new_err(format!("{:?}", e)))?;
let alpha = line.trim_end().parse::<f32>()
.map_err(|_e| PyValueError::new_err(format!("invalid dim! {:?}", line)))?;
let mut vocab = Vocab::new();
let mut p_w = Vec::new();
for line in br.lines() {
let line = line.unwrap();
let pieces: Vec<_> = line.split('\t').collect();
if pieces.len() != 3 {
return Err(PyValueError::new_err("Malformed feature line! Need node_type<TAB>name<TAB>weight ..."))
}
let p_wi = pieces[2].parse::<f64>()
.map_err(|_e| PyValueError::new_err(format!("Tried to parse weight and failed:{:?}", line)))?;
let node_id = vocab.get_or_insert(pieces[0].into(), pieces[1].into());
if node_id < p_w.len() {
return Err(PyValueError::new_err(format!("Duplicate feature found:{} {}", pieces[0], pieces[1])))
}
p_w.push(p_wi as f32);
}
let unigrams = Arc::new(UnigramProbability::from_vec(p_w));
let at = AggregatorType::Weighted { alpha, vocab:Arc::new(vocab), unigrams };
Ok(FeatureAggregator { at })
},
line => Err(PyValueError::new_err(format!("Unknown aggregator type: {}", line)))?
}
}
}
/// Finally, a node embedder. This wraps the FeatureAggregator because who doesn't like more
/// indirection?
#[pyclass]
pub struct NodeEmbedder {
feat_agg: FeatureAggregator
}
impl NodeEmbedder {
fn get_aggregator<'a>(
&'a self,
es: &'a EmbeddingStore,
aggregator_type: &'a AggregatorType
) -> Box<dyn EmbeddingBuilder + Send + Sync + 'a> {
match aggregator_type {
AggregatorType::Weighted {alpha, vocab:_, unigrams } => {
Box::new(WeightedAggregator::new(es, unigrams, *alpha))
},
AggregatorType::Averaged => {
Box::new(AvgAggregator::new(es))
},
AggregatorType::Attention {num_heads, d_k, window} => {
let at = if let Some(window_size) = window {
AttentionType::Sliding { window_size: *window_size }
} else {
AttentionType::Full