tracel-ai/burn · error
Invalid regex pattern
Error message
Invalid regex pattern
What it means
`with_key_remapping` compiles the `from_pattern` you pass as a Rust `regex` and panics via `.expect("Invalid regex pattern")` when `Regex::new` fails. The library's builder API is infallible, so a syntactically invalid regex is treated as a programming error and aborts instead of returning `Result`. The panic happens immediately when building the store, before any tensor is loaded or saved.
Source
Thrown at crates/burn-store/src/safetensors/store.rs:322
/// ```rust,no_run
/// # use burn_store::SafetensorsStore;
/// let store = SafetensorsStore::from_file("model.safetensors")
/// .with_key_remapping(r"^encoder\.", "transformer.encoder.") // encoder.X -> transformer.encoder.X
/// .with_key_remapping(r"\.gamma$", ".weight"); // X.gamma -> X.weight
/// ```
#[cfg(feature = "std")]
pub fn with_key_remapping(
mut self,
from_pattern: impl AsRef<str>,
to_pattern: impl Into<String>,
) -> Self {
match &mut self {
Self::File(p) => {
p.remapper = p
.remapper
.clone()
.add_pattern(from_pattern, to_pattern)
.expect("Invalid regex pattern");
}
Self::Memory(p) => {
p.remapper = p
.remapper
.clone()
.add_pattern(from_pattern, to_pattern)
.expect("Invalid regex pattern");
}
}
self
}
/// Add metadata to be saved with the tensors.
pub fn metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
let key = key.into();
let value = value.into();
match &mut self {
#[cfg(feature = "std")]View on GitHub (pinned to d16f7ba2ed)
Solutions
- Validate the pattern with `regex::Regex::new(from)` before passing it to `with_key_remapping`, and fix any regex syntax error it reports
- Replace unsupported regex features (lookarounds, backreferences) with regex-crate-compatible constructs (e.g. capture groups + expansion in `to`)
- Escape literal special characters with `regex::escape` for dynamic segments, e.g. `format!("{}.*", regex::escape(prefix))`
- If the pattern comes from user config, pre-compile and store the `Regex`, or switch to `with_remapper` with a custom Remapper that handles errors gracefully
Example fix
// before
let store = SafetensorsStore::from_file("model.safetensors")
.with_key_remapping(r"^encoder.(?=.*bn)", "transformer.encoder."); // panics: lookahead unsupported
// after
let store = SafetensorsStore::from_file("model.safetensors")
.with_key_remapping(r"^encoder\.", "transformer.encoder."); Defensive patterns
Strategy: validation
Validate before calling
use regex::Regex;
fn valid_pattern(p: &str) -> bool {
Regex::new(p).is_ok()
}
// before building the store:
assert!(valid_pattern(r"^encoder\."), "invalid remap pattern"); Type guard
fn is_valid_regex(pattern: &str) -> Result<regex::Regex, regex::Error> {
regex::Regex::new(pattern)
} Try / catch
// with_key_remapping panics, so validation must happen first;
// if patterns come from config, do:
let re = regex::Regex::new(&cfg.from_pattern)
.map_err(|e| anyhow::anyhow!("bad remap pattern {:?}: {}", cfg.from_pattern, e))?;
let store = SafetensorsStore::from_file(path).with_key_remapping(cfg.from_pattern, cfg.to_pattern); Prevention
- Validate every remap pattern with regex::Regex::new before calling with_key_remapping
- Avoid regex features unsupported by the Rust regex crate (lookarounds, backreferences)
- Use regex::escape for dynamic or literal segments
- Unit-test all remapping patterns with representative tensor names
When it happens
Trigger: Calling `SafetensorsStore::from_file(..).with_key_remapping(from, to)` (or on a memory-backed store) where `from` is not a valid regex — e.g. unbalanced `(`, `[`, dangling `*` or `+`, invalid escape like `\q`, or an overly large pattern that exceeds the regex size limit. The panic fires on the `Self::File` branch at store.rs:322.
Common situations: Copying Python `re` syntax that Rust's regex crate rejects (lookaheads `(?=...)`, backreferences `\1`, possessive quantifiers); typos in hand-written patterns; interpolating user input or dynamically-built strings into the pattern; forgetting to escape a literal dot or parenthesis.
Related errors
- capture tensor operations must run inside CaptureDevice::cap
- Capture tensors do not support autodiff
- Autodiff should not wrap an autodiff tensor.
- Requires autodiff tensor.
- Distributed operations are not supported for tensor kind {ot
AI-assisted analysis of tracel-ai/burn@d16f7ba2ed (2026-09-05).
Data as JSON: /api/errors/3ecc6a1e1f8f359a.
Report an issue: GitHub.