File size: 30,322 Bytes
fac4d07 4a54697 fac4d07 4a54697 fac4d07 4a54697 fac4d07 4a54697 fac4d07 4a54697 fac4d07 4a54697 fac4d07 4a54697 fac4d07 4a54697 fac4d07 4a54697 fac4d07 4a54697 fac4d07 4a54697 fac4d07 4a54697 fac4d07 36fe364 fac4d07 36fe364 fac4d07 36fe364 fac4d07 | 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 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 | //! Trainable CPU Transformer with the original PyTorch parameter namespace.
use std::collections::BTreeMap;
use std::path::Path;
use serde_json::Value;
use sha2::{Digest, Sha256};
use tch::{Device, Kind, Tensor, nn};
use thiserror::Error;
use crate::config::{ArtifactConfig, ConfigError, ModelConfig, expected_labels};
use crate::tokenizer::TokenizerError;
/// Recoverable model construction, tensor execution and artifact failures.
#[derive(Debug, Error)]
pub enum ModelError {
/// Configuration invariants failed.
#[error(transparent)]
Config(#[from] ConfigError),
/// Input encoding failed.
#[error(transparent)]
Tokenizer(#[from] TokenizerError),
/// A LibTorch operation failed.
#[error(transparent)]
Tensor(#[from] tch::TchError),
/// Filesystem access failed.
#[error(transparent)]
Io(#[from] std::io::Error),
/// Tensor shape arithmetic cannot be represented.
#[error("model dimensions exceed supported integer ranges")]
Dimensions,
/// Artifact tensor names differ from the architecture.
#[error("incompatible parameters: missing={missing:?}, unexpected={unexpected:?}")]
ParameterNames {
/// Required names missing from the artifact.
missing: Vec<String>,
/// Artifact names absent from the architecture.
unexpected: Vec<String>,
},
/// A parameter has a different shape.
#[error("incompatible shape for {name}: expected {expected:?}, received {actual:?}")]
ParameterShape {
/// Parameter identity.
name: String,
/// Architecture shape.
expected: Vec<i64>,
/// Loaded tensor shape.
actual: Vec<i64>,
},
/// A parameter is not a CPU float32 tensor.
#[error("parameter {0} must be a CPU float32 tensor")]
ParameterType(String),
/// Nonfinite parameters are never accepted or serialized.
#[error("parameter {0} contains nonfinite values")]
NonFinite(String),
/// Duplicate parameter names are not allowed.
#[error("duplicate parameter name: {0}")]
DuplicateParameter(String),
/// Native-source provenance must identify the actual SafeTensors file.
#[error("SafeTensors source hash does not match the weight file")]
SourceHashMismatch,
/// The batch shape or leading CLS token is invalid.
#[error("invalid model input: {0}")]
InputShape(&'static str),
/// Word or character identifiers exceed embedding ranges.
#[error("input identifiers are outside the {0} embedding range")]
InputIdentifiers(&'static str),
}
/// A registered affine map; tensor handles share storage with the VarStore.
pub(crate) struct Linear {
/// Row-major [output, input] trainable matrix.
pub(crate) weight: Tensor,
/// One trainable offset per output coordinate.
pub(crate) bias: Tensor,
}
impl Linear {
/// Match PyTorch Linear's uniform initialization from its fan-in width.
pub(crate) fn new(
path: &nn::Path<'_>,
input: i64,
output: i64,
zero_bias: bool,
) -> Result<Self, ModelError> {
let input_float = f64::from(u32::try_from(input).map_err(|_| ModelError::Dimensions)?);
let bound = input_float.sqrt().recip();
let initialization = nn::Init::Uniform {
lo: -bound,
up: bound,
};
Ok(Self {
weight: path.f_var("weight", &[output, input], initialization)?,
bias: path.f_var(
"bias",
&[output],
if zero_bias {
nn::Init::Const(0.0)
} else {
initialization
},
)?,
})
}
/// Apply the affine map to the last axis without changing preceding axes.
pub(crate) fn forward(&self, input: &Tensor) -> Result<Tensor, ModelError> {
Ok(input.f_linear(&self.weight, Some(&self.bias))?)
}
}
/// Affine last-axis normalization with PyTorch's default epsilon of 1e-5.
pub(crate) struct LayerNorm {
/// Trainable coordinate scale, initialized to one.
weight: Tensor,
/// Trainable coordinate shift, initialized to zero.
bias: Tensor,
/// Last-axis length over which mean and population variance are computed.
width: i64,
}
impl LayerNorm {
/// Register the identity affine transform under the owning layer path.
pub(crate) fn new(path: &nn::Path<'_>, width: i64) -> Result<Self, ModelError> {
Ok(Self {
weight: path.f_ones("weight", &[width])?,
bias: path.f_zeros("bias", &[width])?,
width,
})
}
/// Normalize each token independently; padding is handled by attention.
pub(crate) fn forward(&self, input: &Tensor) -> Result<Tensor, ModelError> {
Ok(input.f_layer_norm(
[self.width],
Some(&self.weight),
Some(&self.bias),
1e-5,
true,
)?)
}
}
/// One post-norm TransformerEncoderLayer with packed Q/K/V projections.
pub(crate) struct EncoderLayer {
/// Three concatenated [width, width] projection matrices in Q/K/V order.
projection_weight: Tensor,
/// Three concatenated coordinate biases in Q/K/V order.
projection_bias: Tensor,
/// Projection from concatenated attention heads to hidden width.
attention_output: Linear,
/// Expansion from hidden width to feed-forward width.
feedforward_input: Linear,
/// Projection from activated feed-forward coordinates to hidden width.
feedforward_output: Linear,
/// Normalization after the attention residual addition.
norm1: LayerNorm,
/// Normalization after the feed-forward residual addition.
norm2: LayerNorm,
/// Validated hidden width, divisible by the number of heads.
width: i64,
/// Number of disjoint coordinate groups used by attention.
heads: i64,
/// Shared probability for attention and residual/feed-forward dropout.
dropout: f64,
}
impl EncoderLayer {
/// Preserve the original parameter names and MultiheadAttention reset order.
pub(crate) fn new(path: &nn::Path<'_>, config: &ModelConfig) -> Result<Self, ModelError> {
let width_float =
f64::from(u32::try_from(config.width).map_err(|_| ModelError::Dimensions)?);
let bound = (1.5 / width_float).sqrt();
let projection_size = config.width.checked_mul(3).ok_or(ModelError::Dimensions)?;
let attention = path / "self_attn";
let mut projection_weight =
attention.f_zeros("in_proj_weight", &[projection_size, config.width])?;
let projection_bias = attention.f_zeros("in_proj_bias", &[projection_size])?;
// PyTorch initializes out_proj as Linear before resetting packed QKV.
let mut attention_output = Linear::new(
&(&attention / "out_proj"),
config.width,
config.width,
false,
)?;
tch::no_grad(|| -> Result<(), tch::TchError> {
let _ = projection_weight.f_uniform_(-bound, bound)?;
let _ = attention_output.bias.f_zero_()?;
Ok(())
})?;
Ok(Self {
projection_weight,
projection_bias,
attention_output,
feedforward_input: Linear::new(
&(path / "linear1"),
config.width,
config.feedforward,
false,
)?,
feedforward_output: Linear::new(
&(path / "linear2"),
config.feedforward,
config.width,
false,
)?,
norm1: LayerNorm::new(&(path / "norm1"), config.width)?,
norm2: LayerNorm::new(&(path / "norm2"), config.width)?,
width: config.width,
heads: config.heads,
dropout: config.dropout,
})
}
/// Follow PyTorch's sequence-first packed projection and output layouts.
///
/// Matching layout also preserves the order of floating-point gradient
/// reductions, which matters for theoretically zero key-bias gradients.
fn attention(
&self,
hidden: &Tensor,
mask: &Tensor,
batch: i64,
length: i64,
train: bool,
) -> Result<Tensor, ModelError> {
let projected = hidden
.f_transpose(0, 1)?
.f_linear(&self.projection_weight, Some(&self.projection_bias))?
.f_reshape([length, batch, 3, self.width])?
.f_permute([2, 0, 1, 3])?
.f_contiguous()?;
let head_width = self.width / self.heads;
let batch_heads = batch
.checked_mul(self.heads)
.ok_or(ModelError::Dimensions)?;
let project = |component: i64| -> Result<Tensor, ModelError> {
Ok(projected
.f_select(0, component)?
.f_reshape([length, batch_heads, head_width])?
.f_transpose(0, 1)?
.f_reshape([batch, self.heads, length, head_width])?)
};
let query = project(0)?;
let key = project(1)?;
let value = project(2)?;
let attention_mask = mask
.f_to_kind(Kind::Float)?
.f_masked_fill(mask, f64::NEG_INFINITY)?
.f_reshape([batch, 1, 1, length])?
.f_expand([batch, self.heads, 1, length], false)?
.f_reshape([batch_heads, 1, length])?
.f_reshape([batch, self.heads, 1, length])?;
let output = Tensor::f_scaled_dot_product_attention(
&query,
&key,
&value,
Some(&attention_mask),
if train { self.dropout } else { 0.0 },
false,
None,
false,
)?;
let joined = output.f_permute([2, 0, 1, 3])?.f_contiguous()?.f_reshape([
length.checked_mul(batch).ok_or(ModelError::Dimensions)?,
self.width,
])?;
Ok(self
.attention_output
.forward(&joined)?
.f_reshape([length, batch, self.width])?
.f_transpose(0, 1)?)
}
/// Apply attention/residual/norm followed by ReLU feed-forward/residual/norm.
pub(crate) fn forward(
&self,
hidden: &Tensor,
mask: &Tensor,
batch: i64,
length: i64,
train: bool,
) -> Result<Tensor, ModelError> {
let attention = self
.attention(hidden, mask, batch, length, train)?
.f_dropout(self.dropout, train)?;
let normalized = self.norm1.forward(&hidden.f_add(&attention)?)?;
let intermediate = self
.feedforward_input
.forward(&normalized)?
.f_relu()?
.f_dropout(self.dropout, train)?;
let output = self
.feedforward_output
.forward(&intermediate)?
.f_dropout(self.dropout, train)?;
self.norm2.forward(&normalized.f_add(&output)?)
}
}
/// Initialize a normal embedding table and zero its optional padding row.
pub(crate) fn embedding(
path: &nn::Path<'_>,
rows: i64,
width: i64,
padding: bool,
) -> Result<Tensor, ModelError> {
let weight = path.f_var(
"weight",
&[rows, width],
nn::Init::Randn {
mean: 0.0,
stdev: 1.0,
},
)?;
if padding {
tch::no_grad(|| -> Result<(), tch::TchError> {
let _ = weight.f_get(0)?.f_zero_()?;
Ok(())
})?;
}
Ok(weight)
}
/// The exact post-norm word/subword Transformer, with trainable named tensors.
pub struct IntentClassifier {
/// Architecture used for encoding and forward execution.
pub config: ModelConfig,
/// Whole-word table, with row zero excluded from embedding gradients.
words: Tensor,
/// Hashed character-fragment table, also with a zero padding row.
characters: Tensor,
/// Trainable absolute positions, including position zero for CLS.
positions: Tensor,
/// Normalize the sum of the three embedding components.
norm: LayerNorm,
/// Independently parameterized post-norm encoder layers, in execution order.
layers: Vec<EncoderLayer>,
/// Affine map from the final CLS state to the fixed ordered labels.
output: Linear,
/// Upper exclusive bound for whole-word input identifiers.
vocabulary_size: i64,
}
impl IntentClassifier {
/// Register newly initialized parameters under the original Python names.
pub fn new(
path: &nn::Path<'_>,
config: &ModelConfig,
vocabulary_size: i64,
) -> Result<Self, ModelError> {
config.validate()?;
if vocabulary_size < 3 {
return Err(ConfigError::Vocabulary.into());
}
vocabulary_size
.checked_mul(config.width)
.ok_or(ModelError::Dimensions)?;
let mut layers = Vec::with_capacity(config.layers);
let words = embedding(&(path / "words"), vocabulary_size, config.width, true)?;
let characters = embedding(
&(path / "characters"),
config.char_buckets,
config.width,
true,
)?;
let positions = embedding(&(path / "positions"), config.max_words, config.width, false)?;
let norm = LayerNorm::new(&(path / "norm"), config.width)?;
for index in 0..config.layers {
layers.push(EncoderLayer::new(
&(&(path / "layers") / index.to_string()),
config,
)?);
}
let labels = i64::try_from(expected_labels().len()).map_err(|_| ModelError::Dimensions)?;
Ok(Self {
config: config.clone(),
words,
characters,
positions,
norm,
layers,
output: Linear::new(&(path / "output"), config.width, labels, false)?,
vocabulary_size,
})
}
/// Validate tensor ranks, devices, identifiers and an unmasked leading CLS.
fn validate_inputs(
&self,
words: &Tensor,
characters: &Tensor,
) -> Result<(i64, i64), ModelError> {
let sizes = words.size();
let (batch, length) = match sizes.as_slice() {
[batch, length] if *batch > 0 && *length > 1 && *length <= self.config.max_words => {
(*batch, *length)
}
_ => {
return Err(ModelError::InputShape(
"words must be a nonempty [batch, sequence] tensor",
));
}
};
if characters.size() != [batch, length, self.config.max_ngrams] {
return Err(ModelError::InputShape(
"character shape must be [batch, sequence, max_ngrams]",
));
}
if words.kind() != Kind::Int64
|| characters.kind() != Kind::Int64
|| words.device() != self.words.device()
|| characters.device() != self.words.device()
{
return Err(ModelError::InputShape(
"identifiers must be int64 tensors on the model device",
));
}
for (name, tensor, maximum) in [
("word", words, self.vocabulary_size),
("character", characters, self.config.char_buckets),
] {
if tensor.f_min()?.f_int64_value(&[])? < 0
|| tensor.f_max()?.f_int64_value(&[])? >= maximum
{
return Err(ModelError::InputIdentifiers(name));
}
}
if words.f_select(1, 0)?.f_eq(2)?.f_all()?.f_int64_value(&[])? != 1 {
return Err(ModelError::InputShape(
"every row must begin with CLS identifier 2",
));
}
Ok((batch, length))
}
/// Produce 49 logits; `train` enables all original dropout sites and gradients remain available.
pub fn forward(
&self,
word_ids: &Tensor,
char_ids: &Tensor,
train: bool,
) -> Result<Tensor, ModelError> {
let (batch, length) = self.validate_inputs(word_ids, char_ids)?;
let mask = word_ids.f_eq(0)?;
let count = char_ids
.f_ne(0)?
.f_sum_dim_intlist([-1_i64].as_slice(), true, Kind::Int64)?
.f_clamp_min(1)?;
let character_features = Tensor::f_embedding(&self.characters, char_ids, 0, false, false)?
.f_sum_dim_intlist([-2_i64].as_slice(), false, Kind::Float)?
.f_div(&count.f_sqrt()?)?;
let position_ids = Tensor::f_arange(length, (Kind::Int64, word_ids.device()))?;
let positions = Tensor::f_embedding(&self.positions, &position_ids, -1, false, false)?;
let words = Tensor::f_embedding(&self.words, word_ids, 0, false, false)?;
let mut hidden = self
.norm
.forward(&words.f_add(&character_features)?.f_add(&positions)?)?
.f_dropout(self.config.dropout, train)?;
for layer in &self.layers {
hidden = layer.forward(&hidden, &mask, batch, length, train)?;
}
self.output.forward(&hidden.f_select(1, 0)?)
}
}
/// Derive the complete parameter namespace before allocating a loaded model.
fn parameter_shapes(config: &ArtifactConfig) -> Result<BTreeMap<String, Vec<i64>>, ModelError> {
let architecture = &config.architecture;
let width = architecture.width;
let projected = width.checked_mul(3).ok_or(ModelError::Dimensions)?;
let vocabulary = i64::try_from(config.vocab.len()).map_err(|_| ModelError::Dimensions)?;
let labels = i64::try_from(config.labels.len()).map_err(|_| ModelError::Dimensions)?;
let mut shapes: BTreeMap<String, Vec<i64>> = [
("words.weight", vec![vocabulary, width]),
("characters.weight", vec![architecture.char_buckets, width]),
("positions.weight", vec![architecture.max_words, width]),
("norm.weight", vec![width]),
("norm.bias", vec![width]),
("output.weight", vec![labels, width]),
("output.bias", vec![labels]),
]
.into_iter()
.map(|(name, shape)| (name.to_owned(), shape))
.collect();
for index in 0..architecture.layers {
for (name, shape) in [
("self_attn.in_proj_weight", vec![projected, width]),
("self_attn.in_proj_bias", vec![projected]),
("self_attn.out_proj.weight", vec![width, width]),
("self_attn.out_proj.bias", vec![width]),
("linear1.weight", vec![architecture.feedforward, width]),
("linear1.bias", vec![architecture.feedforward]),
("linear2.weight", vec![width, architecture.feedforward]),
("linear2.bias", vec![width]),
("norm1.weight", vec![width]),
("norm1.bias", vec![width]),
("norm2.weight", vec![width]),
("norm2.bias", vec![width]),
] {
shapes.insert(format!("layers.{index}.{name}"), shape);
}
}
Ok(shapes)
}
/// Admit exactly the architecture's finite, dense CPU float32 parameter set.
fn validate_weights(
weights: &BTreeMap<String, Tensor>,
config: &ArtifactConfig,
) -> Result<(), ModelError> {
let expected = parameter_shapes(config)?;
let missing: Vec<String> = expected
.keys()
.filter(|name| !weights.contains_key(*name))
.cloned()
.collect();
let unexpected: Vec<String> = weights
.keys()
.filter(|name| !expected.contains_key(*name))
.cloned()
.collect();
if !missing.is_empty() || !unexpected.is_empty() {
return Err(ModelError::ParameterNames {
missing,
unexpected,
});
}
for (name, tensor) in weights {
let shape = expected.get(name).ok_or(ModelError::Dimensions)?;
if &tensor.size() != shape {
return Err(ModelError::ParameterShape {
name: name.to_owned(),
expected: shape.to_owned(),
actual: tensor.size(),
});
}
if tensor.kind() != Kind::Float || tensor.device() != Device::Cpu {
return Err(ModelError::ParameterType(name.to_owned()));
}
if tensor.f_isfinite()?.f_all()?.f_int64_value(&[])? != 1 {
return Err(ModelError::NonFinite(name.to_owned()));
}
}
Ok(())
}
/// Hash canonical ordered parameter values independently of SafeTensors headers.
fn weight_fingerprint(weights: &BTreeMap<String, Tensor>) -> Result<String, ModelError> {
let mut digest = Sha256::new();
for (name, tensor) in weights {
digest.update(
u64::try_from(name.len())
.map_err(|_| ModelError::Dimensions)?
.to_le_bytes(),
);
digest.update(name.as_bytes());
for dimension in tensor.size() {
digest.update(dimension.to_le_bytes());
}
let mut values = vec![0_f32; tensor.numel()];
tensor.f_copy_data(&mut values, tensor.numel())?;
for value in values {
digest.update(value.to_le_bytes());
}
}
Ok(format!("{:x}", digest.finalize()))
}
/// Registered trainable parameters, their encoder and validated artifact metadata.
pub struct ModelBundle {
/// Named parameter store used by optimizers and checkpoint snapshots.
pub vs: nn::VarStore,
/// Trainable classifier sharing the store's registered tensors.
pub model: IntentClassifier,
/// Complete metadata; training can update provenance before saving.
pub metadata: ArtifactConfig,
/// Original numerical state, used only to preserve unchanged import provenance.
imported_fingerprint: Option<String>,
}
impl ModelBundle {
/// Initialize a fresh CPU model; seed mutation is explicit at this boundary.
pub fn new(metadata: ArtifactConfig, seed: i64) -> Result<Self, ModelError> {
metadata.validate()?;
tch::manual_seed(seed);
let vs = nn::VarStore::new(Device::Cpu);
let vocabulary = i64::try_from(metadata.vocab.len()).map_err(|_| ModelError::Dimensions)?;
let model = IntentClassifier::new(&vs.root(), &metadata.architecture, vocabulary)?;
Ok(Self {
vs,
model,
metadata,
imported_fingerprint: None,
})
}
/// Load only `config.json` and exact named finite float32 SafeTensors weights.
pub fn load(directory: impl AsRef<Path>) -> Result<Self, ModelError> {
let directory = directory.as_ref();
let metadata = ArtifactConfig::load(directory.join("config.json"))?;
let weight_path = directory.join("model.safetensors");
if metadata
.extra
.get("source_checkpoint_format")
.and_then(Value::as_str)
== Some("safetensors")
{
let actual = format!("{:x}", Sha256::digest(std::fs::read(&weight_path)?));
if metadata
.extra
.get("source_checkpoint_sha256")
.and_then(Value::as_str)
!= Some(actual.as_str())
{
return Err(ModelError::SourceHashMismatch);
}
}
let mut weights = BTreeMap::new();
for (name, tensor) in Tensor::read_safetensors(weight_path)? {
if weights.insert(name.to_owned(), tensor).is_some() {
return Err(ModelError::DuplicateParameter(name));
}
}
validate_weights(&weights, &metadata)?;
let imported_fingerprint = Some(weight_fingerprint(&weights)?);
let vs = nn::VarStore::new(Device::Cpu);
let vocabulary = i64::try_from(metadata.vocab.len()).map_err(|_| ModelError::Dimensions)?;
let model = IntentClassifier::new(&vs.root(), &metadata.architecture, vocabulary)?;
let mut parameters = vs.variables();
tch::no_grad(|| -> Result<(), ModelError> {
for (name, weight) in &weights {
parameters
.get_mut(name)
.ok_or(ModelError::Dimensions)?
.f_copy_(weight)?;
}
Ok(())
})?;
Ok(Self {
vs,
model,
metadata,
imported_fingerprint,
})
}
/// Save named weights and JSON, retaining unrelated files in the directory.
///
/// Unchanged imports preserve historical source provenance. Fresh or modified
/// parameters identify their real new SafeTensors bytes as the source artifact.
pub fn save(&mut self, directory: impl AsRef<Path>) -> Result<(), ModelError> {
self.metadata.validate()?;
let weights: BTreeMap<String, Tensor> = self.vs.variables().into_iter().collect();
validate_weights(&weights, &self.metadata)?;
let fingerprint = weight_fingerprint(&weights)?;
let unchanged = self.imported_fingerprint.as_ref() == Some(&fingerprint);
let directory = directory.as_ref();
std::fs::create_dir_all(directory)?;
let staged = tempfile::tempdir_in(directory)?;
let weight_path = staged.path().join("model.safetensors");
self.vs.save(&weight_path)?;
let mut metadata = self.metadata.clone();
metadata
.extra
.insert("artifact_format_version".into(), Value::from(1));
metadata
.extra
.entry("training".into())
.or_insert_with(|| Value::Object(serde_json::Map::new()));
let native_source = metadata
.extra
.get("source_checkpoint_format")
.and_then(Value::as_str)
== Some("safetensors");
if !unchanged || native_source {
let hash = format!("{:x}", Sha256::digest(std::fs::read(&weight_path)?));
metadata
.extra
.insert("source_checkpoint_sha256".into(), Value::String(hash));
metadata.extra.insert(
"source_checkpoint_format".into(),
Value::String("safetensors".into()),
);
}
let config_path = staged.path().join("config.json");
metadata.save(&config_path)?;
std::fs::rename(weight_path, directory.join("model.safetensors"))?;
std::fs::rename(config_path, directory.join("config.json"))?;
self.metadata = metadata;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::Thresholds;
/// Small real model retaining the complete output-label and token contracts.
fn fixture() -> Result<ModelBundle, ModelError> {
let architecture = ModelConfig {
width: 8,
heads: 2,
layers: 1,
feedforward: 16,
char_buckets: 16,
max_ngrams: 8,
..ModelConfig::default()
};
let metadata = ArtifactConfig {
architecture,
labels: expected_labels(),
vocab: [
("<pad>".into(), 0),
("<unk>".into(), 1),
("<cls>".into(), 2),
("split".into(), 3),
]
.into_iter()
.collect(),
thresholds: Thresholds {
probability: 0.8,
margin: 0.1,
},
extra: BTreeMap::new(),
};
ModelBundle::new(metadata, 7)
}
#[test]
fn missing_and_unexpected_weight_names_are_rejected() -> Result<(), ModelError> {
let _test = crate::runtime::test_serial_guard();
let bundle = fixture()?;
let mut parameters: BTreeMap<_, _> = bundle.vs.variables().into_iter().collect();
parameters.remove("output.bias");
assert!(matches!(validate_weights(¶meters, &bundle.metadata),
Err(ModelError::ParameterNames { missing, .. }) if missing == ["output.bias"]));
let mut parameters: BTreeMap<_, _> = bundle.vs.variables().into_iter().collect();
parameters.insert(
"unregistered.weight".into(),
Tensor::f_zeros([1], (Kind::Float, Device::Cpu))?,
);
assert!(matches!(validate_weights(¶meters, &bundle.metadata),
Err(ModelError::ParameterNames { unexpected, .. }) if unexpected == ["unregistered.weight"]));
Ok(())
}
#[test]
fn incorrect_shapes_dtypes_and_nonfinite_weights_are_rejected() -> Result<(), ModelError> {
let _test = crate::runtime::test_serial_guard();
let bundle = fixture()?;
let mut parameters: BTreeMap<_, _> = bundle.vs.variables().into_iter().collect();
parameters.insert(
"output.weight".into(),
Tensor::f_zeros([48, 8], (Kind::Float, Device::Cpu))?,
);
assert!(matches!(
validate_weights(¶meters, &bundle.metadata),
Err(ModelError::ParameterShape { .. })
));
parameters.insert(
"output.weight".into(),
Tensor::f_zeros([49, 8], (Kind::Double, Device::Cpu))?,
);
assert!(matches!(
validate_weights(¶meters, &bundle.metadata),
Err(ModelError::ParameterType(_))
));
parameters.insert(
"output.weight".into(),
Tensor::f_full([49, 8], f64::NAN, (Kind::Float, Device::Cpu))?,
);
assert!(matches!(
validate_weights(¶meters, &bundle.metadata),
Err(ModelError::NonFinite(_))
));
Ok(())
}
#[test]
fn native_artifacts_bind_the_source_hash_to_the_saved_weights() -> Result<(), ModelError> {
let _test = crate::runtime::test_serial_guard();
let mut bundle = fixture()?;
let directory = tempfile::tempdir()?;
bundle.save(directory.path())?;
let loaded = ModelBundle::load(directory.path())?;
assert_eq!(
loaded
.metadata
.extra
.get("source_checkpoint_format")
.and_then(Value::as_str),
Some("safetensors")
);
std::fs::write(
directory.path().join("model.safetensors"),
b"changed weights",
)?;
assert!(matches!(
ModelBundle::load(directory.path()),
Err(ModelError::SourceHashMismatch)
));
Ok(())
}
}
|