Skip to main content

paper/core/models/
specs.rs

1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
4pub enum ModelKind {
5    Embedding,
6    Reranker,
7}
8
9/// Which query languages a model was trained to handle well.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum LanguageCoverage {
12    English,
13    EnglishChinese,
14    Multilingual,
15}
16
17/// One downloadable artifact, pinned by content hash.
18#[derive(Debug, Clone)]
19pub struct ModelFile {
20    pub name: &'static str,
21    pub sha256: &'static str,
22    pub size: u64,
23}
24
25#[derive(Debug, Clone)]
26pub struct ModelSpec {
27    pub id: &'static str,
28    pub name: &'static str,
29    pub kind: ModelKind,
30    /// First-party Hugging Face repository. Only ungated repositories are used:
31    /// installing Paper never requires an account or a token.
32    pub repo: &'static str,
33    /// Pinned commit, so a re-upload upstream cannot change what we run.
34    pub revision: &'static str,
35    pub files: &'static [ModelFile],
36    pub license: &'static str,
37    pub languages: &'static str,
38    pub coverage: LanguageCoverage,
39    /// Whether this crate's GitHub Release carries the files. When false, only
40    /// the Hugging Face URL is offered.
41    pub mirrored: bool,
42    /// Embedding width. `0` for rerankers, which produce a scalar.
43    pub dims: usize,
44    pub max_tokens: usize,
45    /// Retrieval instruction prefixes. BGE wants one on queries only; E5 wants
46    /// them on both sides. Getting these wrong measurably hurts recall.
47    pub query_prefix: &'static str,
48    pub document_prefix: &'static str,
49}
50
51impl ModelSpec {
52    pub fn size_bytes(&self) -> u64 {
53        self.files.iter().map(|f| f.size).sum()
54    }
55
56    pub fn size_mb(&self) -> u64 {
57        self.size_bytes() / 1_000_000
58    }
59
60    pub fn file(&self, name: &str) -> Option<&ModelFile> {
61        self.files.iter().find(|f| f.name == name)
62    }
63
64    /// Candidate download URLs for one file, in preference order.
65    ///
66    /// The primary source is this crate's own GitHub Release, which carries
67    /// the exact pinned bytes as `<model-id>-<file>` assets (staged by
68    /// `scripts/fetch-models.sh` during release CI). Hugging Face is the
69    /// fallback for development builds whose `v<version>` tag has no release
70    /// yet. Both sources are verified against the same SHA256 pin, so either
71    /// is safe to consume.
72    pub fn download_urls(&self, file_name: &str) -> Vec<String> {
73        let hf = format!(
74            "https://huggingface.co/{}/resolve/{}/{}",
75            self.repo, self.revision, file_name
76        );
77        if !self.mirrored {
78            return vec![hf];
79        }
80        vec![
81            format!(
82                "https://github.com/kintsugi-tools/paperscope/releases/download/v{}/{}-{}",
83                env!("CARGO_PKG_VERSION"),
84                self.id,
85                file_name
86            ),
87            hf,
88        ]
89    }
90}
91
92/// Optional English-only alternative: small, fast. 134 MB total.
93pub const DEFAULT_EMBEDDING: &str = "bge-small-en-v1.5";
94/// Default, downloaded on first run: 100+ languages. 488 MB total.
95pub const MULTILINGUAL_EMBEDDING: &str = "multilingual-e5-small";
96/// Opt-in cross-encoder for precision. 1.13 GB total, multilingual.
97pub const OPTIONAL_RERANKER: &str = "bge-reranker-base";
98/// Small multilingual cross-encoder. 488 MB total.
99pub const MMARCO_RERANKER: &str = "mmarco-mminilmv2-l12-h384";
100/// Large multilingual cross-encoder, Hugging Face only. 2.29 GB total.
101pub const LARGE_RERANKER: &str = "bge-reranker-v2-m3";
102
103/// Width of the vectors in `chunks_vec`. Both supported embedders are 384-dim,
104/// so one index can be rebuilt from either without a schema change.
105pub const EMBEDDING_DIMS: usize = 384;
106
107const BGE_SMALL_FILES: &[ModelFile] = &[
108    ModelFile {
109        name: "model.safetensors",
110        sha256: "3c9f31665447c8911517620762200d2245a2518d6e7208acc78cd9db317e21ad",
111        size: 133_466_304,
112    },
113    ModelFile {
114        name: "config.json",
115        sha256: "094f8e891b932f2000c92cfc663bac4c62069f5d8af5b5278c4306aef3084750",
116        size: 743,
117    },
118    ModelFile {
119        name: "tokenizer.json",
120        sha256: "d241a60d5e8f04cc1b2b3e9ef7a4921b27bf526d9f6050ab90f9267a1f9e5c66",
121        size: 711_396,
122    },
123];
124
125const E5_SMALL_FILES: &[ModelFile] = &[
126    ModelFile {
127        name: "model.safetensors",
128        sha256: "1a55775f53449dac10a2bcbc312469fac40b96d53198c407081a831f81c98477",
129        size: 470_641_600,
130    },
131    ModelFile {
132        name: "config.json",
133        sha256: "69137736cab8b8903a07fe8afaafdda25aac55415a12a55d1bffa9f581abf959",
134        size: 655,
135    },
136    ModelFile {
137        name: "tokenizer.json",
138        sha256: "0b44a9d7b51c3c62626640cda0e2c2f70fdacdc25bbbd68038369d14ebdf4c39",
139        size: 17_082_730,
140    },
141];
142
143const BGE_RERANKER_FILES: &[ModelFile] = &[
144    ModelFile {
145        name: "model.safetensors",
146        sha256: "ced967c45fd1902eb92716c9ceeca7c95a936770ea9db611f5a841b926e33fbd",
147        size: 1_112_206_140,
148    },
149    ModelFile {
150        name: "config.json",
151        sha256: "289adf7ada1eb6b4afa7589a48a032d45a076cf2e46dcdb3b4cabc33be14f708",
152        size: 799,
153    },
154    ModelFile {
155        name: "tokenizer.json",
156        sha256: "9eb652ac4e40cc093272bbbe0f55d521cf67570060227109b5cdc20945a4489e",
157        size: 17_098_107,
158    },
159];
160
161const MMARCO_FILES: &[ModelFile] = &[
162    ModelFile {
163        name: "model.safetensors",
164        sha256: "5daeca2481a76b5976a2bdc32f0a78532b6716da4f8cd3ff59460ef8d2f359b4",
165        size: 470_592_698,
166    },
167    ModelFile {
168        name: "config.json",
169        sha256: "cc2cfe51aa3fd759d21d21acf5dfd6994aa67a3c9210636d22e143699d336c77",
170        size: 891,
171    },
172    ModelFile {
173        name: "tokenizer.json",
174        sha256: "62c24cdc13d4c9952d63718d6c9fa4c287974249e16b7ade6d5a85e7bbb75626",
175        size: 17_082_660,
176    },
177];
178
179const BGE_V2_M3_FILES: &[ModelFile] = &[
180    ModelFile {
181        name: "model.safetensors",
182        sha256: "d9e3e081faff1eefb84019509b2f5558fd74c1a05a2c7db22f74174fcedb5286",
183        size: 2_271_071_852,
184    },
185    ModelFile {
186        name: "config.json",
187        sha256: "13dcd6c31d9fec9d1d8e158702072f62d7fa7d312a64b9fe057bec9a08cfe41a",
188        size: 795,
189    },
190    ModelFile {
191        name: "tokenizer.json",
192        sha256: "69564b696052886ed0ac63fa393e928384e0f8caada38c1f4864a9bfbf379c15",
193        size: 17_098_273,
194    },
195];
196
197pub fn all_specs() -> Vec<ModelSpec> {
198    vec![
199        ModelSpec {
200            id: DEFAULT_EMBEDDING,
201            name: "BGE small English v1.5 (English-only, 384 dims)",
202            kind: ModelKind::Embedding,
203            repo: "BAAI/bge-small-en-v1.5",
204            revision: "5c38ec7c405ec4b44b94cc5a9bb96e735b38267a",
205            files: BGE_SMALL_FILES,
206            license: "MIT",
207            languages: "English",
208            coverage: LanguageCoverage::English,
209            mirrored: true,
210            dims: 384,
211            max_tokens: 512,
212            query_prefix: "Represent this sentence for searching relevant passages: ",
213            document_prefix: "",
214        },
215        ModelSpec {
216            id: MULTILINGUAL_EMBEDDING,
217            name: "Multilingual E5 small (default, 384 dims)",
218            kind: ModelKind::Embedding,
219            repo: "intfloat/multilingual-e5-small",
220            revision: "614241f622f53c4eeff9890bdc4f31cfecc418b3",
221            files: E5_SMALL_FILES,
222            license: "MIT",
223            languages: "100+ languages",
224            coverage: LanguageCoverage::Multilingual,
225            mirrored: true,
226            dims: 384,
227            max_tokens: 512,
228            query_prefix: "query: ",
229            document_prefix: "passage: ",
230        },
231        ModelSpec {
232            id: OPTIONAL_RERANKER,
233            name: "BGE reranker base (opt-in precision)",
234            kind: ModelKind::Reranker,
235            repo: "BAAI/bge-reranker-base",
236            revision: "2cfc18c9415c912f9d8155881c133215df768a70",
237            files: BGE_RERANKER_FILES,
238            license: "MIT",
239            languages: "English, Chinese",
240            coverage: LanguageCoverage::EnglishChinese,
241            mirrored: true,
242            dims: 0,
243            max_tokens: 512,
244            query_prefix: "",
245            document_prefix: "",
246        },
247        ModelSpec {
248            id: MMARCO_RERANKER,
249            name: "mMARCO multilingual MiniLM reranker",
250            kind: ModelKind::Reranker,
251            repo: "cross-encoder/mmarco-mMiniLMv2-L12-H384-v1",
252            revision: "1427fd652930e4ba29e8149678df786c240d8825",
253            files: MMARCO_FILES,
254            license: "Apache-2.0",
255            languages: "Multilingual",
256            coverage: LanguageCoverage::Multilingual,
257            mirrored: true,
258            dims: 0,
259            max_tokens: 512,
260            query_prefix: "",
261            document_prefix: "",
262        },
263        ModelSpec {
264            id: LARGE_RERANKER,
265            name: "BGE reranker v2 m3 (large, multilingual)",
266            kind: ModelKind::Reranker,
267            repo: "BAAI/bge-reranker-v2-m3",
268            revision: "953dc6f6f85a1b2dbfca4c34a2796e7dde08d41e",
269            files: BGE_V2_M3_FILES,
270            license: "Apache-2.0",
271            languages: "Multilingual",
272            coverage: LanguageCoverage::Multilingual,
273            mirrored: false,
274            dims: 0,
275            max_tokens: 512,
276            query_prefix: "",
277            document_prefix: "",
278        },
279    ]
280}
281
282pub fn spec(model_id: &str) -> Option<ModelSpec> {
283    all_specs().into_iter().find(|s| s.id == model_id)
284}
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289
290    #[test]
291    fn download_urls_prefer_github_releases_with_dist_asset_names() {
292        let spec = spec(DEFAULT_EMBEDDING).unwrap();
293        let urls = spec.download_urls("model.safetensors");
294        assert_eq!(urls.len(), 2);
295        // Must match the staged asset names in dist-workspace.toml:
296        // `models/release/<model-id>-<file>`.
297        assert_eq!(
298            urls[0],
299            format!(
300                "https://github.com/kintsugi-tools/paperscope/releases/download/v{}/bge-small-en-v1.5-model.safetensors",
301                env!("CARGO_PKG_VERSION")
302            )
303        );
304        // Hugging Face stays the fallback, pinned to the same revision.
305        assert!(urls[1].starts_with("https://huggingface.co/BAAI/bge-small-en-v1.5/resolve/"));
306        assert!(urls[1].ends_with("/model.safetensors"));
307    }
308
309    #[test]
310    fn new_rerankers_are_pinned_and_mirrored_as_designed() {
311        let hex = |s: &str, n: usize| s.len() == n && s.chars().all(|c| c.is_ascii_hexdigit());
312        for id in [MMARCO_RERANKER, LARGE_RERANKER] {
313            let s = spec(id).unwrap();
314            assert!(hex(s.revision, 40), "{id}");
315            assert_eq!(s.files.len(), 3);
316            for f in s.files {
317                assert!(hex(f.sha256, 64) && f.size > 0, "{id} {}", f.name);
318            }
319            assert_eq!(s.coverage, LanguageCoverage::Multilingual);
320        }
321        assert_eq!(
322            spec(MMARCO_RERANKER)
323                .unwrap()
324                .download_urls("config.json")
325                .len(),
326            2
327        );
328        let large = spec(LARGE_RERANKER).unwrap().download_urls("config.json");
329        assert_eq!(large.len(), 1);
330        assert!(large[0].starts_with("https://huggingface.co/BAAI/bge-reranker-v2-m3/resolve/"));
331    }
332}