cuda-driver: opt-in LELEKA_DRAFT_VOCAB selects an upstream draft subset (en, cyrillic, fr or a file)
The MTP draft head projects over the rows listed in rt/draft_vocab.bin (106,299 ids). Upstream ships draft_vocab_en.bin (40,525 ids, 65,774 head rows fewer: ~110 MiB of VRAM and a shorter draft GEMV, at the price that CJK/Cyrillic tokens can never be proposed). LELEKA_DRAFT_VOCAB=en|cyrillic|fr|<path> picks one; unset (or 0/off/default) keeps rt/draft_vocab.bin and reads, logs and changes nothing. * a selected file must have the sha256 of a recorded upstream subset (a name: that name's digest); another digest, a symlink, a wrong size or a too-large file is refused (the arm fails to load) * a file that does not exist falls back to rt/draft_vocab.bin with one `FALLBACK` log line * the startup VRAM reserve follows the selected file's size, so the freed VRAM reaches the expert slots * one `leleka-serve draft-vocab: ... subset=en ids=40525 sha256=... file=...` line per bind when set * sha2 becomes a dependency of leleka-cuda-driver (already in the workspace) Unit tests (CPU only): setting parsing, table consistency, default reads/logs nothing, missing file falls back, wrong digest refused for a name and a path, accepted digest reads the selected ids and the reserve probe sees its size, malformed/oversized/symlink refused, subset index <-> full id round trip and ids outside a subset. A real-file test runs when LELEKA_TEST_DRAFT_VOCAB_DIR names a directory with the upstream draft_vocab*.bin (digests, counts, en ascending and inside the default list). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
e92513b722
commit
4232adaf44
Generated
+1
@@ -1293,6 +1293,7 @@ dependencies = [
|
||||
"leleka-model-format",
|
||||
"libc",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -10,6 +10,8 @@ rust-version.workspace = true
|
||||
leleka-model-format = { path = "../model-format" }
|
||||
leleka-context = { path = "../context" }
|
||||
leleka-experimental-ref = { path = "../experimental-ref" }
|
||||
# sha256 of the opt-in draft-vocabulary subset file (LELEKA_DRAFT_VOCAB); same version as model-format
|
||||
sha2 = "0.11"
|
||||
|
||||
[features]
|
||||
default = []
|
||||
|
||||
@@ -131,6 +131,7 @@ pub use original_mtp_actor::{OriginalMtpActor, OriginalMtpLoadEvidence, Original
|
||||
target_pointer_width = "64"
|
||||
))]
|
||||
mod original_mtp_draft_head;
|
||||
mod original_mtp_draft_vocab;
|
||||
#[cfg(all(
|
||||
feature = "cuda-driver",
|
||||
any(target_os = "linux", target_os = "windows"),
|
||||
|
||||
@@ -0,0 +1,596 @@
|
||||
//! Opt-in choice of the MTP draft head's token subset: `LELEKA_DRAFT_VOCAB`.
|
||||
//!
|
||||
//! The Original drafts over the rows of the main native head listed in `rt/draft_vocab.bin` (int32 token ids, 106,299 of
|
||||
//! the 248,320 rows, English, code and every CJK token). Upstream Strata ships three smaller or different subsets built
|
||||
//! with the same tool (`engine/strata/tools/draft_vocab.py`) and selects one with `--draft-vocab en|cyrillic|fr` or
|
||||
//! `--mtp-draft-vocab FILE`. The English subset (`draft_vocab_en.bin`, 40,525 ids) drops 65,774 head rows from the draft:
|
||||
//! about 110 MiB less VRAM and a shorter draft LM-head GEMV, at the price that a token outside the subset can never be
|
||||
//! proposed (CJK, most Cyrillic).
|
||||
//!
|
||||
//! The draft only proposes; the verifier decides every token. The output therefore does not depend on the subset in
|
||||
//! principle. In practice a different subset changes which tokens are accepted, so the verifier windows have other
|
||||
//! shapes, which can change the rounding class of the verified rows: that is why this stays an opt-in with its own
|
||||
//! identity gate (`docs/experiments/2026-10-30-draft-vocab-en.md`).
|
||||
//!
|
||||
//! `LELEKA_DRAFT_VOCAB` values:
|
||||
//! * unset, empty, `0`, `off`, `default`: `rt/draft_vocab.bin`, exactly as before (nothing is read or logged).
|
||||
//! * `en`, `cyrillic`, `fr`: `draft_vocab_<name>.bin` in the same RT directory as `draft_vocab.bin`.
|
||||
//! * anything else: a path to a subset file.
|
||||
//!
|
||||
//! A selected file is accepted only when its sha256 is one of the recorded upstream subsets below (for a name, the
|
||||
//! digest of that name). A different digest, a wrong size or an id the next stage rejects (outside the vocabulary) is
|
||||
//! refused: the arm fails to load instead of silently running another subset. A file that does not exist falls back to
|
||||
//! `rt/draft_vocab.bin` with one log line saying so (an A/B harness must treat that line as an invalid arm).
|
||||
|
||||
use crate::original_mtp_rt::{DRAFT_VOCAB_MAX_IDS, DraftVocab, RtError, draft_vocab_path};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{
|
||||
ffi::OsStr,
|
||||
fs,
|
||||
io::{ErrorKind, Read},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
pub(crate) const ENV: &str = "LELEKA_DRAFT_VOCAB";
|
||||
|
||||
/// One recorded upstream subset (Strata `data/`, identical at 41cf05a0, v0.2.7.1 and v0.2.8).
|
||||
pub(crate) struct KnownSubset {
|
||||
pub name: &'static str,
|
||||
pub file: &'static str,
|
||||
pub sha256: &'static str,
|
||||
pub ids: usize,
|
||||
}
|
||||
|
||||
pub(crate) const KNOWN: [KnownSubset; 4] = [
|
||||
KnownSubset {
|
||||
name: "default",
|
||||
file: "draft_vocab.bin",
|
||||
sha256: "b1e1d3a7a9e4bf862dcd5923ce661fb59bbd07907e594df5cf86a62ac235cb91",
|
||||
ids: 106_299,
|
||||
},
|
||||
KnownSubset {
|
||||
name: "en",
|
||||
file: "draft_vocab_en.bin",
|
||||
sha256: "369151522226a5edaa5f12cfd1e2ae7db8f4fbdbd222f3dcf327dced9597fb25",
|
||||
ids: 40_525,
|
||||
},
|
||||
KnownSubset {
|
||||
name: "cyrillic",
|
||||
file: "draft_vocab_cyrillic.bin",
|
||||
sha256: "25d7fd1670a2e0ec885868d1718d410a3baab03bceeacf0a156cf93ffe4e1ef4",
|
||||
ids: 58_963,
|
||||
},
|
||||
KnownSubset {
|
||||
name: "fr",
|
||||
file: "draft_vocab_fr.bin",
|
||||
sha256: "42b9993629f757c17ad30fc8c242533cb702330f359e85ba729a70d10ef12a81",
|
||||
ids: 46_211,
|
||||
},
|
||||
];
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Setting {
|
||||
/// `rt/draft_vocab.bin`.
|
||||
Default,
|
||||
/// An index into [`KNOWN`] (never 0): the file sits beside `draft_vocab.bin`.
|
||||
Named(usize),
|
||||
Path(PathBuf),
|
||||
}
|
||||
|
||||
impl Setting {
|
||||
pub(crate) fn parse(value: Option<&OsStr>) -> Setting {
|
||||
let Some(value) = value else {
|
||||
return Setting::Default;
|
||||
};
|
||||
match value.to_str() {
|
||||
None => Setting::Path(PathBuf::from(value)),
|
||||
Some("" | "0" | "off" | "default") => Setting::Default,
|
||||
Some(text) => match KNOWN.iter().position(|k| k.name == text) {
|
||||
Some(0) => Setting::Default,
|
||||
Some(index) => Setting::Named(index),
|
||||
None => Setting::Path(PathBuf::from(text)),
|
||||
},
|
||||
}
|
||||
}
|
||||
pub(crate) fn from_environment() -> Setting {
|
||||
Setting::parse(std::env::var_os(ENV).as_deref())
|
||||
}
|
||||
}
|
||||
|
||||
/// What the setting resolved to, after the file was read and checked.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Selection {
|
||||
/// Use `rt/draft_vocab.bin` (no setting).
|
||||
Default,
|
||||
/// The selected file does not exist: use `rt/draft_vocab.bin` and say so.
|
||||
Fallback { requested: String },
|
||||
/// A checked subset file.
|
||||
Verified {
|
||||
label: &'static str,
|
||||
path: PathBuf,
|
||||
sha256: &'static str,
|
||||
bytes: Vec<u8>,
|
||||
},
|
||||
}
|
||||
|
||||
pub(crate) fn hex(digest: &[u8]) -> String {
|
||||
digest.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
fn refuse(path: &Path, why: &str) -> RtError {
|
||||
RtError::DraftVocabSelection(format!("{ENV}: {} {why}", path.display()))
|
||||
}
|
||||
|
||||
/// Reads and checks the file the setting names against the recorded subsets. Pure over the filesystem: no environment, no log.
|
||||
pub(crate) fn select(directory: &Path, setting: &Setting) -> Result<Selection, RtError> {
|
||||
select_in(directory, setting, &KNOWN)
|
||||
}
|
||||
|
||||
/// [`select`] over an explicit table (the unit tests install digests of synthetic files).
|
||||
pub(crate) fn select_in(
|
||||
directory: &Path,
|
||||
setting: &Setting,
|
||||
table: &[KnownSubset],
|
||||
) -> Result<Selection, RtError> {
|
||||
let (path, wanted) = match setting {
|
||||
Setting::Default => return Ok(Selection::Default),
|
||||
Setting::Named(index) => (directory.join(table[*index].file), Some(*index)),
|
||||
Setting::Path(path) => (path.clone(), None),
|
||||
};
|
||||
let requested = path.display().to_string();
|
||||
let metadata = match fs::symlink_metadata(&path) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(error) if error.kind() == ErrorKind::NotFound => {
|
||||
return Ok(Selection::Fallback { requested });
|
||||
}
|
||||
Err(error) => {
|
||||
return Err(refuse(
|
||||
&path,
|
||||
&format!("cannot be inspected ({})", error.kind()),
|
||||
));
|
||||
}
|
||||
};
|
||||
if metadata.file_type().is_symlink() || !metadata.is_file() {
|
||||
return Err(refuse(&path, "is not a regular file"));
|
||||
}
|
||||
let length = metadata.len();
|
||||
if length < 4 || length % 4 != 0 {
|
||||
return Err(refuse(&path, "is not a whole number of int32 ids"));
|
||||
}
|
||||
if length / 4 > DRAFT_VOCAB_MAX_IDS {
|
||||
return Err(RtError::DraftVocabTooLarge);
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
bytes
|
||||
.try_reserve_exact(length as usize)
|
||||
.map_err(|_| RtError::Host)?;
|
||||
let mut file = fs::File::open(&path).map_err(|_| refuse(&path, "cannot be opened"))?;
|
||||
// one bounded read: a file that grew since the lstat is cut at `length + 1` and refused below
|
||||
file.by_ref()
|
||||
.take(length + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|_| refuse(&path, "cannot be read"))?;
|
||||
if bytes.len() as u64 != length {
|
||||
return Err(refuse(&path, "changed while it was read"));
|
||||
}
|
||||
let actual = hex(&Sha256::digest(&bytes));
|
||||
let known = match wanted {
|
||||
Some(index) => (table[index].sha256 == actual).then_some(&table[index]),
|
||||
None => table.iter().find(|k| k.sha256 == actual),
|
||||
};
|
||||
let Some(known) = known else {
|
||||
return Err(refuse(
|
||||
&path,
|
||||
&format!(
|
||||
"has sha256 {actual}, which is {}; refused",
|
||||
match wanted {
|
||||
Some(index) => format!(
|
||||
"not the recorded {} subset {}",
|
||||
table[index].name, table[index].sha256
|
||||
),
|
||||
None => "none of the recorded subsets (default, en, cyrillic, fr)".to_string(),
|
||||
}
|
||||
),
|
||||
));
|
||||
};
|
||||
if bytes.len() / 4 != known.ids {
|
||||
// unreachable with a matching digest; kept so a wrong table row cannot pass silently
|
||||
return Err(refuse(&path, "does not hold the recorded number of ids"));
|
||||
}
|
||||
Ok(Selection::Verified {
|
||||
label: known.name,
|
||||
path,
|
||||
sha256: known.sha256,
|
||||
bytes,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn ids_of(bytes: &[u8]) -> Vec<i32> {
|
||||
bytes
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|b| i32::from_le_bytes(*b))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The subset the draft head binds, or `None` to take the default file's own reading.
|
||||
pub(crate) fn subset(selection: &Selection) -> Option<DraftVocab> {
|
||||
match selection {
|
||||
Selection::Verified { bytes, .. } => Some(DraftVocab::Subset(ids_of(bytes))),
|
||||
Selection::Default | Selection::Fallback { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `bind_bytes` probe of the selected file: its size (the default file's size when nothing is selected).
|
||||
pub(crate) fn probe_bytes(directory: &Path, selection: &Selection) -> Option<u64> {
|
||||
match selection {
|
||||
Selection::Verified { bytes, .. } => Some(bytes.len() as u64),
|
||||
Selection::Default | Selection::Fallback { .. } => {
|
||||
let path = draft_vocab_path(directory);
|
||||
let link = fs::symlink_metadata(&path).ok()?;
|
||||
(link.is_file() && !link.file_type().is_symlink()).then_some(link.len())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The one log line of a non-default setting; `None` for the default.
|
||||
pub(crate) fn describe(selection: &Selection) -> Option<String> {
|
||||
match selection {
|
||||
Selection::Default => None,
|
||||
Selection::Fallback { requested } => Some(format!(
|
||||
"leleka-serve draft-vocab: {ENV} file {requested} not found, FALLBACK to rt/draft_vocab.bin"
|
||||
)),
|
||||
Selection::Verified {
|
||||
label,
|
||||
path,
|
||||
sha256,
|
||||
bytes,
|
||||
} => Some(format!(
|
||||
"leleka-serve draft-vocab: {ENV} subset={label} ids={} sha256={sha256} file={}",
|
||||
bytes.len() / 4,
|
||||
path.display()
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::original_mtp_coupled::subset_inverse;
|
||||
use crate::original_mtp_rt::{
|
||||
fixtures::{TempDir, write},
|
||||
observed_draft_vocab_bytes_with, read_draft_vocab_with, validate_subset,
|
||||
};
|
||||
|
||||
fn raw(ids: &[i32]) -> Vec<u8> {
|
||||
ids.iter().flat_map(|i| i.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_parses_names_paths_and_the_default_spellings() {
|
||||
for off in [None, Some(""), Some("0"), Some("off"), Some("default")] {
|
||||
assert_eq!(
|
||||
Setting::parse(off.map(OsStr::new)),
|
||||
Setting::Default,
|
||||
"{off:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(Setting::parse(Some(OsStr::new("en"))), Setting::Named(1));
|
||||
assert_eq!(
|
||||
Setting::parse(Some(OsStr::new("cyrillic"))),
|
||||
Setting::Named(2)
|
||||
);
|
||||
assert_eq!(Setting::parse(Some(OsStr::new("fr"))), Setting::Named(3));
|
||||
assert_eq!(
|
||||
Setting::parse(Some(OsStr::new("/data/x/draft_vocab_en.bin"))),
|
||||
Setting::Path(PathBuf::from("/data/x/draft_vocab_en.bin"))
|
||||
);
|
||||
// case matters: "EN" is a (missing) path, not the English subset
|
||||
assert_eq!(
|
||||
Setting::parse(Some(OsStr::new("EN"))),
|
||||
Setting::Path(PathBuf::from("EN"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recorded_table_is_consistent() {
|
||||
assert_eq!(KNOWN[0].name, "default");
|
||||
assert_eq!(KNOWN[0].file, "draft_vocab.bin");
|
||||
for k in &KNOWN {
|
||||
assert_eq!(k.sha256.len(), 64, "{}", k.name);
|
||||
assert!(
|
||||
k.sha256
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()),
|
||||
"{}",
|
||||
k.name
|
||||
);
|
||||
assert_eq!(
|
||||
k.file,
|
||||
if k.name == "default" {
|
||||
"draft_vocab.bin".to_string()
|
||||
} else {
|
||||
format!("draft_vocab_{}.bin", k.name)
|
||||
}
|
||||
);
|
||||
assert!(k.ids as u64 <= DRAFT_VOCAB_MAX_IDS);
|
||||
}
|
||||
let mut digests: Vec<_> = KNOWN.iter().map(|k| k.sha256).collect();
|
||||
digests.sort_unstable();
|
||||
digests.dedup();
|
||||
assert_eq!(digests.len(), KNOWN.len());
|
||||
// sha256 of the empty input pins the hex spelling used for the comparison
|
||||
assert_eq!(
|
||||
hex(&Sha256::digest(b"")),
|
||||
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_setting_reads_nothing_and_logs_nothing() {
|
||||
let dir = TempDir::new("dv-default");
|
||||
write(&dir, "draft_vocab_en.bin", &raw(&[1, 2, 3]));
|
||||
let selection = select(&dir.0, &Setting::Default).unwrap();
|
||||
assert_eq!(selection, Selection::Default);
|
||||
assert_eq!(describe(&selection), None);
|
||||
assert_eq!(subset(&selection), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_file_falls_back_to_the_default_file_with_a_log_line() {
|
||||
let dir = TempDir::new("dv-missing");
|
||||
let ids = [7i32, 3, 9];
|
||||
write(&dir, "draft_vocab.bin", &raw(&ids));
|
||||
for setting in [Setting::Named(1), Setting::Path(dir.0.join("nowhere.bin"))] {
|
||||
let selection = select(&dir.0, &setting).unwrap();
|
||||
assert!(
|
||||
matches!(selection, Selection::Fallback { .. }),
|
||||
"{setting:?}"
|
||||
);
|
||||
assert!(describe(&selection).unwrap().contains("FALLBACK"));
|
||||
assert_eq!(subset(&selection), None);
|
||||
// the reserve probe and the reader then see rt/draft_vocab.bin
|
||||
assert_eq!(probe_bytes(&dir.0, &selection), Some(12));
|
||||
}
|
||||
assert_eq!(
|
||||
read_draft_vocab_with(&dir.0, &Setting::Named(1)).unwrap(),
|
||||
DraftVocab::Subset(ids.to_vec())
|
||||
);
|
||||
assert_eq!(
|
||||
observed_draft_vocab_bytes_with(&dir.0, &Setting::Named(1)),
|
||||
Some(12)
|
||||
);
|
||||
}
|
||||
|
||||
/// A table whose digests belong to synthetic files, so the accepted path runs without the upstream data.
|
||||
fn table_for(default: &[u8], en: &[u8]) -> [KnownSubset; 2] {
|
||||
let leak = |bytes: &[u8]| -> &'static str {
|
||||
Box::leak(hex(&Sha256::digest(bytes)).into_boxed_str())
|
||||
};
|
||||
[
|
||||
KnownSubset {
|
||||
name: "default",
|
||||
file: "draft_vocab.bin",
|
||||
sha256: leak(default),
|
||||
ids: default.len() / 4,
|
||||
},
|
||||
KnownSubset {
|
||||
name: "en",
|
||||
file: "draft_vocab_en.bin",
|
||||
sha256: leak(en),
|
||||
ids: en.len() / 4,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matching_digest_is_accepted_and_reads_the_selected_ids() {
|
||||
let dir = TempDir::new("dv-ok");
|
||||
let default_ids = [40i32, 3, 9, 63, 0, 17];
|
||||
let english_ids = [0i32, 3, 9, 17];
|
||||
let (default, en) = (raw(&default_ids), raw(&english_ids));
|
||||
write(&dir, "draft_vocab.bin", &default);
|
||||
write(&dir, "draft_vocab_en.bin", &en);
|
||||
write(&dir, "elsewhere.bin", &en);
|
||||
let table = table_for(&default, &en);
|
||||
for setting in [
|
||||
Setting::Named(1),
|
||||
Setting::Path(dir.0.join("elsewhere.bin")),
|
||||
] {
|
||||
let selection = select_in(&dir.0, &setting, &table).unwrap();
|
||||
let Selection::Verified { label, bytes, .. } = &selection else {
|
||||
panic!("{selection:?}")
|
||||
};
|
||||
assert_eq!((*label, bytes.len()), ("en", 16));
|
||||
assert_eq!(
|
||||
crate::original_mtp_rt::read_selected_draft_vocab(&dir.0, &selection).unwrap(),
|
||||
DraftVocab::Subset(english_ids.to_vec())
|
||||
);
|
||||
assert_eq!(probe_bytes(&dir.0, &selection), Some(16));
|
||||
let line = describe(&selection).unwrap();
|
||||
assert!(
|
||||
line.contains("subset=en") && line.contains("ids=4"),
|
||||
"{line}"
|
||||
);
|
||||
}
|
||||
// the digest of another recorded subset does not satisfy a name: `en` pointing at the default bytes is refused
|
||||
write(&dir, "draft_vocab_en.bin", &default);
|
||||
assert!(matches!(
|
||||
select_in(&dir.0, &Setting::Named(1), &table).unwrap_err(),
|
||||
RtError::DraftVocabSelection(_)
|
||||
));
|
||||
// but the same file given as a path is a recorded subset (the default one)
|
||||
let by_path = select_in(
|
||||
&dir.0,
|
||||
&Setting::Path(dir.0.join("draft_vocab_en.bin")),
|
||||
&table,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
by_path,
|
||||
Selection::Verified {
|
||||
label: "default",
|
||||
..
|
||||
}
|
||||
));
|
||||
// a changed byte is refused
|
||||
let mut changed = en.clone();
|
||||
changed[0] ^= 1;
|
||||
write(&dir, "elsewhere.bin", &changed);
|
||||
assert!(select_in(&dir.0, &Setting::Path(dir.0.join("elsewhere.bin")), &table).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_digest_is_refused_for_a_name_and_for_a_path() {
|
||||
let dir = TempDir::new("dv-digest");
|
||||
let bytes = raw(&[1, 2, 3, 4]);
|
||||
write(&dir, "draft_vocab_en.bin", &bytes);
|
||||
write(&dir, "other.bin", &bytes);
|
||||
let digest = hex(&Sha256::digest(&bytes));
|
||||
for setting in [Setting::Named(1), Setting::Path(dir.0.join("other.bin"))] {
|
||||
let error = select(&dir.0, &setting).unwrap_err();
|
||||
let RtError::DraftVocabSelection(text) = &error else {
|
||||
panic!("{error:?}")
|
||||
};
|
||||
assert!(text.contains(&digest), "{text}");
|
||||
assert!(text.contains("refused"), "{text}");
|
||||
// the load path surfaces the same refusal and the reserve probe does not claim a size for it
|
||||
assert_eq!(read_draft_vocab_with(&dir.0, &setting).unwrap_err(), error);
|
||||
assert_eq!(observed_draft_vocab_bytes_with(&dir.0, &setting), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_files_are_refused_not_ignored() {
|
||||
let dir = TempDir::new("dv-shape");
|
||||
for (name, bytes) in [
|
||||
("empty.bin", &b""[..]),
|
||||
("odd.bin", &b"abcdef"[..]),
|
||||
("three.bin", &b"abc"[..]),
|
||||
] {
|
||||
write(&dir, name, bytes);
|
||||
let error = select(&dir.0, &Setting::Path(dir.0.join(name))).unwrap_err();
|
||||
assert!(
|
||||
matches!(error, RtError::DraftVocabSelection(_)),
|
||||
"{name}: {error:?}"
|
||||
);
|
||||
}
|
||||
// a directory is not a subset file
|
||||
std::fs::create_dir(dir.0.join("dir.bin")).unwrap();
|
||||
assert!(matches!(
|
||||
select(&dir.0, &Setting::Path(dir.0.join("dir.bin"))).unwrap_err(),
|
||||
RtError::DraftVocabSelection(_)
|
||||
));
|
||||
write(
|
||||
&dir,
|
||||
"huge.bin",
|
||||
&vec![0u8; (DRAFT_VOCAB_MAX_IDS as usize + 1) * 4],
|
||||
);
|
||||
assert_eq!(
|
||||
select(&dir.0, &Setting::Path(dir.0.join("huge.bin"))).unwrap_err(),
|
||||
RtError::DraftVocabTooLarge
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn symlink_is_refused() {
|
||||
let dir = TempDir::new("dv-link");
|
||||
write(&dir, "real.bin", &raw(&[1]));
|
||||
std::os::unix::fs::symlink(dir.0.join("real.bin"), dir.0.join("link.bin")).unwrap();
|
||||
assert!(matches!(
|
||||
select(&dir.0, &Setting::Path(dir.0.join("link.bin"))).unwrap_err(),
|
||||
RtError::DraftVocabSelection(_)
|
||||
));
|
||||
}
|
||||
|
||||
/// Subset index -> token id -> subset index, and the ids no subset row can propose. Synthetic ids with the shape of
|
||||
/// the real files (ascending English subset inside an unordered, larger default list).
|
||||
#[test]
|
||||
fn draft_tokens_round_trip_to_full_ids() {
|
||||
let vocabulary = 64usize;
|
||||
let default: Vec<i32> = vec![40, 3, 9, 63, 0, 17, 22, 5, 31, 12];
|
||||
let english: Vec<i32> = vec![0, 3, 5, 9, 17, 31];
|
||||
for ids in [&default, &english] {
|
||||
validate_subset(ids, vocabulary).unwrap();
|
||||
let inverse = subset_inverse(vocabulary, ids).unwrap();
|
||||
for (index, &id) in ids.iter().enumerate() {
|
||||
// draft row index -> full vocabulary id (the device `sub_to_id` gather) -> row index (`id_to_sub`)
|
||||
assert_eq!(inverse[id as usize], index as i32, "id {id}");
|
||||
assert_eq!(ids[inverse[id as usize] as usize], id);
|
||||
}
|
||||
let inside: std::collections::HashSet<i32> = ids.iter().copied().collect();
|
||||
for id in 0..vocabulary as i32 {
|
||||
assert_eq!(inverse[id as usize] >= 0, inside.contains(&id), "id {id}");
|
||||
}
|
||||
}
|
||||
// the restricted subset can propose exactly its own ids: a token the default list can draft and `en` cannot
|
||||
let wide = subset_inverse(vocabulary, &default).unwrap();
|
||||
let narrow = subset_inverse(vocabulary, &english).unwrap();
|
||||
for dropped in default.iter().filter(|id| !english.contains(id)) {
|
||||
assert!(
|
||||
wide[*dropped as usize] >= 0 && narrow[*dropped as usize] < 0,
|
||||
"id {dropped}"
|
||||
);
|
||||
}
|
||||
// an id past the vocabulary is refused before any device gather reads a head row with it
|
||||
assert_eq!(
|
||||
validate_subset(&[0, 64], vocabulary),
|
||||
Err(RtError::DraftVocabOutOfRange)
|
||||
);
|
||||
}
|
||||
|
||||
/// The real upstream files, when `LELEKA_TEST_DRAFT_VOCAB_DIR` names a directory holding `draft_vocab*.bin`
|
||||
/// (`git show 41cf05a0:data/draft_vocab_en.bin` of remote strata-upstream; the files stay out of Git).
|
||||
/// Checks the recorded digests, the id counts and that every subset is a valid, duplicate-free list inside the
|
||||
/// 248,320-row vocabulary; for `en` also that it is ascending and contained in the default list.
|
||||
#[test]
|
||||
fn recorded_digests_match_the_upstream_files_when_present() {
|
||||
let Some(dir) = std::env::var_os("LELEKA_TEST_DRAFT_VOCAB_DIR").map(PathBuf::from) else {
|
||||
eprintln!("LELEKA_TEST_DRAFT_VOCAB_DIR is not set: real-file check skipped");
|
||||
return;
|
||||
};
|
||||
let vocabulary = 248_320usize;
|
||||
let mut lists = Vec::new();
|
||||
for (index, k) in KNOWN.iter().enumerate() {
|
||||
let setting = if index == 0 {
|
||||
Setting::Path(dir.join(k.file))
|
||||
} else {
|
||||
Setting::Named(index)
|
||||
};
|
||||
let selection = select(&dir, &setting).unwrap();
|
||||
let Selection::Verified {
|
||||
label,
|
||||
sha256,
|
||||
bytes,
|
||||
..
|
||||
} = &selection
|
||||
else {
|
||||
panic!("{} {selection:?}", k.name)
|
||||
};
|
||||
assert_eq!((*label, *sha256), (k.name, k.sha256));
|
||||
let ids = ids_of(bytes);
|
||||
assert_eq!(ids.len(), k.ids);
|
||||
validate_subset(&ids, vocabulary).unwrap();
|
||||
let inverse = subset_inverse(vocabulary, &ids).unwrap();
|
||||
assert_eq!(
|
||||
inverse.iter().filter(|i| **i >= 0).count(),
|
||||
ids.len(),
|
||||
"{}: duplicate ids",
|
||||
k.name
|
||||
);
|
||||
for (row, &id) in ids.iter().enumerate() {
|
||||
assert_eq!(inverse[id as usize], row as i32);
|
||||
}
|
||||
lists.push(ids);
|
||||
}
|
||||
let default: std::collections::HashSet<i32> = lists[0].iter().copied().collect();
|
||||
assert!(lists[1].windows(2).all(|w| w[0] < w[1]), "en is ascending");
|
||||
assert!(
|
||||
lists[1].iter().all(|id| default.contains(id)),
|
||||
"en is inside the default list"
|
||||
);
|
||||
assert_eq!(lists[0].len() - lists[1].len(), 65_774);
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@
|
||||
//! and expert scale halves must be finite; draft-vocab ids must lie inside the
|
||||
//! vocabulary (the device gather would otherwise read out of bounds).
|
||||
|
||||
use crate::original_mtp_draft_vocab as dv;
|
||||
use std::{
|
||||
fs::{self, File},
|
||||
io::Read,
|
||||
@@ -59,6 +60,8 @@ pub(crate) enum RtError {
|
||||
MissingRequired(&'static str),
|
||||
DraftVocabTooLarge,
|
||||
DraftVocabOutOfRange,
|
||||
/// `LELEKA_DRAFT_VOCAB` named a file that is not an accepted subset (text already says which and why).
|
||||
DraftVocabSelection(String),
|
||||
Host,
|
||||
}
|
||||
|
||||
@@ -90,6 +93,7 @@ impl RtError {
|
||||
Self::DraftVocabOutOfRange => {
|
||||
"mtp: draft_vocab.bin holds an id outside the vocabulary".into()
|
||||
}
|
||||
Self::DraftVocabSelection(text) => format!("mtp: {text}"),
|
||||
Self::Host => "mtp: host allocation failed".into(),
|
||||
}
|
||||
}
|
||||
@@ -431,8 +435,20 @@ pub(crate) fn draft_vocab_path(directory: &Path) -> PathBuf {
|
||||
directory.join("draft_vocab.bin")
|
||||
}
|
||||
|
||||
/// `bind_bytes` probe (mtp.cpp:259-266): `fopen` succeeded -> `ftell` size.
|
||||
/// `bind_bytes` probe (mtp.cpp:259-266): `fopen` succeeded -> `ftell` size. Follows `LELEKA_DRAFT_VOCAB` (opt-in, see
|
||||
/// `original_mtp_draft_vocab`); a refused selection reports no size here and fails in [`read_draft_vocab`].
|
||||
pub(crate) fn observed_draft_vocab_bytes(directory: &Path) -> Option<u64> {
|
||||
observed_draft_vocab_bytes_with(directory, &dv::Setting::from_environment())
|
||||
}
|
||||
|
||||
pub(crate) fn observed_draft_vocab_bytes_with(directory: &Path, setting: &dv::Setting) -> Option<u64> {
|
||||
match setting {
|
||||
dv::Setting::Default => observed_default_bytes(directory),
|
||||
_ => dv::probe_bytes(directory, &dv::select(directory, setting).ok()?),
|
||||
}
|
||||
}
|
||||
|
||||
fn observed_default_bytes(directory: &Path) -> Option<u64> {
|
||||
Some(
|
||||
open_regular(&draft_vocab_path(directory))?
|
||||
.metadata()
|
||||
@@ -450,7 +466,28 @@ pub(crate) enum DraftVocab {
|
||||
|
||||
/// `bind` reads `draft_vocab.bin` (mtp.cpp:393-396). Original ignores a file
|
||||
/// that is unreadable or malformed in size; a valid-size file is a subset.
|
||||
/// `LELEKA_DRAFT_VOCAB` (opt-in) replaces that file by a checked upstream subset; one log line says which.
|
||||
pub(crate) fn read_draft_vocab(directory: &Path) -> RtResult<DraftVocab> {
|
||||
let selection = dv::select(directory, &dv::Setting::from_environment())?;
|
||||
if let Some(line) = dv::describe(&selection) {
|
||||
eprintln!("{line}");
|
||||
}
|
||||
read_selected_draft_vocab(directory, &selection)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn read_draft_vocab_with(directory: &Path, setting: &dv::Setting) -> RtResult<DraftVocab> {
|
||||
read_selected_draft_vocab(directory, &dv::select(directory, setting)?)
|
||||
}
|
||||
|
||||
pub(crate) fn read_selected_draft_vocab(directory: &Path, selection: &dv::Selection) -> RtResult<DraftVocab> {
|
||||
if let Some(subset) = dv::subset(selection) {
|
||||
return Ok(subset);
|
||||
}
|
||||
read_default_draft_vocab(directory)
|
||||
}
|
||||
|
||||
fn read_default_draft_vocab(directory: &Path) -> RtResult<DraftVocab> {
|
||||
let Some(mut file) = open_regular(&draft_vocab_path(directory)) else {
|
||||
return Ok(DraftVocab::Absent);
|
||||
};
|
||||
@@ -467,11 +504,7 @@ pub(crate) fn read_draft_vocab(directory: &Path) -> RtResult<DraftVocab> {
|
||||
if file.read_exact(&mut raw).is_err() {
|
||||
return Ok(DraftVocab::Absent);
|
||||
}
|
||||
Ok(DraftVocab::Subset(
|
||||
raw.chunks_exact(4)
|
||||
.map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]]))
|
||||
.collect(),
|
||||
))
|
||||
Ok(DraftVocab::Subset(dv::ids_of(&raw)))
|
||||
}
|
||||
|
||||
/// Every id must name a vocabulary row before the device gather reads it.
|
||||
@@ -992,19 +1025,19 @@ mod tests {
|
||||
#[test]
|
||||
fn draft_vocab_follows_the_original_size_filter() {
|
||||
let dir = TempDir::new("vocab");
|
||||
assert_eq!(read_draft_vocab(&dir.0).unwrap(), DraftVocab::Absent);
|
||||
assert_eq!(observed_draft_vocab_bytes(&dir.0), None);
|
||||
assert_eq!(read_draft_vocab_with(&dir.0, &dv::Setting::Default).unwrap(), DraftVocab::Absent);
|
||||
assert_eq!(observed_draft_vocab_bytes_with(&dir.0, &dv::Setting::Default), None);
|
||||
for bad in [&b""[..], &b"abc"[..], &b"abcdef"[..]] {
|
||||
write(&dir, "draft_vocab.bin", bad);
|
||||
assert_eq!(read_draft_vocab(&dir.0).unwrap(), DraftVocab::Absent);
|
||||
assert_eq!(read_draft_vocab_with(&dir.0, &dv::Setting::Default).unwrap(), DraftVocab::Absent);
|
||||
// the bind_bytes probe still sees the file size (the caller filters)
|
||||
assert_eq!(observed_draft_vocab_bytes(&dir.0), Some(bad.len() as u64));
|
||||
assert_eq!(observed_draft_vocab_bytes_with(&dir.0, &dv::Setting::Default), Some(bad.len() as u64));
|
||||
}
|
||||
let ids = [5i32, 0, 9, 5];
|
||||
let raw: Vec<u8> = ids.iter().flat_map(|i| i.to_le_bytes()).collect();
|
||||
write(&dir, "draft_vocab.bin", &raw);
|
||||
assert_eq!(
|
||||
read_draft_vocab(&dir.0).unwrap(),
|
||||
read_draft_vocab_with(&dir.0, &dv::Setting::Default).unwrap(),
|
||||
DraftVocab::Subset(ids.to_vec())
|
||||
);
|
||||
validate_subset(&ids, 10).unwrap();
|
||||
@@ -1019,6 +1052,6 @@ mod tests {
|
||||
"draft_vocab.bin",
|
||||
&vec![0u8; (DRAFT_VOCAB_MAX_IDS as usize + 1) * 4],
|
||||
);
|
||||
assert_eq!(read_draft_vocab(&dir.0), Err(RtError::DraftVocabTooLarge));
|
||||
assert_eq!(read_draft_vocab_with(&dir.0, &dv::Setting::Default), Err(RtError::DraftVocabTooLarge));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user