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
use nove_tensor::{DType, Device, Tensor, TensorError};
use std::{collections::HashMap, fmt::Display, path::Path};
use thiserror::Error;
pub mod layer;
pub mod resource;
#[derive(Error, Debug)]
pub enum ModelError {
/// I/O errors from the standard library.
#[error(transparent)]
IoError(#[from] std::io::Error),
/// Tensor errors from the `nove_tensor` crate.
#[error(transparent)]
TensorError(#[from] TensorError),
/// Unexpected parameter.
#[error("Unexpected parameter: {0}")]
UnexpectedParameter(String),
/// Parameter missing name.
#[error("Parameter missing name")]
ParameterMissingName,
/// Parameter count mismatch.
#[error("Parameter count mismatch: expected {expected}, got {actual}")]
ParameterCountMismatch { expected: usize, actual: usize },
/// Other errors.
#[error("{0}")]
OtherError(String),
/// Invalid argument.
#[error("Invalid argument: {0}")]
InvalidArgument(String),
/// Missing argument.
#[error("Missing argument: {0}")]
MissingArgument(String),
}
pub trait Model: Display {
type Input;
type Output;
/// Run the model forward pass.
///
/// # Arguments
/// * `input` - The input tensor.
///
/// # Returns
/// * `Ok(Self::Output)` - The output tensor if successful.
/// * `Err(ModelError)` - The error when running the model forward pass.
fn forward(&mut self, input: Self::Input) -> Result<Self::Output, ModelError>;
/// Set whether to enable gradient tracking for the model.
///
/// # Arguments
/// * `grad_enabled` - Whether to enable gradient tracking for the model.
///
/// # Returns
/// * `Ok(())` - If successful.
/// * `Err(ModelError)` - The error when setting the gradient tracking.
fn require_grad(&mut self, grad_enabled: bool) -> Result<(), ModelError>;
/// Move the model to the specified device.
///
/// # Arguments
/// * `device` - The device to move the model to.
///
/// # Returns
/// * `Ok(())` - If successful.
/// * `Err(ModelError)` - The error when moving the model to the device.
fn to_device(&mut self, device: &Device) -> Result<(), ModelError>;
/// Convert the model to the specified data type.
///
/// # Arguments
/// * `dtype` - The data type to convert the model to.
///
/// # Returns
/// * `Ok(())` - If successful.
/// * `Err(ModelError)` - The error when converting the model to the data type.
fn to_dtype(&mut self, dtype: &DType) -> Result<(), ModelError>;
/// Get the parameters of the model.
///
/// # Returns
/// * `Ok(Vec<Tensor>)` - The parameters of the model.
/// * `Err(ModelError)` - The error when getting the parameters of the model.
fn parameters(&self) -> Result<Vec<Tensor>, ModelError>;
/// Get the named parameters of the model.
///
/// # Returns
/// * `Ok(HashMap<String, Tensor>)` - The named parameters of the model.
/// * `Err(ModelError)` - The error when getting the named parameters of the model.
fn named_parameters(&self) -> Result<HashMap<String, Tensor>, ModelError>;
/// Save the model parameters to a file.
///
/// # Arguments
/// * `file_path` - The path to the file.
///
/// # Returns
/// * `Ok(())` - If successful.
/// * `Err(ModelError)` - The error when saving the model parameters to the file.
fn save(&self, file_path: &str) -> Result<(), ModelError> {
let file = Path::new(file_path);
match file.extension().and_then(|ext| ext.to_str()) {
Some("safetensors") => {
let params = self.named_parameters()?;
nove_tensor::safetensor::save(file_path, params)?;
}
Some(ext) => {
return Err(ModelError::OtherError(format!(
"Unsupported file extension: {}",
ext
)));
}
None => {
return Err(ModelError::OtherError(
"File extension not found".to_string(),
));
}
}
Ok(())
}
/// Load the model parameters from a file.
///
/// # Arguments
/// * `file_path` - The path to the file.
/// * `device` - The device to load the model parameters to.
///
/// # Returns
/// * `Ok(())` - If successful.
/// * `Err(ModelError)` - The error when loading the model parameters from the file.
fn load(&mut self, file_path: &str, device: &Device) -> Result<(), ModelError> {
let file = Path::new(file_path);
match file.extension().and_then(|ext| ext.to_str()) {
Some("safetensors") => {
let new_params = nove_tensor::safetensor::load(file_path, device)?;
let old_params = self.named_parameters()?;
if new_params.len() != old_params.len() {
return Err(ModelError::ParameterCountMismatch {
expected: old_params.len(),
actual: new_params.len(),
});
}
for (new_param_name, new_param) in new_params {
let old_param = old_params
.iter()
.find(|(old_param_name, _)| {
for (old_part, new_part) in
old_param_name.split('.').zip(new_param_name.split('.'))
{
if !old_part.parse::<usize>().is_ok() && old_part != new_part {
return false;
}
}
true
})
.map(|(_, tensor)| tensor)
.ok_or(ModelError::UnexpectedParameter(new_param_name))?;
old_param.update_from_tensor(&new_param)?;
}
}
Some(ext) => {
return Err(ModelError::OtherError(format!(
"Unsupported file extension: {}",
ext
)));
}
None => {
return Err(ModelError::OtherError(
"File extension not found".to_string(),
));
}
}
Ok(())
}
}