scirs2-datasets 0.4.3

Datasets module for SciRS2 (scirs2-datasets)
Documentation
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
//! WikiText-103 synthetic NLP dataset generator.
//!
//! Generates a synthetic dataset mimicking WikiText-103 structure:
//! - Article / paragraph / token hierarchy
//! - Large Zipfian vocabulary (default 100,000 tokens)
//! - Paragraph lengths sampled from a Poisson distribution
//!
//! Also provides [`WikiText103Dataset::load_from_text`] which reads the
//! WikiText on-disk format (articles delimited by `= Title =` lines,
//! paragraphs by blank lines).

use crate::error::{DatasetsError, Result};
use std::collections::HashMap;
use std::fs;
use std::io::{BufRead, BufReader};
use std::path::Path;

// ─────────────────────────────────────────────────────────────────────────────
// Config
// ─────────────────────────────────────────────────────────────────────────────

/// Configuration for the WikiText-103 synthetic dataset generator.
#[derive(Debug, Clone)]
pub struct WikiText103Config {
    /// Vocabulary size (default: 100_000).
    pub vocab_size: usize,
    /// Number of articles to generate (default: 100).
    pub n_articles: usize,
    /// Average number of paragraphs per article (default: 5).
    pub avg_paragraphs: usize,
    /// Average number of tokens per paragraph (default: 100).
    pub avg_para_tokens: usize,
    /// Random seed for reproducibility.
    pub seed: u64,
}

impl Default for WikiText103Config {
    fn default() -> Self {
        Self {
            vocab_size: 100_000,
            n_articles: 100,
            avg_paragraphs: 5,
            avg_para_tokens: 100,
            seed: 42,
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Internal LCG
// ─────────────────────────────────────────────────────────────────────────────

struct Lcg(u64);

impl Lcg {
    fn new(seed: u64) -> Self {
        Self(if seed == 0 {
            6_364_136_223_846_793_005
        } else {
            seed
        })
    }

    fn next_u64(&mut self) -> u64 {
        self.0 = self
            .0
            .wrapping_mul(6_364_136_223_846_793_005)
            .wrapping_add(1_442_695_040_888_963_407);
        self.0
    }

    fn next_f64(&mut self) -> f64 {
        (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64
    }

    /// Knuth Poisson sampler.
    fn next_poisson(&mut self, lambda: f64) -> usize {
        if lambda <= 0.0 {
            return 0;
        }
        let l = (-lambda).exp();
        let mut k = 0usize;
        let mut p = 1.0_f64;
        loop {
            k += 1;
            p *= self.next_f64().max(1e-300);
            if p <= l {
                break;
            }
        }
        k.saturating_sub(1)
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Zipf sampler (shared structure with penn_treebank but independent)
// ─────────────────────────────────────────────────────────────────────────────

struct ZipfSampler {
    cdf: Vec<f64>,
}

impl ZipfSampler {
    fn new(vocab_size: usize) -> Self {
        let mut cdf = Vec::with_capacity(vocab_size);
        let mut cumsum = 0.0_f64;
        for rank in 0..vocab_size {
            cumsum += 1.0 / (rank + 1) as f64;
            cdf.push(cumsum);
        }
        let total = cumsum;
        for v in &mut cdf {
            *v /= total;
        }
        Self { cdf }
    }

    fn sample(&self, u: f64) -> usize {
        match self.cdf.partition_point(|&c| c < u) {
            idx if idx < self.cdf.len() => idx,
            _ => self.cdf.len() - 1,
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// WikiText103Dataset
// ─────────────────────────────────────────────────────────────────────────────

/// Synthetic WikiText-103-style NLP dataset.
///
/// Structure: `articles[article_idx][paragraph_idx][token_idx]`.
/// Token 0 is `<unk>`, tokens 1..vocab_size are Zipf-ranked vocabulary entries.
#[derive(Debug, Clone)]
pub struct WikiText103Dataset {
    /// `[article][paragraph][token]`
    articles: Vec<Vec<Vec<usize>>>,
    vocab_size: usize,
}

impl WikiText103Dataset {
    /// Generate a synthetic WikiText-103 dataset.
    ///
    /// # Errors
    ///
    /// Returns an error if the configuration is invalid.
    pub fn generate(config: WikiText103Config) -> Result<Self> {
        if config.vocab_size == 0 {
            return Err(DatasetsError::InvalidFormat(
                "WikiText103Config: vocab_size must be > 0".to_string(),
            ));
        }
        if config.n_articles == 0 {
            return Err(DatasetsError::InvalidFormat(
                "WikiText103Config: n_articles must be > 0".to_string(),
            ));
        }

        let zipf = ZipfSampler::new(config.vocab_size);
        let mut rng = Lcg::new(config.seed);
        let avg_paras = config.avg_paragraphs.max(1) as f64;
        let avg_toks = config.avg_para_tokens.max(1) as f64;

        let articles: Vec<Vec<Vec<usize>>> = (0..config.n_articles)
            .map(|_| {
                let n_paras = rng.next_poisson(avg_paras).max(1);
                (0..n_paras)
                    .map(|_| {
                        let n_toks = rng.next_poisson(avg_toks).max(1);
                        (0..n_toks)
                            .map(|_| zipf.sample(rng.next_f64()))
                            .collect::<Vec<usize>>()
                    })
                    .collect::<Vec<Vec<usize>>>()
            })
            .collect();

        Ok(Self {
            articles,
            vocab_size: config.vocab_size,
        })
    }

    /// All articles in `[article][paragraph][token]` order.
    pub fn articles(&self) -> &[Vec<Vec<usize>>] {
        &self.articles
    }

    /// All tokens from all articles and paragraphs concatenated.
    pub fn flat_tokens(&self) -> Vec<usize> {
        self.articles
            .iter()
            .flat_map(|art| art.iter().flat_map(|para| para.iter().copied()))
            .collect()
    }

    /// Vocabulary size.
    pub fn vocab_size(&self) -> usize {
        self.vocab_size
    }

    /// Load a WikiText-format dataset from a file.
    ///
    /// Articles are delimited by lines matching `= Title =` (single `=` on
    /// each side, not `==`). Paragraphs are separated by blank lines.
    /// Words are lowercased and space-separated. The most frequent
    /// `vocab_size - 1` words get indices 1..vocab_size; all others map to 0
    /// (`<unk>`).
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be opened or read.
    pub fn load_from_text(path: impl AsRef<Path>, vocab_size: usize) -> Result<Self> {
        let file = fs::File::open(path.as_ref()).map_err(DatasetsError::IoError)?;
        let reader = BufReader::new(file);

        let mut freq: HashMap<String, usize> = HashMap::new();
        let mut raw_articles: Vec<Vec<Vec<String>>> = Vec::new();
        let mut current_article: Vec<Vec<String>> = Vec::new();
        let mut current_para: Vec<String> = Vec::new();

        let is_top_level_title = |line: &str| -> bool {
            let s = line.trim();
            // Matches "= Some Title =" but NOT "== Subtitle ==" etc.
            if s.starts_with("= ") && s.ends_with(" =") {
                let inner = &s[2..s.len() - 2];
                !inner.contains('=')
            } else {
                false
            }
        };

        for line in reader.lines() {
            let line = line.map_err(DatasetsError::IoError)?;
            if is_top_level_title(&line) {
                // Save current paragraph and article
                if !current_para.is_empty() {
                    current_article.push(std::mem::take(&mut current_para));
                }
                if !current_article.is_empty() {
                    raw_articles.push(std::mem::take(&mut current_article));
                }
                current_article = Vec::new();
            } else if line.trim().is_empty() {
                // Blank line = paragraph boundary
                if !current_para.is_empty() {
                    current_article.push(std::mem::take(&mut current_para));
                }
            } else {
                let words: Vec<String> =
                    line.split_whitespace().map(|w| w.to_lowercase()).collect();
                for w in &words {
                    *freq.entry(w.clone()).or_insert(0) += 1;
                }
                current_para.extend(words);
            }
        }
        // Flush
        if !current_para.is_empty() {
            current_article.push(current_para);
        }
        if !current_article.is_empty() {
            raw_articles.push(current_article);
        }

        // Build vocabulary (top-N by frequency)
        let mut sorted_words: Vec<(String, usize)> = freq.into_iter().collect();
        sorted_words.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
        let vocab: HashMap<String, usize> = sorted_words
            .iter()
            .take(vocab_size.saturating_sub(1))
            .enumerate()
            .map(|(i, (word, _))| (word.clone(), i + 1))
            .collect();

        let articles: Vec<Vec<Vec<usize>>> = raw_articles
            .iter()
            .map(|art| {
                art.iter()
                    .map(|para| para.iter().map(|w| *vocab.get(w).unwrap_or(&0)).collect())
                    .collect()
            })
            .collect();

        Ok(Self {
            articles,
            vocab_size,
        })
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;

    #[test]
    fn test_wt103_shape() {
        let cfg = WikiText103Config {
            vocab_size: 5_000,
            n_articles: 10,
            avg_paragraphs: 3,
            avg_para_tokens: 20,
            seed: 1,
        };
        let ds = WikiText103Dataset::generate(cfg.clone()).expect("generate failed");
        assert_eq!(ds.articles().len(), cfg.n_articles);
        assert_eq!(ds.vocab_size(), cfg.vocab_size);
        assert!(!ds.flat_tokens().is_empty());
    }

    #[test]
    fn test_wt103_deterministic() {
        let cfg = WikiText103Config {
            vocab_size: 1_000,
            n_articles: 5,
            avg_paragraphs: 2,
            avg_para_tokens: 10,
            seed: 99,
        };
        let ds1 = WikiText103Dataset::generate(cfg.clone()).expect("generate failed");
        let ds2 = WikiText103Dataset::generate(cfg).expect("generate failed");
        assert_eq!(ds1.flat_tokens(), ds2.flat_tokens());
    }

    #[test]
    fn test_wt103_token_range() {
        let cfg = WikiText103Config {
            vocab_size: 500,
            n_articles: 5,
            avg_paragraphs: 2,
            avg_para_tokens: 15,
            seed: 7,
        };
        let ds = WikiText103Dataset::generate(cfg.clone()).expect("generate failed");
        for tok in ds.flat_tokens() {
            assert!(tok < cfg.vocab_size, "token {tok} out of range");
        }
    }

    #[test]
    fn test_wt103_paragraph_structure() {
        let cfg = WikiText103Config {
            vocab_size: 200,
            n_articles: 4,
            avg_paragraphs: 3,
            avg_para_tokens: 10,
            seed: 42,
        };
        let ds = WikiText103Dataset::generate(cfg).expect("generate failed");
        for art in ds.articles() {
            assert!(
                !art.is_empty(),
                "each article must have at least 1 paragraph"
            );
            for para in art {
                assert!(
                    !para.is_empty(),
                    "each paragraph must have at least 1 token"
                );
            }
        }
    }

    #[test]
    fn test_wt103_load_from_text() {
        let mut tmp = std::env::temp_dir();
        tmp.push("wt103_test.txt");
        {
            let mut f = fs::File::create(&tmp).expect("create tmp");
            writeln!(f, "= First Article =").expect("write");
            writeln!(f, "This is the first paragraph of the article.").expect("write");
            writeln!(f).expect("write");
            writeln!(f, "Another paragraph with more words and content here.").expect("write");
            writeln!(f, "= Second Article =").expect("write");
            writeln!(f, "The second article starts here with some text.").expect("write");
        }
        let ds = WikiText103Dataset::load_from_text(&tmp, 50).expect("load failed");
        assert_eq!(ds.vocab_size(), 50);
        assert_eq!(ds.articles().len(), 2);
        let _ = fs::remove_file(&tmp);
    }

    #[test]
    fn test_wt103_error_zero_articles() {
        let cfg = WikiText103Config {
            n_articles: 0,
            ..WikiText103Config::default()
        };
        assert!(WikiText103Dataset::generate(cfg).is_err());
    }

    #[test]
    fn test_wt103_flat_tokens_count() {
        let cfg = WikiText103Config {
            vocab_size: 100,
            n_articles: 3,
            avg_paragraphs: 2,
            avg_para_tokens: 5,
            seed: 13,
        };
        let ds = WikiText103Dataset::generate(cfg).expect("generate failed");
        let flat = ds.flat_tokens();
        let expected: usize = ds
            .articles()
            .iter()
            .flat_map(|art| art.iter().map(|p| p.len()))
            .sum();
        assert_eq!(flat.len(), expected);
    }
}