Skip to main content

webgraph_cli/run/
llp.rs

1/*
2 * SPDX-FileCopyrightText: 2023-2026 Inria
3 * SPDX-FileCopyrightText: 2023 Sebastiano Vigna
4 * SPDX-FileCopyrightText: 2023 Tommaso Fontana
5 *
6 * SPDX-License-Identifier: Apache-2.0 OR MIT
7 */
8
9use crate::GranularityArgs;
10use crate::IntSliceFormat;
11use crate::NumThreadsArg;
12use crate::create_parent_dir;
13use crate::get_thread_pool;
14use anyhow::{Context, Result, bail};
15use clap::Parser;
16use dsi_bitstream::dispatch::factory::CodesReaderFactoryHelper;
17use dsi_bitstream::prelude::*;
18use epserde::prelude::*;
19use webgraph::prelude::*;
20use webgraph_algo::llp::preds::{MaxUpdates, MinAvgImprov, MinGain, MinModified, PercModified};
21use webgraph_algo::{combine_labels, labels_to_ranks};
22
23use predicates::prelude::*;
24use std::path::PathBuf;
25use tempfile::tempdir;
26
27#[derive(Parser, Debug)]
28#[command(name = "llp", about = "Computes a permutation of a graph using Layered Label Propagation.", long_about = None, next_line_help = true)]
29pub struct CliArgs {
30    /// The basename of the graph.​
31    pub basename: PathBuf,
32
33    /// Output filename for the LLP permutation. If not provided, only labels
34    /// are computed without combining them into a permutation. In that case,
35    /// --work-dir should be set to preserve the labels.​
36    pub perm: Option<PathBuf>,
37
38    /// The folder where the LLP labels are stored as ε-serde files
39    /// (labels_*.bin plus a labels_*.gap objective value per gamma). If not
40    /// specified, a temporary directory is used and
41    /// deleted at the end; the parent folder for temporary directories can be
42    /// set with the TMPDIR environment variable. A work directory serves to
43    /// save the labels and to resume the computation of gammas, whose
44    /// computation on large graphs might take days. Similar nodes will be
45    /// assigned the same label. To resume computation, compute the remaining
46    /// gammas without passing "perm", and then run "llp-combine" to combine
47    /// all labels in the folder into a final permutation.​
48    #[arg(short, long)]
49    pub work_dir: Option<PathBuf>,
50
51    #[arg(long, value_enum, default_value_t)]
52    /// The format of the permutation file.​
53    pub fmt: IntSliceFormat,
54
55    #[arg(short, long, allow_hyphen_values = true, use_value_delimiter = true, value_delimiter = ',', default_values_t = vec!["-0".to_string(), "-1".to_string(), "-2".to_string(), "-3".to_string(), "-4".to_string(), "-5".to_string(), "-6".to_string(), "-7".to_string(), "-8".to_string(), "-9".to_string(), "-10".to_string()])]
56    /// The ɣ's to use in LLP, separated by commas. The format is given by an
57    /// integer numerator (if missing, assumed to be one), a dash, and then a
58    /// power-of-two exponent for the denominator. For example, -2 is 1/4, and
59    /// 0-0 is 0.​
60    pub gammas: Vec<String>,
61
62    #[clap(flatten)]
63    pub num_threads: NumThreadsArg,
64
65    #[arg(long)]
66    /// Whether to use the identity instead of a random permutation
67    pub no_perm: bool,
68
69    #[arg(short = 'u', long, default_value_t = 100)]
70    /// Maximum number of updates for a given ɣ.​
71    pub max_updates: usize,
72
73    #[arg(short = 'M', long)]
74    /// Stop updates when the number of modified nodes falls below the square
75    /// root of the number of nodes.​
76    pub modified: bool,
77
78    #[arg(short = 'p', long)]
79    /// Stop updates when the fraction of modified nodes falls below this
80    /// percentage.​
81    pub perc_modified: Option<f64>,
82
83    #[arg(short = 'G', long, default_value_t = MinGain::DEFAULT_THRESHOLD)]
84    /// The gain threshold used to stop the computation (0 to disable).​
85    pub gain_threshold: f64,
86
87    #[arg(short = 'i', long, default_value_t = MinAvgImprov::DEFAULT_THRESHOLD)]
88    /// The threshold on the average (over the last ten updates) gain
89    /// improvement used to stop the computation (-Inf to disable).​
90    pub improv_threshold: f64,
91
92    #[arg(short, long, default_value_t = 0)]
93    /// The seed to use for the PRNG.​
94    pub seed: u64,
95
96    #[clap(flatten)]
97    pub granularity: GranularityArgs,
98}
99
100/// Stores a permutation using the given format.
101pub fn store_perm(
102    data: &[usize],
103    perm: impl AsRef<std::path::Path>,
104    fmt: IntSliceFormat,
105) -> Result<()> {
106    fmt.store(perm, data, None)
107}
108
109pub fn main(args: CliArgs) -> Result<()> {
110    if args.perm.is_none() && args.work_dir.is_none() {
111        log::warn!(concat!(
112            "If `perm` is not set the llp will just compute the labels and not produce the final permutation. ",
113            "But you didn't set `work_dir` so the labels will be stored in a temp dir that will be deleted at the end of computation. ",
114            "Either set `perm` if you want to compute the permutation, or `work_dir` if you want the labels and combine them later."
115        ));
116        return Ok(());
117    }
118
119    if let Some(perm) = &args.perm {
120        create_parent_dir(perm)?;
121    }
122
123    dispatch_endianness!(&args.basename, |E| llp::<E>(args))
124}
125
126pub fn llp<E: Endianness + 'static + Send + Sync>(args: CliArgs) -> Result<()>
127where
128    MemoryFactory<E, MmapHelper<u32>>: CodesReaderFactoryHelper<E>,
129    for<'a> LoadModeCodesReader<'a, E, LoadMmap>: BitSeek,
130{
131    let start = std::time::Instant::now();
132    // due to ownership problems, we always create the temp dir, but only use it
133    // if the user didn't provide a work_dir
134    let temp_dir = tempdir()?;
135    let work_dir = args.work_dir.as_deref().unwrap_or(temp_dir.path());
136    log::info!("Using workdir: {}", work_dir.display());
137
138    // Load the graph in THP memory
139    log::info!(
140        "Loading graph {} in THP memory...",
141        args.basename.to_string_lossy()
142    );
143    let graph = BvGraph::with_basename(&args.basename)
144        .mode::<LoadMmap>()
145        .flags(MemoryFlags::TRANSPARENT_HUGE_PAGES | MemoryFlags::RANDOM_ACCESS)
146        .endianness::<E>()
147        .load()?;
148    let num_nodes = graph.num_nodes();
149
150    // Load degree cumulative function in THP memory
151    log::info!("Loading DCF in THP memory...");
152    let deg_cumul = unsafe {
153        DCF::load_mmap(
154            args.basename.with_extension(DEG_CUMUL_EXTENSION),
155            Flags::TRANSPARENT_HUGE_PAGES | Flags::RANDOM_ACCESS,
156        )
157        .with_context(|| {
158            format!(
159                "Could not load degree cumulative function for basename {}",
160                args.basename.display()
161            )
162        })
163    }?;
164
165    // parse the gamma format
166    let mut gammas = vec![];
167    for gamma in args.gammas {
168        let t: Vec<_> = gamma.split('-').collect();
169        if t.len() != 2 {
170            bail!("Invalid gamma: {}", gamma);
171        }
172        gammas.push(
173            if t[0].is_empty() {
174                1.0
175            } else {
176                t[0].parse::<usize>()? as f64
177            } * (0.5_f64).powf(t[1].parse::<usize>()? as f64),
178        );
179    }
180
181    gammas.sort_by(|a, b| a.total_cmp(b));
182
183    let mut predicate = MinGain::try_from(args.gain_threshold)?.boxed();
184    predicate = predicate
185        .or(MinAvgImprov::try_from(args.improv_threshold)?)
186        .boxed();
187    predicate = predicate.or(MaxUpdates::from(args.max_updates)).boxed();
188
189    if args.modified {
190        predicate = predicate.or(MinModified::default()).boxed();
191    }
192
193    if let Some(perc_modified) = args.perc_modified {
194        predicate = predicate.or(PercModified::try_from(perc_modified)?).boxed();
195    }
196
197    let granularity = args.granularity.into_granularity();
198
199    let func_perm_gen = |n: usize, s0: u64, s1: u64| {
200        let funcperm = if args.no_perm {
201            None
202        } else {
203            Some(funcperm::murmur(n as u64, s0, s1))
204        };
205        move |x| match funcperm {
206            None => x,
207            Some(funcperm) => funcperm.get(x),
208        }
209    };
210
211    let thread_pool = get_thread_pool(args.num_threads.num_threads);
212    thread_pool.install(|| -> Result<()> {
213        // compute the LLP
214        webgraph_algo::llp::layered_label_propagation_labels_only(
215            graph,
216            deg_cumul.uncase(),
217            gammas,
218            granularity,
219            args.seed,
220            predicate,
221            func_perm_gen,
222            work_dir,
223        )
224        .context("Could not compute LLP")?;
225
226        log::info!("Elapsed: {}", start.elapsed().as_secs_f64());
227
228        if let Some(perm_path) = args.perm {
229            // An empty graph stores no label files, and its permutation is
230            // empty.
231            let rank_perm = if num_nodes == 0 {
232                Vec::new().into_boxed_slice()
233            } else {
234                let labels = combine_labels(work_dir)?;
235                log::info!("Combined labels...");
236                labels_to_ranks(&labels)
237            };
238            log::info!("Saving permutation...");
239            store_perm(&rank_perm, perm_path, args.fmt)?;
240        }
241
242        Ok(())
243    })
244}